From 29cccd823449a76bcc0072f5faa89c5fccd8588d Mon Sep 17 00:00:00 2001 From: Robert Walsh Date: Mon, 19 Sep 2016 14:47:30 -0500 Subject: [PATCH 01/36] Updates Changed orgName and appName to be orgName and appId. Added LoDash.core Fixing tests. Minor changes to Client.js --- .gitignore | 2 + Gruntfile.js | 1 + examples/test/test.js | 4 +- lib/modules/Asset.js | 9 +- lib/modules/Client.js | 39 +- lib/modules/util/Logger.js | 2 +- lib/modules/util/lodash.core.js | 3839 +++++++++++++++++++++++++++++++ tests/mocha/test.js | 21 +- tests/test.js | 4 +- usergrid.js | 3736 +++++++++++++++++++++++++++++- 10 files changed, 7496 insertions(+), 161 deletions(-) create mode 100644 lib/modules/util/lodash.core.js diff --git a/.gitignore b/.gitignore index 485dee6..b7ed6d0 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ .idea +/node_modules +.DS_Store diff --git a/Gruntfile.js b/Gruntfile.js index a2b7b6f..5cfaf62 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -4,6 +4,7 @@ module.exports = function(grunt) { "lib/modules/util/Logger.js", "lib/modules/util/Promise.js", "lib/modules/util/Ajax.js", + "lib/modules/util/lodash.core.js", "lib/Usergrid.js", "lib/modules/Client.js", "lib/modules/Entity.js", diff --git a/examples/test/test.js b/examples/test/test.js index fb65d98..de0f4aa 100755 --- a/examples/test/test.js +++ b/examples/test/test.js @@ -30,8 +30,8 @@ var _password = 'password2'; var _newpassword = 'password3'; var client = new Usergrid.Client({ - orgName:'yourorgname', - appName:'sandbox', + orgId:'rwalsh', + appId:'sandbox', logging: true, //optional - turn on logging, off by default buildCurl: true //optional - turn on curl commands, off by default }); diff --git a/lib/modules/Asset.js b/lib/modules/Asset.js index 862313a..226d611 100644 --- a/lib/modules/Asset.js +++ b/lib/modules/Asset.js @@ -131,11 +131,11 @@ Usergrid.Entity.prototype.attachAsset = function (file, callback) { } if(type != 'assets' && type != 'asset') { - var endpoint = [ this._client.URI, this._client.orgName, this._client.appName, type, self.get("uuid") ].join("/"); + var endpoint = [ this._client.clientAppURL, type, self.get("uuid") ].join("/"); } else { self.set("content-type", file.type); self.set("size", file.size); - var endpoint = [ this._client.URI, this._client.orgName, this._client.appName, "assets", self.get("uuid"), "data" ].join("/"); + var endpoint = [ this._client.clientAppURL, "assets", self.get("uuid"), "data" ].join("/"); } var xhr = new XMLHttpRequest(); @@ -203,9 +203,9 @@ Usergrid.Entity.prototype.downloadAsset = function(callback) { var xhr = new XMLHttpRequest(); if(type != "assets" && type != 'asset') { - endpoint = [ this._client.URI, this._client.orgName, this._client.appName, type, self.get("uuid") ].join("/"); + endpoint = [ this._client.clientAppURL, type, self.get("uuid") ].join("/"); } else { - endpoint = [ this._client.URI, this._client.orgName, this._client.appName, "assets", self.get("uuid"), "data" ].join("/"); + endpoint = [ this._client.clientAppURL, "assets", self.get("uuid"), "data" ].join("/"); } xhr.open("GET", endpoint, true); xhr.responseType = "blob"; @@ -218,6 +218,7 @@ Usergrid.Entity.prototype.downloadAsset = function(callback) { } }; xhr.onerror = function(err) { + callback(true, err); doCallback(callback, [ new UsergridError(err), xhr, self ], self); }; diff --git a/lib/modules/Client.js b/lib/modules/Client.js index e27ae65..069153b 100644 --- a/lib/modules/Client.js +++ b/lib/modules/Client.js @@ -29,26 +29,29 @@ "unauthorized", "auth_invalid" ]; + var defaultOptions = { + baseUrl: 'https://api.usergrid.com' + }; Usergrid.Client = function(options) { - //usergrid endpoint - this.URI = options.URI || 'https://api.usergrid.com'; - - //Find your Orgname and Appname in the Admin portal (http://apigee.com/usergrid) - if (options.orgName) { - this.set('orgName', options.orgName); - } - if (options.appName) { - this.set('appName', options.appName); + if (!options.orgId || !options.appId) { + throw new Error('"orgId" and "appId" parameters are required when instantiating UsergridClient') } + + _.defaults(this,options,defaultOptions); + this.clientAppURL = [this.baseUrl, this.orgId, this.appId].join("/"); + this.isSharedInstance = false; + this.currentUser = undefined; + this.appAuth = undefined; + this.userAuth = undefined; + this.authMode = undefined; + if (options.qs) { this.setObject('default_qs', options.qs); } + //other options this.buildCurl = options.buildCurl || false; this.logging = options.logging || false; - - //timeout and callbacks - // this.logoutCallback = options.logoutCallback || null; }; /* @@ -73,8 +76,8 @@ var body = options.body || {}; var qs = options.qs || {}; var mQuery = options.mQuery || false; //is this a query to the management endpoint? - var orgName = this.get('orgName'); - var appName = this.get('appName'); + var orgId = this.get('orgId'); + var appId = this.get('appId'); var default_qs = this.getObject('default_qs'); var uri; /*var logoutCallback=function(){ @@ -82,13 +85,13 @@ return this.logoutCallback(true, 'no_org_or_app_name_specified'); } }.bind(this);*/ - if (!mQuery && !orgName && !appName) { + if (!mQuery && !orgId && !appId) { return logoutCallback(); } if (mQuery) { - uri = this.URI + '/' + endpoint; + uri = this.baseUrl + '/' + endpoint; } else { - uri = this.URI + '/' + orgName + '/' + appName + '/' + endpoint; + uri = this.baseUrl + '/' + orgId + '/' + appId + '/' + endpoint; } if (this.getToken()) { qs.access_token = this.getToken(); @@ -127,7 +130,7 @@ Usergrid.Client.prototype.buildAssetURL = function(uuid) { var self = this; var qs = {}; - var assetURL = this.URI + '/' + this.orgName + '/' + this.appName + '/assets/' + uuid + '/data'; + var assetURL = this.baseUrl + '/' + this.orgId + '/' + this.appId + '/assets/' + uuid + '/data'; if (self.getToken()) { qs.access_token = self.getToken(); diff --git a/lib/modules/util/Logger.js b/lib/modules/util/Logger.js index c3cf579..df61411 100644 --- a/lib/modules/util/Logger.js +++ b/lib/modules/util/Logger.js @@ -54,7 +54,7 @@ }; Logger.prototype.log=function(){ var args=[].slice.call(arguments); - method=args.shift(); + var method=args.shift(); if(Logger.METHODS.indexOf(method)===-1){ method="log"; } diff --git a/lib/modules/util/lodash.core.js b/lib/modules/util/lodash.core.js new file mode 100644 index 0000000..7b24967 --- /dev/null +++ b/lib/modules/util/lodash.core.js @@ -0,0 +1,3839 @@ +/** + * @license + * lodash (Custom Build) + * Build: `lodash core -o ./dist/lodash.core.js` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ +;(function() { + + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + + /** Used as the semantic version number. */ + var VERSION = '4.16.0'; + + /** Used as the `TypeError` message for "Functions" methods. */ + var FUNC_ERROR_TEXT = 'Expected a function'; + + /** Used to compose bitmasks for function metadata. */ + var BIND_FLAG = 1, + PARTIAL_FLAG = 32; + + /** Used to compose bitmasks for comparison styles. */ + var UNORDERED_COMPARE_FLAG = 1, + PARTIAL_COMPARE_FLAG = 2; + + /** Used as references for various `Number` constants. */ + var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991; + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + numberTag = '[object Number]', + objectTag = '[object Object]', + regexpTag = '[object RegExp]', + stringTag = '[object String]'; + + /** Used to match HTML entities and HTML characters. */ + var reUnescapedHtml = /[&<>"'`]/g, + reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + + /** Used to map characters to HTML entities. */ + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }; + + /** Detect free variable `global` from Node.js. */ + var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + + /** Detect free variable `self`. */ + var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + + /** Used as a reference to the global object. */ + var root = freeGlobal || freeSelf || Function('return this')(); + + /** Detect free variable `exports`. */ + var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + + /*--------------------------------------------------------------------------*/ + + /** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + function arrayPush(array, values) { + array.push.apply(array, values); + return array; + } + + /** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.propertyOf` without support for deep paths. + * + * @private + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyOf(object) { + return function(key) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.reduce` and `_.reduceRight`, without support + * for iteratee shorthands, which iterates over `collection` using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} accumulator The initial value. + * @param {boolean} initAccum Specify using the first or last element of + * `collection` as the initial value. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the accumulated value. + */ + function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { + eachFunc(collection, function(value, index, collection) { + accumulator = initAccum + ? (initAccum = false, value) + : iteratee(accumulator, value, index, collection); + }); + return accumulator; + } + + /** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ + function baseValues(object, props) { + return baseMap(props, function(key) { + return object[key]; + }); + } + + /** + * Used by `_.escape` to convert characters to HTML entities. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + var escapeHtmlChar = basePropertyOf(htmlEscapes); + + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + + /*--------------------------------------------------------------------------*/ + + /** Used for built-in method references. */ + var arrayProto = Array.prototype, + objectProto = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** Used to generate unique IDs. */ + var idCounter = 0; + + /** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + var objectToString = objectProto.toString; + + /** Used to restore the original `_` reference in `_.noConflict`. */ + var oldDash = root._; + + /** Built-in value references. */ + var objectCreate = Object.create, + propertyIsEnumerable = objectProto.propertyIsEnumerable; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeIsFinite = root.isFinite, + nativeKeys = overArg(Object.keys, Object), + nativeMax = Math.max; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` object which wraps `value` to enable implicit method + * chain sequences. Methods that operate on and return arrays, collections, + * and functions can be chained together. Methods that retrieve a single value + * or may return a primitive value will automatically end the chain sequence + * and return the unwrapped value. Otherwise, the value must be unwrapped + * with `_#value`. + * + * Explicit chain sequences, which must be unwrapped with `_#value`, may be + * enabled using `_.chain`. + * + * The execution of chained methods is lazy, that is, it's deferred until + * `_#value` is implicitly or explicitly called. + * + * Lazy evaluation allows several methods to support shortcut fusion. + * Shortcut fusion is an optimization to merge iteratee calls; this avoids + * the creation of intermediate arrays and can greatly reduce the number of + * iteratee executions. Sections of a chain sequence qualify for shortcut + * fusion if the section is applied to an array of at least `200` elements + * and any iteratees accept only one argument. The heuristic for whether a + * section qualifies for shortcut fusion is subject to change. + * + * Chaining is supported in custom builds as long as the `_#value` method is + * directly or indirectly included in the build. + * + * In addition to lodash methods, wrappers have `Array` and `String` methods. + * + * The wrapper `Array` methods are: + * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` + * + * The wrapper `String` methods are: + * `replace` and `split` + * + * The wrapper methods that support shortcut fusion are: + * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, + * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, + * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` + * + * The chainable wrapper methods are: + * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, + * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, + * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, + * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, + * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, + * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, + * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, + * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, + * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, + * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, + * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, + * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, + * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, + * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, + * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, + * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, + * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, + * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, + * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, + * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, + * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, + * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, + * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, + * `zipObject`, `zipObjectDeep`, and `zipWith` + * + * The wrapper methods that are **not** chainable by default are: + * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, + * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, + * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, + * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, + * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, + * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, + * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, + * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, + * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, + * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, + * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, + * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, + * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, + * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, + * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, + * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, + * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, + * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, + * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, + * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, + * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, + * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, + * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, + * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, + * `upperFirst`, `value`, and `words` + * + * @name _ + * @constructor + * @category Seq + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2, 3]); + * + * // Returns an unwrapped value. + * wrapped.reduce(_.add); + * // => 6 + * + * // Returns a wrapped value. + * var squares = wrapped.map(square); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true + */ + function lodash(value) { + return value instanceof LodashWrapper + ? value + : new LodashWrapper(value); + } + + /** + * The base constructor for creating `lodash` wrapper objects. + * + * @private + * @param {*} value The value to wrap. + * @param {boolean} [chainAll] Enable explicit method chain sequences. + */ + function LodashWrapper(value, chainAll) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__chain__ = !!chainAll; + } + + LodashWrapper.prototype = baseCreate(lodash.prototype); + LodashWrapper.prototype.constructor = LodashWrapper; + + /*------------------------------------------------------------------------*/ + + /** + * Used by `_.defaults` to customize its `_.assignIn` use. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to assign. + * @param {Object} object The parent object of `objValue`. + * @returns {*} Returns the value to assign. + */ + function assignInDefaults(objValue, srcValue, key, object) { + if (objValue === undefined || + (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { + return srcValue; + } + return objValue; + } + + /** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function baseAssignValue(object, key, value) { + object[key] = value; + } + + /** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} prototype The object to inherit from. + * @returns {Object} Returns the new object. + */ + function baseCreate(proto) { + return isObject(proto) ? objectCreate(proto) : {}; + } + + /** + * The base implementation of `_.delay` and `_.defer` which accepts `args` + * to provide to `func`. + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {Array} args The arguments to provide to `func`. + * @returns {number|Object} Returns the timer id or timeout object. + */ + function baseDelay(func, wait, args) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return setTimeout(function() { func.apply(undefined, args); }, wait); + } + + /** + * The base implementation of `_.forEach` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ + var baseEach = createBaseEach(baseForOwn); + + /** + * The base implementation of `_.every` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false` + */ + function baseEvery(collection, predicate) { + var result = true; + baseEach(collection, function(value, index, collection) { + result = !!predicate(value, index, collection); + return result; + }); + return result; + } + + /** + * The base implementation of methods like `_.max` and `_.min` which accepts a + * `comparator` to determine the extremum value. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The iteratee invoked per iteration. + * @param {Function} comparator The comparator used to compare values. + * @returns {*} Returns the extremum value. + */ + function baseExtremum(array, iteratee, comparator) { + var index = -1, + length = array.length; + + while (++index < length) { + var value = array[index], + current = iteratee(value); + + if (current != null && (computed === undefined + ? (current === current && !false) + : comparator(current, computed) + )) { + var computed = current, + result = value; + } + } + return result; + } + + /** + * The base implementation of `_.filter` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function baseFilter(collection, predicate) { + var result = []; + baseEach(collection, function(value, index, collection) { + if (predicate(value, index, collection)) { + result.push(value); + } + }); + return result; + } + + /** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ + function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; + + predicate || (predicate = isFlattenable); + result || (result = []); + + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; + } + + /** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseFor = createBaseFor(); + + /** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); + } + + /** + * The base implementation of `_.functions` which creates an array of + * `object` function property names filtered from `props`. + * + * @private + * @param {Object} object The object to inspect. + * @param {Array} props The property names to filter. + * @returns {Array} Returns the function names. + */ + function baseFunctions(object, props) { + return baseFilter(props, function(key) { + return isFunction(object[key]); + }); + } + + /** + * The base implementation of `_.gt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + */ + function baseGt(value, other) { + return value > other; + } + + /** + * The base implementation of `_.isDate` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + */ + function baseIsDate(value) { + return isObjectLike(value) && objectToString.call(value) == dateTag; + } + + /** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparisons. + * @param {boolean} [bitmask] The bitmask of comparison flags. + * The bitmask may be composed of the following flags: + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(value, other, customizer, bitmask, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack); + } + + /** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} [customizer] The function to customize comparisons. + * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual` + * for more details. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = arrayTag, + othTag = arrayTag; + + if (!objIsArr) { + objTag = objectToString.call(object); + objTag = objTag == argsTag ? objectTag : objTag; + } + if (!othIsArr) { + othTag = objectToString.call(other); + othTag = othTag == argsTag ? objectTag : othTag; + } + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; + + stack || (stack = []); + var objStack = find(stack, function(entry) { + return entry[0] == object; + }); + var othStack = find(stack, function(entry) { + return entry[0] == other; + }); + if (objStack && othStack) { + return objStack[1] == other; + } + stack.push([object, other]); + stack.push([other, object]); + if (isSameTag && !objIsObj) { + var result = (objIsArr) + ? equalArrays(object, other, equalFunc, customizer, bitmask, stack) + : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack); + stack.pop(); + return result; + } + if (!(bitmask & PARTIAL_COMPARE_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + var result = equalFunc(objUnwrapped, othUnwrapped, customizer, bitmask, stack); + stack.pop(); + return result; + } + } + if (!isSameTag) { + return false; + } + var result = equalObjects(object, other, equalFunc, customizer, bitmask, stack); + stack.pop(); + return result; + } + + /** + * The base implementation of `_.isRegExp` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + */ + function baseIsRegExp(value) { + return isObject(value) && objectToString.call(value) == regexpTag; + } + + /** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ + function baseIteratee(func) { + if (typeof func == 'function') { + return func; + } + if (func == null) { + return identity; + } + return (typeof func == 'object' ? baseMatches : baseProperty)(func); + } + + /** + * The base implementation of `_.lt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + */ + function baseLt(value, other) { + return value < other; + } + + /** + * The base implementation of `_.map` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function baseMap(collection, iteratee) { + var index = -1, + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; + } + + /** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatches(source) { + var props = nativeKeys(source); + return function(object) { + var length = props.length; + if (object == null) { + return !length; + } + object = Object(object); + while (length--) { + var key = props[length]; + if (!(key in object && + baseIsEqual(source[key], object[key], undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG) + )) { + return false; + } + } + return true; + }; + } + + /** + * The base implementation of `_.pick` without support for individual + * property identifiers. + * + * @private + * @param {Object} object The source object. + * @param {string[]} props The property identifiers to pick. + * @returns {Object} Returns the new object. + */ + function basePick(object, props) { + object = Object(object); + return reduce(props, function(result, key) { + if (key in object) { + result[key] = object[key]; + } + return result; + }, {}); + } + + /** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ + function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); + } + + /** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; + } + + /** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ + function copyArray(source) { + return baseSlice(source, 0, source.length); + } + + /** + * The base implementation of `_.some` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function baseSome(collection, predicate) { + var result; + + baseEach(collection, function(value, index, collection) { + result = predicate(value, index, collection); + return !result; + }); + return !!result; + } + + /** + * The base implementation of `wrapperValue` which returns the result of + * performing a sequence of actions on the unwrapped `value`, where each + * successive action is supplied the return value of the previous. + * + * @private + * @param {*} value The unwrapped value. + * @param {Array} actions Actions to perform to resolve the unwrapped value. + * @returns {*} Returns the resolved value. + */ + function baseWrapperValue(value, actions) { + var result = value; + return reduce(actions, function(result, action) { + return action.func.apply(action.thisArg, arrayPush([result], action.args)); + }, result); + } + + /** + * Compares values to sort them in ascending order. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. + */ + function compareAscending(value, other) { + if (value !== other) { + var valIsDefined = value !== undefined, + valIsNull = value === null, + valIsReflexive = value === value, + valIsSymbol = false; + + var othIsDefined = other !== undefined, + othIsNull = other === null, + othIsReflexive = other === other, + othIsSymbol = false; + + if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || + (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || + (valIsNull && othIsDefined && othIsReflexive) || + (!valIsDefined && othIsReflexive) || + !valIsReflexive) { + return 1; + } + if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || + (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || + (othIsNull && valIsDefined && valIsReflexive) || + (!othIsDefined && valIsReflexive) || + !othIsReflexive) { + return -1; + } + } + return 0; + } + + /** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ + function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; + } + + /** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ + function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); + } + + /** + * Creates a `baseEach` or `baseEachRight` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee) { + if (collection == null) { + return collection; + } + if (!isArrayLike(collection)) { + return eachFunc(collection, iteratee); + } + var length = collection.length, + index = fromRight ? length : -1, + iterable = Object(collection); + + while ((fromRight ? index-- : ++index < length)) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; + } + + /** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } + + /** + * Creates a function that produces an instance of `Ctor` regardless of + * whether it was invoked as part of a `new` expression or by `call` or `apply`. + * + * @private + * @param {Function} Ctor The constructor to wrap. + * @returns {Function} Returns the new wrapped function. + */ + function createCtor(Ctor) { + return function() { + // Use a `switch` statement to work with class constructors. See + // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist + // for more details. + var args = arguments; + var thisBinding = baseCreate(Ctor.prototype), + result = Ctor.apply(thisBinding, args); + + // Mimic the constructor's `return` behavior. + // See https://es5.github.io/#x13.2.2 for more details. + return isObject(result) ? result : thisBinding; + }; + } + + /** + * Creates a `_.find` or `_.findLast` function. + * + * @private + * @param {Function} findIndexFunc The function to find the collection index. + * @returns {Function} Returns the new find function. + */ + function createFind(findIndexFunc) { + return function(collection, predicate, fromIndex) { + var iterable = Object(collection); + if (!isArrayLike(collection)) { + var iteratee = baseIteratee(predicate, 3); + collection = keys(collection); + predicate = function(key) { return iteratee(iterable[key], key, iterable); }; + } + var index = findIndexFunc(collection, predicate, fromIndex); + return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; + }; + } + + /** + * Creates a function that wraps `func` to invoke it with the `this` binding + * of `thisArg` and `partials` prepended to the arguments it receives. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} partials The arguments to prepend to those provided to + * the new function. + * @returns {Function} Returns the new wrapped function. + */ + function createPartial(func, bitmask, thisArg, partials) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + var isBind = bitmask & BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var argsIndex = -1, + argsLength = arguments.length, + leftIndex = -1, + leftLength = partials.length, + args = Array(leftLength + argsLength), + fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + + while (++leftIndex < leftLength) { + args[leftIndex] = partials[leftIndex]; + } + while (argsLength--) { + args[leftIndex++] = arguments[++argsIndex]; + } + return fn.apply(isBind ? thisArg : this, args); + } + return wrapper; + } + + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} customizer The function to customize comparisons. + * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` + * for more details. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + function equalArrays(array, other, equalFunc, customizer, bitmask, stack) { + var isPartial = bitmask & PARTIAL_COMPARE_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + var index = -1, + result = true, + seen = (bitmask & UNORDERED_COMPARE_FLAG) ? [] : undefined; + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + var compared; + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!baseSome(other, function(othValue, othIndex) { + if (!indexOf(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, customizer, bitmask, stack) + )) { + result = false; + break; + } + } + return result; + } + + /** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} customizer The function to customize comparisons. + * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` + * for more details. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) { + switch (tag) { + + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + } + return false; + } + + /** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} customizer The function to customize comparisons. + * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` + * for more details. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalObjects(object, other, equalFunc, customizer, bitmask, stack) { + var isPartial = bitmask & PARTIAL_COMPARE_FLAG, + objProps = keys(object), + objLength = objProps.length, + othProps = keys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + var result = true; + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + var compared; + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + return result; + } + + /** + * A specialized version of `baseRest` which flattens the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ + function flatRest(func) { + return setToString(overRest(func, undefined, flatten), func + ''); + } + + /** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ + function isFlattenable(value) { + return isArray(value) || isArguments(value); + } + + /** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; + } + + /** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ + function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return func.apply(this, otherArgs); + }; + } + + /** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var setToString = identity; + + /** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ + var toKey = String; + + /*------------------------------------------------------------------------*/ + + /** + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are falsey. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to compact. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] + */ + function compact(array) { + return baseFilter(array, Boolean); + } + + /** + * Creates a new array concatenating `array` with any additional arrays + * and/or values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to concatenate. + * @param {...*} [values] The values to concatenate. + * @returns {Array} Returns the new concatenated array. + * @example + * + * var array = [1]; + * var other = _.concat(array, 2, [3], [[4]]); + * + * console.log(other); + * // => [1, 2, 3, [4]] + * + * console.log(array); + * // => [1] + */ + function concat() { + var length = arguments.length; + if (!length) { + return []; + } + var args = Array(length - 1), + array = arguments[0], + index = length; + + while (index--) { + args[index - 1] = arguments[index]; + } + return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); + } + + /** + * This method is like `_.find` except that it returns the index of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] + * The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.findIndex(users, function(o) { return o.user == 'barney'; }); + * // => 0 + * + * // The `_.matches` iteratee shorthand. + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findIndex(users, ['active', false]); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.findIndex(users, 'active'); + * // => 2 + */ + function findIndex(array, predicate, fromIndex) { + var length = array ? array.length : 0; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseFindIndex(array, baseIteratee(predicate, 3), index); + } + + /** + * Flattens `array` a single level deep. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */ + function flatten(array) { + var length = array ? array.length : 0; + return length ? baseFlatten(array, 1) : []; + } + + /** + * Recursively flattens `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flattenDeep([1, [2, [3, [4]], 5]]); + * // => [1, 2, 3, 4, 5] + */ + function flattenDeep(array) { + var length = array ? array.length : 0; + return length ? baseFlatten(array, INFINITY) : []; + } + + /** + * Gets the first element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias first + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the first element of `array`. + * @example + * + * _.head([1, 2, 3]); + * // => 1 + * + * _.head([]); + * // => undefined + */ + function head(array) { + return (array && array.length) ? array[0] : undefined; + } + + /** + * Gets the index at which the first occurrence of `value` is found in `array` + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it's used as the + * offset from the end of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.indexOf([1, 2, 1, 2], 2); + * // => 1 + * + * // Search from the `fromIndex`. + * _.indexOf([1, 2, 1, 2], 2, 2); + * // => 3 + */ + function indexOf(array, value, fromIndex) { + var length = array ? array.length : 0; + if (typeof fromIndex == 'number') { + fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex; + } else { + fromIndex = 0; + } + var index = (fromIndex || 0) - 1, + isReflexive = value === value; + + while (++index < length) { + var other = array[index]; + if ((isReflexive ? other === value : other !== other)) { + return index; + } + } + return -1; + } + + /** + * Gets the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + */ + function last(array) { + var length = array ? array.length : 0; + return length ? array[length - 1] : undefined; + } + + /** + * Creates a slice of `array` from `start` up to, but not including, `end`. + * + * **Note:** This method is used instead of + * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are + * returned. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function slice(array, start, end) { + var length = array ? array.length : 0; + start = start == null ? 0 : +start; + end = end === undefined ? length : +end; + return length ? baseSlice(array, start, end) : []; + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` wrapper instance that wraps `value` with explicit method + * chain sequences enabled. The result of such sequences must be unwrapped + * with `_#value`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Seq + * @param {*} value The value to wrap. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'pebbles', 'age': 1 } + * ]; + * + * var youngest = _ + * .chain(users) + * .sortBy('age') + * .map(function(o) { + * return o.user + ' is ' + o.age; + * }) + * .head() + * .value(); + * // => 'pebbles is 1' + */ + function chain(value) { + var result = lodash(value); + result.__chain__ = true; + return result; + } + + /** + * This method invokes `interceptor` and returns `value`. The interceptor + * is invoked with one argument; (value). The purpose of this method is to + * "tap into" a method chain sequence in order to modify intermediate results. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns `value`. + * @example + * + * _([1, 2, 3]) + * .tap(function(array) { + * // Mutate input array. + * array.pop(); + * }) + * .reverse() + * .value(); + * // => [2, 1] + */ + function tap(value, interceptor) { + interceptor(value); + return value; + } + + /** + * This method is like `_.tap` except that it returns the result of `interceptor`. + * The purpose of this method is to "pass thru" values replacing intermediate + * results in a method chain sequence. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns the result of `interceptor`. + * @example + * + * _(' abc ') + * .chain() + * .trim() + * .thru(function(value) { + * return [value]; + * }) + * .value(); + * // => ['abc'] + */ + function thru(value, interceptor) { + return interceptor(value); + } + + /** + * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. + * + * @name chain + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * // A sequence without explicit chaining. + * _(users).head(); + * // => { 'user': 'barney', 'age': 36 } + * + * // A sequence with explicit chaining. + * _(users) + * .chain() + * .head() + * .pick('user') + * .value(); + * // => { 'user': 'barney' } + */ + function wrapperChain() { + return chain(this); + } + + /** + * Executes the chain sequence to resolve the unwrapped value. + * + * @name value + * @memberOf _ + * @since 0.1.0 + * @alias toJSON, valueOf + * @category Seq + * @returns {*} Returns the resolved unwrapped value. + * @example + * + * _([1, 2, 3]).value(); + * // => [1, 2, 3] + */ + function wrapperValue() { + return baseWrapperValue(this.__wrapped__, this.__actions__); + } + + /*------------------------------------------------------------------------*/ + + /** + * Checks if `predicate` returns truthy for **all** elements of `collection`. + * Iteration is stopped once `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * **Note:** This method returns `true` for + * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because + * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of + * elements of empty collections. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] + * The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes'], Boolean); + * // => false + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.every(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.every(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.every(users, 'active'); + * // => false + */ + function every(collection, predicate, guard) { + predicate = guard ? undefined : predicate; + return baseEvery(collection, baseIteratee(predicate)); + } + + /** + * Iterates over elements of `collection`, returning an array of all elements + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * **Note:** Unlike `_.remove`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] + * The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.reject + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * _.filter(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.filter(users, { 'age': 36, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.filter(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.filter(users, 'active'); + * // => objects for ['barney'] + */ + function filter(collection, predicate) { + return baseFilter(collection, baseIteratee(predicate)); + } + + /** + * Iterates over elements of `collection`, returning the first element + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] + * The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } + * ]; + * + * _.find(users, function(o) { return o.age < 40; }); + * // => object for 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.find(users, { 'age': 1, 'active': true }); + * // => object for 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.find(users, ['active', false]); + * // => object for 'fred' + * + * // The `_.property` iteratee shorthand. + * _.find(users, 'active'); + * // => object for 'barney' + */ + var find = createFind(findIndex); + + /** + * Iterates over elements of `collection` and invokes `iteratee` for each element. + * The iteratee is invoked with three arguments: (value, index|key, collection). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * **Note:** As with other "Collections" methods, objects with a "length" + * property are iterated like arrays. To avoid this behavior use `_.forIn` + * or `_.forOwn` for object iteration. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias each + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEachRight + * @example + * + * _.forEach([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `1` then `2`. + * + * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ + function forEach(collection, iteratee) { + return baseEach(collection, baseIteratee(iteratee)); + } + + /** + * Creates an array of values by running each element in `collection` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. + * + * The guarded methods are: + * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, + * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, + * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, + * `template`, `trim`, `trimEnd`, `trimStart`, and `words` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + * @example + * + * function square(n) { + * return n * n; + * } + * + * _.map([4, 8], square); + * // => [16, 64] + * + * _.map({ 'a': 4, 'b': 8 }, square); + * // => [16, 64] (iteration order is not guaranteed) + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * // The `_.property` iteratee shorthand. + * _.map(users, 'user'); + * // => ['barney', 'fred'] + */ + function map(collection, iteratee) { + return baseMap(collection, baseIteratee(iteratee)); + } + + /** + * Reduces `collection` to a value which is the accumulated result of running + * each element in `collection` thru `iteratee`, where each successive + * invocation is supplied the return value of the previous. If `accumulator` + * is not given, the first element of `collection` is used as the initial + * value. The iteratee is invoked with four arguments: + * (accumulator, value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.reduce`, `_.reduceRight`, and `_.transform`. + * + * The guarded methods are: + * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, + * and `sortBy` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduceRight + * @example + * + * _.reduce([1, 2], function(sum, n) { + * return sum + n; + * }, 0); + * // => 3 + * + * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * return result; + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) + */ + function reduce(collection, iteratee, accumulator) { + return baseReduce(collection, baseIteratee(iteratee), accumulator, arguments.length < 3, baseEach); + } + + /** + * Gets the size of `collection` by returning its length for array-like + * values or the number of own enumerable string keyed properties for objects. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns the collection size. + * @example + * + * _.size([1, 2, 3]); + * // => 3 + * + * _.size({ 'a': 1, 'b': 2 }); + * // => 2 + * + * _.size('pebbles'); + * // => 7 + */ + function size(collection) { + if (collection == null) { + return 0; + } + collection = isArrayLike(collection) ? collection : nativeKeys(collection); + return collection.length; + } + + /** + * Checks if `predicate` returns truthy for **any** element of `collection`. + * Iteration is stopped once `predicate` returns truthy. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + * @example + * + * _.some([null, 0, 'yes', false], Boolean); + * // => true + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.some(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.some(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.some(users, 'active'); + * // => true + */ + function some(collection, predicate, guard) { + predicate = guard ? undefined : predicate; + return baseSome(collection, baseIteratee(predicate)); + } + + /** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection thru each iteratee. This method + * performs a stable sort, that is, it preserves the original sort order of + * equal elements. The iteratees are invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {...(Function|Function[])} [iteratees=[_.identity]] + * The iteratees to sort by. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 34 } + * ]; + * + * _.sortBy(users, [function(o) { return o.user; }]); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + * + * _.sortBy(users, ['user', 'age']); + * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] + */ + function sortBy(collection, iteratee) { + var index = 0; + iteratee = baseIteratee(iteratee); + + return baseMap(baseMap(collection, function(value, key, collection) { + return { 'value': value, 'index': index++, 'criteria': iteratee(value, key, collection) }; + }).sort(function(object, other) { + return compareAscending(object.criteria, other.criteria) || (object.index - other.index); + }), baseProperty('value')); + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it's called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * jQuery(element).on('click', _.before(5, addContactToList)); + * // => Allows adding up to 4 contacts to the list. + */ + function before(n, func) { + var result; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } + if (n <= 1) { + func = undefined; + } + return result; + }; + } + + /** + * Creates a function that invokes `func` with the `this` binding of `thisArg` + * and `partials` prepended to the arguments it receives. + * + * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for partially applied arguments. + * + * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" + * property of bound functions. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * function greet(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * + * var object = { 'user': 'fred' }; + * + * var bound = _.bind(greet, object, 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * // Bound with placeholders. + * var bound = _.bind(greet, object, _, '!'); + * bound('hi'); + * // => 'hi fred!' + */ + var bind = baseRest(function(func, thisArg, partials) { + return createPartial(func, BIND_FLAG | PARTIAL_FLAG, thisArg, partials); + }); + + /** + * Defers invoking the `func` until the current call stack has cleared. Any + * additional arguments are provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to defer. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.defer(function(text) { + * console.log(text); + * }, 'deferred'); + * // => Logs 'deferred' after one millisecond. + */ + var defer = baseRest(function(func, args) { + return baseDelay(func, 1, args); + }); + + /** + * Invokes `func` after `wait` milliseconds. Any additional arguments are + * provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.delay(function(text) { + * console.log(text); + * }, 1000, 'later'); + * // => Logs 'later' after one second. + */ + var delay = baseRest(function(func, wait, args) { + return baseDelay(func, toNumber(wait) || 0, args); + }); + + /** + * Creates a function that negates the result of the predicate `func`. The + * `func` predicate is invoked with the `this` binding and arguments of the + * created function. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} predicate The predicate to negate. + * @returns {Function} Returns the new negated function. + * @example + * + * function isEven(n) { + * return n % 2 == 0; + * } + * + * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); + * // => [1, 3, 5] + */ + function negate(predicate) { + if (typeof predicate != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return function() { + var args = arguments; + return !predicate.apply(this, args); + }; + } + + /** + * Creates a function that is restricted to invoking `func` once. Repeat calls + * to the function return the value of the first invocation. The `func` is + * invoked with the `this` binding and arguments of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // => `createApplication` is invoked once + */ + function once(func) { + return before(2, func); + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates a shallow clone of `value`. + * + * **Note:** This method is loosely based on the + * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) + * and supports cloning arrays, array buffers, booleans, date objects, maps, + * numbers, `Object` objects, regexes, sets, strings, symbols, and typed + * arrays. The own enumerable properties of `arguments` objects are cloned + * as plain objects. An empty object is returned for uncloneable values such + * as error objects, functions, DOM nodes, and WeakMaps. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to clone. + * @returns {*} Returns the cloned value. + * @see _.cloneDeep + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var shallow = _.clone(objects); + * console.log(shallow[0] === objects[0]); + * // => true + */ + function clone(value) { + if (!isObject(value)) { + return value; + } + return isArray(value) ? copyArray(value) : copyObject(value, nativeKeys(value)); + } + + /** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ + function eq(value, other) { + return value === other || (value !== value && other !== other); + } + + /** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); + } + + /** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ + var isArray = Array.isArray; + + /** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); + } + + /** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ + function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); + } + + /** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ + function isBoolean(value) { + return value === true || value === false || + (isObjectLike(value) && objectToString.call(value) == boolTag); + } + + /** + * Checks if `value` is classified as a `Date` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + * @example + * + * _.isDate(new Date); + * // => true + * + * _.isDate('Mon April 23 2012'); + * // => false + */ + var isDate = baseIsDate; + + /** + * Checks if `value` is an empty object, collection, map, or set. + * + * Objects are considered empty if they have no own enumerable string keyed + * properties. + * + * Array-like values such as `arguments` objects, arrays, buffers, strings, or + * jQuery-like collections are considered empty if they have a `length` of `0`. + * Similarly, maps and sets are considered empty if they have a `size` of `0`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is empty, else `false`. + * @example + * + * _.isEmpty(null); + * // => true + * + * _.isEmpty(true); + * // => true + * + * _.isEmpty(1); + * // => true + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({ 'a': 1 }); + * // => false + */ + function isEmpty(value) { + if (isArrayLike(value) && + (isArray(value) || isString(value) || + isFunction(value.splice) || isArguments(value))) { + return !value.length; + } + return !nativeKeys(value).length; + } + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are **not** supported. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ + function isEqual(value, other) { + return baseIsEqual(value, other); + } + + /** + * Checks if `value` is a finite primitive number. + * + * **Note:** This method is based on + * [`Number.isFinite`](https://mdn.io/Number/isFinite). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. + * @example + * + * _.isFinite(3); + * // => true + * + * _.isFinite(Number.MIN_VALUE); + * // => true + * + * _.isFinite(Infinity); + * // => false + * + * _.isFinite('3'); + * // => false + */ + function isFinite(value) { + return typeof value == 'number' && nativeIsFinite(value); + } + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; + } + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); + } + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return value != null && typeof value == 'object'; + } + + /** + * Checks if `value` is `NaN`. + * + * **Note:** This method is based on + * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as + * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for + * `undefined` and other non-number values. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ + function isNaN(value) { + // An `NaN` primitive is the only value that is not equal to itself. + // Perform the `toStringTag` check first to avoid errors with some + // ActiveX objects in IE. + return isNumber(value) && value != +value; + } + + /** + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(void 0); + * // => false + */ + function isNull(value) { + return value === null; + } + + /** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are + * classified as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a number, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ + function isNumber(value) { + return typeof value == 'number' || + (isObjectLike(value) && objectToString.call(value) == numberTag); + } + + /** + * Checks if `value` is classified as a `RegExp` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + * @example + * + * _.isRegExp(/abc/); + * // => true + * + * _.isRegExp('/abc/'); + * // => false + */ + var isRegExp = baseIsRegExp; + + /** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ + function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); + } + + /** + * Checks if `value` is `undefined`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + * + * _.isUndefined(null); + * // => false + */ + function isUndefined(value) { + return value === undefined; + } + + /** + * Converts `value` to an array. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to convert. + * @returns {Array} Returns the converted array. + * @example + * + * _.toArray({ 'a': 1, 'b': 2 }); + * // => [1, 2] + * + * _.toArray('abc'); + * // => ['a', 'b', 'c'] + * + * _.toArray(1); + * // => [] + * + * _.toArray(null); + * // => [] + */ + function toArray(value) { + if (!isArrayLike(value)) { + return values(value); + } + return value.length ? copyArray(value) : []; + } + + /** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ + var toInteger = Number; + + /** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ + var toNumber = Number; + + /** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {string} Returns the string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ + function toString(value) { + if (typeof value == 'string') { + return value; + } + return value == null ? '' : (value + ''); + } + + /*------------------------------------------------------------------------*/ + + /** + * Assigns own enumerable string keyed properties of source objects to the + * destination object. Source objects are applied from left to right. + * Subsequent sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object` and is loosely based on + * [`Object.assign`](https://mdn.io/Object/assign). + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assignIn + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assign({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'c': 3 } + */ + var assign = createAssigner(function(object, source) { + copyObject(source, nativeKeys(source), object); + }); + + /** + * This method is like `_.assign` except that it iterates over own and + * inherited source properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extend + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assign + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assignIn({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } + */ + var assignIn = createAssigner(function(object, source) { + copyObject(source, nativeKeysIn(source), object); + }); + + /** + * This method is like `_.assignIn` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extendWith + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignInWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keysIn(source), object, customizer); + }); + + /** + * Creates an object that inherits from the `prototype` object. If a + * `properties` object is given, its own enumerable string keyed properties + * are assigned to the created object. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Object + * @param {Object} prototype The object to inherit from. + * @param {Object} [properties] The properties to assign to the object. + * @returns {Object} Returns the new object. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * function Circle() { + * Shape.call(this); + * } + * + * Circle.prototype = _.create(Shape.prototype, { + * 'constructor': Circle + * }); + * + * var circle = new Circle; + * circle instanceof Circle; + * // => true + * + * circle instanceof Shape; + * // => true + */ + function create(prototype, properties) { + var result = baseCreate(prototype); + return properties ? assign(result, properties) : result; + } + + /** + * Assigns own and inherited enumerable string keyed properties of source + * objects to the destination object for all destination properties that + * resolve to `undefined`. Source objects are applied from left to right. + * Once a property is set, additional values of the same property are ignored. + * + * **Note:** This method mutates `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaultsDeep + * @example + * + * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var defaults = baseRest(function(args) { + args.push(undefined, assignInDefaults); + return assignInWith.apply(undefined, args); + }); + + /** + * Checks if `path` is a direct property of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = { 'a': { 'b': 2 } }; + * var other = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.has(object, 'a'); + * // => true + * + * _.has(object, 'a.b'); + * // => true + * + * _.has(object, ['a', 'b']); + * // => true + * + * _.has(other, 'a'); + * // => false + */ + function has(object, path) { + return object != null && hasOwnProperty.call(object, path); + } + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + var keys = nativeKeys; + + /** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ + var keysIn = nativeKeysIn; + + /** + * Creates an object composed of the picked `object` properties. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [props] The property identifiers to pick. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pick(object, ['a', 'c']); + * // => { 'a': 1, 'c': 3 } + */ + var pick = flatRest(function(object, props) { + return object == null ? {} : basePick(object, baseMap(props, toKey)); + }); + + /** + * This method is like `_.get` except that if the resolved value is a + * function it's invoked with the `this` binding of its parent object and + * its result is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to resolve. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; + * + * _.result(object, 'a[0].b.c1'); + * // => 3 + * + * _.result(object, 'a[0].b.c2'); + * // => 4 + * + * _.result(object, 'a[0].b.c3', 'default'); + * // => 'default' + * + * _.result(object, 'a[0].b.c3', _.constant('default')); + * // => 'default' + */ + function result(object, path, defaultValue) { + var value = object == null ? undefined : object[path]; + if (value === undefined) { + value = defaultValue; + } + return isFunction(value) ? value.call(object) : value; + } + + /** + * Creates an array of the own enumerable string keyed property values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.values(new Foo); + * // => [1, 2] (iteration order is not guaranteed) + * + * _.values('hi'); + * // => ['h', 'i'] + */ + function values(object) { + return object ? baseValues(object, keys(object)) : []; + } + + /*------------------------------------------------------------------------*/ + + /** + * Converts the characters "&", "<", ">", '"', and "'" in `string` to their + * corresponding HTML entities. + * + * **Note:** No other characters are escaped. To escape additional + * characters use a third-party library like [_he_](https://mths.be/he). + * + * Though the ">" character is escaped for symmetry, characters like + * ">" and "/" don't need escaping in HTML and have no special meaning + * unless they're part of a tag or unquoted attribute value. See + * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) + * (under "semi-related fun fact") for more details. + * + * When working with HTML you should always + * [quote attribute values](http://wonko.com/post/html-escaping) to reduce + * XSS vectors. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escape('fred, barney, & pebbles'); + * // => 'fred, barney, & pebbles' + */ + function escape(string) { + string = toString(string); + return (string && reHasUnescapedHtml.test(string)) + ? string.replace(reUnescapedHtml, escapeHtmlChar) + : string; + } + + /*------------------------------------------------------------------------*/ + + /** + * This method returns the first argument it receives. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'a': 1 }; + * + * console.log(_.identity(object) === object); + * // => true + */ + function identity(value) { + return value; + } + + /** + * Creates a function that invokes `func` with the arguments of the created + * function. If `func` is a property name, the created function returns the + * property value for a given element. If `func` is an array or object, the + * created function returns `true` for elements that contain the equivalent + * source properties, otherwise it returns `false`. + * + * @static + * @since 4.0.0 + * @memberOf _ + * @category Util + * @param {*} [func=_.identity] The value to convert to a callback. + * @returns {Function} Returns the callback. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true })); + * // => [{ 'user': 'barney', 'age': 36, 'active': true }] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.filter(users, _.iteratee(['user', 'fred'])); + * // => [{ 'user': 'fred', 'age': 40 }] + * + * // The `_.property` iteratee shorthand. + * _.map(users, _.iteratee('user')); + * // => ['barney', 'fred'] + * + * // Create custom iteratee shorthands. + * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) { + * return !_.isRegExp(func) ? iteratee(func) : function(string) { + * return func.test(string); + * }; + * }); + * + * _.filter(['abc', 'def'], /ef/); + * // => ['def'] + */ + var iteratee = baseIteratee; + + /** + * Creates a function that performs a partial deep comparison between a given + * object and `source`, returning `true` if the given object has equivalent + * property values, else `false`. + * + * **Note:** The created function is equivalent to `_.isMatch` with `source` + * partially applied. + * + * Partial comparisons will match empty array and empty object `source` + * values against any array or object value, respectively. See `_.isEqual` + * for a list of supported value comparisons. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Util + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + * @example + * + * var objects = [ + * { 'a': 1, 'b': 2, 'c': 3 }, + * { 'a': 4, 'b': 5, 'c': 6 } + * ]; + * + * _.filter(objects, _.matches({ 'a': 4, 'c': 6 })); + * // => [{ 'a': 4, 'b': 5, 'c': 6 }] + */ + function matches(source) { + return baseMatches(assign({}, source)); + } + + /** + * Adds all own enumerable string keyed function properties of a source + * object to the destination object. If `object` is a function, then methods + * are added to its prototype as well. + * + * **Note:** Use `_.runInContext` to create a pristine `lodash` function to + * avoid conflicts caused by modifying the original. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {Function|Object} [object=lodash] The destination object. + * @param {Object} source The object of functions to add. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.chain=true] Specify whether mixins are chainable. + * @returns {Function|Object} Returns `object`. + * @example + * + * function vowels(string) { + * return _.filter(string, function(v) { + * return /[aeiou]/i.test(v); + * }); + * } + * + * _.mixin({ 'vowels': vowels }); + * _.vowels('fred'); + * // => ['e'] + * + * _('fred').vowels().value(); + * // => ['e'] + * + * _.mixin({ 'vowels': vowels }, { 'chain': false }); + * _('fred').vowels(); + * // => ['e'] + */ + function mixin(object, source, options) { + var props = keys(source), + methodNames = baseFunctions(source, props); + + if (options == null && + !(isObject(source) && (methodNames.length || !props.length))) { + options = source; + source = object; + object = this; + methodNames = baseFunctions(source, keys(source)); + } + var chain = !(isObject(options) && 'chain' in options) || !!options.chain, + isFunc = isFunction(object); + + baseEach(methodNames, function(methodName) { + var func = source[methodName]; + object[methodName] = func; + if (isFunc) { + object.prototype[methodName] = function() { + var chainAll = this.__chain__; + if (chain || chainAll) { + var result = object(this.__wrapped__), + actions = result.__actions__ = copyArray(this.__actions__); + + actions.push({ 'func': func, 'args': arguments, 'thisArg': object }); + result.__chain__ = chainAll; + return result; + } + return func.apply(object, arrayPush([this.value()], arguments)); + }; + } + }); + + return object; + } + + /** + * Reverts the `_` variable to its previous value and returns a reference to + * the `lodash` function. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @returns {Function} Returns the `lodash` function. + * @example + * + * var lodash = _.noConflict(); + */ + function noConflict() { + if (root._ === this) { + root._ = oldDash; + } + return this; + } + + /** + * This method returns `undefined`. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Util + * @example + * + * _.times(2, _.noop); + * // => [undefined, undefined] + */ + function noop() { + // No operation performed. + } + + /** + * Generates a unique ID. If `prefix` is given, the ID is appended to it. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {string} [prefix=''] The value to prefix the ID with. + * @returns {string} Returns the unique ID. + * @example + * + * _.uniqueId('contact_'); + * // => 'contact_104' + * + * _.uniqueId(); + * // => '105' + */ + function uniqueId(prefix) { + var id = ++idCounter; + return toString(prefix) + id; + } + + /*------------------------------------------------------------------------*/ + + /** + * Computes the maximum value of `array`. If `array` is empty or falsey, + * `undefined` is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Math + * @param {Array} array The array to iterate over. + * @returns {*} Returns the maximum value. + * @example + * + * _.max([4, 2, 8, 6]); + * // => 8 + * + * _.max([]); + * // => undefined + */ + function max(array) { + return (array && array.length) + ? baseExtremum(array, identity, baseGt) + : undefined; + } + + /** + * Computes the minimum value of `array`. If `array` is empty or falsey, + * `undefined` is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Math + * @param {Array} array The array to iterate over. + * @returns {*} Returns the minimum value. + * @example + * + * _.min([4, 2, 8, 6]); + * // => 2 + * + * _.min([]); + * // => undefined + */ + function min(array) { + return (array && array.length) + ? baseExtremum(array, identity, baseLt) + : undefined; + } + + /*------------------------------------------------------------------------*/ + + // Add methods that return wrapped values in chain sequences. + lodash.assignIn = assignIn; + lodash.before = before; + lodash.bind = bind; + lodash.chain = chain; + lodash.compact = compact; + lodash.concat = concat; + lodash.create = create; + lodash.defaults = defaults; + lodash.defer = defer; + lodash.delay = delay; + lodash.filter = filter; + lodash.flatten = flatten; + lodash.flattenDeep = flattenDeep; + lodash.iteratee = iteratee; + lodash.keys = keys; + lodash.map = map; + lodash.matches = matches; + lodash.mixin = mixin; + lodash.negate = negate; + lodash.once = once; + lodash.pick = pick; + lodash.slice = slice; + lodash.sortBy = sortBy; + lodash.tap = tap; + lodash.thru = thru; + lodash.toArray = toArray; + lodash.values = values; + + // Add aliases. + lodash.extend = assignIn; + + // Add methods to `lodash.prototype`. + mixin(lodash, lodash); + + /*------------------------------------------------------------------------*/ + + // Add methods that return unwrapped values in chain sequences. + lodash.clone = clone; + lodash.escape = escape; + lodash.every = every; + lodash.find = find; + lodash.forEach = forEach; + lodash.has = has; + lodash.head = head; + lodash.identity = identity; + lodash.indexOf = indexOf; + lodash.isArguments = isArguments; + lodash.isArray = isArray; + lodash.isBoolean = isBoolean; + lodash.isDate = isDate; + lodash.isEmpty = isEmpty; + lodash.isEqual = isEqual; + lodash.isFinite = isFinite; + lodash.isFunction = isFunction; + lodash.isNaN = isNaN; + lodash.isNull = isNull; + lodash.isNumber = isNumber; + lodash.isObject = isObject; + lodash.isRegExp = isRegExp; + lodash.isString = isString; + lodash.isUndefined = isUndefined; + lodash.last = last; + lodash.max = max; + lodash.min = min; + lodash.noConflict = noConflict; + lodash.noop = noop; + lodash.reduce = reduce; + lodash.result = result; + lodash.size = size; + lodash.some = some; + lodash.uniqueId = uniqueId; + + // Add aliases. + lodash.each = forEach; + lodash.first = head; + + mixin(lodash, (function() { + var source = {}; + baseForOwn(lodash, function(func, methodName) { + if (!hasOwnProperty.call(lodash.prototype, methodName)) { + source[methodName] = func; + } + }); + return source; + }()), { 'chain': false }); + + /*------------------------------------------------------------------------*/ + + /** + * The semantic version number. + * + * @static + * @memberOf _ + * @type {string} + */ + lodash.VERSION = VERSION; + + // Add `Array` methods to `lodash.prototype`. + baseEach(['pop', 'join', 'replace', 'reverse', 'split', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) { + var func = (/^(?:replace|split)$/.test(methodName) ? String.prototype : arrayProto)[methodName], + chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru', + retUnwrapped = /^(?:pop|join|replace|shift)$/.test(methodName); + + lodash.prototype[methodName] = function() { + var args = arguments; + if (retUnwrapped && !this.__chain__) { + var value = this.value(); + return func.apply(isArray(value) ? value : [], args); + } + return this[chainName](function(value) { + return func.apply(isArray(value) ? value : [], args); + }); + }; + }); + + // Add chain sequence methods to the `lodash` wrapper. + lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue; + + /*--------------------------------------------------------------------------*/ + + // Some AMD build optimizers, like r.js, check for condition patterns like: + if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + // Expose Lodash on the global object to prevent errors when Lodash is + // loaded by a script tag in the presence of an AMD loader. + // See http://requirejs.org/docs/errors.html#mismatch for more details. + // Use `_.noConflict` to remove Lodash from the global object. + root._ = lodash; + + // Define as an anonymous module so, through path mapping, it can be + // referenced as the "underscore" module. + define(function() { + return lodash; + }); + } + // Check for `exports` after `define` in case a build optimizer adds it. + else if (freeModule) { + // Export for Node.js. + (freeModule.exports = lodash)._ = lodash; + // Export for CommonJS support. + freeExports._ = lodash; + } + else { + // Export to the global object. + root._ = lodash; + } +}.call(this)); diff --git a/tests/mocha/test.js b/tests/mocha/test.js index ef4ff54..fbe1e67 100644 --- a/tests/mocha/test.js +++ b/tests/mocha/test.js @@ -21,8 +21,8 @@ */ function getClient() { return new Usergrid.Client({ - orgName: 'yourorgname', - appName: 'sandbox', + orgId: 'rwalsh', + appId: 'sandbox', logging: false, //optional - turn on logging, off by default buildCurl: true //optional - turn on curl commands, off by default }); @@ -47,10 +47,12 @@ function usergridTestHarness(err, data, done, tests, ignoreError) { done(); } describe('Ajax', function() { + var client = getClient(); var dogName="dog"+Math.floor(Math.random()*10000); var dogData=JSON.stringify({type:"dog",name:dogName}); - var dogURI='https://api.usergrid.com/yourorgname/sandbox/dogs' - it('should POST to a URI',function(done){ + var dogURI=client.clientAppURL + '/dogs'; + + it('should POST to a URI ' + client.clientAppURL,function(done){ Ajax.post(dogURI, dogData).then(function(err, data){ assert(!err, err); done(); @@ -100,9 +102,10 @@ describe('Usergrid', function(){ }); }); describe('Usergrid Request/Response', function() { + var client = getClient(); var dogName="dog"+Math.floor(Math.random()*10000); var dogData=JSON.stringify({type:"dog",name:dogName}); - var dogURI='https://api.usergrid.com/yourorgname/sandbox/dogs' + var dogURI=client.clientAppURL + '/dogs' it('should POST to a URI',function(done){ var req=new Usergrid.Request("POST", dogURI, {}, dogData, function(err, response){ console.error(err, response); @@ -201,8 +204,8 @@ describe('Usergrid', function(){ it('should persist default query parameters', function(done) { //create new client with default params var client=new Usergrid.Client({ - orgName: 'yourorgname', - appName: 'sandbox', + orgId: 'rwalsh', + appId: 'sandbox', logging: false, //optional - turn on logging, off by default buildCurl: true, //optional - turn on curl commands, off by default qs:{ @@ -350,7 +353,7 @@ describe('Usergrid', function(){ done(); }) it('buildAssetURL',function(done){ - var assetURL='https://api.usergrid.com/yourorgname/sandbox/assets/00000000-0000-0000-000000000000/data'; + var assetURL=client.clientAppURL + '/assets/00000000-0000-0000-000000000000/data'; assert(assetURL===client.buildAssetURL('00000000-0000-0000-000000000000'), "buildAssetURL doesn't work") done(); }) @@ -376,7 +379,7 @@ describe('Usergrid', function(){ }) var dogCollection; it('createCollection',function(done){ - client.createCollection({type:'dogs'},function(err, response, dogs){ + client.createCollection({type:'dogs2s'},function(err, response, dogs){ assert(!err, "createCollection returned an error"); assert(dogs, "createCollection did not return a dogs collection"); dogCollection=dogs; diff --git a/tests/test.js b/tests/test.js index f726680..ee52261 100755 --- a/tests/test.js +++ b/tests/test.js @@ -46,8 +46,8 @@ var _password = 'password2'; var _newpassword = 'password3'; var client = new Usergrid.Client({ - orgName:'yourorgname', - appName:'sandbox', + orgId:'rwalsh', + appId:'sandbox', logging: true, //optional - turn on logging, off by default buildCurl: true //optional - turn on curl commands, off by default }); diff --git a/usergrid.js b/usergrid.js index 5989d8a..370b4c1 100644 --- a/usergrid.js +++ b/usergrid.js @@ -1,20 +1,23 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at +/*! + *Licensed to the Apache Software Foundation (ASF) under one + *or more contributor license agreements. See the NOTICE file + *distributed with this work for additional information + *regarding copyright ownership. The ASF licenses this file + *to you under the Apache License, Version 2.0 (the + *"License"); you may not use this file except in compliance + *with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. + *Unless required by applicable law or agreed to in writing, + *software distributed under the License is distributed on an + *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + *KIND, either express or implied. See the License for the + *specific language governing permissions and limitations + *under the License. + * + * + * usergrid@0.11.0 2016-09-19 */ var UsergridEventable = function() { throw Error("'UsergridEventable' is not intended to be invoked directly"); @@ -84,7 +87,7 @@ UsergridEventable.mixin = function(destObject) { }; Logger.prototype.log = function() { var args = [].slice.call(arguments); - method = args.shift(); + var method = args.shift(); if (Logger.METHODS.indexOf(method) === -1) { method = "log"; } @@ -184,109 +187,3559 @@ UsergridEventable.mixin = function(destObject) { if (overwrittenName) { global[name] = overwrittenName; } - return Promise; - }; - return global[name]; -})(this); - -(function() { - var name = "Ajax", global = this, overwrittenName = global[name], exports; - function partial() { - var args = Array.prototype.slice.call(arguments); - var fn = args.shift(); - return fn.bind(this, args); + return Promise; + }; + return global[name]; +})(this); + +(function() { + var name = "Ajax", global = this, overwrittenName = global[name], exports; + function partial() { + var args = Array.prototype.slice.call(arguments); + var fn = args.shift(); + return fn.bind(this, args); + } + function Ajax() { + this.logger = new global.Logger(name); + var self = this; + function encode(data) { + var result = ""; + if (typeof data === "string") { + result = data; + } else { + var e = encodeURIComponent; + for (var i in data) { + if (data.hasOwnProperty(i)) { + result += "&" + e(i) + "=" + e(data[i]); + } + } + } + return result; + } + function request(m, u, d) { + var p = new Promise(), timeout; + self.logger.time(m + " " + u); + (function(xhr) { + xhr.onreadystatechange = function() { + if (this.readyState === 4) { + self.logger.timeEnd(m + " " + u); + clearTimeout(timeout); + p.done(null, this); + } + }; + xhr.onerror = function(response) { + clearTimeout(timeout); + p.done(response, null); + }; + xhr.oncomplete = function(response) { + clearTimeout(timeout); + self.logger.timeEnd(m + " " + u); + self.info("%s request to %s returned %s", m, u, this.status); + }; + xhr.open(m, u); + if (d) { + if ("object" === typeof d) { + d = JSON.stringify(d); + } + xhr.setRequestHeader("Content-Type", "application/json"); + xhr.setRequestHeader("Accept", "application/json"); + } + timeout = setTimeout(function() { + xhr.abort(); + p.done("API Call timed out.", null); + }, 3e4); + xhr.send(encode(d)); + })(new XMLHttpRequest()); + return p; + } + this.request = request; + this.get = partial(request, "GET"); + this.post = partial(request, "POST"); + this.put = partial(request, "PUT"); + this.delete = partial(request, "DELETE"); + } + global[name] = new Ajax(); + global[name].noConflict = function() { + if (overwrittenName) { + global[name] = overwrittenName; + } + return exports; + }; + return global[name]; +})(); + +(function() { + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + /** Used as the semantic version number. */ + var VERSION = "4.16.0"; + /** Used as the `TypeError` message for "Functions" methods. */ + var FUNC_ERROR_TEXT = "Expected a function"; + /** Used to compose bitmasks for function metadata. */ + var BIND_FLAG = 1, PARTIAL_FLAG = 32; + /** Used to compose bitmasks for comparison styles. */ + var UNORDERED_COMPARE_FLAG = 1, PARTIAL_COMPARE_FLAG = 2; + /** Used as references for various `Number` constants. */ + var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991; + /** `Object#toString` result references. */ + var argsTag = "[object Arguments]", arrayTag = "[object Array]", boolTag = "[object Boolean]", dateTag = "[object Date]", errorTag = "[object Error]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", numberTag = "[object Number]", objectTag = "[object Object]", regexpTag = "[object RegExp]", stringTag = "[object String]"; + /** Used to match HTML entities and HTML characters. */ + var reUnescapedHtml = /[&<>"'`]/g, reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + /** Used to map characters to HTML entities. */ + var htmlEscapes = { + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'" + }; + /** Detect free variable `global` from Node.js. */ + var freeGlobal = typeof global == "object" && global && global.Object === Object && global; + /** Detect free variable `self`. */ + var freeSelf = typeof self == "object" && self && self.Object === Object && self; + /** Used as a reference to the global object. */ + var root = freeGlobal || freeSelf || Function("return this")(); + /** Detect free variable `exports`. */ + var freeExports = typeof exports == "object" && exports && !exports.nodeType && exports; + /** Detect free variable `module`. */ + var freeModule = freeExports && typeof module == "object" && module && !module.nodeType && module; + /*--------------------------------------------------------------------------*/ + /** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + function arrayPush(array, values) { + array.push.apply(array, values); + return array; + } + /** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, index = fromIndex + (fromRight ? 1 : -1); + while (fromRight ? index-- : ++index < length) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; + } + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + /** + * The base implementation of `_.propertyOf` without support for deep paths. + * + * @private + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyOf(object) { + return function(key) { + return object == null ? undefined : object[key]; + }; + } + /** + * The base implementation of `_.reduce` and `_.reduceRight`, without support + * for iteratee shorthands, which iterates over `collection` using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} accumulator The initial value. + * @param {boolean} initAccum Specify using the first or last element of + * `collection` as the initial value. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the accumulated value. + */ + function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { + eachFunc(collection, function(value, index, collection) { + accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); + }); + return accumulator; + } + /** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ + function baseValues(object, props) { + return baseMap(props, function(key) { + return object[key]; + }); + } + /** + * Used by `_.escape` to convert characters to HTML entities. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + var escapeHtmlChar = basePropertyOf(htmlEscapes); + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + /*--------------------------------------------------------------------------*/ + /** Used for built-in method references. */ + var arrayProto = Array.prototype, objectProto = Object.prototype; + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + /** Used to generate unique IDs. */ + var idCounter = 0; + /** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + var objectToString = objectProto.toString; + /** Used to restore the original `_` reference in `_.noConflict`. */ + var oldDash = root._; + /** Built-in value references. */ + var objectCreate = Object.create, propertyIsEnumerable = objectProto.propertyIsEnumerable; + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeIsFinite = root.isFinite, nativeKeys = overArg(Object.keys, Object), nativeMax = Math.max; + /*------------------------------------------------------------------------*/ + /** + * Creates a `lodash` object which wraps `value` to enable implicit method + * chain sequences. Methods that operate on and return arrays, collections, + * and functions can be chained together. Methods that retrieve a single value + * or may return a primitive value will automatically end the chain sequence + * and return the unwrapped value. Otherwise, the value must be unwrapped + * with `_#value`. + * + * Explicit chain sequences, which must be unwrapped with `_#value`, may be + * enabled using `_.chain`. + * + * The execution of chained methods is lazy, that is, it's deferred until + * `_#value` is implicitly or explicitly called. + * + * Lazy evaluation allows several methods to support shortcut fusion. + * Shortcut fusion is an optimization to merge iteratee calls; this avoids + * the creation of intermediate arrays and can greatly reduce the number of + * iteratee executions. Sections of a chain sequence qualify for shortcut + * fusion if the section is applied to an array of at least `200` elements + * and any iteratees accept only one argument. The heuristic for whether a + * section qualifies for shortcut fusion is subject to change. + * + * Chaining is supported in custom builds as long as the `_#value` method is + * directly or indirectly included in the build. + * + * In addition to lodash methods, wrappers have `Array` and `String` methods. + * + * The wrapper `Array` methods are: + * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` + * + * The wrapper `String` methods are: + * `replace` and `split` + * + * The wrapper methods that support shortcut fusion are: + * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, + * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, + * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` + * + * The chainable wrapper methods are: + * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, + * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, + * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, + * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, + * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, + * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, + * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, + * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, + * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, + * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, + * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, + * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, + * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, + * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, + * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, + * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, + * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, + * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, + * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, + * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, + * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, + * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, + * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, + * `zipObject`, `zipObjectDeep`, and `zipWith` + * + * The wrapper methods that are **not** chainable by default are: + * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, + * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, + * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, + * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, + * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, + * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, + * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, + * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, + * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, + * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, + * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, + * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, + * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, + * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, + * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, + * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, + * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, + * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, + * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, + * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, + * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, + * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, + * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, + * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, + * `upperFirst`, `value`, and `words` + * + * @name _ + * @constructor + * @category Seq + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2, 3]); + * + * // Returns an unwrapped value. + * wrapped.reduce(_.add); + * // => 6 + * + * // Returns a wrapped value. + * var squares = wrapped.map(square); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true + */ + function lodash(value) { + return value instanceof LodashWrapper ? value : new LodashWrapper(value); + } + /** + * The base constructor for creating `lodash` wrapper objects. + * + * @private + * @param {*} value The value to wrap. + * @param {boolean} [chainAll] Enable explicit method chain sequences. + */ + function LodashWrapper(value, chainAll) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__chain__ = !!chainAll; + } + LodashWrapper.prototype = baseCreate(lodash.prototype); + LodashWrapper.prototype.constructor = LodashWrapper; + /*------------------------------------------------------------------------*/ + /** + * Used by `_.defaults` to customize its `_.assignIn` use. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to assign. + * @param {Object} object The parent object of `objValue`. + * @returns {*} Returns the value to assign. + */ + function assignInDefaults(objValue, srcValue, key, object) { + if (objValue === undefined || eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key)) { + return srcValue; + } + return objValue; + } + /** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || value === undefined && !(key in object)) { + baseAssignValue(object, key, value); + } + } + /** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function baseAssignValue(object, key, value) { + object[key] = value; + } + /** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} prototype The object to inherit from. + * @returns {Object} Returns the new object. + */ + function baseCreate(proto) { + return isObject(proto) ? objectCreate(proto) : {}; + } + /** + * The base implementation of `_.delay` and `_.defer` which accepts `args` + * to provide to `func`. + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {Array} args The arguments to provide to `func`. + * @returns {number|Object} Returns the timer id or timeout object. + */ + function baseDelay(func, wait, args) { + if (typeof func != "function") { + throw new TypeError(FUNC_ERROR_TEXT); + } + return setTimeout(function() { + func.apply(undefined, args); + }, wait); + } + /** + * The base implementation of `_.forEach` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ + var baseEach = createBaseEach(baseForOwn); + /** + * The base implementation of `_.every` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false` + */ + function baseEvery(collection, predicate) { + var result = true; + baseEach(collection, function(value, index, collection) { + result = !!predicate(value, index, collection); + return result; + }); + return result; + } + /** + * The base implementation of methods like `_.max` and `_.min` which accepts a + * `comparator` to determine the extremum value. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The iteratee invoked per iteration. + * @param {Function} comparator The comparator used to compare values. + * @returns {*} Returns the extremum value. + */ + function baseExtremum(array, iteratee, comparator) { + var index = -1, length = array.length; + while (++index < length) { + var value = array[index], current = iteratee(value); + if (current != null && (computed === undefined ? current === current && !false : comparator(current, computed))) { + var computed = current, result = value; + } + } + return result; + } + /** + * The base implementation of `_.filter` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function baseFilter(collection, predicate) { + var result = []; + baseEach(collection, function(value, index, collection) { + if (predicate(value, index, collection)) { + result.push(value); + } + }); + return result; + } + /** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ + function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, length = array.length; + predicate || (predicate = isFlattenable); + result || (result = []); + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; + } + /** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseFor = createBaseFor(); + /** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); + } + /** + * The base implementation of `_.functions` which creates an array of + * `object` function property names filtered from `props`. + * + * @private + * @param {Object} object The object to inspect. + * @param {Array} props The property names to filter. + * @returns {Array} Returns the function names. + */ + function baseFunctions(object, props) { + return baseFilter(props, function(key) { + return isFunction(object[key]); + }); + } + /** + * The base implementation of `_.gt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + */ + function baseGt(value, other) { + return value > other; + } + /** + * The base implementation of `_.isDate` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + */ + function baseIsDate(value) { + return isObjectLike(value) && objectToString.call(value) == dateTag; + } + /** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparisons. + * @param {boolean} [bitmask] The bitmask of comparison flags. + * The bitmask may be composed of the following flags: + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(value, other, customizer, bitmask, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || !isObject(value) && !isObjectLike(other)) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack); + } + /** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} [customizer] The function to customize comparisons. + * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual` + * for more details. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) { + var objIsArr = isArray(object), othIsArr = isArray(other), objTag = arrayTag, othTag = arrayTag; + if (!objIsArr) { + objTag = objectToString.call(object); + objTag = objTag == argsTag ? objectTag : objTag; + } + if (!othIsArr) { + othTag = objectToString.call(other); + othTag = othTag == argsTag ? objectTag : othTag; + } + var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; + stack || (stack = []); + var objStack = find(stack, function(entry) { + return entry[0] == object; + }); + var othStack = find(stack, function(entry) { + return entry[0] == other; + }); + if (objStack && othStack) { + return objStack[1] == other; + } + stack.push([ object, other ]); + stack.push([ other, object ]); + if (isSameTag && !objIsObj) { + var result = objIsArr ? equalArrays(object, other, equalFunc, customizer, bitmask, stack) : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack); + stack.pop(); + return result; + } + if (!(bitmask & PARTIAL_COMPARE_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty.call(other, "__wrapped__"); + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; + var result = equalFunc(objUnwrapped, othUnwrapped, customizer, bitmask, stack); + stack.pop(); + return result; + } + } + if (!isSameTag) { + return false; + } + var result = equalObjects(object, other, equalFunc, customizer, bitmask, stack); + stack.pop(); + return result; + } + /** + * The base implementation of `_.isRegExp` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + */ + function baseIsRegExp(value) { + return isObject(value) && objectToString.call(value) == regexpTag; + } + /** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ + function baseIteratee(func) { + if (typeof func == "function") { + return func; + } + if (func == null) { + return identity; + } + return (typeof func == "object" ? baseMatches : baseProperty)(func); + } + /** + * The base implementation of `_.lt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + */ + function baseLt(value, other) { + return value < other; + } + /** + * The base implementation of `_.map` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function baseMap(collection, iteratee) { + var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; + baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; + } + /** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatches(source) { + var props = nativeKeys(source); + return function(object) { + var length = props.length; + if (object == null) { + return !length; + } + object = Object(object); + while (length--) { + var key = props[length]; + if (!(key in object && baseIsEqual(source[key], object[key], undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG))) { + return false; + } + } + return true; + }; + } + /** + * The base implementation of `_.pick` without support for individual + * property identifiers. + * + * @private + * @param {Object} object The source object. + * @param {string[]} props The property identifiers to pick. + * @returns {Object} Returns the new object. + */ + function basePick(object, props) { + object = Object(object); + return reduce(props, function(result, key) { + if (key in object) { + result[key] = object[key]; + } + return result; + }, {}); + } + /** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ + function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ""); + } + /** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function baseSlice(array, start, end) { + var index = -1, length = array.length; + if (start < 0) { + start = -start > length ? 0 : length + start; + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : end - start >>> 0; + start >>>= 0; + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; + } + /** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ + function copyArray(source) { + return baseSlice(source, 0, source.length); + } + /** + * The base implementation of `_.some` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function baseSome(collection, predicate) { + var result; + baseEach(collection, function(value, index, collection) { + result = predicate(value, index, collection); + return !result; + }); + return !!result; + } + /** + * The base implementation of `wrapperValue` which returns the result of + * performing a sequence of actions on the unwrapped `value`, where each + * successive action is supplied the return value of the previous. + * + * @private + * @param {*} value The unwrapped value. + * @param {Array} actions Actions to perform to resolve the unwrapped value. + * @returns {*} Returns the resolved value. + */ + function baseWrapperValue(value, actions) { + var result = value; + return reduce(actions, function(result, action) { + return action.func.apply(action.thisArg, arrayPush([ result ], action.args)); + }, result); + } + /** + * Compares values to sort them in ascending order. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. + */ + function compareAscending(value, other) { + if (value !== other) { + var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = false; + var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = false; + if (!othIsNull && !othIsSymbol && !valIsSymbol && value > other || valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol || valIsNull && othIsDefined && othIsReflexive || !valIsDefined && othIsReflexive || !valIsReflexive) { + return 1; + } + if (!valIsNull && !valIsSymbol && !othIsSymbol && value < other || othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol || othIsNull && valIsDefined && valIsReflexive || !othIsDefined && valIsReflexive || !othIsReflexive) { + return -1; + } + } + return 0; + } + /** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ + function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + var index = -1, length = props.length; + while (++index < length) { + var key = props[index]; + var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; + } + /** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ + function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined; + customizer = assigner.length > 3 && typeof customizer == "function" ? (length--, + customizer) : undefined; + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); + } + /** + * Creates a `baseEach` or `baseEachRight` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee) { + if (collection == null) { + return collection; + } + if (!isArrayLike(collection)) { + return eachFunc(collection, iteratee); + } + var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); + while (fromRight ? index-- : ++index < length) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; + } + /** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } + /** + * Creates a function that produces an instance of `Ctor` regardless of + * whether it was invoked as part of a `new` expression or by `call` or `apply`. + * + * @private + * @param {Function} Ctor The constructor to wrap. + * @returns {Function} Returns the new wrapped function. + */ + function createCtor(Ctor) { + return function() { + var args = arguments; + var thisBinding = baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); + return isObject(result) ? result : thisBinding; + }; + } + /** + * Creates a `_.find` or `_.findLast` function. + * + * @private + * @param {Function} findIndexFunc The function to find the collection index. + * @returns {Function} Returns the new find function. + */ + function createFind(findIndexFunc) { + return function(collection, predicate, fromIndex) { + var iterable = Object(collection); + if (!isArrayLike(collection)) { + var iteratee = baseIteratee(predicate, 3); + collection = keys(collection); + predicate = function(key) { + return iteratee(iterable[key], key, iterable); + }; + } + var index = findIndexFunc(collection, predicate, fromIndex); + return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; + }; + } + /** + * Creates a function that wraps `func` to invoke it with the `this` binding + * of `thisArg` and `partials` prepended to the arguments it receives. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} partials The arguments to prepend to those provided to + * the new function. + * @returns {Function} Returns the new wrapped function. + */ + function createPartial(func, bitmask, thisArg, partials) { + if (typeof func != "function") { + throw new TypeError(FUNC_ERROR_TEXT); + } + var isBind = bitmask & BIND_FLAG, Ctor = createCtor(func); + function wrapper() { + var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = this && this !== root && this instanceof wrapper ? Ctor : func; + while (++leftIndex < leftLength) { + args[leftIndex] = partials[leftIndex]; + } + while (argsLength--) { + args[leftIndex++] = arguments[++argsIndex]; + } + return fn.apply(isBind ? thisArg : this, args); + } + return wrapper; + } + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} customizer The function to customize comparisons. + * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` + * for more details. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + function equalArrays(array, other, equalFunc, customizer, bitmask, stack) { + var isPartial = bitmask & PARTIAL_COMPARE_FLAG, arrLength = array.length, othLength = other.length; + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + var index = -1, result = true, seen = bitmask & UNORDERED_COMPARE_FLAG ? [] : undefined; + while (++index < arrLength) { + var arrValue = array[index], othValue = other[index]; + var compared; + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + if (seen) { + if (!baseSome(other, function(othValue, othIndex) { + if (!indexOf(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) { + result = false; + break; + } + } + return result; + } + /** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} customizer The function to customize comparisons. + * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` + * for more details. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) { + switch (tag) { + case boolTag: + case dateTag: + case numberTag: + return eq(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + return object == other + ""; + } + return false; + } + /** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} customizer The function to customize comparisons. + * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` + * for more details. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalObjects(object, other, equalFunc, customizer, bitmask, stack) { + var isPartial = bitmask & PARTIAL_COMPARE_FLAG, objProps = keys(object), objLength = objProps.length, othProps = keys(other), othLength = othProps.length; + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + var result = true; + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], othValue = other[key]; + var compared; + if (!(compared === undefined ? objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack) : compared)) { + result = false; + break; + } + skipCtor || (skipCtor = key == "constructor"); + } + if (result && !skipCtor) { + var objCtor = object.constructor, othCtor = other.constructor; + if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) { + result = false; + } + } + return result; + } + /** + * A specialized version of `baseRest` which flattens the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ + function flatRest(func) { + return setToString(overRest(func, undefined, flatten), func + ""); + } + /** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ + function isFlattenable(value) { + return isArray(value) || isArguments(value); + } + /** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; + } + /** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ + function overRest(func, start, transform) { + start = nativeMax(start === undefined ? func.length - 1 : start, 0); + return function() { + var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return func.apply(this, otherArgs); + }; + } + /** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var setToString = identity; + /** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ + var toKey = String; + /*------------------------------------------------------------------------*/ + /** + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are falsey. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to compact. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] + */ + function compact(array) { + return baseFilter(array, Boolean); + } + /** + * Creates a new array concatenating `array` with any additional arrays + * and/or values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to concatenate. + * @param {...*} [values] The values to concatenate. + * @returns {Array} Returns the new concatenated array. + * @example + * + * var array = [1]; + * var other = _.concat(array, 2, [3], [[4]]); + * + * console.log(other); + * // => [1, 2, 3, [4]] + * + * console.log(array); + * // => [1] + */ + function concat() { + var length = arguments.length; + if (!length) { + return []; + } + var args = Array(length - 1), array = arguments[0], index = length; + while (index--) { + args[index - 1] = arguments[index]; + } + return arrayPush(isArray(array) ? copyArray(array) : [ array ], baseFlatten(args, 1)); + } + /** + * This method is like `_.find` except that it returns the index of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] + * The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.findIndex(users, function(o) { return o.user == 'barney'; }); + * // => 0 + * + * // The `_.matches` iteratee shorthand. + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findIndex(users, ['active', false]); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.findIndex(users, 'active'); + * // => 2 + */ + function findIndex(array, predicate, fromIndex) { + var length = array ? array.length : 0; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseFindIndex(array, baseIteratee(predicate, 3), index); + } + /** + * Flattens `array` a single level deep. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */ + function flatten(array) { + var length = array ? array.length : 0; + return length ? baseFlatten(array, 1) : []; + } + /** + * Recursively flattens `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flattenDeep([1, [2, [3, [4]], 5]]); + * // => [1, 2, 3, 4, 5] + */ + function flattenDeep(array) { + var length = array ? array.length : 0; + return length ? baseFlatten(array, INFINITY) : []; + } + /** + * Gets the first element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias first + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the first element of `array`. + * @example + * + * _.head([1, 2, 3]); + * // => 1 + * + * _.head([]); + * // => undefined + */ + function head(array) { + return array && array.length ? array[0] : undefined; + } + /** + * Gets the index at which the first occurrence of `value` is found in `array` + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it's used as the + * offset from the end of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.indexOf([1, 2, 1, 2], 2); + * // => 1 + * + * // Search from the `fromIndex`. + * _.indexOf([1, 2, 1, 2], 2, 2); + * // => 3 + */ + function indexOf(array, value, fromIndex) { + var length = array ? array.length : 0; + if (typeof fromIndex == "number") { + fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex; + } else { + fromIndex = 0; + } + var index = (fromIndex || 0) - 1, isReflexive = value === value; + while (++index < length) { + var other = array[index]; + if (isReflexive ? other === value : other !== other) { + return index; + } + } + return -1; + } + /** + * Gets the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + */ + function last(array) { + var length = array ? array.length : 0; + return length ? array[length - 1] : undefined; + } + /** + * Creates a slice of `array` from `start` up to, but not including, `end`. + * + * **Note:** This method is used instead of + * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are + * returned. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function slice(array, start, end) { + var length = array ? array.length : 0; + start = start == null ? 0 : +start; + end = end === undefined ? length : +end; + return length ? baseSlice(array, start, end) : []; + } + /*------------------------------------------------------------------------*/ + /** + * Creates a `lodash` wrapper instance that wraps `value` with explicit method + * chain sequences enabled. The result of such sequences must be unwrapped + * with `_#value`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Seq + * @param {*} value The value to wrap. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'pebbles', 'age': 1 } + * ]; + * + * var youngest = _ + * .chain(users) + * .sortBy('age') + * .map(function(o) { + * return o.user + ' is ' + o.age; + * }) + * .head() + * .value(); + * // => 'pebbles is 1' + */ + function chain(value) { + var result = lodash(value); + result.__chain__ = true; + return result; + } + /** + * This method invokes `interceptor` and returns `value`. The interceptor + * is invoked with one argument; (value). The purpose of this method is to + * "tap into" a method chain sequence in order to modify intermediate results. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns `value`. + * @example + * + * _([1, 2, 3]) + * .tap(function(array) { + * // Mutate input array. + * array.pop(); + * }) + * .reverse() + * .value(); + * // => [2, 1] + */ + function tap(value, interceptor) { + interceptor(value); + return value; + } + /** + * This method is like `_.tap` except that it returns the result of `interceptor`. + * The purpose of this method is to "pass thru" values replacing intermediate + * results in a method chain sequence. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns the result of `interceptor`. + * @example + * + * _(' abc ') + * .chain() + * .trim() + * .thru(function(value) { + * return [value]; + * }) + * .value(); + * // => ['abc'] + */ + function thru(value, interceptor) { + return interceptor(value); + } + /** + * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. + * + * @name chain + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * // A sequence without explicit chaining. + * _(users).head(); + * // => { 'user': 'barney', 'age': 36 } + * + * // A sequence with explicit chaining. + * _(users) + * .chain() + * .head() + * .pick('user') + * .value(); + * // => { 'user': 'barney' } + */ + function wrapperChain() { + return chain(this); + } + /** + * Executes the chain sequence to resolve the unwrapped value. + * + * @name value + * @memberOf _ + * @since 0.1.0 + * @alias toJSON, valueOf + * @category Seq + * @returns {*} Returns the resolved unwrapped value. + * @example + * + * _([1, 2, 3]).value(); + * // => [1, 2, 3] + */ + function wrapperValue() { + return baseWrapperValue(this.__wrapped__, this.__actions__); + } + /*------------------------------------------------------------------------*/ + /** + * Checks if `predicate` returns truthy for **all** elements of `collection`. + * Iteration is stopped once `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * **Note:** This method returns `true` for + * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because + * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of + * elements of empty collections. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] + * The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes'], Boolean); + * // => false + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.every(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.every(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.every(users, 'active'); + * // => false + */ + function every(collection, predicate, guard) { + predicate = guard ? undefined : predicate; + return baseEvery(collection, baseIteratee(predicate)); + } + /** + * Iterates over elements of `collection`, returning an array of all elements + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * **Note:** Unlike `_.remove`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] + * The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.reject + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * _.filter(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.filter(users, { 'age': 36, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.filter(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.filter(users, 'active'); + * // => objects for ['barney'] + */ + function filter(collection, predicate) { + return baseFilter(collection, baseIteratee(predicate)); + } + /** + * Iterates over elements of `collection`, returning the first element + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] + * The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } + * ]; + * + * _.find(users, function(o) { return o.age < 40; }); + * // => object for 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.find(users, { 'age': 1, 'active': true }); + * // => object for 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.find(users, ['active', false]); + * // => object for 'fred' + * + * // The `_.property` iteratee shorthand. + * _.find(users, 'active'); + * // => object for 'barney' + */ + var find = createFind(findIndex); + /** + * Iterates over elements of `collection` and invokes `iteratee` for each element. + * The iteratee is invoked with three arguments: (value, index|key, collection). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * **Note:** As with other "Collections" methods, objects with a "length" + * property are iterated like arrays. To avoid this behavior use `_.forIn` + * or `_.forOwn` for object iteration. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias each + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEachRight + * @example + * + * _.forEach([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `1` then `2`. + * + * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ + function forEach(collection, iteratee) { + return baseEach(collection, baseIteratee(iteratee)); + } + /** + * Creates an array of values by running each element in `collection` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. + * + * The guarded methods are: + * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, + * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, + * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, + * `template`, `trim`, `trimEnd`, `trimStart`, and `words` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + * @example + * + * function square(n) { + * return n * n; + * } + * + * _.map([4, 8], square); + * // => [16, 64] + * + * _.map({ 'a': 4, 'b': 8 }, square); + * // => [16, 64] (iteration order is not guaranteed) + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * // The `_.property` iteratee shorthand. + * _.map(users, 'user'); + * // => ['barney', 'fred'] + */ + function map(collection, iteratee) { + return baseMap(collection, baseIteratee(iteratee)); + } + /** + * Reduces `collection` to a value which is the accumulated result of running + * each element in `collection` thru `iteratee`, where each successive + * invocation is supplied the return value of the previous. If `accumulator` + * is not given, the first element of `collection` is used as the initial + * value. The iteratee is invoked with four arguments: + * (accumulator, value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.reduce`, `_.reduceRight`, and `_.transform`. + * + * The guarded methods are: + * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, + * and `sortBy` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduceRight + * @example + * + * _.reduce([1, 2], function(sum, n) { + * return sum + n; + * }, 0); + * // => 3 + * + * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * return result; + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) + */ + function reduce(collection, iteratee, accumulator) { + return baseReduce(collection, baseIteratee(iteratee), accumulator, arguments.length < 3, baseEach); + } + /** + * Gets the size of `collection` by returning its length for array-like + * values or the number of own enumerable string keyed properties for objects. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns the collection size. + * @example + * + * _.size([1, 2, 3]); + * // => 3 + * + * _.size({ 'a': 1, 'b': 2 }); + * // => 2 + * + * _.size('pebbles'); + * // => 7 + */ + function size(collection) { + if (collection == null) { + return 0; + } + collection = isArrayLike(collection) ? collection : nativeKeys(collection); + return collection.length; + } + /** + * Checks if `predicate` returns truthy for **any** element of `collection`. + * Iteration is stopped once `predicate` returns truthy. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + * @example + * + * _.some([null, 0, 'yes', false], Boolean); + * // => true + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.some(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.some(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.some(users, 'active'); + * // => true + */ + function some(collection, predicate, guard) { + predicate = guard ? undefined : predicate; + return baseSome(collection, baseIteratee(predicate)); + } + /** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection thru each iteratee. This method + * performs a stable sort, that is, it preserves the original sort order of + * equal elements. The iteratees are invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {...(Function|Function[])} [iteratees=[_.identity]] + * The iteratees to sort by. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 34 } + * ]; + * + * _.sortBy(users, [function(o) { return o.user; }]); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + * + * _.sortBy(users, ['user', 'age']); + * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] + */ + function sortBy(collection, iteratee) { + var index = 0; + iteratee = baseIteratee(iteratee); + return baseMap(baseMap(collection, function(value, key, collection) { + return { + value: value, + index: index++, + criteria: iteratee(value, key, collection) + }; + }).sort(function(object, other) { + return compareAscending(object.criteria, other.criteria) || object.index - other.index; + }), baseProperty("value")); + } + /*------------------------------------------------------------------------*/ + /** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it's called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * jQuery(element).on('click', _.before(5, addContactToList)); + * // => Allows adding up to 4 contacts to the list. + */ + function before(n, func) { + var result; + if (typeof func != "function") { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } + if (n <= 1) { + func = undefined; + } + return result; + }; + } + /** + * Creates a function that invokes `func` with the `this` binding of `thisArg` + * and `partials` prepended to the arguments it receives. + * + * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for partially applied arguments. + * + * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" + * property of bound functions. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * function greet(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * + * var object = { 'user': 'fred' }; + * + * var bound = _.bind(greet, object, 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * // Bound with placeholders. + * var bound = _.bind(greet, object, _, '!'); + * bound('hi'); + * // => 'hi fred!' + */ + var bind = baseRest(function(func, thisArg, partials) { + return createPartial(func, BIND_FLAG | PARTIAL_FLAG, thisArg, partials); + }); + /** + * Defers invoking the `func` until the current call stack has cleared. Any + * additional arguments are provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to defer. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.defer(function(text) { + * console.log(text); + * }, 'deferred'); + * // => Logs 'deferred' after one millisecond. + */ + var defer = baseRest(function(func, args) { + return baseDelay(func, 1, args); + }); + /** + * Invokes `func` after `wait` milliseconds. Any additional arguments are + * provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.delay(function(text) { + * console.log(text); + * }, 1000, 'later'); + * // => Logs 'later' after one second. + */ + var delay = baseRest(function(func, wait, args) { + return baseDelay(func, toNumber(wait) || 0, args); + }); + /** + * Creates a function that negates the result of the predicate `func`. The + * `func` predicate is invoked with the `this` binding and arguments of the + * created function. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} predicate The predicate to negate. + * @returns {Function} Returns the new negated function. + * @example + * + * function isEven(n) { + * return n % 2 == 0; + * } + * + * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); + * // => [1, 3, 5] + */ + function negate(predicate) { + if (typeof predicate != "function") { + throw new TypeError(FUNC_ERROR_TEXT); + } + return function() { + var args = arguments; + return !predicate.apply(this, args); + }; + } + /** + * Creates a function that is restricted to invoking `func` once. Repeat calls + * to the function return the value of the first invocation. The `func` is + * invoked with the `this` binding and arguments of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // => `createApplication` is invoked once + */ + function once(func) { + return before(2, func); + } + /*------------------------------------------------------------------------*/ + /** + * Creates a shallow clone of `value`. + * + * **Note:** This method is loosely based on the + * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) + * and supports cloning arrays, array buffers, booleans, date objects, maps, + * numbers, `Object` objects, regexes, sets, strings, symbols, and typed + * arrays. The own enumerable properties of `arguments` objects are cloned + * as plain objects. An empty object is returned for uncloneable values such + * as error objects, functions, DOM nodes, and WeakMaps. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to clone. + * @returns {*} Returns the cloned value. + * @see _.cloneDeep + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var shallow = _.clone(objects); + * console.log(shallow[0] === objects[0]); + * // => true + */ + function clone(value) { + if (!isObject(value)) { + return value; + } + return isArray(value) ? copyArray(value) : copyObject(value, nativeKeys(value)); + } + /** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ + function eq(value, other) { + return value === other || value !== value && other !== other; + } + /** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + function isArguments(value) { + return isArrayLikeObject(value) && hasOwnProperty.call(value, "callee") && (!propertyIsEnumerable.call(value, "callee") || objectToString.call(value) == argsTag); + } + /** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ + var isArray = Array.isArray; + /** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); + } + /** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ + function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); + } + /** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ + function isBoolean(value) { + return value === true || value === false || isObjectLike(value) && objectToString.call(value) == boolTag; + } + /** + * Checks if `value` is classified as a `Date` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + * @example + * + * _.isDate(new Date); + * // => true + * + * _.isDate('Mon April 23 2012'); + * // => false + */ + var isDate = baseIsDate; + /** + * Checks if `value` is an empty object, collection, map, or set. + * + * Objects are considered empty if they have no own enumerable string keyed + * properties. + * + * Array-like values such as `arguments` objects, arrays, buffers, strings, or + * jQuery-like collections are considered empty if they have a `length` of `0`. + * Similarly, maps and sets are considered empty if they have a `size` of `0`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is empty, else `false`. + * @example + * + * _.isEmpty(null); + * // => true + * + * _.isEmpty(true); + * // => true + * + * _.isEmpty(1); + * // => true + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({ 'a': 1 }); + * // => false + */ + function isEmpty(value) { + if (isArrayLike(value) && (isArray(value) || isString(value) || isFunction(value.splice) || isArguments(value))) { + return !value.length; + } + return !nativeKeys(value).length; + } + /** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are **not** supported. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ + function isEqual(value, other) { + return baseIsEqual(value, other); + } + /** + * Checks if `value` is a finite primitive number. + * + * **Note:** This method is based on + * [`Number.isFinite`](https://mdn.io/Number/isFinite). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. + * @example + * + * _.isFinite(3); + * // => true + * + * _.isFinite(Number.MIN_VALUE); + * // => true + * + * _.isFinite(Infinity); + * // => false + * + * _.isFinite('3'); + * // => false + */ + function isFinite(value) { + return typeof value == "number" && nativeIsFinite(value); + } + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + var tag = isObject(value) ? objectToString.call(value) : ""; + return tag == funcTag || tag == genTag; + } + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + } + /** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + var type = typeof value; + return value != null && (type == "object" || type == "function"); + } + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return value != null && typeof value == "object"; + } + /** + * Checks if `value` is `NaN`. + * + * **Note:** This method is based on + * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as + * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for + * `undefined` and other non-number values. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ + function isNaN(value) { + return isNumber(value) && value != +value; + } + /** + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(void 0); + * // => false + */ + function isNull(value) { + return value === null; + } + /** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are + * classified as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a number, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ + function isNumber(value) { + return typeof value == "number" || isObjectLike(value) && objectToString.call(value) == numberTag; + } + /** + * Checks if `value` is classified as a `RegExp` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + * @example + * + * _.isRegExp(/abc/); + * // => true + * + * _.isRegExp('/abc/'); + * // => false + */ + var isRegExp = baseIsRegExp; + /** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ + function isString(value) { + return typeof value == "string" || !isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag; + } + /** + * Checks if `value` is `undefined`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + * + * _.isUndefined(null); + * // => false + */ + function isUndefined(value) { + return value === undefined; + } + /** + * Converts `value` to an array. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to convert. + * @returns {Array} Returns the converted array. + * @example + * + * _.toArray({ 'a': 1, 'b': 2 }); + * // => [1, 2] + * + * _.toArray('abc'); + * // => ['a', 'b', 'c'] + * + * _.toArray(1); + * // => [] + * + * _.toArray(null); + * // => [] + */ + function toArray(value) { + if (!isArrayLike(value)) { + return values(value); + } + return value.length ? copyArray(value) : []; + } + /** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ + var toInteger = Number; + /** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ + var toNumber = Number; + /** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {string} Returns the string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ + function toString(value) { + if (typeof value == "string") { + return value; + } + return value == null ? "" : value + ""; + } + /*------------------------------------------------------------------------*/ + /** + * Assigns own enumerable string keyed properties of source objects to the + * destination object. Source objects are applied from left to right. + * Subsequent sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object` and is loosely based on + * [`Object.assign`](https://mdn.io/Object/assign). + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assignIn + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assign({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'c': 3 } + */ + var assign = createAssigner(function(object, source) { + copyObject(source, nativeKeys(source), object); + }); + /** + * This method is like `_.assign` except that it iterates over own and + * inherited source properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extend + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assign + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assignIn({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } + */ + var assignIn = createAssigner(function(object, source) { + copyObject(source, nativeKeysIn(source), object); + }); + /** + * This method is like `_.assignIn` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extendWith + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignInWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keysIn(source), object, customizer); + }); + /** + * Creates an object that inherits from the `prototype` object. If a + * `properties` object is given, its own enumerable string keyed properties + * are assigned to the created object. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Object + * @param {Object} prototype The object to inherit from. + * @param {Object} [properties] The properties to assign to the object. + * @returns {Object} Returns the new object. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * function Circle() { + * Shape.call(this); + * } + * + * Circle.prototype = _.create(Shape.prototype, { + * 'constructor': Circle + * }); + * + * var circle = new Circle; + * circle instanceof Circle; + * // => true + * + * circle instanceof Shape; + * // => true + */ + function create(prototype, properties) { + var result = baseCreate(prototype); + return properties ? assign(result, properties) : result; + } + /** + * Assigns own and inherited enumerable string keyed properties of source + * objects to the destination object for all destination properties that + * resolve to `undefined`. Source objects are applied from left to right. + * Once a property is set, additional values of the same property are ignored. + * + * **Note:** This method mutates `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaultsDeep + * @example + * + * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var defaults = baseRest(function(args) { + args.push(undefined, assignInDefaults); + return assignInWith.apply(undefined, args); + }); + /** + * Checks if `path` is a direct property of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = { 'a': { 'b': 2 } }; + * var other = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.has(object, 'a'); + * // => true + * + * _.has(object, 'a.b'); + * // => true + * + * _.has(object, ['a', 'b']); + * // => true + * + * _.has(other, 'a'); + * // => false + */ + function has(object, path) { + return object != null && hasOwnProperty.call(object, path); + } + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + var keys = nativeKeys; + /** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ + var keysIn = nativeKeysIn; + /** + * Creates an object composed of the picked `object` properties. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [props] The property identifiers to pick. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pick(object, ['a', 'c']); + * // => { 'a': 1, 'c': 3 } + */ + var pick = flatRest(function(object, props) { + return object == null ? {} : basePick(object, baseMap(props, toKey)); + }); + /** + * This method is like `_.get` except that if the resolved value is a + * function it's invoked with the `this` binding of its parent object and + * its result is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to resolve. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; + * + * _.result(object, 'a[0].b.c1'); + * // => 3 + * + * _.result(object, 'a[0].b.c2'); + * // => 4 + * + * _.result(object, 'a[0].b.c3', 'default'); + * // => 'default' + * + * _.result(object, 'a[0].b.c3', _.constant('default')); + * // => 'default' + */ + function result(object, path, defaultValue) { + var value = object == null ? undefined : object[path]; + if (value === undefined) { + value = defaultValue; + } + return isFunction(value) ? value.call(object) : value; } - function Ajax() { - this.logger = new global.Logger(name); - var self = this; - function encode(data) { - var result = ""; - if (typeof data === "string") { - result = data; - } else { - var e = encodeURIComponent; - for (var i in data) { - if (data.hasOwnProperty(i)) { - result += "&" + e(i) + "=" + e(data[i]); - } - } - } - return result; + /** + * Creates an array of the own enumerable string keyed property values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.values(new Foo); + * // => [1, 2] (iteration order is not guaranteed) + * + * _.values('hi'); + * // => ['h', 'i'] + */ + function values(object) { + return object ? baseValues(object, keys(object)) : []; + } + /*------------------------------------------------------------------------*/ + /** + * Converts the characters "&", "<", ">", '"', and "'" in `string` to their + * corresponding HTML entities. + * + * **Note:** No other characters are escaped. To escape additional + * characters use a third-party library like [_he_](https://mths.be/he). + * + * Though the ">" character is escaped for symmetry, characters like + * ">" and "/" don't need escaping in HTML and have no special meaning + * unless they're part of a tag or unquoted attribute value. See + * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) + * (under "semi-related fun fact") for more details. + * + * When working with HTML you should always + * [quote attribute values](http://wonko.com/post/html-escaping) to reduce + * XSS vectors. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escape('fred, barney, & pebbles'); + * // => 'fred, barney, & pebbles' + */ + function escape(string) { + string = toString(string); + return string && reHasUnescapedHtml.test(string) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string; + } + /*------------------------------------------------------------------------*/ + /** + * This method returns the first argument it receives. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'a': 1 }; + * + * console.log(_.identity(object) === object); + * // => true + */ + function identity(value) { + return value; + } + /** + * Creates a function that invokes `func` with the arguments of the created + * function. If `func` is a property name, the created function returns the + * property value for a given element. If `func` is an array or object, the + * created function returns `true` for elements that contain the equivalent + * source properties, otherwise it returns `false`. + * + * @static + * @since 4.0.0 + * @memberOf _ + * @category Util + * @param {*} [func=_.identity] The value to convert to a callback. + * @returns {Function} Returns the callback. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true })); + * // => [{ 'user': 'barney', 'age': 36, 'active': true }] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.filter(users, _.iteratee(['user', 'fred'])); + * // => [{ 'user': 'fred', 'age': 40 }] + * + * // The `_.property` iteratee shorthand. + * _.map(users, _.iteratee('user')); + * // => ['barney', 'fred'] + * + * // Create custom iteratee shorthands. + * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) { + * return !_.isRegExp(func) ? iteratee(func) : function(string) { + * return func.test(string); + * }; + * }); + * + * _.filter(['abc', 'def'], /ef/); + * // => ['def'] + */ + var iteratee = baseIteratee; + /** + * Creates a function that performs a partial deep comparison between a given + * object and `source`, returning `true` if the given object has equivalent + * property values, else `false`. + * + * **Note:** The created function is equivalent to `_.isMatch` with `source` + * partially applied. + * + * Partial comparisons will match empty array and empty object `source` + * values against any array or object value, respectively. See `_.isEqual` + * for a list of supported value comparisons. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Util + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + * @example + * + * var objects = [ + * { 'a': 1, 'b': 2, 'c': 3 }, + * { 'a': 4, 'b': 5, 'c': 6 } + * ]; + * + * _.filter(objects, _.matches({ 'a': 4, 'c': 6 })); + * // => [{ 'a': 4, 'b': 5, 'c': 6 }] + */ + function matches(source) { + return baseMatches(assign({}, source)); + } + /** + * Adds all own enumerable string keyed function properties of a source + * object to the destination object. If `object` is a function, then methods + * are added to its prototype as well. + * + * **Note:** Use `_.runInContext` to create a pristine `lodash` function to + * avoid conflicts caused by modifying the original. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {Function|Object} [object=lodash] The destination object. + * @param {Object} source The object of functions to add. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.chain=true] Specify whether mixins are chainable. + * @returns {Function|Object} Returns `object`. + * @example + * + * function vowels(string) { + * return _.filter(string, function(v) { + * return /[aeiou]/i.test(v); + * }); + * } + * + * _.mixin({ 'vowels': vowels }); + * _.vowels('fred'); + * // => ['e'] + * + * _('fred').vowels().value(); + * // => ['e'] + * + * _.mixin({ 'vowels': vowels }, { 'chain': false }); + * _('fred').vowels(); + * // => ['e'] + */ + function mixin(object, source, options) { + var props = keys(source), methodNames = baseFunctions(source, props); + if (options == null && !(isObject(source) && (methodNames.length || !props.length))) { + options = source; + source = object; + object = this; + methodNames = baseFunctions(source, keys(source)); } - function request(m, u, d) { - var p = new Promise(), timeout; - self.logger.time(m + " " + u); - (function(xhr) { - xhr.onreadystatechange = function() { - if (this.readyState === 4) { - self.logger.timeEnd(m + " " + u); - clearTimeout(timeout); - p.done(null, this); + var chain = !(isObject(options) && "chain" in options) || !!options.chain, isFunc = isFunction(object); + baseEach(methodNames, function(methodName) { + var func = source[methodName]; + object[methodName] = func; + if (isFunc) { + object.prototype[methodName] = function() { + var chainAll = this.__chain__; + if (chain || chainAll) { + var result = object(this.__wrapped__), actions = result.__actions__ = copyArray(this.__actions__); + actions.push({ + func: func, + args: arguments, + thisArg: object + }); + result.__chain__ = chainAll; + return result; } + return func.apply(object, arrayPush([ this.value() ], arguments)); }; - xhr.onerror = function(response) { - clearTimeout(timeout); - p.done(response, null); - }; - xhr.oncomplete = function(response) { - clearTimeout(timeout); - self.logger.timeEnd(m + " " + u); - self.info("%s request to %s returned %s", m, u, this.status); - }; - xhr.open(m, u); - if (d) { - if ("object" === typeof d) { - d = JSON.stringify(d); - } - xhr.setRequestHeader("Content-Type", "application/json"); - xhr.setRequestHeader("Accept", "application/json"); - } - timeout = setTimeout(function() { - xhr.abort(); - p.done("API Call timed out.", null); - }, 3e4); - xhr.send(encode(d)); - })(new XMLHttpRequest()); - return p; - } - this.request = request; - this.get = partial(request, "GET"); - this.post = partial(request, "POST"); - this.put = partial(request, "PUT"); - this.delete = partial(request, "DELETE"); + } + }); + return object; } - global[name] = new Ajax(); - global[name].noConflict = function() { - if (overwrittenName) { - global[name] = overwrittenName; + /** + * Reverts the `_` variable to its previous value and returns a reference to + * the `lodash` function. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @returns {Function} Returns the `lodash` function. + * @example + * + * var lodash = _.noConflict(); + */ + function noConflict() { + if (root._ === this) { + root._ = oldDash; } - return exports; - }; - return global[name]; -})(); + return this; + } + /** + * This method returns `undefined`. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Util + * @example + * + * _.times(2, _.noop); + * // => [undefined, undefined] + */ + function noop() {} + /** + * Generates a unique ID. If `prefix` is given, the ID is appended to it. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {string} [prefix=''] The value to prefix the ID with. + * @returns {string} Returns the unique ID. + * @example + * + * _.uniqueId('contact_'); + * // => 'contact_104' + * + * _.uniqueId(); + * // => '105' + */ + function uniqueId(prefix) { + var id = ++idCounter; + return toString(prefix) + id; + } + /*------------------------------------------------------------------------*/ + /** + * Computes the maximum value of `array`. If `array` is empty or falsey, + * `undefined` is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Math + * @param {Array} array The array to iterate over. + * @returns {*} Returns the maximum value. + * @example + * + * _.max([4, 2, 8, 6]); + * // => 8 + * + * _.max([]); + * // => undefined + */ + function max(array) { + return array && array.length ? baseExtremum(array, identity, baseGt) : undefined; + } + /** + * Computes the minimum value of `array`. If `array` is empty or falsey, + * `undefined` is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Math + * @param {Array} array The array to iterate over. + * @returns {*} Returns the minimum value. + * @example + * + * _.min([4, 2, 8, 6]); + * // => 2 + * + * _.min([]); + * // => undefined + */ + function min(array) { + return array && array.length ? baseExtremum(array, identity, baseLt) : undefined; + } + /*------------------------------------------------------------------------*/ + lodash.assignIn = assignIn; + lodash.before = before; + lodash.bind = bind; + lodash.chain = chain; + lodash.compact = compact; + lodash.concat = concat; + lodash.create = create; + lodash.defaults = defaults; + lodash.defer = defer; + lodash.delay = delay; + lodash.filter = filter; + lodash.flatten = flatten; + lodash.flattenDeep = flattenDeep; + lodash.iteratee = iteratee; + lodash.keys = keys; + lodash.map = map; + lodash.matches = matches; + lodash.mixin = mixin; + lodash.negate = negate; + lodash.once = once; + lodash.pick = pick; + lodash.slice = slice; + lodash.sortBy = sortBy; + lodash.tap = tap; + lodash.thru = thru; + lodash.toArray = toArray; + lodash.values = values; + lodash.extend = assignIn; + mixin(lodash, lodash); + /*------------------------------------------------------------------------*/ + lodash.clone = clone; + lodash.escape = escape; + lodash.every = every; + lodash.find = find; + lodash.forEach = forEach; + lodash.has = has; + lodash.head = head; + lodash.identity = identity; + lodash.indexOf = indexOf; + lodash.isArguments = isArguments; + lodash.isArray = isArray; + lodash.isBoolean = isBoolean; + lodash.isDate = isDate; + lodash.isEmpty = isEmpty; + lodash.isEqual = isEqual; + lodash.isFinite = isFinite; + lodash.isFunction = isFunction; + lodash.isNaN = isNaN; + lodash.isNull = isNull; + lodash.isNumber = isNumber; + lodash.isObject = isObject; + lodash.isRegExp = isRegExp; + lodash.isString = isString; + lodash.isUndefined = isUndefined; + lodash.last = last; + lodash.max = max; + lodash.min = min; + lodash.noConflict = noConflict; + lodash.noop = noop; + lodash.reduce = reduce; + lodash.result = result; + lodash.size = size; + lodash.some = some; + lodash.uniqueId = uniqueId; + lodash.each = forEach; + lodash.first = head; + mixin(lodash, function() { + var source = {}; + baseForOwn(lodash, function(func, methodName) { + if (!hasOwnProperty.call(lodash.prototype, methodName)) { + source[methodName] = func; + } + }); + return source; + }(), { + chain: false + }); + /*------------------------------------------------------------------------*/ + /** + * The semantic version number. + * + * @static + * @memberOf _ + * @type {string} + */ + lodash.VERSION = VERSION; + baseEach([ "pop", "join", "replace", "reverse", "split", "push", "shift", "sort", "splice", "unshift" ], function(methodName) { + var func = (/^(?:replace|split)$/.test(methodName) ? String.prototype : arrayProto)[methodName], chainName = /^(?:push|sort|unshift)$/.test(methodName) ? "tap" : "thru", retUnwrapped = /^(?:pop|join|replace|shift)$/.test(methodName); + lodash.prototype[methodName] = function() { + var args = arguments; + if (retUnwrapped && !this.__chain__) { + var value = this.value(); + return func.apply(isArray(value) ? value : [], args); + } + return this[chainName](function(value) { + return func.apply(isArray(value) ? value : [], args); + }); + }; + }); + lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue; + /*--------------------------------------------------------------------------*/ + if (typeof define == "function" && typeof define.amd == "object" && define.amd) { + root._ = lodash; + define(function() { + return lodash; + }); + } else if (freeModule) { + (freeModule.exports = lodash)._ = lodash; + freeExports._ = lodash; + } else { + root._ = lodash; + } +}).call(this); /* - * This module is a collection of classes designed to make working with - * the Appigee App Services API as easy as possible. - * Learn more at http://Usergrid.com/docs/usergrid - * - * Copyright 2012 Usergrid Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * @author rod simpson (rod@Usergrid.com) - * @author matt dobson (matt@Usergrid.com) - * @author ryan bridges (rbridges@Usergrid.com) + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ window.console = window.console || {}; @@ -566,14 +4019,20 @@ function doCallback(callback, params, context) { (function() { var name = "Client", global = this, overwrittenName = global[name], exports; var AUTH_ERRORS = [ "auth_expired_session_token", "auth_missing_credentials", "auth_unverified_oath", "expired_token", "unauthorized", "auth_invalid" ]; + var defaultOptions = { + baseUrl: "https://api.usergrid.com" + }; Usergrid.Client = function(options) { - this.URI = options.URI || "https://api.usergrid.com"; - if (options.orgName) { - this.set("orgName", options.orgName); - } - if (options.appName) { - this.set("appName", options.appName); + if (!options.orgId || !options.appId) { + throw new Error('"orgId" and "appId" parameters are required when instantiating UsergridClient'); } + _.defaults(this, options, defaultOptions); + this.clientAppURL = [ this.baseUrl, this.orgId, this.appId ].join("/"); + this.isSharedInstance = false; + this.currentUser = undefined; + this.appAuth = undefined; + this.userAuth = undefined; + this.authMode = undefined; if (options.qs) { this.setObject("default_qs", options.qs); } @@ -602,8 +4061,8 @@ function doCallback(callback, params, context) { var body = options.body || {}; var qs = options.qs || {}; var mQuery = options.mQuery || false; - var orgName = this.get("orgName"); - var appName = this.get("appName"); + var orgId = this.get("orgId"); + var appId = this.get("appId"); var default_qs = this.getObject("default_qs"); var uri; /*var logoutCallback=function(){ @@ -611,13 +4070,13 @@ function doCallback(callback, params, context) { return this.logoutCallback(true, 'no_org_or_app_name_specified'); } }.bind(this);*/ - if (!mQuery && !orgName && !appName) { + if (!mQuery && !orgId && !appId) { return logoutCallback(); } if (mQuery) { - uri = this.URI + "/" + endpoint; + uri = this.baseUrl + "/" + endpoint; } else { - uri = this.URI + "/" + orgName + "/" + appName + "/" + endpoint; + uri = this.baseUrl + "/" + orgId + "/" + appId + "/" + endpoint; } if (this.getToken()) { qs.access_token = this.getToken(); @@ -648,7 +4107,7 @@ function doCallback(callback, params, context) { Usergrid.Client.prototype.buildAssetURL = function(uuid) { var self = this; var qs = {}; - var assetURL = this.URI + "/" + this.orgName + "/" + this.appName + "/assets/" + uuid + "/data"; + var assetURL = this.baseUrl + "/" + this.orgId + "/" + this.appId + "/assets/" + uuid + "/data"; if (self.getToken()) { qs.access_token = self.getToken(); } @@ -1048,6 +4507,33 @@ function doCallback(callback, params, context) { doCallback(callback, [ err, response, user ]); }); }; + Usergrid.Client.prototype.adminlogin = function(username, password, callback) { + var self = this; + var options = { + method: "POST", + endpoint: "management/token", + body: { + username: username, + password: password, + grant_type: "password" + }, + mQuery: true + }; + self.request(options, function(err, response) { + var user = {}; + if (err) { + if (self.logging) console.log("error trying to log adminuser in"); + } else { + var options = { + client: self, + data: response.user + }; + user = new Usergrid.Entity(options); + self.setToken(response.access_token); + } + doCallback(callback, [ err, response, user ]); + }); + }; Usergrid.Client.prototype.reAuthenticateLite = function(callback) { var self = this; var options = { @@ -3051,11 +6537,11 @@ Usergrid.Entity.prototype.attachAsset = function(file, callback) { attempts = 3; } if (type != "assets" && type != "asset") { - var endpoint = [ this._client.URI, this._client.orgName, this._client.appName, type, self.get("uuid") ].join("/"); + var endpoint = [ this._client.clientAppURL, type, self.get("uuid") ].join("/"); } else { self.set("content-type", file.type); self.set("size", file.size); - var endpoint = [ this._client.URI, this._client.orgName, this._client.appName, "assets", self.get("uuid"), "data" ].join("/"); + var endpoint = [ this._client.clientAppURL, "assets", self.get("uuid"), "data" ].join("/"); } var xhr = new XMLHttpRequest(); xhr.open("POST", endpoint, true); @@ -3120,9 +6606,9 @@ Usergrid.Entity.prototype.downloadAsset = function(callback) { var type = this._data.type; var xhr = new XMLHttpRequest(); if (type != "assets" && type != "asset") { - endpoint = [ this._client.URI, this._client.orgName, this._client.appName, type, self.get("uuid") ].join("/"); + endpoint = [ this._client.clientAppURL, type, self.get("uuid") ].join("/"); } else { - endpoint = [ this._client.URI, this._client.orgName, this._client.appName, "assets", self.get("uuid"), "data" ].join("/"); + endpoint = [ this._client.clientAppURL, "assets", self.get("uuid"), "data" ].join("/"); } xhr.open("GET", endpoint, true); xhr.responseType = "blob"; From f8e1e017eb18e72e767dad23ab6880fe0c3c7f70 Mon Sep 17 00:00:00 2001 From: Robert Walsh Date: Mon, 19 Sep 2016 16:17:22 -0500 Subject: [PATCH 02/36] Updates Removing failing groups test since we wont need that anymore. Got all other tests working. --- lib/modules/Client.js | 6 +++--- tests/mocha/test.js | 26 +++----------------------- usergrid.js | 9 ++++++--- 3 files changed, 12 insertions(+), 29 deletions(-) diff --git a/lib/modules/Client.js b/lib/modules/Client.js index 069153b..fd462db 100644 --- a/lib/modules/Client.js +++ b/lib/modules/Client.js @@ -291,9 +291,9 @@ */ Usergrid.Client.prototype.createCollection = function (options, callback) { options.client = this; - return new Usergrid.Collection(options, function(err, data, collection) { - console.log("createCollection", arguments); - doCallback(callback, [err, collection, data]); + var collection = new Usergrid.Collection(options); + this.request({method: "POST",endpoint:options.type}, function(err, data) { + doCallback(callback, [ err, data, collection], self); }); }; diff --git a/tests/mocha/test.js b/tests/mocha/test.js index fbe1e67..9678a24 100644 --- a/tests/mocha/test.js +++ b/tests/mocha/test.js @@ -108,7 +108,6 @@ describe('Usergrid', function(){ var dogURI=client.clientAppURL + '/dogs' it('should POST to a URI',function(done){ var req=new Usergrid.Request("POST", dogURI, {}, dogData, function(err, response){ - console.error(err, response); assert(!err, err); assert(response instanceof Usergrid.Response, "Response is not and instance of Usergrid.Response"); done(); @@ -316,7 +315,6 @@ describe('Usergrid', function(){ before(function(){ client.logout();}); it('createEntity',function(done){ client.createEntity({type:'dog',name:'createEntityTestDog'}, function(err, response, dog){ - console.warn(err, response, dog); assert(!err, "createEntity returned an error") assert(dog, "createEntity did not return a dog") assert(dog.get("name")==='createEntityTestDog', "The dog's name is not 'createEntityTestDog'") @@ -334,24 +332,6 @@ describe('Usergrid', function(){ } }); }) - var testGroup; - it('createGroup',function(done){ - client.createGroup({path:'dogLovers'},function(err, response, group){ - try{ - assert(!err, "createGroup returned an error") - }catch(e){ - assert(true, "trying to create a group that already exists throws an error"); - }finally{ - done(); - } - /*assert(!err, "createGroup returned an error: "+err); - assert(group, "createGroup did not return a group"); - assert(group instanceof Usergrid.Group, "createGroup did not return a Usergrid.Group"); - testGroup=group; - done();*/ - }) - done(); - }) it('buildAssetURL',function(done){ var assetURL=client.clientAppURL + '/assets/00000000-0000-0000-000000000000/data'; assert(assetURL===client.buildAssetURL('00000000-0000-0000-000000000000'), "buildAssetURL doesn't work") @@ -379,7 +359,7 @@ describe('Usergrid', function(){ }) var dogCollection; it('createCollection',function(done){ - client.createCollection({type:'dogs2s'},function(err, response, dogs){ + client.createCollection({type:'dogs' + Math.floor(Math.random()*10000)},function(err, response, dogs){ assert(!err, "createCollection returned an error"); assert(dogs, "createCollection did not return a dogs collection"); dogCollection=dogs; @@ -568,7 +548,6 @@ describe('Usergrid', function(){ after(function(done){ dogEntity.destroy(); //dogCollection.destroy(); - //testGroup.destroy(); done(); }) }); @@ -1024,10 +1003,11 @@ describe('Usergrid', function(){ }); it('should retrieve asset data', function(done) { this.timeout(5000); - asset.download(function(err, response, asset) { + asset.download(function(err, response, asset1) { if(err){ assert(false, err.error_description); } + assert(err == undefined); assert(asset.get('content-type') == test_image.type, "MIME types don't match"); assert(asset.get('size') == test_image.size, "sizes don't match"); done(); diff --git a/usergrid.js b/usergrid.js index 370b4c1..3cf8de8 100644 --- a/usergrid.js +++ b/usergrid.js @@ -4260,9 +4260,12 @@ function doCallback(callback, params, context) { */ Usergrid.Client.prototype.createCollection = function(options, callback) { options.client = this; - return new Usergrid.Collection(options, function(err, data, collection) { - console.log("createCollection", arguments); - doCallback(callback, [ err, collection, data ]); + var collection = new Usergrid.Collection(options); + this.request({ + method: "POST", + endpoint: options.type + }, function(err, data) { + doCallback(callback, [ err, data, collection ], self); }); }; /* From 570f423a3d3ce4a59671f2820d689011f70b4aad Mon Sep 17 00:00:00 2001 From: Robert Walsh Date: Mon, 19 Sep 2016 17:07:01 -0500 Subject: [PATCH 03/36] Fixing more tests and minor updates. --- lib/modules/Client.js | 15 ++++- tests/test.js | 152 +++++++++++++----------------------------- usergrid.js | 8 ++- 3 files changed, 67 insertions(+), 108 deletions(-) diff --git a/lib/modules/Client.js b/lib/modules/Client.js index fd462db..7276abf 100644 --- a/lib/modules/Client.js +++ b/lib/modules/Client.js @@ -289,11 +289,20 @@ * @param {function} callback * @return {callback} callback(err, data) */ - Usergrid.Client.prototype.createCollection = function (options, callback) { + Usergrid.Client.prototype.createCollection = function(options, callback) { options.client = this; var collection = new Usergrid.Collection(options); - this.request({method: "POST",endpoint:options.type}, function(err, data) { - doCallback(callback, [ err, data, collection], self); + this.request({ + method: "POST", + endpoint: options.type + }, function(err, data) { + if( !err ) { + collection.fetch(function(err,response,collection) { + doCallback(callback, [ err, response, collection ], self); + }) + } else { + doCallback(callback, [ err, data, collection ], self); + } }); }; diff --git a/tests/test.js b/tests/test.js index ee52261..6a9e5b8 100755 --- a/tests/test.js +++ b/tests/test.js @@ -179,10 +179,6 @@ function runner(step, arg, arg2){ destroyUser(step, arg); break; case 31: - notice('-----running step '+step+': try to create existing entity'); - createExistingEntity(step, arg); - break; - case 32: notice('-----running step '+step+': try to create new entity with no name'); createNewEntityNoName(step, arg); break; @@ -311,7 +307,7 @@ function makeNewDog(step) { name:'Rocky' } - client.createEntity(options, function (err, dog) { + client.createEntity(options, function (err, response, dog) { if (err) { error('dog not created'); } else { @@ -332,6 +328,7 @@ function makeNewDog(step) { dog.save(function(err){ if (err){ error('dog not saved'); + runner(step, dog); } else { success('new dog is saved'); runner(step, dog); @@ -422,7 +419,7 @@ function testDogsCollection(step) { qs:{ql:'order by index'} } - client.createCollection(options, function (err, dogs) { + client.createCollection(options, function (err, data, dogs) { if (err) { error('could not make collection'); } else { @@ -527,37 +524,48 @@ function cleanupAllDogs(step){ qs:{limit:50} //limit statement set to 50 } - client.createCollection(options, function (err, dogs) { + client.createCollection(options, function (err, response, dogs) { if (err) { error('could not get all dogs'); } else { success('got at most 50 dogs'); //we got 50 dogs, now display the Entities: - while(dogs.hasNextEntity()) { - //get a reference to the dog - var dog = dogs.getNextEntity(); - var name = dog.get('name'); - notice('dog is called ' + name); - } - dogs.resetEntityPointer(); - //do doggy cleanup - while(dogs.hasNextEntity()) { - //get a reference to the dog - var dog = dogs.getNextEntity(); - var dogname = dog.get('name'); - notice('removing dog ' + dogname + ' from database'); - dog.destroy(function(err, data) { - if (err) { - error('dog not removed'); - } else { - success('dog removed'); - } - }); - } + + do { + while(dogs.hasNextEntity()) { + //get a reference to the dog + var dog = dogs.getNextEntity(); + var name = dog.get('name'); + notice('dog is called ' + name); + } + success('Poop'); + dogs.resetEntityPointer(); + //do doggy cleanup + + while(dogs.hasNextEntity()) { + //get a reference to the dog + var dog = dogs.getNextEntity(); + var dogname = dog.get('name'); + notice('removing dog ' + dogname + ' from database'); + dog.destroy(function(err, data) { + if (err) { + error('dog not removed'); + } else { + success('dog removed'); + } + }); + } + if( !dogs.hasNextPage() ) { + break; + } else { + dogs.getNextPage(function(err,data) {}); + } + } while(true) + //no need to wait around for dogs to be removed, so go on to next test - runner(step); } + runner(step); }); } @@ -582,7 +590,7 @@ function prepareDatabaseForNewUser(step) { function createUser(step) { client.signup(_username, _password, _email, 'Marty McFly', - function (err, marty) { + function (err, response, marty) { if (err){ error('user not created'); runner(step, marty); @@ -616,7 +624,7 @@ function getExistingUser(step, marty) { type:'users', username:_username } - client.getEntity(options, function(err, existingUser){ + client.getEntity(options, function(err, response, existingUser){ if (err){ error('existing user not retrieved'); } else { @@ -686,10 +694,7 @@ function loginUser(step, marty) { } function changeUsersPassword(step, marty) { - - marty.set('oldpassword', _password); - marty.set('newpassword', _newpassword); - marty.save(function(err){ + marty.changePassword(_password, _newpassword, function(err){ if (err){ error('user password not updated'); } else { @@ -719,7 +724,7 @@ function reloginUser(step, marty) { username = _username password = _newpassword; - client.login(username, password, + client.login(_username, _newpassword, function (err) { if (err) { error('could not relog user in'); @@ -749,7 +754,7 @@ function createDog(step, marty) { breed:'mutt' } - client.createEntity(options, function (err, dog) { + client.createEntity(options, function (err, response, dog) { if (err) { error('POST new dog by logged in user failed'); } else { @@ -762,7 +767,7 @@ function createDog(step, marty) { function userLikesDog(step, marty, dog) { - marty.connect('likes', dog, function (err, data) { + marty.connect('likes', dog, function (err, response, data) { if (err) { error('connection not created'); runner(step, marty); @@ -790,14 +795,14 @@ function userLikesDog(step, marty, dog) { function removeUserLikesDog(step, marty, dog) { - marty.disconnect('likes', dog, function (err, data) { + marty.disconnect('likes', dog, function (err, response, data) { if (err) { error('connection not deleted'); runner(step, marty); } else { //call succeeded, so pull the connections back down - marty.getConnections('likes', function (err, data) { + marty.getConnections('likes', function (err, response, data) { if (err) { error('error getting connections'); } else { @@ -831,8 +836,8 @@ function removeDog(step, marty, dog) { function destroyUser(step, marty) { - marty.destroy(function(err){ - if (err){ + marty.destroy(function (err) { + if (err) { error('user not deleted from database'); } else { success('user deleted from database'); @@ -843,67 +848,6 @@ function destroyUser(step, marty) { } -function createExistingEntity(step, marty) { - - var options = { - type:'dogs', - name:'einstein' - } - - client.createEntity(options, function (err, dog) { - if (err) { - error('Create new entity to use for existing entity failed'); - } else { - success('Create new entity to use for existing entity succeeded'); - - var uuid = dog.get('uuid'); - //now create new entity, but use same entity name of einstein. This means that - //the original einstein entity now exists. Thus, the new einstein entity should - //be the same as the original + any data differences from the options var: - - options = { - type:'dogs', - name:'einstein', - breed:'mutt' - } - client.createEntity(options, function (err, newdog) { - if (err) { - error('Create new entity to use for existing entity failed'); - } else { - success('Create new entity to use for existing entity succeeded'); - - var newuuid = newdog.get('uuid'); - if (newuuid === uuid) { - success('UUIDs of new and old entities match'); - } else { - error('UUIDs of new and old entities do not match'); - } - - var breed = newdog.get('breed'); - if (breed === 'mutt') { - success('attribute sucesfully set on new entity'); - } else { - error('attribute not sucesfully set on new entity'); - } - - newdog.destroy(function(err){ - if (err){ - error('existing entity not deleted from database'); - } else { - success('existing entity deleted from database'); - dog = null; //blow away the local object - newdog = null; //blow away the local object - runner(step); - } - }); - - } - }); - } - }); - -} - function createNewEntityNoName(step, marty) { var options = { @@ -911,7 +855,7 @@ function createNewEntityNoName(step, marty) { othervalue:"something else" } - client.createEntity(options, function (err, entity) { + client.createEntity(options, function (err, response, entity) { if (err) { error('Create new entity with no name failed'); } else { diff --git a/usergrid.js b/usergrid.js index 3cf8de8..b19e1e4 100644 --- a/usergrid.js +++ b/usergrid.js @@ -4265,7 +4265,13 @@ function doCallback(callback, params, context) { method: "POST", endpoint: options.type }, function(err, data) { - doCallback(callback, [ err, data, collection ], self); + if (!err) { + collection.fetch(function(err, response, collection) { + doCallback(callback, [ err, response, collection ], self); + }); + } else { + doCallback(callback, [ err, data, collection ], self); + } }); }; /* From c8039ffe5bbb00a39978db6851e1db9fd7907db5 Mon Sep 17 00:00:00 2001 From: Robert Walsh Date: Tue, 20 Sep 2016 15:41:09 -0500 Subject: [PATCH 04/36] Updates --- Gruntfile.js | 11 +- lib/Usergrid.js | 17 +- lib/modules/Auth.js | 96 + lib/modules/Client.js | 34 +- lib/modules/Enums.js | 30 + lib/modules/util/Helpers.js | 37 + lib/modules/util/lodash.core.js | 3839 ------- lib/modules/util/lodash.js | 16895 ++++++++++++++++++++++++++++ tests/mocha/test.js | 13 +- usergrid.js | 18110 +++++++++++++++++++++++++----- 10 files changed, 32130 insertions(+), 6952 deletions(-) create mode 100644 lib/modules/Auth.js create mode 100644 lib/modules/Enums.js create mode 100644 lib/modules/util/Helpers.js delete mode 100644 lib/modules/util/lodash.core.js create mode 100644 lib/modules/util/lodash.js diff --git a/Gruntfile.js b/Gruntfile.js index 5cfaf62..5911e6b 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -1,20 +1,23 @@ module.exports = function(grunt) { var files = [ + "lib/modules/Enums.js", "lib/modules/util/Event.js", "lib/modules/util/Logger.js", "lib/modules/util/Promise.js", "lib/modules/util/Ajax.js", - "lib/modules/util/lodash.core.js", + "lib/modules/util/lodash.js", + "lib/modules/util/Helpers.js", "lib/Usergrid.js", - "lib/modules/Client.js", + "lib/modules/Client.js", "lib/modules/Entity.js", "lib/modules/Collection.js", "lib/modules/Group.js", "lib/modules/Counter.js", "lib/modules/Folder.js", "lib/modules/Asset.js", - "lib/modules/Error.js" - ]; + "lib/modules/Error.js", + "lib/modules/Auth.js" + ]; var tests = ["tests/mocha/index.html", "tests/mocha/test_*.html"]; // Project configuration. grunt.initConfig({ diff --git a/lib/Usergrid.js b/lib/Usergrid.js index f1bb218..8871a03 100644 --- a/lib/Usergrid.js +++ b/lib/Usergrid.js @@ -21,7 +21,6 @@ window.console = window.console || {}; window.console.log = window.console.log || function() {}; - function extend(subClass, superClass) { var F = function() {}; F.prototype = superClass.prototype; @@ -176,11 +175,27 @@ function doCallback(callback, params, context) { var name = 'Usergrid', overwrittenName = global[name]; var VALID_REQUEST_METHODS = ['GET', 'POST', 'PUT', 'DELETE']; + var __sharedInstance; + var isInitialized = false function Usergrid() { this.logger = new Logger(name); } + Usergrid.initSharedInstance = function(options) { + console.warn("TRYING TO INITIALIZING SHARED INSTANCE") + if( !this.isInitialized ) { + console.warn("INITIALIZING SHARED INSTANCE") + this.__sharedInstance = new Usergrid.Client(options) + this.isInitialized = true + } + return this.__sharedInstance + } + + Usergrid.getInstance = function () { + return this.__sharedInstance + } + Usergrid.isValidEndpoint = function(endpoint) { //TODO actually implement this return true; diff --git a/lib/modules/Auth.js b/lib/modules/Auth.js new file mode 100644 index 0000000..d202a5c --- /dev/null +++ b/lib/modules/Auth.js @@ -0,0 +1,96 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +'use strict' + +var UsergridAuth = function(token, expiry) { + var self = this + + self.token = token + self.expiry = expiry || 0 + + var usingToken = (token) ? true : false + + Object.defineProperty(self, "hasToken", { + get: function() { + return (self.token) ? true : false + }, + configurable: true + }) + + Object.defineProperty(self, "isExpired", { + get: function() { + return (usingToken) ? false : (Date.now() >= self.expiry) + }, + configurable: true + }) + + Object.defineProperty(self, "isValid", { + get: function() { + return (!self.isExpired && self.hasToken) + }, + configurable: true + }) + + Object.defineProperty(self, 'tokenTtl', { + configurable: true, + writable: true + }) + + return self +} + +UsergridAuth.prototype = { + destroy: function () { + this.token = undefined + this.expiry = 0 + this.tokenTtl = undefined + } +} + +var UsergridAppAuth = function() { + var self = this + var args = flattenArgs(arguments) + if (_.isPlainObject(args[0])) { + self.clientId = args[0].clientId + self.clientSecret = args[0].clientSecret + self.tokenTtl = args[0].tokenTtl + } else { + self.clientId = args[0] + self.clientSecret = args[1] + self.tokenTtl = args[2] + } + UsergridAuth.call(self) + _.assign(self, UsergridAuth) + return self +} +inherits(UsergridAppAuth,UsergridAuth) + +var UsergridUserAuth = function() { + var self = this + var args = flattenArgs(arguments) + if (_.isPlainObject(args[0])) { + options = args[0] + } + self.username = options.username || args[0] + self.email = options.email + if (options.password || args[1]) { + self.password = options.password || args[1] + } + self.tokenTtl = options.tokenTtl || args[2] + UsergridAuth.call(self) + _.assign(self, UsergridAuth) + return self +} +inherits(UsergridUserAuth,UsergridAuth) diff --git a/lib/modules/Client.js b/lib/modules/Client.js index 7276abf..211742a 100644 --- a/lib/modules/Client.js +++ b/lib/modules/Client.js @@ -16,6 +16,12 @@ *specific language governing permissions and limitations *under the License. */ + +var defaultOptions = { + baseUrl: 'https://api.usergrid.com', + authMode: UsergridAuthMode.USER +}; + (function() { var name = 'Client', global = this, @@ -29,21 +35,33 @@ "unauthorized", "auth_invalid" ]; - var defaultOptions = { - baseUrl: 'https://api.usergrid.com' - }; + Usergrid.Client = function(options) { + var self = this if (!options.orgId || !options.appId) { throw new Error('"orgId" and "appId" parameters are required when instantiating UsergridClient') } _.defaults(this,options,defaultOptions); - this.clientAppURL = [this.baseUrl, this.orgId, this.appId].join("/"); - this.isSharedInstance = false; - this.currentUser = undefined; - this.appAuth = undefined; + self.clientAppURL = [self.baseUrl, self.orgId, self.appId].join("/"); + self.isSharedInstance = false; + self.currentUser = undefined; + + self.__appAuth = undefined; + Object.defineProperty(self, 'appAuth', { + get: function() { + return self.__appAuth + }, + set: function(options) { + if (options instanceof UsergridAppAuth) { + self.__appAuth = options + } else if (typeof options !== "undefined") { + self.__appAuth = new UsergridAppAuth(options) + } + } + }) + this.userAuth = undefined; - this.authMode = undefined; if (options.qs) { this.setObject('default_qs', options.qs); diff --git a/lib/modules/Enums.js b/lib/modules/Enums.js new file mode 100644 index 0000000..786e2a5 --- /dev/null +++ b/lib/modules/Enums.js @@ -0,0 +1,30 @@ +var UsergridAuthMode = Object.freeze({ + NONE: "none", + USER: "user", + APP: "app" +}); + +var UsergridDirection = Object.freeze({ + IN: "connecting", + OUT: "connections" +}); + +var UsergridHttpMethod = Object.freeze({ + GET: "GET", + PUT: "PUT", + POST: "POST", + DELETE: "DELETE" +}); + +var UsergridQueryOperator = Object.freeze({ + EQUAL: "=", + GREATER_THAN: ">", + GREATER_THAN_EQUAL_TO: ">=", + LESS_THAN: "<", + LESS_THAN_EQUAL_TO: "<=" +}); + +var UsergridQuerySortOrder = Object.freeze({ + ASC: "asc", + DESC: "desc" +}); diff --git a/lib/modules/util/Helpers.js b/lib/modules/util/Helpers.js new file mode 100644 index 0000000..2e1fe04 --- /dev/null +++ b/lib/modules/util/Helpers.js @@ -0,0 +1,37 @@ + +function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); +} + +function flattenArgs(args) { + return _.flattenDeep(Array.prototype.slice.call(args)) +} + +function validateAndRetrieveClient(args) { + var client = undefined; + if (args instanceof UsergridClient) { client = args } + else if (args[0] instanceof UsergridClient) { client = args[0] } + else if (Usergrid.isInitialized) { client = Usergrid.getInstance() } + else { throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument") } + return client +} + +function configureTempAuth(auth) { + if (_.isString(auth) && auth !== UsergridAuthMode.NONE) { + return new UsergridAuth(auth) + } else if (!auth || auth === UsergridAuthMode.NONE) { + return undefined + } else if (auth instanceof UsergridAuth) { + return auth + } else { + return undefined + } +} diff --git a/lib/modules/util/lodash.core.js b/lib/modules/util/lodash.core.js deleted file mode 100644 index 7b24967..0000000 --- a/lib/modules/util/lodash.core.js +++ /dev/null @@ -1,3839 +0,0 @@ -/** - * @license - * lodash (Custom Build) - * Build: `lodash core -o ./dist/lodash.core.js` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ -;(function() { - - /** Used as a safe reference for `undefined` in pre-ES5 environments. */ - var undefined; - - /** Used as the semantic version number. */ - var VERSION = '4.16.0'; - - /** Used as the `TypeError` message for "Functions" methods. */ - var FUNC_ERROR_TEXT = 'Expected a function'; - - /** Used to compose bitmasks for function metadata. */ - var BIND_FLAG = 1, - PARTIAL_FLAG = 32; - - /** Used to compose bitmasks for comparison styles. */ - var UNORDERED_COMPARE_FLAG = 1, - PARTIAL_COMPARE_FLAG = 2; - - /** Used as references for various `Number` constants. */ - var INFINITY = 1 / 0, - MAX_SAFE_INTEGER = 9007199254740991; - - /** `Object#toString` result references. */ - var argsTag = '[object Arguments]', - arrayTag = '[object Array]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - errorTag = '[object Error]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - numberTag = '[object Number]', - objectTag = '[object Object]', - regexpTag = '[object RegExp]', - stringTag = '[object String]'; - - /** Used to match HTML entities and HTML characters. */ - var reUnescapedHtml = /[&<>"'`]/g, - reHasUnescapedHtml = RegExp(reUnescapedHtml.source); - - /** Used to map characters to HTML entities. */ - var htmlEscapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - "'": ''' - }; - - /** Detect free variable `global` from Node.js. */ - var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; - - /** Detect free variable `self`. */ - var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - - /** Used as a reference to the global object. */ - var root = freeGlobal || freeSelf || Function('return this')(); - - /** Detect free variable `exports`. */ - var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; - - /*--------------------------------------------------------------------------*/ - - /** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ - function arrayPush(array, values) { - array.push.apply(array, values); - return array; - } - - /** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); - - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; - } - - /** - * The base implementation of `_.property` without support for deep paths. - * - * @private - * @param {string} key The key of the property to get. - * @returns {Function} Returns the new accessor function. - */ - function baseProperty(key) { - return function(object) { - return object == null ? undefined : object[key]; - }; - } - - /** - * The base implementation of `_.propertyOf` without support for deep paths. - * - * @private - * @param {Object} object The object to query. - * @returns {Function} Returns the new accessor function. - */ - function basePropertyOf(object) { - return function(key) { - return object == null ? undefined : object[key]; - }; - } - - /** - * The base implementation of `_.reduce` and `_.reduceRight`, without support - * for iteratee shorthands, which iterates over `collection` using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} accumulator The initial value. - * @param {boolean} initAccum Specify using the first or last element of - * `collection` as the initial value. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the accumulated value. - */ - function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { - eachFunc(collection, function(value, index, collection) { - accumulator = initAccum - ? (initAccum = false, value) - : iteratee(accumulator, value, index, collection); - }); - return accumulator; - } - - /** - * The base implementation of `_.values` and `_.valuesIn` which creates an - * array of `object` property values corresponding to the property names - * of `props`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} props The property names to get values for. - * @returns {Object} Returns the array of property values. - */ - function baseValues(object, props) { - return baseMap(props, function(key) { - return object[key]; - }); - } - - /** - * Used by `_.escape` to convert characters to HTML entities. - * - * @private - * @param {string} chr The matched character to escape. - * @returns {string} Returns the escaped character. - */ - var escapeHtmlChar = basePropertyOf(htmlEscapes); - - /** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } - - /*--------------------------------------------------------------------------*/ - - /** Used for built-in method references. */ - var arrayProto = Array.prototype, - objectProto = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; - - /** Used to generate unique IDs. */ - var idCounter = 0; - - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - var objectToString = objectProto.toString; - - /** Used to restore the original `_` reference in `_.noConflict`. */ - var oldDash = root._; - - /** Built-in value references. */ - var objectCreate = Object.create, - propertyIsEnumerable = objectProto.propertyIsEnumerable; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeIsFinite = root.isFinite, - nativeKeys = overArg(Object.keys, Object), - nativeMax = Math.max; - - /*------------------------------------------------------------------------*/ - - /** - * Creates a `lodash` object which wraps `value` to enable implicit method - * chain sequences. Methods that operate on and return arrays, collections, - * and functions can be chained together. Methods that retrieve a single value - * or may return a primitive value will automatically end the chain sequence - * and return the unwrapped value. Otherwise, the value must be unwrapped - * with `_#value`. - * - * Explicit chain sequences, which must be unwrapped with `_#value`, may be - * enabled using `_.chain`. - * - * The execution of chained methods is lazy, that is, it's deferred until - * `_#value` is implicitly or explicitly called. - * - * Lazy evaluation allows several methods to support shortcut fusion. - * Shortcut fusion is an optimization to merge iteratee calls; this avoids - * the creation of intermediate arrays and can greatly reduce the number of - * iteratee executions. Sections of a chain sequence qualify for shortcut - * fusion if the section is applied to an array of at least `200` elements - * and any iteratees accept only one argument. The heuristic for whether a - * section qualifies for shortcut fusion is subject to change. - * - * Chaining is supported in custom builds as long as the `_#value` method is - * directly or indirectly included in the build. - * - * In addition to lodash methods, wrappers have `Array` and `String` methods. - * - * The wrapper `Array` methods are: - * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` - * - * The wrapper `String` methods are: - * `replace` and `split` - * - * The wrapper methods that support shortcut fusion are: - * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, - * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, - * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` - * - * The chainable wrapper methods are: - * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, - * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, - * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, - * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, - * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, - * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, - * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, - * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, - * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, - * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, - * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, - * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, - * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, - * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, - * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, - * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, - * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, - * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, - * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, - * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, - * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, - * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, - * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, - * `zipObject`, `zipObjectDeep`, and `zipWith` - * - * The wrapper methods that are **not** chainable by default are: - * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, - * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, - * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, - * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, - * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, - * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, - * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, - * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, - * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, - * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, - * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, - * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, - * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, - * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, - * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, - * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, - * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, - * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, - * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, - * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, - * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, - * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, - * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, - * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, - * `upperFirst`, `value`, and `words` - * - * @name _ - * @constructor - * @category Seq - * @param {*} value The value to wrap in a `lodash` instance. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * function square(n) { - * return n * n; - * } - * - * var wrapped = _([1, 2, 3]); - * - * // Returns an unwrapped value. - * wrapped.reduce(_.add); - * // => 6 - * - * // Returns a wrapped value. - * var squares = wrapped.map(square); - * - * _.isArray(squares); - * // => false - * - * _.isArray(squares.value()); - * // => true - */ - function lodash(value) { - return value instanceof LodashWrapper - ? value - : new LodashWrapper(value); - } - - /** - * The base constructor for creating `lodash` wrapper objects. - * - * @private - * @param {*} value The value to wrap. - * @param {boolean} [chainAll] Enable explicit method chain sequences. - */ - function LodashWrapper(value, chainAll) { - this.__wrapped__ = value; - this.__actions__ = []; - this.__chain__ = !!chainAll; - } - - LodashWrapper.prototype = baseCreate(lodash.prototype); - LodashWrapper.prototype.constructor = LodashWrapper; - - /*------------------------------------------------------------------------*/ - - /** - * Used by `_.defaults` to customize its `_.assignIn` use. - * - * @private - * @param {*} objValue The destination value. - * @param {*} srcValue The source value. - * @param {string} key The key of the property to assign. - * @param {Object} object The parent object of `objValue`. - * @returns {*} Returns the value to assign. - */ - function assignInDefaults(objValue, srcValue, key, object) { - if (objValue === undefined || - (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { - return srcValue; - } - return objValue; - } - - /** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } - } - - /** - * The base implementation of `assignValue` and `assignMergeValue` without - * value checks. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function baseAssignValue(object, key, value) { - object[key] = value; - } - - /** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} prototype The object to inherit from. - * @returns {Object} Returns the new object. - */ - function baseCreate(proto) { - return isObject(proto) ? objectCreate(proto) : {}; - } - - /** - * The base implementation of `_.delay` and `_.defer` which accepts `args` - * to provide to `func`. - * - * @private - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @param {Array} args The arguments to provide to `func`. - * @returns {number|Object} Returns the timer id or timeout object. - */ - function baseDelay(func, wait, args) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - return setTimeout(function() { func.apply(undefined, args); }, wait); - } - - /** - * The base implementation of `_.forEach` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - */ - var baseEach = createBaseEach(baseForOwn); - - /** - * The base implementation of `_.every` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false` - */ - function baseEvery(collection, predicate) { - var result = true; - baseEach(collection, function(value, index, collection) { - result = !!predicate(value, index, collection); - return result; - }); - return result; - } - - /** - * The base implementation of methods like `_.max` and `_.min` which accepts a - * `comparator` to determine the extremum value. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The iteratee invoked per iteration. - * @param {Function} comparator The comparator used to compare values. - * @returns {*} Returns the extremum value. - */ - function baseExtremum(array, iteratee, comparator) { - var index = -1, - length = array.length; - - while (++index < length) { - var value = array[index], - current = iteratee(value); - - if (current != null && (computed === undefined - ? (current === current && !false) - : comparator(current, computed) - )) { - var computed = current, - result = value; - } - } - return result; - } - - /** - * The base implementation of `_.filter` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ - function baseFilter(collection, predicate) { - var result = []; - baseEach(collection, function(value, index, collection) { - if (predicate(value, index, collection)) { - result.push(value); - } - }); - return result; - } - - /** - * The base implementation of `_.flatten` with support for restricting flattening. - * - * @private - * @param {Array} array The array to flatten. - * @param {number} depth The maximum recursion depth. - * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. - * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. - * @param {Array} [result=[]] The initial result value. - * @returns {Array} Returns the new flattened array. - */ - function baseFlatten(array, depth, predicate, isStrict, result) { - var index = -1, - length = array.length; - - predicate || (predicate = isFlattenable); - result || (result = []); - - while (++index < length) { - var value = array[index]; - if (depth > 0 && predicate(value)) { - if (depth > 1) { - // Recursively flatten arrays (susceptible to call stack limits). - baseFlatten(value, depth - 1, predicate, isStrict, result); - } else { - arrayPush(result, value); - } - } else if (!isStrict) { - result[result.length] = value; - } - } - return result; - } - - /** - * The base implementation of `baseForOwn` which iterates over `object` - * properties returned by `keysFunc` and invokes `iteratee` for each property. - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ - var baseFor = createBaseFor(); - - /** - * The base implementation of `_.forOwn` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ - function baseForOwn(object, iteratee) { - return object && baseFor(object, iteratee, keys); - } - - /** - * The base implementation of `_.functions` which creates an array of - * `object` function property names filtered from `props`. - * - * @private - * @param {Object} object The object to inspect. - * @param {Array} props The property names to filter. - * @returns {Array} Returns the function names. - */ - function baseFunctions(object, props) { - return baseFilter(props, function(key) { - return isFunction(object[key]); - }); - } - - /** - * The base implementation of `_.gt` which doesn't coerce arguments. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than `other`, - * else `false`. - */ - function baseGt(value, other) { - return value > other; - } - - /** - * The base implementation of `_.isDate` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a date object, else `false`. - */ - function baseIsDate(value) { - return isObjectLike(value) && objectToString.call(value) == dateTag; - } - - /** - * The base implementation of `_.isEqual` which supports partial comparisons - * and tracks traversed objects. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {Function} [customizer] The function to customize comparisons. - * @param {boolean} [bitmask] The bitmask of comparison flags. - * The bitmask may be composed of the following flags: - * 1 - Unordered comparison - * 2 - Partial comparison - * @param {Object} [stack] Tracks traversed `value` and `other` objects. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - */ - function baseIsEqual(value, other, customizer, bitmask, stack) { - if (value === other) { - return true; - } - if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) { - return value !== value && other !== other; - } - return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack); - } - - /** - * A specialized version of `baseIsEqual` for arrays and objects which performs - * deep comparisons and tracks traversed objects enabling objects with circular - * references to be compared. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Function} [customizer] The function to customize comparisons. - * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual` - * for more details. - * @param {Object} [stack] Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) { - var objIsArr = isArray(object), - othIsArr = isArray(other), - objTag = arrayTag, - othTag = arrayTag; - - if (!objIsArr) { - objTag = objectToString.call(object); - objTag = objTag == argsTag ? objectTag : objTag; - } - if (!othIsArr) { - othTag = objectToString.call(other); - othTag = othTag == argsTag ? objectTag : othTag; - } - var objIsObj = objTag == objectTag, - othIsObj = othTag == objectTag, - isSameTag = objTag == othTag; - - stack || (stack = []); - var objStack = find(stack, function(entry) { - return entry[0] == object; - }); - var othStack = find(stack, function(entry) { - return entry[0] == other; - }); - if (objStack && othStack) { - return objStack[1] == other; - } - stack.push([object, other]); - stack.push([other, object]); - if (isSameTag && !objIsObj) { - var result = (objIsArr) - ? equalArrays(object, other, equalFunc, customizer, bitmask, stack) - : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack); - stack.pop(); - return result; - } - if (!(bitmask & PARTIAL_COMPARE_FLAG)) { - var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), - othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); - - if (objIsWrapped || othIsWrapped) { - var objUnwrapped = objIsWrapped ? object.value() : object, - othUnwrapped = othIsWrapped ? other.value() : other; - - var result = equalFunc(objUnwrapped, othUnwrapped, customizer, bitmask, stack); - stack.pop(); - return result; - } - } - if (!isSameTag) { - return false; - } - var result = equalObjects(object, other, equalFunc, customizer, bitmask, stack); - stack.pop(); - return result; - } - - /** - * The base implementation of `_.isRegExp` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. - */ - function baseIsRegExp(value) { - return isObject(value) && objectToString.call(value) == regexpTag; - } - - /** - * The base implementation of `_.iteratee`. - * - * @private - * @param {*} [value=_.identity] The value to convert to an iteratee. - * @returns {Function} Returns the iteratee. - */ - function baseIteratee(func) { - if (typeof func == 'function') { - return func; - } - if (func == null) { - return identity; - } - return (typeof func == 'object' ? baseMatches : baseProperty)(func); - } - - /** - * The base implementation of `_.lt` which doesn't coerce arguments. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than `other`, - * else `false`. - */ - function baseLt(value, other) { - return value < other; - } - - /** - * The base implementation of `_.map` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ - function baseMap(collection, iteratee) { - var index = -1, - result = isArrayLike(collection) ? Array(collection.length) : []; - - baseEach(collection, function(value, key, collection) { - result[++index] = iteratee(value, key, collection); - }); - return result; - } - - /** - * The base implementation of `_.matches` which doesn't clone `source`. - * - * @private - * @param {Object} source The object of property values to match. - * @returns {Function} Returns the new spec function. - */ - function baseMatches(source) { - var props = nativeKeys(source); - return function(object) { - var length = props.length; - if (object == null) { - return !length; - } - object = Object(object); - while (length--) { - var key = props[length]; - if (!(key in object && - baseIsEqual(source[key], object[key], undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG) - )) { - return false; - } - } - return true; - }; - } - - /** - * The base implementation of `_.pick` without support for individual - * property identifiers. - * - * @private - * @param {Object} object The source object. - * @param {string[]} props The property identifiers to pick. - * @returns {Object} Returns the new object. - */ - function basePick(object, props) { - object = Object(object); - return reduce(props, function(result, key) { - if (key in object) { - result[key] = object[key]; - } - return result; - }, {}); - } - - /** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ - function baseRest(func, start) { - return setToString(overRest(func, start, identity), func + ''); - } - - /** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ - function baseSlice(array, start, end) { - var index = -1, - length = array.length; - - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; - - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; - } - - /** - * Copies the values of `source` to `array`. - * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. - */ - function copyArray(source) { - return baseSlice(source, 0, source.length); - } - - /** - * The base implementation of `_.some` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ - function baseSome(collection, predicate) { - var result; - - baseEach(collection, function(value, index, collection) { - result = predicate(value, index, collection); - return !result; - }); - return !!result; - } - - /** - * The base implementation of `wrapperValue` which returns the result of - * performing a sequence of actions on the unwrapped `value`, where each - * successive action is supplied the return value of the previous. - * - * @private - * @param {*} value The unwrapped value. - * @param {Array} actions Actions to perform to resolve the unwrapped value. - * @returns {*} Returns the resolved value. - */ - function baseWrapperValue(value, actions) { - var result = value; - return reduce(actions, function(result, action) { - return action.func.apply(action.thisArg, arrayPush([result], action.args)); - }, result); - } - - /** - * Compares values to sort them in ascending order. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {number} Returns the sort order indicator for `value`. - */ - function compareAscending(value, other) { - if (value !== other) { - var valIsDefined = value !== undefined, - valIsNull = value === null, - valIsReflexive = value === value, - valIsSymbol = false; - - var othIsDefined = other !== undefined, - othIsNull = other === null, - othIsReflexive = other === other, - othIsSymbol = false; - - if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || - (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || - (valIsNull && othIsDefined && othIsReflexive) || - (!valIsDefined && othIsReflexive) || - !valIsReflexive) { - return 1; - } - if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || - (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || - (othIsNull && valIsDefined && valIsReflexive) || - (!othIsDefined && valIsReflexive) || - !othIsReflexive) { - return -1; - } - } - return 0; - } - - /** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ - function copyObject(source, props, object, customizer) { - var isNew = !object; - object || (object = {}); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; - - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; - - if (newValue === undefined) { - newValue = source[key]; - } - if (isNew) { - baseAssignValue(object, key, newValue); - } else { - assignValue(object, key, newValue); - } - } - return object; - } - - /** - * Creates a function like `_.assign`. - * - * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. - */ - function createAssigner(assigner) { - return baseRest(function(object, sources) { - var index = -1, - length = sources.length, - customizer = length > 1 ? sources[length - 1] : undefined; - - customizer = (assigner.length > 3 && typeof customizer == 'function') - ? (length--, customizer) - : undefined; - - object = Object(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); - } - } - return object; - }); - } - - /** - * Creates a `baseEach` or `baseEachRight` function. - * - * @private - * @param {Function} eachFunc The function to iterate over a collection. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ - function createBaseEach(eachFunc, fromRight) { - return function(collection, iteratee) { - if (collection == null) { - return collection; - } - if (!isArrayLike(collection)) { - return eachFunc(collection, iteratee); - } - var length = collection.length, - index = fromRight ? length : -1, - iterable = Object(collection); - - while ((fromRight ? index-- : ++index < length)) { - if (iteratee(iterable[index], index, iterable) === false) { - break; - } - } - return collection; - }; - } - - /** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ - function createBaseFor(fromRight) { - return function(object, iteratee, keysFunc) { - var index = -1, - iterable = Object(object), - props = keysFunc(object), - length = props.length; - - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; - } - - /** - * Creates a function that produces an instance of `Ctor` regardless of - * whether it was invoked as part of a `new` expression or by `call` or `apply`. - * - * @private - * @param {Function} Ctor The constructor to wrap. - * @returns {Function} Returns the new wrapped function. - */ - function createCtor(Ctor) { - return function() { - // Use a `switch` statement to work with class constructors. See - // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist - // for more details. - var args = arguments; - var thisBinding = baseCreate(Ctor.prototype), - result = Ctor.apply(thisBinding, args); - - // Mimic the constructor's `return` behavior. - // See https://es5.github.io/#x13.2.2 for more details. - return isObject(result) ? result : thisBinding; - }; - } - - /** - * Creates a `_.find` or `_.findLast` function. - * - * @private - * @param {Function} findIndexFunc The function to find the collection index. - * @returns {Function} Returns the new find function. - */ - function createFind(findIndexFunc) { - return function(collection, predicate, fromIndex) { - var iterable = Object(collection); - if (!isArrayLike(collection)) { - var iteratee = baseIteratee(predicate, 3); - collection = keys(collection); - predicate = function(key) { return iteratee(iterable[key], key, iterable); }; - } - var index = findIndexFunc(collection, predicate, fromIndex); - return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; - }; - } - - /** - * Creates a function that wraps `func` to invoke it with the `this` binding - * of `thisArg` and `partials` prepended to the arguments it receives. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} partials The arguments to prepend to those provided to - * the new function. - * @returns {Function} Returns the new wrapped function. - */ - function createPartial(func, bitmask, thisArg, partials) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - var isBind = bitmask & BIND_FLAG, - Ctor = createCtor(func); - - function wrapper() { - var argsIndex = -1, - argsLength = arguments.length, - leftIndex = -1, - leftLength = partials.length, - args = Array(leftLength + argsLength), - fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - - while (++leftIndex < leftLength) { - args[leftIndex] = partials[leftIndex]; - } - while (argsLength--) { - args[leftIndex++] = arguments[++argsIndex]; - } - return fn.apply(isBind ? thisArg : this, args); - } - return wrapper; - } - - /** - * A specialized version of `baseIsEqualDeep` for arrays with support for - * partial deep comparisons. - * - * @private - * @param {Array} array The array to compare. - * @param {Array} other The other array to compare. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Function} customizer The function to customize comparisons. - * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` - * for more details. - * @param {Object} stack Tracks traversed `array` and `other` objects. - * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. - */ - function equalArrays(array, other, equalFunc, customizer, bitmask, stack) { - var isPartial = bitmask & PARTIAL_COMPARE_FLAG, - arrLength = array.length, - othLength = other.length; - - if (arrLength != othLength && !(isPartial && othLength > arrLength)) { - return false; - } - var index = -1, - result = true, - seen = (bitmask & UNORDERED_COMPARE_FLAG) ? [] : undefined; - - // Ignore non-index properties. - while (++index < arrLength) { - var arrValue = array[index], - othValue = other[index]; - - var compared; - if (compared !== undefined) { - if (compared) { - continue; - } - result = false; - break; - } - // Recursively compare arrays (susceptible to call stack limits). - if (seen) { - if (!baseSome(other, function(othValue, othIndex) { - if (!indexOf(seen, othIndex) && - (arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) { - return seen.push(othIndex); - } - })) { - result = false; - break; - } - } else if (!( - arrValue === othValue || - equalFunc(arrValue, othValue, customizer, bitmask, stack) - )) { - result = false; - break; - } - } - return result; - } - - /** - * A specialized version of `baseIsEqualDeep` for comparing objects of - * the same `toStringTag`. - * - * **Note:** This function only supports comparing values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {string} tag The `toStringTag` of the objects to compare. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Function} customizer The function to customize comparisons. - * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` - * for more details. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) { - switch (tag) { - - case boolTag: - case dateTag: - case numberTag: - // Coerce booleans to `1` or `0` and dates to milliseconds. - // Invalid dates are coerced to `NaN`. - return eq(+object, +other); - - case errorTag: - return object.name == other.name && object.message == other.message; - - case regexpTag: - case stringTag: - // Coerce regexes to strings and treat strings, primitives and objects, - // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring - // for more details. - return object == (other + ''); - - } - return false; - } - - /** - * A specialized version of `baseIsEqualDeep` for objects with support for - * partial deep comparisons. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Function} customizer The function to customize comparisons. - * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` - * for more details. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalObjects(object, other, equalFunc, customizer, bitmask, stack) { - var isPartial = bitmask & PARTIAL_COMPARE_FLAG, - objProps = keys(object), - objLength = objProps.length, - othProps = keys(other), - othLength = othProps.length; - - if (objLength != othLength && !isPartial) { - return false; - } - var index = objLength; - while (index--) { - var key = objProps[index]; - if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { - return false; - } - } - var result = true; - - var skipCtor = isPartial; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], - othValue = other[key]; - - var compared; - // Recursively compare objects (susceptible to call stack limits). - if (!(compared === undefined - ? (objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack)) - : compared - )) { - result = false; - break; - } - skipCtor || (skipCtor = key == 'constructor'); - } - if (result && !skipCtor) { - var objCtor = object.constructor, - othCtor = other.constructor; - - // Non `Object` object instances with different constructors are not equal. - if (objCtor != othCtor && - ('constructor' in object && 'constructor' in other) && - !(typeof objCtor == 'function' && objCtor instanceof objCtor && - typeof othCtor == 'function' && othCtor instanceof othCtor)) { - result = false; - } - } - return result; - } - - /** - * A specialized version of `baseRest` which flattens the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @returns {Function} Returns the new function. - */ - function flatRest(func) { - return setToString(overRest(func, undefined, flatten), func + ''); - } - - /** - * Checks if `value` is a flattenable `arguments` object or array. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. - */ - function isFlattenable(value) { - return isArray(value) || isArguments(value); - } - - /** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function nativeKeysIn(object) { - var result = []; - if (object != null) { - for (var key in Object(object)) { - result.push(key); - } - } - return result; - } - - /** - * A specialized version of `baseRest` which transforms the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @param {Function} transform The rest array transform. - * @returns {Function} Returns the new function. - */ - function overRest(func, start, transform) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); - - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = transform(array); - return func.apply(this, otherArgs); - }; - } - - /** - * Sets the `toString` method of `func` to return `string`. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var setToString = identity; - - /** - * Converts `value` to a string key if it's not a string or symbol. - * - * @private - * @param {*} value The value to inspect. - * @returns {string|symbol} Returns the key. - */ - var toKey = String; - - /*------------------------------------------------------------------------*/ - - /** - * Creates an array with all falsey values removed. The values `false`, `null`, - * `0`, `""`, `undefined`, and `NaN` are falsey. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to compact. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * _.compact([0, 1, false, 2, '', 3]); - * // => [1, 2, 3] - */ - function compact(array) { - return baseFilter(array, Boolean); - } - - /** - * Creates a new array concatenating `array` with any additional arrays - * and/or values. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to concatenate. - * @param {...*} [values] The values to concatenate. - * @returns {Array} Returns the new concatenated array. - * @example - * - * var array = [1]; - * var other = _.concat(array, 2, [3], [[4]]); - * - * console.log(other); - * // => [1, 2, 3, [4]] - * - * console.log(array); - * // => [1] - */ - function concat() { - var length = arguments.length; - if (!length) { - return []; - } - var args = Array(length - 1), - array = arguments[0], - index = length; - - while (index--) { - args[index - 1] = arguments[index]; - } - return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); - } - - /** - * This method is like `_.find` except that it returns the index of the first - * element `predicate` returns truthy for instead of the element itself. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [predicate=_.identity] - * The function invoked per iteration. - * @param {number} [fromIndex=0] The index to search from. - * @returns {number} Returns the index of the found element, else `-1`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.findIndex(users, function(o) { return o.user == 'barney'; }); - * // => 0 - * - * // The `_.matches` iteratee shorthand. - * _.findIndex(users, { 'user': 'fred', 'active': false }); - * // => 1 - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findIndex(users, ['active', false]); - * // => 0 - * - * // The `_.property` iteratee shorthand. - * _.findIndex(users, 'active'); - * // => 2 - */ - function findIndex(array, predicate, fromIndex) { - var length = array ? array.length : 0; - if (!length) { - return -1; - } - var index = fromIndex == null ? 0 : toInteger(fromIndex); - if (index < 0) { - index = nativeMax(length + index, 0); - } - return baseFindIndex(array, baseIteratee(predicate, 3), index); - } - - /** - * Flattens `array` a single level deep. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to flatten. - * @returns {Array} Returns the new flattened array. - * @example - * - * _.flatten([1, [2, [3, [4]], 5]]); - * // => [1, 2, [3, [4]], 5] - */ - function flatten(array) { - var length = array ? array.length : 0; - return length ? baseFlatten(array, 1) : []; - } - - /** - * Recursively flattens `array`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to flatten. - * @returns {Array} Returns the new flattened array. - * @example - * - * _.flattenDeep([1, [2, [3, [4]], 5]]); - * // => [1, 2, 3, 4, 5] - */ - function flattenDeep(array) { - var length = array ? array.length : 0; - return length ? baseFlatten(array, INFINITY) : []; - } - - /** - * Gets the first element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @alias first - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the first element of `array`. - * @example - * - * _.head([1, 2, 3]); - * // => 1 - * - * _.head([]); - * // => undefined - */ - function head(array) { - return (array && array.length) ? array[0] : undefined; - } - - /** - * Gets the index at which the first occurrence of `value` is found in `array` - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. If `fromIndex` is negative, it's used as the - * offset from the end of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.indexOf([1, 2, 1, 2], 2); - * // => 1 - * - * // Search from the `fromIndex`. - * _.indexOf([1, 2, 1, 2], 2, 2); - * // => 3 - */ - function indexOf(array, value, fromIndex) { - var length = array ? array.length : 0; - if (typeof fromIndex == 'number') { - fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex; - } else { - fromIndex = 0; - } - var index = (fromIndex || 0) - 1, - isReflexive = value === value; - - while (++index < length) { - var other = array[index]; - if ((isReflexive ? other === value : other !== other)) { - return index; - } - } - return -1; - } - - /** - * Gets the last element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the last element of `array`. - * @example - * - * _.last([1, 2, 3]); - * // => 3 - */ - function last(array) { - var length = array ? array.length : 0; - return length ? array[length - 1] : undefined; - } - - /** - * Creates a slice of `array` from `start` up to, but not including, `end`. - * - * **Note:** This method is used instead of - * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are - * returned. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ - function slice(array, start, end) { - var length = array ? array.length : 0; - start = start == null ? 0 : +start; - end = end === undefined ? length : +end; - return length ? baseSlice(array, start, end) : []; - } - - /*------------------------------------------------------------------------*/ - - /** - * Creates a `lodash` wrapper instance that wraps `value` with explicit method - * chain sequences enabled. The result of such sequences must be unwrapped - * with `_#value`. - * - * @static - * @memberOf _ - * @since 1.3.0 - * @category Seq - * @param {*} value The value to wrap. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'pebbles', 'age': 1 } - * ]; - * - * var youngest = _ - * .chain(users) - * .sortBy('age') - * .map(function(o) { - * return o.user + ' is ' + o.age; - * }) - * .head() - * .value(); - * // => 'pebbles is 1' - */ - function chain(value) { - var result = lodash(value); - result.__chain__ = true; - return result; - } - - /** - * This method invokes `interceptor` and returns `value`. The interceptor - * is invoked with one argument; (value). The purpose of this method is to - * "tap into" a method chain sequence in order to modify intermediate results. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Seq - * @param {*} value The value to provide to `interceptor`. - * @param {Function} interceptor The function to invoke. - * @returns {*} Returns `value`. - * @example - * - * _([1, 2, 3]) - * .tap(function(array) { - * // Mutate input array. - * array.pop(); - * }) - * .reverse() - * .value(); - * // => [2, 1] - */ - function tap(value, interceptor) { - interceptor(value); - return value; - } - - /** - * This method is like `_.tap` except that it returns the result of `interceptor`. - * The purpose of this method is to "pass thru" values replacing intermediate - * results in a method chain sequence. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Seq - * @param {*} value The value to provide to `interceptor`. - * @param {Function} interceptor The function to invoke. - * @returns {*} Returns the result of `interceptor`. - * @example - * - * _(' abc ') - * .chain() - * .trim() - * .thru(function(value) { - * return [value]; - * }) - * .value(); - * // => ['abc'] - */ - function thru(value, interceptor) { - return interceptor(value); - } - - /** - * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. - * - * @name chain - * @memberOf _ - * @since 0.1.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 } - * ]; - * - * // A sequence without explicit chaining. - * _(users).head(); - * // => { 'user': 'barney', 'age': 36 } - * - * // A sequence with explicit chaining. - * _(users) - * .chain() - * .head() - * .pick('user') - * .value(); - * // => { 'user': 'barney' } - */ - function wrapperChain() { - return chain(this); - } - - /** - * Executes the chain sequence to resolve the unwrapped value. - * - * @name value - * @memberOf _ - * @since 0.1.0 - * @alias toJSON, valueOf - * @category Seq - * @returns {*} Returns the resolved unwrapped value. - * @example - * - * _([1, 2, 3]).value(); - * // => [1, 2, 3] - */ - function wrapperValue() { - return baseWrapperValue(this.__wrapped__, this.__actions__); - } - - /*------------------------------------------------------------------------*/ - - /** - * Checks if `predicate` returns truthy for **all** elements of `collection`. - * Iteration is stopped once `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index|key, collection). - * - * **Note:** This method returns `true` for - * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because - * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of - * elements of empty collections. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] - * The function invoked per iteration. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false`. - * @example - * - * _.every([true, 1, null, 'yes'], Boolean); - * // => false - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; - * - * // The `_.matches` iteratee shorthand. - * _.every(users, { 'user': 'barney', 'active': false }); - * // => false - * - * // The `_.matchesProperty` iteratee shorthand. - * _.every(users, ['active', false]); - * // => true - * - * // The `_.property` iteratee shorthand. - * _.every(users, 'active'); - * // => false - */ - function every(collection, predicate, guard) { - predicate = guard ? undefined : predicate; - return baseEvery(collection, baseIteratee(predicate)); - } - - /** - * Iterates over elements of `collection`, returning an array of all elements - * `predicate` returns truthy for. The predicate is invoked with three - * arguments: (value, index|key, collection). - * - * **Note:** Unlike `_.remove`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] - * The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - * @see _.reject - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; - * - * _.filter(users, function(o) { return !o.active; }); - * // => objects for ['fred'] - * - * // The `_.matches` iteratee shorthand. - * _.filter(users, { 'age': 36, 'active': true }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.filter(users, ['active', false]); - * // => objects for ['fred'] - * - * // The `_.property` iteratee shorthand. - * _.filter(users, 'active'); - * // => objects for ['barney'] - */ - function filter(collection, predicate) { - return baseFilter(collection, baseIteratee(predicate)); - } - - /** - * Iterates over elements of `collection`, returning the first element - * `predicate` returns truthy for. The predicate is invoked with three - * arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to inspect. - * @param {Function} [predicate=_.identity] - * The function invoked per iteration. - * @param {number} [fromIndex=0] The index to search from. - * @returns {*} Returns the matched element, else `undefined`. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false }, - * { 'user': 'pebbles', 'age': 1, 'active': true } - * ]; - * - * _.find(users, function(o) { return o.age < 40; }); - * // => object for 'barney' - * - * // The `_.matches` iteratee shorthand. - * _.find(users, { 'age': 1, 'active': true }); - * // => object for 'pebbles' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.find(users, ['active', false]); - * // => object for 'fred' - * - * // The `_.property` iteratee shorthand. - * _.find(users, 'active'); - * // => object for 'barney' - */ - var find = createFind(findIndex); - - /** - * Iterates over elements of `collection` and invokes `iteratee` for each element. - * The iteratee is invoked with three arguments: (value, index|key, collection). - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * **Note:** As with other "Collections" methods, objects with a "length" - * property are iterated like arrays. To avoid this behavior use `_.forIn` - * or `_.forOwn` for object iteration. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @alias each - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - * @see _.forEachRight - * @example - * - * _.forEach([1, 2], function(value) { - * console.log(value); - * }); - * // => Logs `1` then `2`. - * - * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a' then 'b' (iteration order is not guaranteed). - */ - function forEach(collection, iteratee) { - return baseEach(collection, baseIteratee(iteratee)); - } - - /** - * Creates an array of values by running each element in `collection` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, index|key, collection). - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. - * - * The guarded methods are: - * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, - * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, - * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, - * `template`, `trim`, `trimEnd`, `trimStart`, and `words` - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - * @example - * - * function square(n) { - * return n * n; - * } - * - * _.map([4, 8], square); - * // => [16, 64] - * - * _.map({ 'a': 4, 'b': 8 }, square); - * // => [16, 64] (iteration order is not guaranteed) - * - * var users = [ - * { 'user': 'barney' }, - * { 'user': 'fred' } - * ]; - * - * // The `_.property` iteratee shorthand. - * _.map(users, 'user'); - * // => ['barney', 'fred'] - */ - function map(collection, iteratee) { - return baseMap(collection, baseIteratee(iteratee)); - } - - /** - * Reduces `collection` to a value which is the accumulated result of running - * each element in `collection` thru `iteratee`, where each successive - * invocation is supplied the return value of the previous. If `accumulator` - * is not given, the first element of `collection` is used as the initial - * value. The iteratee is invoked with four arguments: - * (accumulator, value, index|key, collection). - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.reduce`, `_.reduceRight`, and `_.transform`. - * - * The guarded methods are: - * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, - * and `sortBy` - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @returns {*} Returns the accumulated value. - * @see _.reduceRight - * @example - * - * _.reduce([1, 2], function(sum, n) { - * return sum + n; - * }, 0); - * // => 3 - * - * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { - * (result[value] || (result[value] = [])).push(key); - * return result; - * }, {}); - * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) - */ - function reduce(collection, iteratee, accumulator) { - return baseReduce(collection, baseIteratee(iteratee), accumulator, arguments.length < 3, baseEach); - } - - /** - * Gets the size of `collection` by returning its length for array-like - * values or the number of own enumerable string keyed properties for objects. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object|string} collection The collection to inspect. - * @returns {number} Returns the collection size. - * @example - * - * _.size([1, 2, 3]); - * // => 3 - * - * _.size({ 'a': 1, 'b': 2 }); - * // => 2 - * - * _.size('pebbles'); - * // => 7 - */ - function size(collection) { - if (collection == null) { - return 0; - } - collection = isArrayLike(collection) ? collection : nativeKeys(collection); - return collection.length; - } - - /** - * Checks if `predicate` returns truthy for **any** element of `collection`. - * Iteration is stopped once `predicate` returns truthy. The predicate is - * invoked with three arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - * @example - * - * _.some([null, 0, 'yes', false], Boolean); - * // => true - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false } - * ]; - * - * // The `_.matches` iteratee shorthand. - * _.some(users, { 'user': 'barney', 'active': false }); - * // => false - * - * // The `_.matchesProperty` iteratee shorthand. - * _.some(users, ['active', false]); - * // => true - * - * // The `_.property` iteratee shorthand. - * _.some(users, 'active'); - * // => true - */ - function some(collection, predicate, guard) { - predicate = guard ? undefined : predicate; - return baseSome(collection, baseIteratee(predicate)); - } - - /** - * Creates an array of elements, sorted in ascending order by the results of - * running each element in a collection thru each iteratee. This method - * performs a stable sort, that is, it preserves the original sort order of - * equal elements. The iteratees are invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {...(Function|Function[])} [iteratees=[_.identity]] - * The iteratees to sort by. - * @returns {Array} Returns the new sorted array. - * @example - * - * var users = [ - * { 'user': 'fred', 'age': 48 }, - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'barney', 'age': 34 } - * ]; - * - * _.sortBy(users, [function(o) { return o.user; }]); - * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] - * - * _.sortBy(users, ['user', 'age']); - * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] - */ - function sortBy(collection, iteratee) { - var index = 0; - iteratee = baseIteratee(iteratee); - - return baseMap(baseMap(collection, function(value, key, collection) { - return { 'value': value, 'index': index++, 'criteria': iteratee(value, key, collection) }; - }).sort(function(object, other) { - return compareAscending(object.criteria, other.criteria) || (object.index - other.index); - }), baseProperty('value')); - } - - /*------------------------------------------------------------------------*/ - - /** - * Creates a function that invokes `func`, with the `this` binding and arguments - * of the created function, while it's called less than `n` times. Subsequent - * calls to the created function return the result of the last `func` invocation. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {number} n The number of calls at which `func` is no longer invoked. - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * jQuery(element).on('click', _.before(5, addContactToList)); - * // => Allows adding up to 4 contacts to the list. - */ - function before(n, func) { - var result; - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - n = toInteger(n); - return function() { - if (--n > 0) { - result = func.apply(this, arguments); - } - if (n <= 1) { - func = undefined; - } - return result; - }; - } - - /** - * Creates a function that invokes `func` with the `this` binding of `thisArg` - * and `partials` prepended to the arguments it receives. - * - * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, - * may be used as a placeholder for partially applied arguments. - * - * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" - * property of bound functions. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to bind. - * @param {*} thisArg The `this` binding of `func`. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new bound function. - * @example - * - * function greet(greeting, punctuation) { - * return greeting + ' ' + this.user + punctuation; - * } - * - * var object = { 'user': 'fred' }; - * - * var bound = _.bind(greet, object, 'hi'); - * bound('!'); - * // => 'hi fred!' - * - * // Bound with placeholders. - * var bound = _.bind(greet, object, _, '!'); - * bound('hi'); - * // => 'hi fred!' - */ - var bind = baseRest(function(func, thisArg, partials) { - return createPartial(func, BIND_FLAG | PARTIAL_FLAG, thisArg, partials); - }); - - /** - * Defers invoking the `func` until the current call stack has cleared. Any - * additional arguments are provided to `func` when it's invoked. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to defer. - * @param {...*} [args] The arguments to invoke `func` with. - * @returns {number} Returns the timer id. - * @example - * - * _.defer(function(text) { - * console.log(text); - * }, 'deferred'); - * // => Logs 'deferred' after one millisecond. - */ - var defer = baseRest(function(func, args) { - return baseDelay(func, 1, args); - }); - - /** - * Invokes `func` after `wait` milliseconds. Any additional arguments are - * provided to `func` when it's invoked. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @param {...*} [args] The arguments to invoke `func` with. - * @returns {number} Returns the timer id. - * @example - * - * _.delay(function(text) { - * console.log(text); - * }, 1000, 'later'); - * // => Logs 'later' after one second. - */ - var delay = baseRest(function(func, wait, args) { - return baseDelay(func, toNumber(wait) || 0, args); - }); - - /** - * Creates a function that negates the result of the predicate `func`. The - * `func` predicate is invoked with the `this` binding and arguments of the - * created function. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} predicate The predicate to negate. - * @returns {Function} Returns the new negated function. - * @example - * - * function isEven(n) { - * return n % 2 == 0; - * } - * - * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); - * // => [1, 3, 5] - */ - function negate(predicate) { - if (typeof predicate != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - return function() { - var args = arguments; - return !predicate.apply(this, args); - }; - } - - /** - * Creates a function that is restricted to invoking `func` once. Repeat calls - * to the function return the value of the first invocation. The `func` is - * invoked with the `this` binding and arguments of the created function. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * var initialize = _.once(createApplication); - * initialize(); - * initialize(); - * // => `createApplication` is invoked once - */ - function once(func) { - return before(2, func); - } - - /*------------------------------------------------------------------------*/ - - /** - * Creates a shallow clone of `value`. - * - * **Note:** This method is loosely based on the - * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) - * and supports cloning arrays, array buffers, booleans, date objects, maps, - * numbers, `Object` objects, regexes, sets, strings, symbols, and typed - * arrays. The own enumerable properties of `arguments` objects are cloned - * as plain objects. An empty object is returned for uncloneable values such - * as error objects, functions, DOM nodes, and WeakMaps. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to clone. - * @returns {*} Returns the cloned value. - * @see _.cloneDeep - * @example - * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; - * - * var shallow = _.clone(objects); - * console.log(shallow[0] === objects[0]); - * // => true - */ - function clone(value) { - if (!isObject(value)) { - return value; - } - return isArray(value) ? copyArray(value) : copyObject(value, nativeKeys(value)); - } - - /** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ - function eq(value, other) { - return value === other || (value !== value && other !== other); - } - - /** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ - function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); - } - - /** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ - var isArray = Array.isArray; - - /** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ - function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); - } - - /** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ - function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); - } - - /** - * Checks if `value` is classified as a boolean primitive or object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. - * @example - * - * _.isBoolean(false); - * // => true - * - * _.isBoolean(null); - * // => false - */ - function isBoolean(value) { - return value === true || value === false || - (isObjectLike(value) && objectToString.call(value) == boolTag); - } - - /** - * Checks if `value` is classified as a `Date` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a date object, else `false`. - * @example - * - * _.isDate(new Date); - * // => true - * - * _.isDate('Mon April 23 2012'); - * // => false - */ - var isDate = baseIsDate; - - /** - * Checks if `value` is an empty object, collection, map, or set. - * - * Objects are considered empty if they have no own enumerable string keyed - * properties. - * - * Array-like values such as `arguments` objects, arrays, buffers, strings, or - * jQuery-like collections are considered empty if they have a `length` of `0`. - * Similarly, maps and sets are considered empty if they have a `size` of `0`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is empty, else `false`. - * @example - * - * _.isEmpty(null); - * // => true - * - * _.isEmpty(true); - * // => true - * - * _.isEmpty(1); - * // => true - * - * _.isEmpty([1, 2, 3]); - * // => false - * - * _.isEmpty({ 'a': 1 }); - * // => false - */ - function isEmpty(value) { - if (isArrayLike(value) && - (isArray(value) || isString(value) || - isFunction(value.splice) || isArguments(value))) { - return !value.length; - } - return !nativeKeys(value).length; - } - - /** - * Performs a deep comparison between two values to determine if they are - * equivalent. - * - * **Note:** This method supports comparing arrays, array buffers, booleans, - * date objects, error objects, maps, numbers, `Object` objects, regexes, - * sets, strings, symbols, and typed arrays. `Object` objects are compared - * by their own, not inherited, enumerable properties. Functions and DOM - * nodes are **not** supported. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.isEqual(object, other); - * // => true - * - * object === other; - * // => false - */ - function isEqual(value, other) { - return baseIsEqual(value, other); - } - - /** - * Checks if `value` is a finite primitive number. - * - * **Note:** This method is based on - * [`Number.isFinite`](https://mdn.io/Number/isFinite). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. - * @example - * - * _.isFinite(3); - * // => true - * - * _.isFinite(Number.MIN_VALUE); - * // => true - * - * _.isFinite(Infinity); - * // => false - * - * _.isFinite('3'); - * // => false - */ - function isFinite(value) { - return typeof value == 'number' && nativeIsFinite(value); - } - - /** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ - function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; - } - - /** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ - function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; - } - - /** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ - function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); - } - - /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ - function isObjectLike(value) { - return value != null && typeof value == 'object'; - } - - /** - * Checks if `value` is `NaN`. - * - * **Note:** This method is based on - * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as - * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for - * `undefined` and other non-number values. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - * @example - * - * _.isNaN(NaN); - * // => true - * - * _.isNaN(new Number(NaN)); - * // => true - * - * isNaN(undefined); - * // => true - * - * _.isNaN(undefined); - * // => false - */ - function isNaN(value) { - // An `NaN` primitive is the only value that is not equal to itself. - // Perform the `toStringTag` check first to avoid errors with some - // ActiveX objects in IE. - return isNumber(value) && value != +value; - } - - /** - * Checks if `value` is `null`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `null`, else `false`. - * @example - * - * _.isNull(null); - * // => true - * - * _.isNull(void 0); - * // => false - */ - function isNull(value) { - return value === null; - } - - /** - * Checks if `value` is classified as a `Number` primitive or object. - * - * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are - * classified as numbers, use the `_.isFinite` method. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a number, else `false`. - * @example - * - * _.isNumber(3); - * // => true - * - * _.isNumber(Number.MIN_VALUE); - * // => true - * - * _.isNumber(Infinity); - * // => true - * - * _.isNumber('3'); - * // => false - */ - function isNumber(value) { - return typeof value == 'number' || - (isObjectLike(value) && objectToString.call(value) == numberTag); - } - - /** - * Checks if `value` is classified as a `RegExp` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. - * @example - * - * _.isRegExp(/abc/); - * // => true - * - * _.isRegExp('/abc/'); - * // => false - */ - var isRegExp = baseIsRegExp; - - /** - * Checks if `value` is classified as a `String` primitive or object. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a string, else `false`. - * @example - * - * _.isString('abc'); - * // => true - * - * _.isString(1); - * // => false - */ - function isString(value) { - return typeof value == 'string' || - (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); - } - - /** - * Checks if `value` is `undefined`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. - * @example - * - * _.isUndefined(void 0); - * // => true - * - * _.isUndefined(null); - * // => false - */ - function isUndefined(value) { - return value === undefined; - } - - /** - * Converts `value` to an array. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to convert. - * @returns {Array} Returns the converted array. - * @example - * - * _.toArray({ 'a': 1, 'b': 2 }); - * // => [1, 2] - * - * _.toArray('abc'); - * // => ['a', 'b', 'c'] - * - * _.toArray(1); - * // => [] - * - * _.toArray(null); - * // => [] - */ - function toArray(value) { - if (!isArrayLike(value)) { - return values(value); - } - return value.length ? copyArray(value) : []; - } - - /** - * Converts `value` to an integer. - * - * **Note:** This method is loosely based on - * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toInteger(3.2); - * // => 3 - * - * _.toInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toInteger(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toInteger('3.2'); - * // => 3 - */ - var toInteger = Number; - - /** - * Converts `value` to a number. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. - * @example - * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toNumber(Infinity); - * // => Infinity - * - * _.toNumber('3.2'); - * // => 3.2 - */ - var toNumber = Number; - - /** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {string} Returns the string. - * @example - * - * _.toString(null); - * // => '' - * - * _.toString(-0); - * // => '-0' - * - * _.toString([1, 2, 3]); - * // => '1,2,3' - */ - function toString(value) { - if (typeof value == 'string') { - return value; - } - return value == null ? '' : (value + ''); - } - - /*------------------------------------------------------------------------*/ - - /** - * Assigns own enumerable string keyed properties of source objects to the - * destination object. Source objects are applied from left to right. - * Subsequent sources overwrite property assignments of previous sources. - * - * **Note:** This method mutates `object` and is loosely based on - * [`Object.assign`](https://mdn.io/Object/assign). - * - * @static - * @memberOf _ - * @since 0.10.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.assignIn - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * function Bar() { - * this.c = 3; - * } - * - * Foo.prototype.b = 2; - * Bar.prototype.d = 4; - * - * _.assign({ 'a': 0 }, new Foo, new Bar); - * // => { 'a': 1, 'c': 3 } - */ - var assign = createAssigner(function(object, source) { - copyObject(source, nativeKeys(source), object); - }); - - /** - * This method is like `_.assign` except that it iterates over own and - * inherited source properties. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias extend - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.assign - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * function Bar() { - * this.c = 3; - * } - * - * Foo.prototype.b = 2; - * Bar.prototype.d = 4; - * - * _.assignIn({ 'a': 0 }, new Foo, new Bar); - * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } - */ - var assignIn = createAssigner(function(object, source) { - copyObject(source, nativeKeysIn(source), object); - }); - - /** - * This method is like `_.assignIn` except that it accepts `customizer` - * which is invoked to produce the assigned values. If `customizer` returns - * `undefined`, assignment is handled by the method instead. The `customizer` - * is invoked with five arguments: (objValue, srcValue, key, object, source). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias extendWith - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @see _.assignWith - * @example - * - * function customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } - * - * var defaults = _.partialRight(_.assignInWith, customizer); - * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ - var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keysIn(source), object, customizer); - }); - - /** - * Creates an object that inherits from the `prototype` object. If a - * `properties` object is given, its own enumerable string keyed properties - * are assigned to the created object. - * - * @static - * @memberOf _ - * @since 2.3.0 - * @category Object - * @param {Object} prototype The object to inherit from. - * @param {Object} [properties] The properties to assign to the object. - * @returns {Object} Returns the new object. - * @example - * - * function Shape() { - * this.x = 0; - * this.y = 0; - * } - * - * function Circle() { - * Shape.call(this); - * } - * - * Circle.prototype = _.create(Shape.prototype, { - * 'constructor': Circle - * }); - * - * var circle = new Circle; - * circle instanceof Circle; - * // => true - * - * circle instanceof Shape; - * // => true - */ - function create(prototype, properties) { - var result = baseCreate(prototype); - return properties ? assign(result, properties) : result; - } - - /** - * Assigns own and inherited enumerable string keyed properties of source - * objects to the destination object for all destination properties that - * resolve to `undefined`. Source objects are applied from left to right. - * Once a property is set, additional values of the same property are ignored. - * - * **Note:** This method mutates `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.defaultsDeep - * @example - * - * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ - var defaults = baseRest(function(args) { - args.push(undefined, assignInDefaults); - return assignInWith.apply(undefined, args); - }); - - /** - * Checks if `path` is a direct property of `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - * @example - * - * var object = { 'a': { 'b': 2 } }; - * var other = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.has(object, 'a'); - * // => true - * - * _.has(object, 'a.b'); - * // => true - * - * _.has(object, ['a', 'b']); - * // => true - * - * _.has(other, 'a'); - * // => false - */ - function has(object, path) { - return object != null && hasOwnProperty.call(object, path); - } - - /** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ - var keys = nativeKeys; - - /** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) - */ - var keysIn = nativeKeysIn; - - /** - * Creates an object composed of the picked `object` properties. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The source object. - * @param {...(string|string[])} [props] The property identifiers to pick. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.pick(object, ['a', 'c']); - * // => { 'a': 1, 'c': 3 } - */ - var pick = flatRest(function(object, props) { - return object == null ? {} : basePick(object, baseMap(props, toKey)); - }); - - /** - * This method is like `_.get` except that if the resolved value is a - * function it's invoked with the `this` binding of its parent object and - * its result is returned. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to resolve. - * @param {*} [defaultValue] The value returned for `undefined` resolved values. - * @returns {*} Returns the resolved value. - * @example - * - * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; - * - * _.result(object, 'a[0].b.c1'); - * // => 3 - * - * _.result(object, 'a[0].b.c2'); - * // => 4 - * - * _.result(object, 'a[0].b.c3', 'default'); - * // => 'default' - * - * _.result(object, 'a[0].b.c3', _.constant('default')); - * // => 'default' - */ - function result(object, path, defaultValue) { - var value = object == null ? undefined : object[path]; - if (value === undefined) { - value = defaultValue; - } - return isFunction(value) ? value.call(object) : value; - } - - /** - * Creates an array of the own enumerable string keyed property values of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property values. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.values(new Foo); - * // => [1, 2] (iteration order is not guaranteed) - * - * _.values('hi'); - * // => ['h', 'i'] - */ - function values(object) { - return object ? baseValues(object, keys(object)) : []; - } - - /*------------------------------------------------------------------------*/ - - /** - * Converts the characters "&", "<", ">", '"', and "'" in `string` to their - * corresponding HTML entities. - * - * **Note:** No other characters are escaped. To escape additional - * characters use a third-party library like [_he_](https://mths.be/he). - * - * Though the ">" character is escaped for symmetry, characters like - * ">" and "/" don't need escaping in HTML and have no special meaning - * unless they're part of a tag or unquoted attribute value. See - * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) - * (under "semi-related fun fact") for more details. - * - * When working with HTML you should always - * [quote attribute values](http://wonko.com/post/html-escaping) to reduce - * XSS vectors. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category String - * @param {string} [string=''] The string to escape. - * @returns {string} Returns the escaped string. - * @example - * - * _.escape('fred, barney, & pebbles'); - * // => 'fred, barney, & pebbles' - */ - function escape(string) { - string = toString(string); - return (string && reHasUnescapedHtml.test(string)) - ? string.replace(reUnescapedHtml, escapeHtmlChar) - : string; - } - - /*------------------------------------------------------------------------*/ - - /** - * This method returns the first argument it receives. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Util - * @param {*} value Any value. - * @returns {*} Returns `value`. - * @example - * - * var object = { 'a': 1 }; - * - * console.log(_.identity(object) === object); - * // => true - */ - function identity(value) { - return value; - } - - /** - * Creates a function that invokes `func` with the arguments of the created - * function. If `func` is a property name, the created function returns the - * property value for a given element. If `func` is an array or object, the - * created function returns `true` for elements that contain the equivalent - * source properties, otherwise it returns `false`. - * - * @static - * @since 4.0.0 - * @memberOf _ - * @category Util - * @param {*} [func=_.identity] The value to convert to a callback. - * @returns {Function} Returns the callback. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; - * - * // The `_.matches` iteratee shorthand. - * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true })); - * // => [{ 'user': 'barney', 'age': 36, 'active': true }] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.filter(users, _.iteratee(['user', 'fred'])); - * // => [{ 'user': 'fred', 'age': 40 }] - * - * // The `_.property` iteratee shorthand. - * _.map(users, _.iteratee('user')); - * // => ['barney', 'fred'] - * - * // Create custom iteratee shorthands. - * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) { - * return !_.isRegExp(func) ? iteratee(func) : function(string) { - * return func.test(string); - * }; - * }); - * - * _.filter(['abc', 'def'], /ef/); - * // => ['def'] - */ - var iteratee = baseIteratee; - - /** - * Creates a function that performs a partial deep comparison between a given - * object and `source`, returning `true` if the given object has equivalent - * property values, else `false`. - * - * **Note:** The created function is equivalent to `_.isMatch` with `source` - * partially applied. - * - * Partial comparisons will match empty array and empty object `source` - * values against any array or object value, respectively. See `_.isEqual` - * for a list of supported value comparisons. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Util - * @param {Object} source The object of property values to match. - * @returns {Function} Returns the new spec function. - * @example - * - * var objects = [ - * { 'a': 1, 'b': 2, 'c': 3 }, - * { 'a': 4, 'b': 5, 'c': 6 } - * ]; - * - * _.filter(objects, _.matches({ 'a': 4, 'c': 6 })); - * // => [{ 'a': 4, 'b': 5, 'c': 6 }] - */ - function matches(source) { - return baseMatches(assign({}, source)); - } - - /** - * Adds all own enumerable string keyed function properties of a source - * object to the destination object. If `object` is a function, then methods - * are added to its prototype as well. - * - * **Note:** Use `_.runInContext` to create a pristine `lodash` function to - * avoid conflicts caused by modifying the original. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Util - * @param {Function|Object} [object=lodash] The destination object. - * @param {Object} source The object of functions to add. - * @param {Object} [options={}] The options object. - * @param {boolean} [options.chain=true] Specify whether mixins are chainable. - * @returns {Function|Object} Returns `object`. - * @example - * - * function vowels(string) { - * return _.filter(string, function(v) { - * return /[aeiou]/i.test(v); - * }); - * } - * - * _.mixin({ 'vowels': vowels }); - * _.vowels('fred'); - * // => ['e'] - * - * _('fred').vowels().value(); - * // => ['e'] - * - * _.mixin({ 'vowels': vowels }, { 'chain': false }); - * _('fred').vowels(); - * // => ['e'] - */ - function mixin(object, source, options) { - var props = keys(source), - methodNames = baseFunctions(source, props); - - if (options == null && - !(isObject(source) && (methodNames.length || !props.length))) { - options = source; - source = object; - object = this; - methodNames = baseFunctions(source, keys(source)); - } - var chain = !(isObject(options) && 'chain' in options) || !!options.chain, - isFunc = isFunction(object); - - baseEach(methodNames, function(methodName) { - var func = source[methodName]; - object[methodName] = func; - if (isFunc) { - object.prototype[methodName] = function() { - var chainAll = this.__chain__; - if (chain || chainAll) { - var result = object(this.__wrapped__), - actions = result.__actions__ = copyArray(this.__actions__); - - actions.push({ 'func': func, 'args': arguments, 'thisArg': object }); - result.__chain__ = chainAll; - return result; - } - return func.apply(object, arrayPush([this.value()], arguments)); - }; - } - }); - - return object; - } - - /** - * Reverts the `_` variable to its previous value and returns a reference to - * the `lodash` function. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Util - * @returns {Function} Returns the `lodash` function. - * @example - * - * var lodash = _.noConflict(); - */ - function noConflict() { - if (root._ === this) { - root._ = oldDash; - } - return this; - } - - /** - * This method returns `undefined`. - * - * @static - * @memberOf _ - * @since 2.3.0 - * @category Util - * @example - * - * _.times(2, _.noop); - * // => [undefined, undefined] - */ - function noop() { - // No operation performed. - } - - /** - * Generates a unique ID. If `prefix` is given, the ID is appended to it. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Util - * @param {string} [prefix=''] The value to prefix the ID with. - * @returns {string} Returns the unique ID. - * @example - * - * _.uniqueId('contact_'); - * // => 'contact_104' - * - * _.uniqueId(); - * // => '105' - */ - function uniqueId(prefix) { - var id = ++idCounter; - return toString(prefix) + id; - } - - /*------------------------------------------------------------------------*/ - - /** - * Computes the maximum value of `array`. If `array` is empty or falsey, - * `undefined` is returned. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Math - * @param {Array} array The array to iterate over. - * @returns {*} Returns the maximum value. - * @example - * - * _.max([4, 2, 8, 6]); - * // => 8 - * - * _.max([]); - * // => undefined - */ - function max(array) { - return (array && array.length) - ? baseExtremum(array, identity, baseGt) - : undefined; - } - - /** - * Computes the minimum value of `array`. If `array` is empty or falsey, - * `undefined` is returned. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Math - * @param {Array} array The array to iterate over. - * @returns {*} Returns the minimum value. - * @example - * - * _.min([4, 2, 8, 6]); - * // => 2 - * - * _.min([]); - * // => undefined - */ - function min(array) { - return (array && array.length) - ? baseExtremum(array, identity, baseLt) - : undefined; - } - - /*------------------------------------------------------------------------*/ - - // Add methods that return wrapped values in chain sequences. - lodash.assignIn = assignIn; - lodash.before = before; - lodash.bind = bind; - lodash.chain = chain; - lodash.compact = compact; - lodash.concat = concat; - lodash.create = create; - lodash.defaults = defaults; - lodash.defer = defer; - lodash.delay = delay; - lodash.filter = filter; - lodash.flatten = flatten; - lodash.flattenDeep = flattenDeep; - lodash.iteratee = iteratee; - lodash.keys = keys; - lodash.map = map; - lodash.matches = matches; - lodash.mixin = mixin; - lodash.negate = negate; - lodash.once = once; - lodash.pick = pick; - lodash.slice = slice; - lodash.sortBy = sortBy; - lodash.tap = tap; - lodash.thru = thru; - lodash.toArray = toArray; - lodash.values = values; - - // Add aliases. - lodash.extend = assignIn; - - // Add methods to `lodash.prototype`. - mixin(lodash, lodash); - - /*------------------------------------------------------------------------*/ - - // Add methods that return unwrapped values in chain sequences. - lodash.clone = clone; - lodash.escape = escape; - lodash.every = every; - lodash.find = find; - lodash.forEach = forEach; - lodash.has = has; - lodash.head = head; - lodash.identity = identity; - lodash.indexOf = indexOf; - lodash.isArguments = isArguments; - lodash.isArray = isArray; - lodash.isBoolean = isBoolean; - lodash.isDate = isDate; - lodash.isEmpty = isEmpty; - lodash.isEqual = isEqual; - lodash.isFinite = isFinite; - lodash.isFunction = isFunction; - lodash.isNaN = isNaN; - lodash.isNull = isNull; - lodash.isNumber = isNumber; - lodash.isObject = isObject; - lodash.isRegExp = isRegExp; - lodash.isString = isString; - lodash.isUndefined = isUndefined; - lodash.last = last; - lodash.max = max; - lodash.min = min; - lodash.noConflict = noConflict; - lodash.noop = noop; - lodash.reduce = reduce; - lodash.result = result; - lodash.size = size; - lodash.some = some; - lodash.uniqueId = uniqueId; - - // Add aliases. - lodash.each = forEach; - lodash.first = head; - - mixin(lodash, (function() { - var source = {}; - baseForOwn(lodash, function(func, methodName) { - if (!hasOwnProperty.call(lodash.prototype, methodName)) { - source[methodName] = func; - } - }); - return source; - }()), { 'chain': false }); - - /*------------------------------------------------------------------------*/ - - /** - * The semantic version number. - * - * @static - * @memberOf _ - * @type {string} - */ - lodash.VERSION = VERSION; - - // Add `Array` methods to `lodash.prototype`. - baseEach(['pop', 'join', 'replace', 'reverse', 'split', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) { - var func = (/^(?:replace|split)$/.test(methodName) ? String.prototype : arrayProto)[methodName], - chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru', - retUnwrapped = /^(?:pop|join|replace|shift)$/.test(methodName); - - lodash.prototype[methodName] = function() { - var args = arguments; - if (retUnwrapped && !this.__chain__) { - var value = this.value(); - return func.apply(isArray(value) ? value : [], args); - } - return this[chainName](function(value) { - return func.apply(isArray(value) ? value : [], args); - }); - }; - }); - - // Add chain sequence methods to the `lodash` wrapper. - lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue; - - /*--------------------------------------------------------------------------*/ - - // Some AMD build optimizers, like r.js, check for condition patterns like: - if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { - // Expose Lodash on the global object to prevent errors when Lodash is - // loaded by a script tag in the presence of an AMD loader. - // See http://requirejs.org/docs/errors.html#mismatch for more details. - // Use `_.noConflict` to remove Lodash from the global object. - root._ = lodash; - - // Define as an anonymous module so, through path mapping, it can be - // referenced as the "underscore" module. - define(function() { - return lodash; - }); - } - // Check for `exports` after `define` in case a build optimizer adds it. - else if (freeModule) { - // Export for Node.js. - (freeModule.exports = lodash)._ = lodash; - // Export for CommonJS support. - freeExports._ = lodash; - } - else { - // Export to the global object. - root._ = lodash; - } -}.call(this)); diff --git a/lib/modules/util/lodash.js b/lib/modules/util/lodash.js new file mode 100644 index 0000000..100e388 --- /dev/null +++ b/lib/modules/util/lodash.js @@ -0,0 +1,16895 @@ +/** + * @license + * lodash + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ +;(function() { + + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + + /** Used as the semantic version number. */ + var VERSION = '4.16.0'; + + /** Used as the size to enable large array optimizations. */ + var LARGE_ARRAY_SIZE = 200; + + /** Used as the `TypeError` message for "Functions" methods. */ + var FUNC_ERROR_TEXT = 'Expected a function'; + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED = '__lodash_hash_undefined__'; + + /** Used as the maximum memoize cache size. */ + var MAX_MEMOIZE_SIZE = 500; + + /** Used as the internal argument placeholder. */ + var PLACEHOLDER = '__lodash_placeholder__'; + + /** Used to compose bitmasks for function metadata. */ + var BIND_FLAG = 1, + BIND_KEY_FLAG = 2, + CURRY_BOUND_FLAG = 4, + CURRY_FLAG = 8, + CURRY_RIGHT_FLAG = 16, + PARTIAL_FLAG = 32, + PARTIAL_RIGHT_FLAG = 64, + ARY_FLAG = 128, + REARG_FLAG = 256, + FLIP_FLAG = 512; + + /** Used to compose bitmasks for comparison styles. */ + var UNORDERED_COMPARE_FLAG = 1, + PARTIAL_COMPARE_FLAG = 2; + + /** Used as default options for `_.truncate`. */ + var DEFAULT_TRUNC_LENGTH = 30, + DEFAULT_TRUNC_OMISSION = '...'; + + /** Used to detect hot functions by number of calls within a span of milliseconds. */ + var HOT_COUNT = 500, + HOT_SPAN = 16; + + /** Used to indicate the type of lazy iteratees. */ + var LAZY_FILTER_FLAG = 1, + LAZY_MAP_FLAG = 2, + LAZY_WHILE_FLAG = 3; + + /** Used as references for various `Number` constants. */ + var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; + + /** Used as references for the maximum length and index of an array. */ + var MAX_ARRAY_LENGTH = 4294967295, + MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, + HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; + + /** Used to associate wrap methods with their bit flags. */ + var wrapFlags = [ + ['ary', ARY_FLAG], + ['bind', BIND_FLAG], + ['bindKey', BIND_KEY_FLAG], + ['curry', CURRY_FLAG], + ['curryRight', CURRY_RIGHT_FLAG], + ['flip', FLIP_FLAG], + ['partial', PARTIAL_FLAG], + ['partialRight', PARTIAL_RIGHT_FLAG], + ['rearg', REARG_FLAG] + ]; + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]', + weakMapTag = '[object WeakMap]', + weakSetTag = '[object WeakSet]'; + + var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + + /** Used to match empty string literals in compiled template source. */ + var reEmptyStringLeading = /\b__p \+= '';/g, + reEmptyStringMiddle = /\b(__p \+=) '' \+/g, + reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; + + /** Used to match HTML entities and HTML characters. */ + var reEscapedHtml = /&(?:amp|lt|gt|quot|#39|#96);/g, + reUnescapedHtml = /[&<>"'`]/g, + reHasEscapedHtml = RegExp(reEscapedHtml.source), + reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + + /** Used to match template delimiters. */ + var reEscape = /<%-([\s\S]+?)%>/g, + reEvaluate = /<%([\s\S]+?)%>/g, + reInterpolate = /<%=([\s\S]+?)%>/g; + + /** Used to match property names within property paths. */ + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/, + reLeadingDot = /^\./, + rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, + reHasRegExpChar = RegExp(reRegExpChar.source); + + /** Used to match leading and trailing whitespace. */ + var reTrim = /^\s+|\s+$/g, + reTrimStart = /^\s+/, + reTrimEnd = /\s+$/; + + /** Used to match wrap detail comments. */ + var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, + reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, + reSplitDetails = /,? & /; + + /** Used to match words composed of alphanumeric characters. */ + var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + + /** Used to match backslashes in property paths. */ + var reEscapeChar = /\\(\\)?/g; + + /** + * Used to match + * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). + */ + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + + /** Used to match `RegExp` flags from their coerced string values. */ + var reFlags = /\w*$/; + + /** Used to detect bad signed hexadecimal string values. */ + var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + + /** Used to detect binary string values. */ + var reIsBinary = /^0b[01]+$/i; + + /** Used to detect host constructors (Safari). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; + + /** Used to detect octal string values. */ + var reIsOctal = /^0o[0-7]+$/i; + + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; + + /** Used to match Latin Unicode letters (excluding mathematical operators). */ + var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; + + /** Used to ensure capturing order of template delimiters. */ + var reNoMatch = /($^)/; + + /** Used to match unescaped characters in compiled string literals. */ + var reUnescapedString = /['\n\r\u2028\u2029\\]/g; + + /** Used to compose unicode character classes. */ + var rsAstralRange = '\\ud800-\\udfff', + rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23', + rsComboSymbolsRange = '\\u20d0-\\u20f0', + rsDingbatRange = '\\u2700-\\u27bf', + rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', + rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', + rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', + rsPunctuationRange = '\\u2000-\\u206f', + rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', + rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', + rsVarRange = '\\ufe0e\\ufe0f', + rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; + + /** Used to compose unicode capture groups. */ + var rsApos = "['\u2019]", + rsAstral = '[' + rsAstralRange + ']', + rsBreak = '[' + rsBreakRange + ']', + rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']', + rsDigits = '\\d+', + rsDingbat = '[' + rsDingbatRange + ']', + rsLower = '[' + rsLowerRange + ']', + rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', + rsFitz = '\\ud83c[\\udffb-\\udfff]', + rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', + rsNonAstral = '[^' + rsAstralRange + ']', + rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsUpper = '[' + rsUpperRange + ']', + rsZWJ = '\\u200d'; + + /** Used to compose unicode regexes. */ + var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')', + rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')', + rsOptLowerContr = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', + rsOptUpperContr = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', + reOptMod = rsModifier + '?', + rsOptVar = '[' + rsVarRange + ']?', + rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', + rsSeq = rsOptVar + reOptMod + rsOptJoin, + rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, + rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; + + /** Used to match apostrophes. */ + var reApos = RegExp(rsApos, 'g'); + + /** + * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and + * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). + */ + var reComboMark = RegExp(rsCombo, 'g'); + + /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ + var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); + + /** Used to match complex or compound words. */ + var reUnicodeWord = RegExp([ + rsUpper + '?' + rsLower + '+' + rsOptLowerContr + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', + rsUpperMisc + '+' + rsOptUpperContr + '(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')', + rsUpper + '?' + rsLowerMisc + '+' + rsOptLowerContr, + rsUpper + '+' + rsOptUpperContr, + rsDigits, + rsEmoji + ].join('|'), 'g'); + + /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ + var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']'); + + /** Used to detect strings that need a more robust regexp to match words. */ + var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; + + /** Used to assign default `context` object properties. */ + var contextProps = [ + 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', + 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', + 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', + 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', + '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' + ]; + + /** Used to make template sourceURLs easier to identify. */ + var templateCounter = -1; + + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = + typedArrayTags[errorTag] = typedArrayTags[funcTag] = + typedArrayTags[mapTag] = typedArrayTags[numberTag] = + typedArrayTags[objectTag] = typedArrayTags[regexpTag] = + typedArrayTags[setTag] = typedArrayTags[stringTag] = + typedArrayTags[weakMapTag] = false; + + /** Used to identify `toStringTag` values supported by `_.clone`. */ + var cloneableTags = {}; + cloneableTags[argsTag] = cloneableTags[arrayTag] = + cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = + cloneableTags[boolTag] = cloneableTags[dateTag] = + cloneableTags[float32Tag] = cloneableTags[float64Tag] = + cloneableTags[int8Tag] = cloneableTags[int16Tag] = + cloneableTags[int32Tag] = cloneableTags[mapTag] = + cloneableTags[numberTag] = cloneableTags[objectTag] = + cloneableTags[regexpTag] = cloneableTags[setTag] = + cloneableTags[stringTag] = cloneableTags[symbolTag] = + cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = + cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; + cloneableTags[errorTag] = cloneableTags[funcTag] = + cloneableTags[weakMapTag] = false; + + /** Used to map Latin Unicode letters to basic Latin letters. */ + var deburredLetters = { + // Latin-1 Supplement block. + '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', + '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', + '\xc7': 'C', '\xe7': 'c', + '\xd0': 'D', '\xf0': 'd', + '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', + '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', + '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', + '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', + '\xd1': 'N', '\xf1': 'n', + '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', + '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', + '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', + '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', + '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', + '\xc6': 'Ae', '\xe6': 'ae', + '\xde': 'Th', '\xfe': 'th', + '\xdf': 'ss', + // Latin Extended-A block. + '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', + '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', + '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', + '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', + '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', + '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', + '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', + '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', + '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', + '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', + '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', + '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', + '\u0134': 'J', '\u0135': 'j', + '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', + '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', + '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', + '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', + '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', + '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', + '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', + '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', + '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', + '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', + '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', + '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', + '\u0163': 't', '\u0165': 't', '\u0167': 't', + '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', + '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', + '\u0174': 'W', '\u0175': 'w', + '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', + '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', + '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', + '\u0132': 'IJ', '\u0133': 'ij', + '\u0152': 'Oe', '\u0153': 'oe', + '\u0149': "'n", '\u017f': 's' + }; + + /** Used to map characters to HTML entities. */ + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }; + + /** Used to map HTML entities to characters. */ + var htmlUnescapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + ''': "'" + }; + + /** Used to escape characters for inclusion in compiled string literals. */ + var stringEscapes = { + '\\': '\\', + "'": "'", + '\n': 'n', + '\r': 'r', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + /** Built-in method references without a dependency on `root`. */ + var freeParseFloat = parseFloat, + freeParseInt = parseInt; + + /** Detect free variable `global` from Node.js. */ + var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + + /** Detect free variable `self`. */ + var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + + /** Used as a reference to the global object. */ + var root = freeGlobal || freeSelf || Function('return this')(); + + /** Detect free variable `exports`. */ + var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; + + /** Detect free variable `process` from Node.js. */ + var freeProcess = moduleExports && freeGlobal.process; + + /** Used to access faster Node.js helpers. */ + var nodeUtil = (function() { + try { + return freeProcess && freeProcess.binding('util'); + } catch (e) {} + }()); + + /* Node.js helper references. */ + var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, + nodeIsDate = nodeUtil && nodeUtil.isDate, + nodeIsMap = nodeUtil && nodeUtil.isMap, + nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, + nodeIsSet = nodeUtil && nodeUtil.isSet, + nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + + /*--------------------------------------------------------------------------*/ + + /** + * Adds the key-value `pair` to `map`. + * + * @private + * @param {Object} map The map to modify. + * @param {Array} pair The key-value pair to add. + * @returns {Object} Returns `map`. + */ + function addMapEntry(map, pair) { + // Don't return `map.set` because it's not chainable in IE 11. + map.set(pair[0], pair[1]); + return map; + } + + /** + * Adds `value` to `set`. + * + * @private + * @param {Object} set The set to modify. + * @param {*} value The value to add. + * @returns {Object} Returns `set`. + */ + function addSetEntry(set, value) { + // Don't return `set.add` because it's not chainable in IE 11. + set.add(value); + return set; + } + + /** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ + function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); + } + + /** + * A specialized version of `baseAggregator` for arrays. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ + function arrayAggregator(array, setter, iteratee, accumulator) { + var index = -1, + length = array ? array.length : 0; + + while (++index < length) { + var value = array[index]; + setter(accumulator, value, iteratee(value), array); + } + return accumulator; + } + + /** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEach(array, iteratee) { + var index = -1, + length = array ? array.length : 0; + + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; + } + + /** + * A specialized version of `_.forEachRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEachRight(array, iteratee) { + var length = array ? array.length : 0; + + while (length--) { + if (iteratee(array[length], length, array) === false) { + break; + } + } + return array; + } + + /** + * A specialized version of `_.every` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + */ + function arrayEvery(array, predicate) { + var index = -1, + length = array ? array.length : 0; + + while (++index < length) { + if (!predicate(array[index], index, array)) { + return false; + } + } + return true; + } + + /** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function arrayFilter(array, predicate) { + var index = -1, + length = array ? array.length : 0, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; + } + + /** + * A specialized version of `_.includes` for arrays without support for + * specifying an index to search from. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + function arrayIncludes(array, value) { + var length = array ? array.length : 0; + return !!length && baseIndexOf(array, value, 0) > -1; + } + + /** + * This function is like `arrayIncludes` except that it accepts a comparator. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @param {Function} comparator The comparator invoked per element. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + function arrayIncludesWith(array, value, comparator) { + var index = -1, + length = array ? array.length : 0; + + while (++index < length) { + if (comparator(value, array[index])) { + return true; + } + } + return false; + } + + /** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function arrayMap(array, iteratee) { + var index = -1, + length = array ? array.length : 0, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; + } + + /** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; + } + + /** + * A specialized version of `_.reduce` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the first element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, + length = array ? array.length : 0; + + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; + } + + /** + * A specialized version of `_.reduceRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the last element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduceRight(array, iteratee, accumulator, initAccum) { + var length = array ? array.length : 0; + if (initAccum && length) { + accumulator = array[--length]; + } + while (length--) { + accumulator = iteratee(accumulator, array[length], length, array); + } + return accumulator; + } + + /** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function arraySome(array, predicate) { + var index = -1, + length = array ? array.length : 0; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; + } + + /** + * Gets the size of an ASCII `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + var asciiSize = baseProperty('length'); + + /** + * Converts an ASCII `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function asciiToArray(string) { + return string.split(''); + } + + /** + * Splits an ASCII `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ + function asciiWords(string) { + return string.match(reAsciiWord) || []; + } + + /** + * The base implementation of methods like `_.findKey` and `_.findLastKey`, + * without support for iteratee shorthands, which iterates over `collection` + * using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the found element or its key, else `undefined`. + */ + function baseFindKey(collection, predicate, eachFunc) { + var result; + eachFunc(collection, function(value, key, collection) { + if (predicate(value, key, collection)) { + result = key; + return false; + } + }); + return result; + } + + /** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOf(array, value, fromIndex) { + return value === value + ? strictIndexOf(array, value, fromIndex) + : baseFindIndex(array, baseIsNaN, fromIndex); + } + + /** + * This function is like `baseIndexOf` except that it accepts a comparator. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @param {Function} comparator The comparator invoked per element. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOfWith(array, value, fromIndex, comparator) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (comparator(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ + function baseIsNaN(value) { + return value !== value; + } + + /** + * The base implementation of `_.mean` and `_.meanBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the mean. + */ + function baseMean(array, iteratee) { + var length = array ? array.length : 0; + return length ? (baseSum(array, iteratee) / length) : NAN; + } + + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.propertyOf` without support for deep paths. + * + * @private + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyOf(object) { + return function(key) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.reduce` and `_.reduceRight`, without support + * for iteratee shorthands, which iterates over `collection` using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} accumulator The initial value. + * @param {boolean} initAccum Specify using the first or last element of + * `collection` as the initial value. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the accumulated value. + */ + function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { + eachFunc(collection, function(value, index, collection) { + accumulator = initAccum + ? (initAccum = false, value) + : iteratee(accumulator, value, index, collection); + }); + return accumulator; + } + + /** + * The base implementation of `_.sortBy` which uses `comparer` to define the + * sort order of `array` and replaces criteria objects with their corresponding + * values. + * + * @private + * @param {Array} array The array to sort. + * @param {Function} comparer The function to define sort order. + * @returns {Array} Returns `array`. + */ + function baseSortBy(array, comparer) { + var length = array.length; + + array.sort(comparer); + while (length--) { + array[length] = array[length].value; + } + return array; + } + + /** + * The base implementation of `_.sum` and `_.sumBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the sum. + */ + function baseSum(array, iteratee) { + var result, + index = -1, + length = array.length; + + while (++index < length) { + var current = iteratee(array[index]); + if (current !== undefined) { + result = result === undefined ? current : (result + current); + } + } + return result; + } + + /** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; + } + + /** + * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array + * of key-value pairs for `object` corresponding to the property names of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the key-value pairs. + */ + function baseToPairs(object, props) { + return arrayMap(props, function(key) { + return [key, object[key]]; + }); + } + + /** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function(value) { + return func(value); + }; + } + + /** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ + function baseValues(object, props) { + return arrayMap(props, function(key) { + return object[key]; + }); + } + + /** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function cacheHas(cache, key) { + return cache.has(key); + } + + /** + * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the first unmatched string symbol. + */ + function charsStartIndex(strSymbols, chrSymbols) { + var index = -1, + length = strSymbols.length; + + while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } + + /** + * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the last unmatched string symbol. + */ + function charsEndIndex(strSymbols, chrSymbols) { + var index = strSymbols.length; + + while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } + + /** + * Gets the number of `placeholder` occurrences in `array`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} placeholder The placeholder to search for. + * @returns {number} Returns the placeholder count. + */ + function countHolders(array, placeholder) { + var length = array.length, + result = 0; + + while (length--) { + if (array[length] === placeholder) { + ++result; + } + } + return result; + } + + /** + * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A + * letters to basic Latin letters. + * + * @private + * @param {string} letter The matched letter to deburr. + * @returns {string} Returns the deburred letter. + */ + var deburrLetter = basePropertyOf(deburredLetters); + + /** + * Used by `_.escape` to convert characters to HTML entities. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + var escapeHtmlChar = basePropertyOf(htmlEscapes); + + /** + * Used by `_.template` to escape characters for inclusion in compiled string literals. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + function escapeStringChar(chr) { + return '\\' + stringEscapes[chr]; + } + + /** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function getValue(object, key) { + return object == null ? undefined : object[key]; + } + + /** + * Checks if `string` contains Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a symbol is found, else `false`. + */ + function hasUnicode(string) { + return reHasUnicode.test(string); + } + + /** + * Checks if `string` contains a word composed of Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a word is found, else `false`. + */ + function hasUnicodeWord(string) { + return reHasUnicodeWord.test(string); + } + + /** + * Converts `iterator` to an array. + * + * @private + * @param {Object} iterator The iterator to convert. + * @returns {Array} Returns the converted array. + */ + function iteratorToArray(iterator) { + var data, + result = []; + + while (!(data = iterator.next()).done) { + result.push(data.value); + } + return result; + } + + /** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ + function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; + } + + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + + /** + * Replaces all `placeholder` elements in `array` with an internal placeholder + * and returns an array of their indexes. + * + * @private + * @param {Array} array The array to modify. + * @param {*} placeholder The placeholder to replace. + * @returns {Array} Returns the new array of placeholder indexes. + */ + function replaceHolders(array, placeholder) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value === placeholder || value === PLACEHOLDER) { + array[index] = PLACEHOLDER; + result[resIndex++] = index; + } + } + return result; + } + + /** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ + function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; + } + + /** + * Converts `set` to its value-value pairs. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the value-value pairs. + */ + function setToPairs(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = [value, value]; + }); + return result; + } + + /** + * A specialized version of `_.indexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * A specialized version of `_.lastIndexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictLastIndexOf(array, value, fromIndex) { + var index = fromIndex + 1; + while (index--) { + if (array[index] === value) { + return index; + } + } + return index; + } + + /** + * Gets the number of symbols in `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the string size. + */ + function stringSize(string) { + return hasUnicode(string) + ? unicodeSize(string) + : asciiSize(string); + } + + /** + * Converts `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function stringToArray(string) { + return hasUnicode(string) + ? unicodeToArray(string) + : asciiToArray(string); + } + + /** + * Used by `_.unescape` to convert HTML entities to characters. + * + * @private + * @param {string} chr The matched character to unescape. + * @returns {string} Returns the unescaped character. + */ + var unescapeHtmlChar = basePropertyOf(htmlUnescapes); + + /** + * Gets the size of a Unicode `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + function unicodeSize(string) { + var result = reUnicode.lastIndex = 0; + while (reUnicode.test(string)) { + ++result; + } + return result; + } + + /** + * Converts a Unicode `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function unicodeToArray(string) { + return string.match(reUnicode) || []; + } + + /** + * Splits a Unicode `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ + function unicodeWords(string) { + return string.match(reUnicodeWord) || []; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Create a new pristine `lodash` function using the `context` object. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Util + * @param {Object} [context=root] The context object. + * @returns {Function} Returns a new `lodash` function. + * @example + * + * _.mixin({ 'foo': _.constant('foo') }); + * + * var lodash = _.runInContext(); + * lodash.mixin({ 'bar': lodash.constant('bar') }); + * + * _.isFunction(_.foo); + * // => true + * _.isFunction(_.bar); + * // => false + * + * lodash.isFunction(lodash.foo); + * // => false + * lodash.isFunction(lodash.bar); + * // => true + * + * // Create a suped-up `defer` in Node.js. + * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; + */ + function runInContext(context) { + context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root; + + /** Built-in constructor references. */ + var Array = context.Array, + Date = context.Date, + Error = context.Error, + Function = context.Function, + Math = context.Math, + Object = context.Object, + RegExp = context.RegExp, + String = context.String, + TypeError = context.TypeError; + + /** Used for built-in method references. */ + var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; + + /** Used to detect overreaching core-js shims. */ + var coreJsData = context['__core-js_shared__']; + + /** Used to detect methods masquerading as native. */ + var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; + }()); + + /** Used to resolve the decompiled source of functions. */ + var funcToString = funcProto.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** Used to generate unique IDs. */ + var idCounter = 0; + + /** Used to infer the `Object` constructor. */ + var objectCtorString = funcToString.call(Object); + + /** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + var objectToString = objectProto.toString; + + /** Used to restore the original `_` reference in `_.noConflict`. */ + var oldDash = root._; + + /** Used to detect if a method is native. */ + var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); + + /** Built-in value references. */ + var Buffer = moduleExports ? context.Buffer : undefined, + Symbol = context.Symbol, + Uint8Array = context.Uint8Array, + defineProperty = Object.defineProperty, + getPrototype = overArg(Object.getPrototypeOf, Object), + iteratorSymbol = Symbol ? Symbol.iterator : undefined, + objectCreate = Object.create, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice, + spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; + + /** Mocked built-ins. */ + var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, + ctxNow = Date && Date.now !== root.Date.now && Date.now, + ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeCeil = Math.ceil, + nativeFloor = Math.floor, + nativeGetSymbols = Object.getOwnPropertySymbols, + nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, + nativeIsFinite = context.isFinite, + nativeJoin = arrayProto.join, + nativeKeys = overArg(Object.keys, Object), + nativeMax = Math.max, + nativeMin = Math.min, + nativeNow = Date.now, + nativeParseInt = context.parseInt, + nativeRandom = Math.random, + nativeReverse = arrayProto.reverse; + + /* Built-in method references that are verified to be native. */ + var DataView = getNative(context, 'DataView'), + Map = getNative(context, 'Map'), + Promise = getNative(context, 'Promise'), + Set = getNative(context, 'Set'), + WeakMap = getNative(context, 'WeakMap'), + nativeCreate = getNative(Object, 'create'), + nativeDefineProperty = getNative(Object, 'defineProperty'); + + /** Used to store function metadata. */ + var metaMap = WeakMap && new WeakMap; + + /** Used to lookup unminified function names. */ + var realNames = {}; + + /** Used to detect maps, sets, and weakmaps. */ + var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); + + /** Used to convert symbols to primitives and strings. */ + var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` object which wraps `value` to enable implicit method + * chain sequences. Methods that operate on and return arrays, collections, + * and functions can be chained together. Methods that retrieve a single value + * or may return a primitive value will automatically end the chain sequence + * and return the unwrapped value. Otherwise, the value must be unwrapped + * with `_#value`. + * + * Explicit chain sequences, which must be unwrapped with `_#value`, may be + * enabled using `_.chain`. + * + * The execution of chained methods is lazy, that is, it's deferred until + * `_#value` is implicitly or explicitly called. + * + * Lazy evaluation allows several methods to support shortcut fusion. + * Shortcut fusion is an optimization to merge iteratee calls; this avoids + * the creation of intermediate arrays and can greatly reduce the number of + * iteratee executions. Sections of a chain sequence qualify for shortcut + * fusion if the section is applied to an array of at least `200` elements + * and any iteratees accept only one argument. The heuristic for whether a + * section qualifies for shortcut fusion is subject to change. + * + * Chaining is supported in custom builds as long as the `_#value` method is + * directly or indirectly included in the build. + * + * In addition to lodash methods, wrappers have `Array` and `String` methods. + * + * The wrapper `Array` methods are: + * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` + * + * The wrapper `String` methods are: + * `replace` and `split` + * + * The wrapper methods that support shortcut fusion are: + * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, + * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, + * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` + * + * The chainable wrapper methods are: + * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, + * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, + * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, + * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, + * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, + * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, + * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, + * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, + * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, + * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, + * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, + * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, + * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, + * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, + * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, + * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, + * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, + * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, + * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, + * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, + * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, + * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, + * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, + * `zipObject`, `zipObjectDeep`, and `zipWith` + * + * The wrapper methods that are **not** chainable by default are: + * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, + * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, + * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, + * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, + * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, + * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, + * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, + * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, + * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, + * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, + * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, + * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, + * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, + * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, + * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, + * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, + * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, + * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, + * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, + * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, + * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, + * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, + * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, + * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, + * `upperFirst`, `value`, and `words` + * + * @name _ + * @constructor + * @category Seq + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2, 3]); + * + * // Returns an unwrapped value. + * wrapped.reduce(_.add); + * // => 6 + * + * // Returns a wrapped value. + * var squares = wrapped.map(square); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true + */ + function lodash(value) { + if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { + if (value instanceof LodashWrapper) { + return value; + } + if (hasOwnProperty.call(value, '__wrapped__')) { + return wrapperClone(value); + } + } + return new LodashWrapper(value); + } + + /** + * The function whose prototype chain sequence wrappers inherit from. + * + * @private + */ + function baseLodash() { + // No operation performed. + } + + /** + * The base constructor for creating `lodash` wrapper objects. + * + * @private + * @param {*} value The value to wrap. + * @param {boolean} [chainAll] Enable explicit method chain sequences. + */ + function LodashWrapper(value, chainAll) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__chain__ = !!chainAll; + this.__index__ = 0; + this.__values__ = undefined; + } + + /** + * By default, the template delimiters used by lodash are like those in + * embedded Ruby (ERB). Change the following template settings to use + * alternative delimiters. + * + * @static + * @memberOf _ + * @type {Object} + */ + lodash.templateSettings = { + + /** + * Used to detect `data` property values to be HTML-escaped. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'escape': reEscape, + + /** + * Used to detect code to be evaluated. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'evaluate': reEvaluate, + + /** + * Used to detect `data` property values to inject. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'interpolate': reInterpolate, + + /** + * Used to reference the data object in the template text. + * + * @memberOf _.templateSettings + * @type {string} + */ + 'variable': '', + + /** + * Used to import variables into the compiled template. + * + * @memberOf _.templateSettings + * @type {Object} + */ + 'imports': { + + /** + * A reference to the `lodash` function. + * + * @memberOf _.templateSettings.imports + * @type {Function} + */ + '_': lodash + } + }; + + // Ensure wrappers are instances of `baseLodash`. + lodash.prototype = baseLodash.prototype; + lodash.prototype.constructor = lodash; + + LodashWrapper.prototype = baseCreate(baseLodash.prototype); + LodashWrapper.prototype.constructor = LodashWrapper; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. + * + * @private + * @constructor + * @param {*} value The value to wrap. + */ + function LazyWrapper(value) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__dir__ = 1; + this.__filtered__ = false; + this.__iteratees__ = []; + this.__takeCount__ = MAX_ARRAY_LENGTH; + this.__views__ = []; + } + + /** + * Creates a clone of the lazy wrapper object. + * + * @private + * @name clone + * @memberOf LazyWrapper + * @returns {Object} Returns the cloned `LazyWrapper` object. + */ + function lazyClone() { + var result = new LazyWrapper(this.__wrapped__); + result.__actions__ = copyArray(this.__actions__); + result.__dir__ = this.__dir__; + result.__filtered__ = this.__filtered__; + result.__iteratees__ = copyArray(this.__iteratees__); + result.__takeCount__ = this.__takeCount__; + result.__views__ = copyArray(this.__views__); + return result; + } + + /** + * Reverses the direction of lazy iteration. + * + * @private + * @name reverse + * @memberOf LazyWrapper + * @returns {Object} Returns the new reversed `LazyWrapper` object. + */ + function lazyReverse() { + if (this.__filtered__) { + var result = new LazyWrapper(this); + result.__dir__ = -1; + result.__filtered__ = true; + } else { + result = this.clone(); + result.__dir__ *= -1; + } + return result; + } + + /** + * Extracts the unwrapped value from its lazy wrapper. + * + * @private + * @name value + * @memberOf LazyWrapper + * @returns {*} Returns the unwrapped value. + */ + function lazyValue() { + var array = this.__wrapped__.value(), + dir = this.__dir__, + isArr = isArray(array), + isRight = dir < 0, + arrLength = isArr ? array.length : 0, + view = getView(0, arrLength, this.__views__), + start = view.start, + end = view.end, + length = end - start, + index = isRight ? end : (start - 1), + iteratees = this.__iteratees__, + iterLength = iteratees.length, + resIndex = 0, + takeCount = nativeMin(length, this.__takeCount__); + + if (!isArr || arrLength < LARGE_ARRAY_SIZE || + (arrLength == length && takeCount == length)) { + return baseWrapperValue(array, this.__actions__); + } + var result = []; + + outer: + while (length-- && resIndex < takeCount) { + index += dir; + + var iterIndex = -1, + value = array[index]; + + while (++iterIndex < iterLength) { + var data = iteratees[iterIndex], + iteratee = data.iteratee, + type = data.type, + computed = iteratee(value); + + if (type == LAZY_MAP_FLAG) { + value = computed; + } else if (!computed) { + if (type == LAZY_FILTER_FLAG) { + continue outer; + } else { + break outer; + } + } + } + result[resIndex++] = value; + } + return result; + } + + // Ensure `LazyWrapper` is an instance of `baseLodash`. + LazyWrapper.prototype = baseCreate(baseLodash.prototype); + LazyWrapper.prototype.constructor = LazyWrapper; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Hash(entries) { + var index = -1, + length = entries ? entries.length : 0; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; + } + + /** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; + } + + /** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); + } + + /** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; + } + + // Add methods to `Hash`. + Hash.prototype.clear = hashClear; + Hash.prototype['delete'] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function ListCache(entries) { + var index = -1, + length = entries ? entries.length : 0; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } + + /** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; + } + + /** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; + } + + /** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; + } + + /** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ + function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; + } + + // Add methods to `ListCache`. + ListCache.prototype.clear = listCacheClear; + ListCache.prototype['delete'] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function MapCache(entries) { + var index = -1, + length = entries ? entries.length : 0; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ + function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; + } + + /** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function mapCacheGet(key) { + return getMapData(this, key).get(key); + } + + /** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function mapCacheHas(key) { + return getMapData(this, key).has(key); + } + + /** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ + function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; + } + + // Add methods to `MapCache`. + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype['delete'] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + + /*------------------------------------------------------------------------*/ + + /** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ + function SetCache(values) { + var index = -1, + length = values ? values.length : 0; + + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } + } + + /** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; + } + + /** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ + function setCacheHas(value) { + return this.__data__.has(value); + } + + // Add methods to `SetCache`. + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; + } + + /** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ + function stackClear() { + this.__data__ = new ListCache; + this.size = 0; + } + + /** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; + } + + /** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function stackGet(key) { + return this.__data__.get(key); + } + + /** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function stackHas(key) { + return this.__data__.has(key); + } + + /** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ + function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; + } + + // Add methods to `Stack`. + Stack.prototype.clear = stackClear; + Stack.prototype['delete'] = stackDelete; + Stack.prototype.get = stackGet; + Stack.prototype.has = stackHas; + Stack.prototype.set = stackSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ + function arrayLikeKeys(value, inherited) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + // Safari 9 makes `arguments.length` enumerable in strict mode. + var result = (isArray(value) || isArguments(value)) + ? baseTimes(value.length, String) + : []; + + var length = result.length, + skipIndexes = !!length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && (key == 'length' || isIndex(key, length)))) { + result.push(key); + } + } + return result; + } + + /** + * A specialized version of `_.sample` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} array The array to sample. + * @returns {*} Returns the random element. + */ + function arraySample(array) { + var length = array.length; + return length ? array[baseRandom(0, length - 1)] : undefined; + } + + /** + * A specialized version of `_.sampleSize` for arrays. + * + * @private + * @param {Array} array The array to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. + */ + function arraySampleSize(array, n) { + var result = arrayShuffle(array); + result.length = baseClamp(n, 0, result.length); + return result; + } + + /** + * A specialized version of `_.shuffle` for arrays. + * + * @private + * @param {Array} array The array to shuffle. + * @returns {Array} Returns the new shuffled array. + */ + function arrayShuffle(array) { + return shuffleSelf(copyArray(array)); + } + + /** + * Used by `_.defaults` to customize its `_.assignIn` use. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to assign. + * @param {Object} object The parent object of `objValue`. + * @returns {*} Returns the value to assign. + */ + function assignInDefaults(objValue, srcValue, key, object) { + if (objValue === undefined || + (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { + return srcValue; + } + return objValue; + } + + /** + * This function is like `assignValue` except that it doesn't assign + * `undefined` values. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignMergeValue(object, key, value) { + if ((value !== undefined && !eq(object[key], value)) || + (typeof key == 'number' && value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; + } + + /** + * Aggregates elements of `collection` on `accumulator` with keys transformed + * by `iteratee` and values set by `setter`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ + function baseAggregator(collection, setter, iteratee, accumulator) { + baseEach(collection, function(value, key, collection) { + setter(accumulator, value, iteratee(value), collection); + }); + return accumulator; + } + + /** + * The base implementation of `_.assign` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ + function baseAssign(object, source) { + return object && copyObject(source, keys(source), object); + } + + /** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function baseAssignValue(object, key, value) { + if (key == '__proto__' && defineProperty) { + defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; + } + } + + /** + * The base implementation of `_.at` without support for individual paths. + * + * @private + * @param {Object} object The object to iterate over. + * @param {string[]} paths The property paths of elements to pick. + * @returns {Array} Returns the picked elements. + */ + function baseAt(object, paths) { + var index = -1, + isNil = object == null, + length = paths.length, + result = Array(length); + + while (++index < length) { + result[index] = isNil ? undefined : get(object, paths[index]); + } + return result; + } + + /** + * The base implementation of `_.clamp` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. + */ + function baseClamp(number, lower, upper) { + if (number === number) { + if (upper !== undefined) { + number = number <= upper ? number : upper; + } + if (lower !== undefined) { + number = number >= lower ? number : lower; + } + } + return number; + } + + /** + * The base implementation of `_.clone` and `_.cloneDeep` which tracks + * traversed objects. + * + * @private + * @param {*} value The value to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @param {boolean} [isFull] Specify a clone including symbols. + * @param {Function} [customizer] The function to customize cloning. + * @param {string} [key] The key of `value`. + * @param {Object} [object] The parent object of `value`. + * @param {Object} [stack] Tracks traversed objects and their clone counterparts. + * @returns {*} Returns the cloned value. + */ + function baseClone(value, isDeep, isFull, customizer, key, object, stack) { + var result; + if (customizer) { + result = object ? customizer(value, key, object, stack) : customizer(value); + } + if (result !== undefined) { + return result; + } + if (!isObject(value)) { + return value; + } + var isArr = isArray(value); + if (isArr) { + result = initCloneArray(value); + if (!isDeep) { + return copyArray(value, result); + } + } else { + var tag = getTag(value), + isFunc = tag == funcTag || tag == genTag; + + if (isBuffer(value)) { + return cloneBuffer(value, isDeep); + } + if (tag == objectTag || tag == argsTag || (isFunc && !object)) { + result = initCloneObject(isFunc ? {} : value); + if (!isDeep) { + return copySymbols(value, baseAssign(result, value)); + } + } else { + if (!cloneableTags[tag]) { + return object ? value : {}; + } + result = initCloneByTag(value, tag, baseClone, isDeep); + } + } + // Check for circular references and return its corresponding clone. + stack || (stack = new Stack); + var stacked = stack.get(value); + if (stacked) { + return stacked; + } + stack.set(value, result); + + if (!isArr) { + var props = isFull ? getAllKeys(value) : keys(value); + } + arrayEach(props || value, function(subValue, key) { + if (props) { + key = subValue; + subValue = value[key]; + } + // Recursively populate clone (susceptible to call stack limits). + assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack)); + }); + return result; + } + + /** + * The base implementation of `_.conforms` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property predicates to conform to. + * @returns {Function} Returns the new spec function. + */ + function baseConforms(source) { + var props = keys(source); + return function(object) { + return baseConformsTo(object, source, props); + }; + } + + /** + * The base implementation of `_.conformsTo` which accepts `props` to check. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + */ + function baseConformsTo(object, source, props) { + var length = props.length; + if (object == null) { + return !length; + } + object = Object(object); + while (length--) { + var key = props[length], + predicate = source[key], + value = object[key]; + + if ((value === undefined && !(key in object)) || !predicate(value)) { + return false; + } + } + return true; + } + + /** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} prototype The object to inherit from. + * @returns {Object} Returns the new object. + */ + function baseCreate(proto) { + return isObject(proto) ? objectCreate(proto) : {}; + } + + /** + * The base implementation of `_.delay` and `_.defer` which accepts `args` + * to provide to `func`. + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {Array} args The arguments to provide to `func`. + * @returns {number|Object} Returns the timer id or timeout object. + */ + function baseDelay(func, wait, args) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return setTimeout(function() { func.apply(undefined, args); }, wait); + } + + /** + * The base implementation of methods like `_.difference` without support + * for excluding multiple arrays or iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Array} values The values to exclude. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + */ + function baseDifference(array, values, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + isCommon = true, + length = array.length, + result = [], + valuesLength = values.length; + + if (!length) { + return result; + } + if (iteratee) { + values = arrayMap(values, baseUnary(iteratee)); + } + if (comparator) { + includes = arrayIncludesWith; + isCommon = false; + } + else if (values.length >= LARGE_ARRAY_SIZE) { + includes = cacheHas; + isCommon = false; + values = new SetCache(values); + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var valuesIndex = valuesLength; + while (valuesIndex--) { + if (values[valuesIndex] === computed) { + continue outer; + } + } + result.push(value); + } + else if (!includes(values, computed, comparator)) { + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.forEach` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ + var baseEach = createBaseEach(baseForOwn); + + /** + * The base implementation of `_.forEachRight` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ + var baseEachRight = createBaseEach(baseForOwnRight, true); + + /** + * The base implementation of `_.every` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false` + */ + function baseEvery(collection, predicate) { + var result = true; + baseEach(collection, function(value, index, collection) { + result = !!predicate(value, index, collection); + return result; + }); + return result; + } + + /** + * The base implementation of methods like `_.max` and `_.min` which accepts a + * `comparator` to determine the extremum value. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The iteratee invoked per iteration. + * @param {Function} comparator The comparator used to compare values. + * @returns {*} Returns the extremum value. + */ + function baseExtremum(array, iteratee, comparator) { + var index = -1, + length = array.length; + + while (++index < length) { + var value = array[index], + current = iteratee(value); + + if (current != null && (computed === undefined + ? (current === current && !isSymbol(current)) + : comparator(current, computed) + )) { + var computed = current, + result = value; + } + } + return result; + } + + /** + * The base implementation of `_.fill` without an iteratee call guard. + * + * @private + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + */ + function baseFill(array, value, start, end) { + var length = array.length; + + start = toInteger(start); + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = (end === undefined || end > length) ? length : toInteger(end); + if (end < 0) { + end += length; + } + end = start > end ? 0 : toLength(end); + while (start < end) { + array[start++] = value; + } + return array; + } + + /** + * The base implementation of `_.filter` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function baseFilter(collection, predicate) { + var result = []; + baseEach(collection, function(value, index, collection) { + if (predicate(value, index, collection)) { + result.push(value); + } + }); + return result; + } + + /** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ + function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; + + predicate || (predicate = isFlattenable); + result || (result = []); + + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; + } + + /** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseFor = createBaseFor(); + + /** + * This function is like `baseFor` except that it iterates over properties + * in the opposite order. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseForRight = createBaseFor(true); + + /** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); + } + + /** + * The base implementation of `_.forOwnRight` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwnRight(object, iteratee) { + return object && baseForRight(object, iteratee, keys); + } + + /** + * The base implementation of `_.functions` which creates an array of + * `object` function property names filtered from `props`. + * + * @private + * @param {Object} object The object to inspect. + * @param {Array} props The property names to filter. + * @returns {Array} Returns the function names. + */ + function baseFunctions(object, props) { + return arrayFilter(props, function(key) { + return isFunction(object[key]); + }); + } + + /** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ + function baseGet(object, path) { + path = isKey(path, object) ? [path] : castPath(path); + + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return (index && index == length) ? object : undefined; + } + + /** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ + function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); + } + + /** + * The base implementation of `getTag`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + function baseGetTag(value) { + return objectToString.call(value); + } + + /** + * The base implementation of `_.gt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + */ + function baseGt(value, other) { + return value > other; + } + + /** + * The base implementation of `_.has` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + function baseHas(object, key) { + return object != null && hasOwnProperty.call(object, key); + } + + /** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + function baseHasIn(object, key) { + return object != null && key in Object(object); + } + + /** + * The base implementation of `_.inRange` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to check. + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + */ + function baseInRange(number, start, end) { + return number >= nativeMin(start, end) && number < nativeMax(start, end); + } + + /** + * The base implementation of methods like `_.intersection`, without support + * for iteratee shorthands, that accepts an array of arrays to inspect. + * + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of shared values. + */ + function baseIntersection(arrays, iteratee, comparator) { + var includes = comparator ? arrayIncludesWith : arrayIncludes, + length = arrays[0].length, + othLength = arrays.length, + othIndex = othLength, + caches = Array(othLength), + maxLength = Infinity, + result = []; + + while (othIndex--) { + var array = arrays[othIndex]; + if (othIndex && iteratee) { + array = arrayMap(array, baseUnary(iteratee)); + } + maxLength = nativeMin(array.length, maxLength); + caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) + ? new SetCache(othIndex && array) + : undefined; + } + array = arrays[0]; + + var index = -1, + seen = caches[0]; + + outer: + while (++index < length && result.length < maxLength) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (!(seen + ? cacheHas(seen, computed) + : includes(result, computed, comparator) + )) { + othIndex = othLength; + while (--othIndex) { + var cache = caches[othIndex]; + if (!(cache + ? cacheHas(cache, computed) + : includes(arrays[othIndex], computed, comparator)) + ) { + continue outer; + } + } + if (seen) { + seen.push(computed); + } + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.invert` and `_.invertBy` which inverts + * `object` with values transformed by `iteratee` and set by `setter`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform values. + * @param {Object} accumulator The initial inverted object. + * @returns {Function} Returns `accumulator`. + */ + function baseInverter(object, setter, iteratee, accumulator) { + baseForOwn(object, function(value, key, object) { + setter(accumulator, iteratee(value), key, object); + }); + return accumulator; + } + + /** + * The base implementation of `_.invoke` without support for individual + * method arguments. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {Array} args The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + */ + function baseInvoke(object, path, args) { + if (!isKey(path, object)) { + path = castPath(path); + object = parent(object, path); + path = last(path); + } + var func = object == null ? object : object[toKey(path)]; + return func == null ? undefined : apply(func, object, args); + } + + /** + * The base implementation of `_.isArrayBuffer` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + */ + function baseIsArrayBuffer(value) { + return isObjectLike(value) && objectToString.call(value) == arrayBufferTag; + } + + /** + * The base implementation of `_.isDate` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + */ + function baseIsDate(value) { + return isObjectLike(value) && objectToString.call(value) == dateTag; + } + + /** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparisons. + * @param {boolean} [bitmask] The bitmask of comparison flags. + * The bitmask may be composed of the following flags: + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(value, other, customizer, bitmask, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack); + } + + /** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} [customizer] The function to customize comparisons. + * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual` + * for more details. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = arrayTag, + othTag = arrayTag; + + if (!objIsArr) { + objTag = getTag(object); + objTag = objTag == argsTag ? objectTag : objTag; + } + if (!othIsArr) { + othTag = getTag(other); + othTag = othTag == argsTag ? objectTag : othTag; + } + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; + + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, equalFunc, customizer, bitmask, stack) + : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack); + } + if (!(bitmask & PARTIAL_COMPARE_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, customizer, bitmask, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, equalFunc, customizer, bitmask, stack); + } + + /** + * The base implementation of `_.isMap` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + */ + function baseIsMap(value) { + return isObjectLike(value) && getTag(value) == mapTag; + } + + /** + * The base implementation of `_.isMatch` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ + function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new Stack; + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined + ? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack) + : result + )) { + return false; + } + } + } + return true; + } + + /** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); + } + + /** + * The base implementation of `_.isRegExp` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + */ + function baseIsRegExp(value) { + return isObject(value) && objectToString.call(value) == regexpTag; + } + + /** + * The base implementation of `_.isSet` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + */ + function baseIsSet(value) { + return isObjectLike(value) && getTag(value) == setTag; + } + + /** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ + function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[objectToString.call(value)]; + } + + /** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ + function baseIteratee(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + if (value == null) { + return identity; + } + if (typeof value == 'object') { + return isArray(value) + ? baseMatchesProperty(value[0], value[1]) + : baseMatches(value); + } + return property(value); + } + + /** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; + } + + /** + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype(object), + result = []; + + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); + } + } + return result; + } + + /** + * The base implementation of `_.lt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + */ + function baseLt(value, other) { + return value < other; + } + + /** + * The base implementation of `_.map` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function baseMap(collection, iteratee) { + var index = -1, + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; + } + + /** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; + } + + /** + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatchesProperty(path, srcValue) { + if (isKey(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey(path), srcValue); + } + return function(object) { + var objValue = get(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn(object, path) + : baseIsEqual(srcValue, objValue, undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG); + }; + } + + /** + * The base implementation of `_.merge` without support for multiple sources. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {number} srcIndex The index of `source`. + * @param {Function} [customizer] The function to customize merged values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ + function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; + } + if (!(isArray(source) || isTypedArray(source))) { + var props = baseKeysIn(source); + } + arrayEach(props || source, function(srcValue, key) { + if (props) { + key = srcValue; + srcValue = source[key]; + } + if (isObject(srcValue)) { + stack || (stack = new Stack); + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); + } + else { + var newValue = customizer + ? customizer(object[key], srcValue, (key + ''), object, source, stack) + : undefined; + + if (newValue === undefined) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }); + } + + /** + * A specialized version of `baseMerge` for arrays and objects which performs + * deep merges and tracks traversed objects enabling objects with circular + * references to be merged. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {string} key The key of the value to merge. + * @param {number} srcIndex The index of `source`. + * @param {Function} mergeFunc The function to merge values. + * @param {Function} [customizer] The function to customize assigned values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ + function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = object[key], + srcValue = source[key], + stacked = stack.get(srcValue); + + if (stacked) { + assignMergeValue(object, key, stacked); + return; + } + var newValue = customizer + ? customizer(objValue, srcValue, (key + ''), object, source, stack) + : undefined; + + var isCommon = newValue === undefined; + + if (isCommon) { + newValue = srcValue; + if (isArray(srcValue) || isTypedArray(srcValue)) { + if (isArray(objValue)) { + newValue = objValue; + } + else if (isArrayLikeObject(objValue)) { + newValue = copyArray(objValue); + } + else { + isCommon = false; + newValue = baseClone(srcValue, true); + } + } + else if (isPlainObject(srcValue) || isArguments(srcValue)) { + if (isArguments(objValue)) { + newValue = toPlainObject(objValue); + } + else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) { + isCommon = false; + newValue = baseClone(srcValue, true); + } + else { + newValue = objValue; + } + } + else { + isCommon = false; + } + } + if (isCommon) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, newValue); + mergeFunc(newValue, srcValue, srcIndex, customizer, stack); + stack['delete'](srcValue); + } + assignMergeValue(object, key, newValue); + } + + /** + * The base implementation of `_.nth` which doesn't coerce arguments. + * + * @private + * @param {Array} array The array to query. + * @param {number} n The index of the element to return. + * @returns {*} Returns the nth element of `array`. + */ + function baseNth(array, n) { + var length = array.length; + if (!length) { + return; + } + n += n < 0 ? length : 0; + return isIndex(n, length) ? array[n] : undefined; + } + + /** + * The base implementation of `_.orderBy` without param guards. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. + * @param {string[]} orders The sort orders of `iteratees`. + * @returns {Array} Returns the new sorted array. + */ + function baseOrderBy(collection, iteratees, orders) { + var index = -1; + iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(getIteratee())); + + var result = baseMap(collection, function(value, key, collection) { + var criteria = arrayMap(iteratees, function(iteratee) { + return iteratee(value); + }); + return { 'criteria': criteria, 'index': ++index, 'value': value }; + }); + + return baseSortBy(result, function(object, other) { + return compareMultiple(object, other, orders); + }); + } + + /** + * The base implementation of `_.pick` without support for individual + * property identifiers. + * + * @private + * @param {Object} object The source object. + * @param {string[]} props The property identifiers to pick. + * @returns {Object} Returns the new object. + */ + function basePick(object, props) { + object = Object(object); + return basePickBy(object, props, function(value, key) { + return key in object; + }); + } + + /** + * The base implementation of `_.pickBy` without support for iteratee shorthands. + * + * @private + * @param {Object} object The source object. + * @param {string[]} props The property identifiers to pick from. + * @param {Function} predicate The function invoked per property. + * @returns {Object} Returns the new object. + */ + function basePickBy(object, props, predicate) { + var index = -1, + length = props.length, + result = {}; + + while (++index < length) { + var key = props[index], + value = object[key]; + + if (predicate(value, key)) { + baseAssignValue(result, key, value); + } + } + return result; + } + + /** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; + } + + /** + * The base implementation of `_.pullAllBy` without support for iteratee + * shorthands. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + */ + function basePullAll(array, values, iteratee, comparator) { + var indexOf = comparator ? baseIndexOfWith : baseIndexOf, + index = -1, + length = values.length, + seen = array; + + if (array === values) { + values = copyArray(values); + } + if (iteratee) { + seen = arrayMap(array, baseUnary(iteratee)); + } + while (++index < length) { + var fromIndex = 0, + value = values[index], + computed = iteratee ? iteratee(value) : value; + + while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { + if (seen !== array) { + splice.call(seen, fromIndex, 1); + } + splice.call(array, fromIndex, 1); + } + } + return array; + } + + /** + * The base implementation of `_.pullAt` without support for individual + * indexes or capturing the removed elements. + * + * @private + * @param {Array} array The array to modify. + * @param {number[]} indexes The indexes of elements to remove. + * @returns {Array} Returns `array`. + */ + function basePullAt(array, indexes) { + var length = array ? indexes.length : 0, + lastIndex = length - 1; + + while (length--) { + var index = indexes[length]; + if (length == lastIndex || index !== previous) { + var previous = index; + if (isIndex(index)) { + splice.call(array, index, 1); + } + else if (!isKey(index, array)) { + var path = castPath(index), + object = parent(array, path); + + if (object != null) { + delete object[toKey(last(path))]; + } + } + else { + delete array[toKey(index)]; + } + } + } + return array; + } + + /** + * The base implementation of `_.random` without support for returning + * floating-point numbers. + * + * @private + * @param {number} lower The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the random number. + */ + function baseRandom(lower, upper) { + return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); + } + + /** + * The base implementation of `_.range` and `_.rangeRight` which doesn't + * coerce arguments. + * + * @private + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @param {number} step The value to increment or decrement by. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the range of numbers. + */ + function baseRange(start, end, step, fromRight) { + var index = -1, + length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), + result = Array(length); + + while (length--) { + result[fromRight ? length : ++index] = start; + start += step; + } + return result; + } + + /** + * The base implementation of `_.repeat` which doesn't coerce arguments. + * + * @private + * @param {string} string The string to repeat. + * @param {number} n The number of times to repeat the string. + * @returns {string} Returns the repeated string. + */ + function baseRepeat(string, n) { + var result = ''; + if (!string || n < 1 || n > MAX_SAFE_INTEGER) { + return result; + } + // Leverage the exponentiation by squaring algorithm for a faster repeat. + // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. + do { + if (n % 2) { + result += string; + } + n = nativeFloor(n / 2); + if (n) { + string += string; + } + } while (n); + + return result; + } + + /** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ + function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); + } + + /** + * The base implementation of `_.set`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ + function baseSet(object, path, value, customizer) { + if (!isObject(object)) { + return object; + } + path = isKey(path, object) ? [path] : castPath(path); + + var index = -1, + length = path.length, + lastIndex = length - 1, + nested = object; + + while (nested != null && ++index < length) { + var key = toKey(path[index]), + newValue = value; + + if (index != lastIndex) { + var objValue = nested[key]; + newValue = customizer ? customizer(objValue, key, nested) : undefined; + if (newValue === undefined) { + newValue = isObject(objValue) + ? objValue + : (isIndex(path[index + 1]) ? [] : {}); + } + } + assignValue(nested, key, newValue); + nested = nested[key]; + } + return object; + } + + /** + * The base implementation of `setData` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ + var baseSetData = !metaMap ? identity : function(func, data) { + metaMap.set(func, data); + return func; + }; + + /** + * The base implementation of `setToString` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var baseSetToString = !nativeDefineProperty ? identity : function(func, string) { + return nativeDefineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant(string), + 'writable': true + }); + }; + + /** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; + } + + /** + * The base implementation of `_.some` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function baseSome(collection, predicate) { + var result; + + baseEach(collection, function(value, index, collection) { + result = predicate(value, index, collection); + return !result; + }); + return !!result; + } + + /** + * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which + * performs a binary search of `array` to determine the index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ + function baseSortedIndex(array, value, retHighest) { + var low = 0, + high = array ? array.length : low; + + if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { + while (low < high) { + var mid = (low + high) >>> 1, + computed = array[mid]; + + if (computed !== null && !isSymbol(computed) && + (retHighest ? (computed <= value) : (computed < value))) { + low = mid + 1; + } else { + high = mid; + } + } + return high; + } + return baseSortedIndexBy(array, value, identity, retHighest); + } + + /** + * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` + * which invokes `iteratee` for `value` and each element of `array` to compute + * their sort ranking. The iteratee is invoked with one argument; (value). + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} iteratee The iteratee invoked per element. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ + function baseSortedIndexBy(array, value, iteratee, retHighest) { + value = iteratee(value); + + var low = 0, + high = array ? array.length : 0, + valIsNaN = value !== value, + valIsNull = value === null, + valIsSymbol = isSymbol(value), + valIsUndefined = value === undefined; + + while (low < high) { + var mid = nativeFloor((low + high) / 2), + computed = iteratee(array[mid]), + othIsDefined = computed !== undefined, + othIsNull = computed === null, + othIsReflexive = computed === computed, + othIsSymbol = isSymbol(computed); + + if (valIsNaN) { + var setLow = retHighest || othIsReflexive; + } else if (valIsUndefined) { + setLow = othIsReflexive && (retHighest || othIsDefined); + } else if (valIsNull) { + setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); + } else if (valIsSymbol) { + setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); + } else if (othIsNull || othIsSymbol) { + setLow = false; + } else { + setLow = retHighest ? (computed <= value) : (computed < value); + } + if (setLow) { + low = mid + 1; + } else { + high = mid; + } + } + return nativeMin(high, MAX_ARRAY_INDEX); + } + + /** + * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ + function baseSortedUniq(array, iteratee) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + if (!index || !eq(computed, seen)) { + var seen = computed; + result[resIndex++] = value === 0 ? 0 : value; + } + } + return result; + } + + /** + * The base implementation of `_.toNumber` which doesn't ensure correct + * conversions of binary, hexadecimal, or octal string values. + * + * @private + * @param {*} value The value to process. + * @returns {number} Returns the number. + */ + function baseToNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + return +value; + } + + /** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ + function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + } + + /** + * The base implementation of `_.uniqBy` without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ + function baseUniq(array, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + length = array.length, + isCommon = true, + result = [], + seen = result; + + if (comparator) { + isCommon = false; + includes = arrayIncludesWith; + } + else if (length >= LARGE_ARRAY_SIZE) { + var set = iteratee ? null : createSet(array); + if (set) { + return setToArray(set); + } + isCommon = false; + includes = cacheHas; + seen = new SetCache; + } + else { + seen = iteratee ? [] : result; + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; + } + } + if (iteratee) { + seen.push(computed); + } + result.push(value); + } + else if (!includes(seen, computed, comparator)) { + if (seen !== result) { + seen.push(computed); + } + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.unset`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. + */ + function baseUnset(object, path) { + path = isKey(path, object) ? [path] : castPath(path); + object = parent(object, path); + + var key = toKey(last(path)); + return !(object != null && hasOwnProperty.call(object, key)) || delete object[key]; + } + + /** + * The base implementation of `_.update`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to update. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ + function baseUpdate(object, path, updater, customizer) { + return baseSet(object, path, updater(baseGet(object, path)), customizer); + } + + /** + * The base implementation of methods like `_.dropWhile` and `_.takeWhile` + * without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to query. + * @param {Function} predicate The function invoked per iteration. + * @param {boolean} [isDrop] Specify dropping elements instead of taking them. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the slice of `array`. + */ + function baseWhile(array, predicate, isDrop, fromRight) { + var length = array.length, + index = fromRight ? length : -1; + + while ((fromRight ? index-- : ++index < length) && + predicate(array[index], index, array)) {} + + return isDrop + ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) + : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); + } + + /** + * The base implementation of `wrapperValue` which returns the result of + * performing a sequence of actions on the unwrapped `value`, where each + * successive action is supplied the return value of the previous. + * + * @private + * @param {*} value The unwrapped value. + * @param {Array} actions Actions to perform to resolve the unwrapped value. + * @returns {*} Returns the resolved value. + */ + function baseWrapperValue(value, actions) { + var result = value; + if (result instanceof LazyWrapper) { + result = result.value(); + } + return arrayReduce(actions, function(result, action) { + return action.func.apply(action.thisArg, arrayPush([result], action.args)); + }, result); + } + + /** + * The base implementation of methods like `_.xor`, without support for + * iteratee shorthands, that accepts an array of arrays to inspect. + * + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of values. + */ + function baseXor(arrays, iteratee, comparator) { + var index = -1, + length = arrays.length; + + while (++index < length) { + var result = result + ? arrayPush( + baseDifference(result, arrays[index], iteratee, comparator), + baseDifference(arrays[index], result, iteratee, comparator) + ) + : arrays[index]; + } + return (result && result.length) ? baseUniq(result, iteratee, comparator) : []; + } + + /** + * This base implementation of `_.zipObject` which assigns values using `assignFunc`. + * + * @private + * @param {Array} props The property identifiers. + * @param {Array} values The property values. + * @param {Function} assignFunc The function to assign values. + * @returns {Object} Returns the new object. + */ + function baseZipObject(props, values, assignFunc) { + var index = -1, + length = props.length, + valsLength = values.length, + result = {}; + + while (++index < length) { + var value = index < valsLength ? values[index] : undefined; + assignFunc(result, props[index], value); + } + return result; + } + + /** + * Casts `value` to an empty array if it's not an array like object. + * + * @private + * @param {*} value The value to inspect. + * @returns {Array|Object} Returns the cast array-like object. + */ + function castArrayLikeObject(value) { + return isArrayLikeObject(value) ? value : []; + } + + /** + * Casts `value` to `identity` if it's not a function. + * + * @private + * @param {*} value The value to inspect. + * @returns {Function} Returns cast function. + */ + function castFunction(value) { + return typeof value == 'function' ? value : identity; + } + + /** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @returns {Array} Returns the cast property path array. + */ + function castPath(value) { + return isArray(value) ? value : stringToPath(value); + } + + /** + * A `baseRest` alias which can be replaced with `identity` by module + * replacement plugins. + * + * @private + * @type {Function} + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ + var castRest = baseRest; + + /** + * Casts `array` to a slice if it's needed. + * + * @private + * @param {Array} array The array to inspect. + * @param {number} start The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the cast slice. + */ + function castSlice(array, start, end) { + var length = array.length; + end = end === undefined ? length : end; + return (!start && end >= length) ? array : baseSlice(array, start, end); + } + + /** + * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). + * + * @private + * @param {number|Object} id The timer id or timeout object of the timer to clear. + */ + var clearTimeout = ctxClearTimeout || function(id) { + return root.clearTimeout(id); + }; + + /** + * Creates a clone of `buffer`. + * + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. + */ + function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var result = new buffer.constructor(buffer.length); + buffer.copy(result); + return result; + } + + /** + * Creates a clone of `arrayBuffer`. + * + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ + function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array(result).set(new Uint8Array(arrayBuffer)); + return result; + } + + /** + * Creates a clone of `dataView`. + * + * @private + * @param {Object} dataView The data view to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned data view. + */ + function cloneDataView(dataView, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; + return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); + } + + /** + * Creates a clone of `map`. + * + * @private + * @param {Object} map The map to clone. + * @param {Function} cloneFunc The function to clone values. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned map. + */ + function cloneMap(map, isDeep, cloneFunc) { + var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map); + return arrayReduce(array, addMapEntry, new map.constructor); + } + + /** + * Creates a clone of `regexp`. + * + * @private + * @param {Object} regexp The regexp to clone. + * @returns {Object} Returns the cloned regexp. + */ + function cloneRegExp(regexp) { + var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); + result.lastIndex = regexp.lastIndex; + return result; + } + + /** + * Creates a clone of `set`. + * + * @private + * @param {Object} set The set to clone. + * @param {Function} cloneFunc The function to clone values. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned set. + */ + function cloneSet(set, isDeep, cloneFunc) { + var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set); + return arrayReduce(array, addSetEntry, new set.constructor); + } + + /** + * Creates a clone of the `symbol` object. + * + * @private + * @param {Object} symbol The symbol object to clone. + * @returns {Object} Returns the cloned symbol object. + */ + function cloneSymbol(symbol) { + return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; + } + + /** + * Creates a clone of `typedArray`. + * + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */ + function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); + } + + /** + * Compares values to sort them in ascending order. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. + */ + function compareAscending(value, other) { + if (value !== other) { + var valIsDefined = value !== undefined, + valIsNull = value === null, + valIsReflexive = value === value, + valIsSymbol = isSymbol(value); + + var othIsDefined = other !== undefined, + othIsNull = other === null, + othIsReflexive = other === other, + othIsSymbol = isSymbol(other); + + if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || + (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || + (valIsNull && othIsDefined && othIsReflexive) || + (!valIsDefined && othIsReflexive) || + !valIsReflexive) { + return 1; + } + if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || + (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || + (othIsNull && valIsDefined && valIsReflexive) || + (!othIsDefined && valIsReflexive) || + !othIsReflexive) { + return -1; + } + } + return 0; + } + + /** + * Used by `_.orderBy` to compare multiple properties of a value to another + * and stable sort them. + * + * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, + * specify an order of "desc" for descending or "asc" for ascending sort order + * of corresponding values. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {boolean[]|string[]} orders The order to sort by for each property. + * @returns {number} Returns the sort order indicator for `object`. + */ + function compareMultiple(object, other, orders) { + var index = -1, + objCriteria = object.criteria, + othCriteria = other.criteria, + length = objCriteria.length, + ordersLength = orders.length; + + while (++index < length) { + var result = compareAscending(objCriteria[index], othCriteria[index]); + if (result) { + if (index >= ordersLength) { + return result; + } + var order = orders[index]; + return result * (order == 'desc' ? -1 : 1); + } + } + // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications + // that causes it, under certain circumstances, to provide the same value for + // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 + // for more details. + // + // This also ensures a stable sort in V8 and other engines. + // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. + return object.index - other.index; + } + + /** + * Creates an array that is the composition of partially applied arguments, + * placeholders, and provided arguments into a single array of arguments. + * + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to prepend to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. + */ + function composeArgs(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersLength = holders.length, + leftIndex = -1, + leftLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(leftLength + rangeLength), + isUncurried = !isCurried; + + while (++leftIndex < leftLength) { + result[leftIndex] = partials[leftIndex]; + } + while (++argsIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[holders[argsIndex]] = args[argsIndex]; + } + } + while (rangeLength--) { + result[leftIndex++] = args[argsIndex++]; + } + return result; + } + + /** + * This function is like `composeArgs` except that the arguments composition + * is tailored for `_.partialRight`. + * + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to append to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. + */ + function composeArgsRight(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersIndex = -1, + holdersLength = holders.length, + rightIndex = -1, + rightLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(rangeLength + rightLength), + isUncurried = !isCurried; + + while (++argsIndex < rangeLength) { + result[argsIndex] = args[argsIndex]; + } + var offset = argsIndex; + while (++rightIndex < rightLength) { + result[offset + rightIndex] = partials[rightIndex]; + } + while (++holdersIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[offset + holders[holdersIndex]] = args[argsIndex++]; + } + } + return result; + } + + /** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ + function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; + } + + /** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ + function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; + } + + /** + * Copies own symbol properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ + function copySymbols(source, object) { + return copyObject(source, getSymbols(source), object); + } + + /** + * Creates a function like `_.groupBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} [initializer] The accumulator object initializer. + * @returns {Function} Returns the new aggregator function. + */ + function createAggregator(setter, initializer) { + return function(collection, iteratee) { + var func = isArray(collection) ? arrayAggregator : baseAggregator, + accumulator = initializer ? initializer() : {}; + + return func(collection, setter, getIteratee(iteratee, 2), accumulator); + }; + } + + /** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ + function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); + } + + /** + * Creates a `baseEach` or `baseEachRight` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee) { + if (collection == null) { + return collection; + } + if (!isArrayLike(collection)) { + return eachFunc(collection, iteratee); + } + var length = collection.length, + index = fromRight ? length : -1, + iterable = Object(collection); + + while ((fromRight ? index-- : ++index < length)) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; + } + + /** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } + + /** + * Creates a function that wraps `func` to invoke it with the optional `this` + * binding of `thisArg`. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createBind(func, bitmask, thisArg) { + var isBind = bitmask & BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return fn.apply(isBind ? thisArg : this, arguments); + } + return wrapper; + } + + /** + * Creates a function like `_.lowerFirst`. + * + * @private + * @param {string} methodName The name of the `String` case method to use. + * @returns {Function} Returns the new case function. + */ + function createCaseFirst(methodName) { + return function(string) { + string = toString(string); + + var strSymbols = hasUnicode(string) + ? stringToArray(string) + : undefined; + + var chr = strSymbols + ? strSymbols[0] + : string.charAt(0); + + var trailing = strSymbols + ? castSlice(strSymbols, 1).join('') + : string.slice(1); + + return chr[methodName]() + trailing; + }; + } + + /** + * Creates a function like `_.camelCase`. + * + * @private + * @param {Function} callback The function to combine each word. + * @returns {Function} Returns the new compounder function. + */ + function createCompounder(callback) { + return function(string) { + return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); + }; + } + + /** + * Creates a function that produces an instance of `Ctor` regardless of + * whether it was invoked as part of a `new` expression or by `call` or `apply`. + * + * @private + * @param {Function} Ctor The constructor to wrap. + * @returns {Function} Returns the new wrapped function. + */ + function createCtor(Ctor) { + return function() { + // Use a `switch` statement to work with class constructors. See + // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist + // for more details. + var args = arguments; + switch (args.length) { + case 0: return new Ctor; + case 1: return new Ctor(args[0]); + case 2: return new Ctor(args[0], args[1]); + case 3: return new Ctor(args[0], args[1], args[2]); + case 4: return new Ctor(args[0], args[1], args[2], args[3]); + case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); + case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); + case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + } + var thisBinding = baseCreate(Ctor.prototype), + result = Ctor.apply(thisBinding, args); + + // Mimic the constructor's `return` behavior. + // See https://es5.github.io/#x13.2.2 for more details. + return isObject(result) ? result : thisBinding; + }; + } + + /** + * Creates a function that wraps `func` to enable currying. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {number} arity The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createCurry(func, bitmask, arity) { + var Ctor = createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length, + placeholder = getHolder(wrapper); + + while (index--) { + args[index] = arguments[index]; + } + var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) + ? [] + : replaceHolders(args, placeholder); + + length -= holders.length; + if (length < arity) { + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, undefined, + args, holders, undefined, undefined, arity - length); + } + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return apply(fn, this, args); + } + return wrapper; + } + + /** + * Creates a `_.find` or `_.findLast` function. + * + * @private + * @param {Function} findIndexFunc The function to find the collection index. + * @returns {Function} Returns the new find function. + */ + function createFind(findIndexFunc) { + return function(collection, predicate, fromIndex) { + var iterable = Object(collection); + if (!isArrayLike(collection)) { + var iteratee = getIteratee(predicate, 3); + collection = keys(collection); + predicate = function(key) { return iteratee(iterable[key], key, iterable); }; + } + var index = findIndexFunc(collection, predicate, fromIndex); + return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; + }; + } + + /** + * Creates a `_.flow` or `_.flowRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new flow function. + */ + function createFlow(fromRight) { + return flatRest(function(funcs) { + var length = funcs.length, + index = length, + prereq = LodashWrapper.prototype.thru; + + if (fromRight) { + funcs.reverse(); + } + while (index--) { + var func = funcs[index]; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (prereq && !wrapper && getFuncName(func) == 'wrapper') { + var wrapper = new LodashWrapper([], true); + } + } + index = wrapper ? index : length; + while (++index < length) { + func = funcs[index]; + + var funcName = getFuncName(func), + data = funcName == 'wrapper' ? getData(func) : undefined; + + if (data && isLaziable(data[0]) && + data[1] == (ARY_FLAG | CURRY_FLAG | PARTIAL_FLAG | REARG_FLAG) && + !data[4].length && data[9] == 1 + ) { + wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); + } else { + wrapper = (func.length == 1 && isLaziable(func)) + ? wrapper[funcName]() + : wrapper.thru(func); + } + } + return function() { + var args = arguments, + value = args[0]; + + if (wrapper && args.length == 1 && + isArray(value) && value.length >= LARGE_ARRAY_SIZE) { + return wrapper.plant(value).value(); + } + var index = 0, + result = length ? funcs[index].apply(this, args) : value; + + while (++index < length) { + result = funcs[index].call(this, result); + } + return result; + }; + }); + } + + /** + * Creates a function that wraps `func` to invoke it with optional `this` + * binding of `thisArg`, partial application, and currying. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [partialsRight] The arguments to append to those provided + * to the new function. + * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { + var isAry = bitmask & ARY_FLAG, + isBind = bitmask & BIND_FLAG, + isBindKey = bitmask & BIND_KEY_FLAG, + isCurried = bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG), + isFlip = bitmask & FLIP_FLAG, + Ctor = isBindKey ? undefined : createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length; + + while (index--) { + args[index] = arguments[index]; + } + if (isCurried) { + var placeholder = getHolder(wrapper), + holdersCount = countHolders(args, placeholder); + } + if (partials) { + args = composeArgs(args, partials, holders, isCurried); + } + if (partialsRight) { + args = composeArgsRight(args, partialsRight, holdersRight, isCurried); + } + length -= holdersCount; + if (isCurried && length < arity) { + var newHolders = replaceHolders(args, placeholder); + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, thisArg, + args, newHolders, argPos, ary, arity - length + ); + } + var thisBinding = isBind ? thisArg : this, + fn = isBindKey ? thisBinding[func] : func; + + length = args.length; + if (argPos) { + args = reorder(args, argPos); + } else if (isFlip && length > 1) { + args.reverse(); + } + if (isAry && ary < length) { + args.length = ary; + } + if (this && this !== root && this instanceof wrapper) { + fn = Ctor || createCtor(fn); + } + return fn.apply(thisBinding, args); + } + return wrapper; + } + + /** + * Creates a function like `_.invertBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} toIteratee The function to resolve iteratees. + * @returns {Function} Returns the new inverter function. + */ + function createInverter(setter, toIteratee) { + return function(object, iteratee) { + return baseInverter(object, setter, toIteratee(iteratee), {}); + }; + } + + /** + * Creates a function that performs a mathematical operation on two values. + * + * @private + * @param {Function} operator The function to perform the operation. + * @param {number} [defaultValue] The value used for `undefined` arguments. + * @returns {Function} Returns the new mathematical operation function. + */ + function createMathOperation(operator, defaultValue) { + return function(value, other) { + var result; + if (value === undefined && other === undefined) { + return defaultValue; + } + if (value !== undefined) { + result = value; + } + if (other !== undefined) { + if (result === undefined) { + return other; + } + if (typeof value == 'string' || typeof other == 'string') { + value = baseToString(value); + other = baseToString(other); + } else { + value = baseToNumber(value); + other = baseToNumber(other); + } + result = operator(value, other); + } + return result; + }; + } + + /** + * Creates a function like `_.over`. + * + * @private + * @param {Function} arrayFunc The function to iterate over iteratees. + * @returns {Function} Returns the new over function. + */ + function createOver(arrayFunc) { + return flatRest(function(iteratees) { + iteratees = arrayMap(iteratees, baseUnary(getIteratee())); + return baseRest(function(args) { + var thisArg = this; + return arrayFunc(iteratees, function(iteratee) { + return apply(iteratee, thisArg, args); + }); + }); + }); + } + + /** + * Creates the padding for `string` based on `length`. The `chars` string + * is truncated if the number of characters exceeds `length`. + * + * @private + * @param {number} length The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padding for `string`. + */ + function createPadding(length, chars) { + chars = chars === undefined ? ' ' : baseToString(chars); + + var charsLength = chars.length; + if (charsLength < 2) { + return charsLength ? baseRepeat(chars, length) : chars; + } + var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); + return hasUnicode(chars) + ? castSlice(stringToArray(result), 0, length).join('') + : result.slice(0, length); + } + + /** + * Creates a function that wraps `func` to invoke it with the `this` binding + * of `thisArg` and `partials` prepended to the arguments it receives. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} partials The arguments to prepend to those provided to + * the new function. + * @returns {Function} Returns the new wrapped function. + */ + function createPartial(func, bitmask, thisArg, partials) { + var isBind = bitmask & BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var argsIndex = -1, + argsLength = arguments.length, + leftIndex = -1, + leftLength = partials.length, + args = Array(leftLength + argsLength), + fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + + while (++leftIndex < leftLength) { + args[leftIndex] = partials[leftIndex]; + } + while (argsLength--) { + args[leftIndex++] = arguments[++argsIndex]; + } + return apply(fn, isBind ? thisArg : this, args); + } + return wrapper; + } + + /** + * Creates a `_.range` or `_.rangeRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new range function. + */ + function createRange(fromRight) { + return function(start, end, step) { + if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { + end = step = undefined; + } + // Ensure the sign of `-0` is preserved. + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); + return baseRange(start, end, step, fromRight); + }; + } + + /** + * Creates a function that performs a relational operation on two values. + * + * @private + * @param {Function} operator The function to perform the operation. + * @returns {Function} Returns the new relational operation function. + */ + function createRelationalOperation(operator) { + return function(value, other) { + if (!(typeof value == 'string' && typeof other == 'string')) { + value = toNumber(value); + other = toNumber(other); + } + return operator(value, other); + }; + } + + /** + * Creates a function that wraps `func` to continue currying. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {Function} wrapFunc The function to create the `func` wrapper. + * @param {*} placeholder The placeholder value. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { + var isCurry = bitmask & CURRY_FLAG, + newHolders = isCurry ? holders : undefined, + newHoldersRight = isCurry ? undefined : holders, + newPartials = isCurry ? partials : undefined, + newPartialsRight = isCurry ? undefined : partials; + + bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG); + bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG); + + if (!(bitmask & CURRY_BOUND_FLAG)) { + bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG); + } + var newData = [ + func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, + newHoldersRight, argPos, ary, arity + ]; + + var result = wrapFunc.apply(undefined, newData); + if (isLaziable(func)) { + setData(result, newData); + } + result.placeholder = placeholder; + return setWrapToString(result, func, bitmask); + } + + /** + * Creates a function like `_.round`. + * + * @private + * @param {string} methodName The name of the `Math` method to use when rounding. + * @returns {Function} Returns the new round function. + */ + function createRound(methodName) { + var func = Math[methodName]; + return function(number, precision) { + number = toNumber(number); + precision = nativeMin(toInteger(precision), 292); + if (precision) { + // Shift with exponential notation to avoid floating-point issues. + // See [MDN](https://mdn.io/round#Examples) for more details. + var pair = (toString(number) + 'e').split('e'), + value = func(pair[0] + 'e' + (+pair[1] + precision)); + + pair = (toString(value) + 'e').split('e'); + return +(pair[0] + 'e' + (+pair[1] - precision)); + } + return func(number); + }; + } + + /** + * Creates a set object of `values`. + * + * @private + * @param {Array} values The values to add to the set. + * @returns {Object} Returns the new set. + */ + var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { + return new Set(values); + }; + + /** + * Creates a `_.toPairs` or `_.toPairsIn` function. + * + * @private + * @param {Function} keysFunc The function to get the keys of a given object. + * @returns {Function} Returns the new pairs function. + */ + function createToPairs(keysFunc) { + return function(object) { + var tag = getTag(object); + if (tag == mapTag) { + return mapToArray(object); + } + if (tag == setTag) { + return setToPairs(object); + } + return baseToPairs(object, keysFunc(object)); + }; + } + + /** + * Creates a function that either curries or invokes `func` with optional + * `this` binding and partially applied arguments. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. + * The bitmask may be composed of the following flags: + * 1 - `_.bind` + * 2 - `_.bindKey` + * 4 - `_.curry` or `_.curryRight` of a bound function + * 8 - `_.curry` + * 16 - `_.curryRight` + * 32 - `_.partial` + * 64 - `_.partialRight` + * 128 - `_.rearg` + * 256 - `_.ary` + * 512 - `_.flip` + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to be partially applied. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { + var isBindKey = bitmask & BIND_KEY_FLAG; + if (!isBindKey && typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + var length = partials ? partials.length : 0; + if (!length) { + bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG); + partials = holders = undefined; + } + ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); + arity = arity === undefined ? arity : toInteger(arity); + length -= holders ? holders.length : 0; + + if (bitmask & PARTIAL_RIGHT_FLAG) { + var partialsRight = partials, + holdersRight = holders; + + partials = holders = undefined; + } + var data = isBindKey ? undefined : getData(func); + + var newData = [ + func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, + argPos, ary, arity + ]; + + if (data) { + mergeData(newData, data); + } + func = newData[0]; + bitmask = newData[1]; + thisArg = newData[2]; + partials = newData[3]; + holders = newData[4]; + arity = newData[9] = newData[9] == null + ? (isBindKey ? 0 : func.length) + : nativeMax(newData[9] - length, 0); + + if (!arity && bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG)) { + bitmask &= ~(CURRY_FLAG | CURRY_RIGHT_FLAG); + } + if (!bitmask || bitmask == BIND_FLAG) { + var result = createBind(func, bitmask, thisArg); + } else if (bitmask == CURRY_FLAG || bitmask == CURRY_RIGHT_FLAG) { + result = createCurry(func, bitmask, arity); + } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !holders.length) { + result = createPartial(func, bitmask, thisArg, partials); + } else { + result = createHybrid.apply(undefined, newData); + } + var setter = data ? baseSetData : setData; + return setWrapToString(setter(result, newData), func, bitmask); + } + + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} customizer The function to customize comparisons. + * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` + * for more details. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + function equalArrays(array, other, equalFunc, customizer, bitmask, stack) { + var isPartial = bitmask & PARTIAL_COMPARE_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(array); + if (stacked && stack.get(other)) { + return stacked == other; + } + var index = -1, + result = true, + seen = (bitmask & UNORDERED_COMPARE_FLAG) ? new SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, customizer, bitmask, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; + } + + /** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} customizer The function to customize comparisons. + * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` + * for more details. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) { + switch (tag) { + case dataViewTag: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; + } + return true; + + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag: + var convert = mapToArray; + + case setTag: + var isPartial = bitmask & PARTIAL_COMPARE_FLAG; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= UNORDERED_COMPARE_FLAG; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask, stack); + stack['delete'](object); + return result; + + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; + } + + /** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} customizer The function to customize comparisons. + * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` + * for more details. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalObjects(object, other, equalFunc, customizer, bitmask, stack) { + var isPartial = bitmask & PARTIAL_COMPARE_FLAG, + objProps = keys(object), + objLength = objProps.length, + othProps = keys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked && stack.get(other)) { + return stacked == other; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; + } + + /** + * A specialized version of `baseRest` which flattens the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ + function flatRest(func) { + return setToString(overRest(func, undefined, flatten), func + ''); + } + + /** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); + } + + /** + * Creates an array of own and inherited enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeysIn(object) { + return baseGetAllKeys(object, keysIn, getSymbolsIn); + } + + /** + * Gets metadata for `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {*} Returns the metadata for `func`. + */ + var getData = !metaMap ? noop : function(func) { + return metaMap.get(func); + }; + + /** + * Gets the name of `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {string} Returns the function name. + */ + function getFuncName(func) { + var result = (func.name + ''), + array = realNames[result], + length = hasOwnProperty.call(realNames, result) ? array.length : 0; + + while (length--) { + var data = array[length], + otherFunc = data.func; + if (otherFunc == null || otherFunc == func) { + return data.name; + } + } + return result; + } + + /** + * Gets the argument placeholder value for `func`. + * + * @private + * @param {Function} func The function to inspect. + * @returns {*} Returns the placeholder value. + */ + function getHolder(func) { + var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; + return object.placeholder; + } + + /** + * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, + * this function returns the custom method, otherwise it returns `baseIteratee`. + * If arguments are provided, the chosen function is invoked with them and + * its result is returned. + * + * @private + * @param {*} [value] The value to convert to an iteratee. + * @param {number} [arity] The arity of the created iteratee. + * @returns {Function} Returns the chosen function or its result. + */ + function getIteratee() { + var result = lodash.iteratee || iteratee; + result = result === iteratee ? baseIteratee : result; + return arguments.length ? result(arguments[0], arguments[1]) : result; + } + + /** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ + function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; + } + + /** + * Gets the property names, values, and compare flags of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. + */ + function getMatchData(object) { + var result = keys(object), + length = result.length; + + while (length--) { + var key = result[length], + value = object[key]; + + result[length] = [key, value, isStrictComparable(value)]; + } + return result; + } + + /** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ + function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; + } + + /** + * Creates an array of the own enumerable symbol properties of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray; + + /** + * Creates an array of the own and inherited enumerable symbol properties + * of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { + var result = []; + while (object) { + arrayPush(result, getSymbols(object)); + object = getPrototype(object); + } + return result; + }; + + /** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + var getTag = baseGetTag; + + // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. + if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set) != setTag) || + (WeakMap && getTag(new WeakMap) != weakMapTag)) { + getTag = function(value) { + var result = objectToString.call(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : undefined; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag; + case mapCtorString: return mapTag; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag; + case weakMapCtorString: return weakMapTag; + } + } + return result; + }; + } + + /** + * Gets the view, applying any `transforms` to the `start` and `end` positions. + * + * @private + * @param {number} start The start of the view. + * @param {number} end The end of the view. + * @param {Array} transforms The transformations to apply to the view. + * @returns {Object} Returns an object containing the `start` and `end` + * positions of the view. + */ + function getView(start, end, transforms) { + var index = -1, + length = transforms.length; + + while (++index < length) { + var data = transforms[index], + size = data.size; + + switch (data.type) { + case 'drop': start += size; break; + case 'dropRight': end -= size; break; + case 'take': end = nativeMin(end, start + size); break; + case 'takeRight': start = nativeMax(start, end - size); break; + } + } + return { 'start': start, 'end': end }; + } + + /** + * Extracts wrapper details from the `source` body comment. + * + * @private + * @param {string} source The source to inspect. + * @returns {Array} Returns the wrapper details. + */ + function getWrapDetails(source) { + var match = source.match(reWrapDetails); + return match ? match[1].split(reSplitDetails) : []; + } + + /** + * Checks if `path` exists on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + */ + function hasPath(object, path, hasFunc) { + path = isKey(path, object) ? [path] : castPath(path); + + var index = -1, + length = path.length, + result = false; + + while (++index < length) { + var key = toKey(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result || ++index != length) { + return result; + } + length = object ? object.length : 0; + return !!length && isLength(length) && isIndex(key, length) && + (isArray(object) || isArguments(object)); + } + + /** + * Initializes an array clone. + * + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the initialized clone. + */ + function initCloneArray(array) { + var length = array.length, + result = array.constructor(length); + + // Add properties assigned by `RegExp#exec`. + if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { + result.index = array.index; + result.input = array.input; + } + return result; + } + + /** + * Initializes an object clone. + * + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneObject(object) { + return (typeof object.constructor == 'function' && !isPrototype(object)) + ? baseCreate(getPrototype(object)) + : {}; + } + + /** + * Initializes an object clone based on its `toStringTag`. + * + * **Note:** This function only supports cloning values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to clone. + * @param {string} tag The `toStringTag` of the object to clone. + * @param {Function} cloneFunc The function to clone values. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneByTag(object, tag, cloneFunc, isDeep) { + var Ctor = object.constructor; + switch (tag) { + case arrayBufferTag: + return cloneArrayBuffer(object); + + case boolTag: + case dateTag: + return new Ctor(+object); + + case dataViewTag: + return cloneDataView(object, isDeep); + + case float32Tag: case float64Tag: + case int8Tag: case int16Tag: case int32Tag: + case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: + return cloneTypedArray(object, isDeep); + + case mapTag: + return cloneMap(object, isDeep, cloneFunc); + + case numberTag: + case stringTag: + return new Ctor(object); + + case regexpTag: + return cloneRegExp(object); + + case setTag: + return cloneSet(object, isDeep, cloneFunc); + + case symbolTag: + return cloneSymbol(object); + } + } + + /** + * Inserts wrapper `details` in a comment at the top of the `source` body. + * + * @private + * @param {string} source The source to modify. + * @returns {Array} details The details to insert. + * @returns {string} Returns the modified source. + */ + function insertWrapDetails(source, details) { + var length = details.length; + if (!length) { + return source; + } + var lastIndex = length - 1; + details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; + details = details.join(length > 2 ? ', ' : ' '); + return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); + } + + /** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ + function isFlattenable(value) { + return isArray(value) || isArguments(value) || + !!(spreadableSymbol && value && value[spreadableSymbol]); + } + + /** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); + } + + /** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ + function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; + } + + /** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ + function isKey(value, object) { + if (isArray(value)) { + return false; + } + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); + } + + /** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ + function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); + } + + /** + * Checks if `func` has a lazy counterpart. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` has a lazy counterpart, + * else `false`. + */ + function isLaziable(func) { + var funcName = getFuncName(func), + other = lodash[funcName]; + + if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { + return false; + } + if (func === other) { + return true; + } + var data = getData(other); + return !!data && func === data[0]; + } + + /** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ + function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); + } + + /** + * Checks if `func` is capable of being masked. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `func` is maskable, else `false`. + */ + var isMaskable = coreJsData ? isFunction : stubFalse; + + /** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ + function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; + } + + /** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ + function isStrictComparable(value) { + return value === value && !isObject(value); + } + + /** + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. + * + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; + } + + /** + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. + */ + function memoizeCapped(func) { + var result = memoize(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); + + var cache = result.cache; + return result; + } + + /** + * Merges the function metadata of `source` into `data`. + * + * Merging metadata reduces the number of wrappers used to invoke a function. + * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` + * may be applied regardless of execution order. Methods like `_.ary` and + * `_.rearg` modify function arguments, making the order in which they are + * executed important, preventing the merging of metadata. However, we make + * an exception for a safe combined case where curried functions have `_.ary` + * and or `_.rearg` applied. + * + * @private + * @param {Array} data The destination metadata. + * @param {Array} source The source metadata. + * @returns {Array} Returns `data`. + */ + function mergeData(data, source) { + var bitmask = data[1], + srcBitmask = source[1], + newBitmask = bitmask | srcBitmask, + isCommon = newBitmask < (BIND_FLAG | BIND_KEY_FLAG | ARY_FLAG); + + var isCombo = + ((srcBitmask == ARY_FLAG) && (bitmask == CURRY_FLAG)) || + ((srcBitmask == ARY_FLAG) && (bitmask == REARG_FLAG) && (data[7].length <= source[8])) || + ((srcBitmask == (ARY_FLAG | REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == CURRY_FLAG)); + + // Exit early if metadata can't be merged. + if (!(isCommon || isCombo)) { + return data; + } + // Use source `thisArg` if available. + if (srcBitmask & BIND_FLAG) { + data[2] = source[2]; + // Set when currying a bound function. + newBitmask |= bitmask & BIND_FLAG ? 0 : CURRY_BOUND_FLAG; + } + // Compose partial arguments. + var value = source[3]; + if (value) { + var partials = data[3]; + data[3] = partials ? composeArgs(partials, value, source[4]) : value; + data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; + } + // Compose partial right arguments. + value = source[5]; + if (value) { + partials = data[5]; + data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; + data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; + } + // Use source `argPos` if available. + value = source[7]; + if (value) { + data[7] = value; + } + // Use source `ary` if it's smaller. + if (srcBitmask & ARY_FLAG) { + data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); + } + // Use source `arity` if one is not provided. + if (data[9] == null) { + data[9] = source[9]; + } + // Use source `func` and merge bitmasks. + data[0] = source[0]; + data[1] = newBitmask; + + return data; + } + + /** + * Used by `_.defaultsDeep` to customize its `_.merge` use. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to merge. + * @param {Object} object The parent object of `objValue`. + * @param {Object} source The parent object of `srcValue`. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + * @returns {*} Returns the value to assign. + */ + function mergeDefaults(objValue, srcValue, key, object, source, stack) { + if (isObject(objValue) && isObject(srcValue)) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, objValue); + baseMerge(objValue, srcValue, undefined, mergeDefaults, stack); + stack['delete'](srcValue); + } + return objValue; + } + + /** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; + } + + /** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ + function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return apply(func, this, otherArgs); + }; + } + + /** + * Gets the parent value at `path` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} path The path to get the parent value of. + * @returns {*} Returns the parent value. + */ + function parent(object, path) { + return path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); + } + + /** + * Reorder `array` according to the specified indexes where the element at + * the first index is assigned as the first element, the element at + * the second index is assigned as the second element, and so on. + * + * @private + * @param {Array} array The array to reorder. + * @param {Array} indexes The arranged array indexes. + * @returns {Array} Returns `array`. + */ + function reorder(array, indexes) { + var arrLength = array.length, + length = nativeMin(indexes.length, arrLength), + oldArray = copyArray(array); + + while (length--) { + var index = indexes[length]; + array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; + } + return array; + } + + /** + * Sets metadata for `func`. + * + * **Note:** If this function becomes hot, i.e. is invoked a lot in a short + * period of time, it will trip its breaker and transition to an identity + * function to avoid garbage collection pauses in V8. See + * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) + * for more details. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ + var setData = shortOut(baseSetData); + + /** + * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @returns {number|Object} Returns the timer id or timeout object. + */ + var setTimeout = ctxSetTimeout || function(func, wait) { + return root.setTimeout(func, wait); + }; + + /** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var setToString = shortOut(baseSetToString); + + /** + * Sets the `toString` method of `wrapper` to mimic the source of `reference` + * with wrapper details in a comment at the top of the source body. + * + * @private + * @param {Function} wrapper The function to modify. + * @param {Function} reference The reference function. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Function} Returns `wrapper`. + */ + function setWrapToString(wrapper, reference, bitmask) { + var source = (reference + ''); + return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); + } + + /** + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. + * + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. + */ + function shortOut(func) { + var count = 0, + lastCalled = 0; + + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; + } + + /** + * A specialized version of `arrayShuffle` which mutates `array`. + * + * @private + * @param {Array} array The array to shuffle. + * @returns {Array} Returns `array`. + */ + function shuffleSelf(array) { + var index = -1, + length = array.length, + lastIndex = length - 1; + + while (++index < length) { + var rand = baseRandom(index, lastIndex), + value = array[rand]; + + array[rand] = array[index]; + array[index] = value; + } + return array; + } + + /** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ + var stringToPath = memoizeCapped(function(string) { + string = toString(string); + + var result = []; + if (reLeadingDot.test(string)) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, string) { + result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; + }); + + /** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ + function toKey(value) { + if (typeof value == 'string' || isSymbol(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + } + + /** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to process. + * @returns {string} Returns the source code. + */ + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; + } + + /** + * Updates wrapper `details` based on `bitmask` flags. + * + * @private + * @returns {Array} details The details to modify. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Array} Returns `details`. + */ + function updateWrapDetails(details, bitmask) { + arrayEach(wrapFlags, function(pair) { + var value = '_.' + pair[0]; + if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { + details.push(value); + } + }); + return details.sort(); + } + + /** + * Creates a clone of `wrapper`. + * + * @private + * @param {Object} wrapper The wrapper to clone. + * @returns {Object} Returns the cloned wrapper. + */ + function wrapperClone(wrapper) { + if (wrapper instanceof LazyWrapper) { + return wrapper.clone(); + } + var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); + result.__actions__ = copyArray(wrapper.__actions__); + result.__index__ = wrapper.__index__; + result.__values__ = wrapper.__values__; + return result; + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates an array of elements split into groups the length of `size`. + * If `array` can't be split evenly, the final chunk will be the remaining + * elements. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to process. + * @param {number} [size=1] The length of each chunk + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the new array of chunks. + * @example + * + * _.chunk(['a', 'b', 'c', 'd'], 2); + * // => [['a', 'b'], ['c', 'd']] + * + * _.chunk(['a', 'b', 'c', 'd'], 3); + * // => [['a', 'b', 'c'], ['d']] + */ + function chunk(array, size, guard) { + if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { + size = 1; + } else { + size = nativeMax(toInteger(size), 0); + } + var length = array ? array.length : 0; + if (!length || size < 1) { + return []; + } + var index = 0, + resIndex = 0, + result = Array(nativeCeil(length / size)); + + while (index < length) { + result[resIndex++] = baseSlice(array, index, (index += size)); + } + return result; + } + + /** + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are falsey. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to compact. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] + */ + function compact(array) { + var index = -1, + length = array ? array.length : 0, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result[resIndex++] = value; + } + } + return result; + } + + /** + * Creates a new array concatenating `array` with any additional arrays + * and/or values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to concatenate. + * @param {...*} [values] The values to concatenate. + * @returns {Array} Returns the new concatenated array. + * @example + * + * var array = [1]; + * var other = _.concat(array, 2, [3], [[4]]); + * + * console.log(other); + * // => [1, 2, 3, [4]] + * + * console.log(array); + * // => [1] + */ + function concat() { + var length = arguments.length; + if (!length) { + return []; + } + var args = Array(length - 1), + array = arguments[0], + index = length; + + while (index--) { + args[index - 1] = arguments[index]; + } + return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); + } + + /** + * Creates an array of `array` values not included in the other given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * **Note:** Unlike `_.pullAll`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.without, _.xor + * @example + * + * _.difference([2, 1], [2, 3]); + * // => [1] + */ + var difference = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) + : []; + }); + + /** + * This method is like `_.difference` except that it accepts `iteratee` which + * is invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * **Note:** Unlike `_.pullAllBy`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2] + * + * // The `_.property` iteratee shorthand. + * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */ + var differenceBy = baseRest(function(array, values) { + var iteratee = last(values); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) + : []; + }); + + /** + * This method is like `_.difference` except that it accepts `comparator` + * which is invoked to compare elements of `array` to `values`. The order and + * references of result values are determined by the first array. The comparator + * is invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.pullAllWith`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * + * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); + * // => [{ 'x': 2, 'y': 1 }] + */ + var differenceWith = baseRest(function(array, values) { + var comparator = last(values); + if (isArrayLikeObject(comparator)) { + comparator = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) + : []; + }); + + /** + * Creates a slice of `array` with `n` elements dropped from the beginning. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.drop([1, 2, 3]); + * // => [2, 3] + * + * _.drop([1, 2, 3], 2); + * // => [3] + * + * _.drop([1, 2, 3], 5); + * // => [] + * + * _.drop([1, 2, 3], 0); + * // => [1, 2, 3] + */ + function drop(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, n < 0 ? 0 : n, length); + } + + /** + * Creates a slice of `array` with `n` elements dropped from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropRight([1, 2, 3]); + * // => [1, 2] + * + * _.dropRight([1, 2, 3], 2); + * // => [1] + * + * _.dropRight([1, 2, 3], 5); + * // => [] + * + * _.dropRight([1, 2, 3], 0); + * // => [1, 2, 3] + */ + function dropRight(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, 0, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` excluding elements dropped from the end. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.dropRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney'] + * + * // The `_.matches` iteratee shorthand. + * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropRightWhile(users, ['active', false]); + * // => objects for ['barney'] + * + * // The `_.property` iteratee shorthand. + * _.dropRightWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ + function dropRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true, true) + : []; + } + + /** + * Creates a slice of `array` excluding elements dropped from the beginning. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] + * The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.dropWhile(users, function(o) { return !o.active; }); + * // => objects for ['pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.dropWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropWhile(users, ['active', false]); + * // => objects for ['pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.dropWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ + function dropWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true) + : []; + } + + /** + * Fills elements of `array` with `value` from `start` up to, but not + * including, `end`. + * + * **Note:** This method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Array + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.fill(array, 'a'); + * console.log(array); + * // => ['a', 'a', 'a'] + * + * _.fill(Array(3), 2); + * // => [2, 2, 2] + * + * _.fill([4, 6, 8, 10], '*', 1, 3); + * // => [4, '*', '*', 10] + */ + function fill(array, value, start, end) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { + start = 0; + end = length; + } + return baseFill(array, value, start, end); + } + + /** + * This method is like `_.find` except that it returns the index of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] + * The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.findIndex(users, function(o) { return o.user == 'barney'; }); + * // => 0 + * + * // The `_.matches` iteratee shorthand. + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findIndex(users, ['active', false]); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.findIndex(users, 'active'); + * // => 2 + */ + function findIndex(array, predicate, fromIndex) { + var length = array ? array.length : 0; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseFindIndex(array, getIteratee(predicate, 3), index); + } + + /** + * This method is like `_.findIndex` except that it iterates over elements + * of `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] + * The function invoked per iteration. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); + * // => 2 + * + * // The `_.matches` iteratee shorthand. + * _.findLastIndex(users, { 'user': 'barney', 'active': true }); + * // => 0 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastIndex(users, ['active', false]); + * // => 2 + * + * // The `_.property` iteratee shorthand. + * _.findLastIndex(users, 'active'); + * // => 0 + */ + function findLastIndex(array, predicate, fromIndex) { + var length = array ? array.length : 0; + if (!length) { + return -1; + } + var index = length - 1; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = fromIndex < 0 + ? nativeMax(length + index, 0) + : nativeMin(index, length - 1); + } + return baseFindIndex(array, getIteratee(predicate, 3), index, true); + } + + /** + * Flattens `array` a single level deep. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */ + function flatten(array) { + var length = array ? array.length : 0; + return length ? baseFlatten(array, 1) : []; + } + + /** + * Recursively flattens `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flattenDeep([1, [2, [3, [4]], 5]]); + * // => [1, 2, 3, 4, 5] + */ + function flattenDeep(array) { + var length = array ? array.length : 0; + return length ? baseFlatten(array, INFINITY) : []; + } + + /** + * Recursively flatten `array` up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Array + * @param {Array} array The array to flatten. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * var array = [1, [2, [3, [4]], 5]]; + * + * _.flattenDepth(array, 1); + * // => [1, 2, [3, [4]], 5] + * + * _.flattenDepth(array, 2); + * // => [1, 2, 3, [4], 5] + */ + function flattenDepth(array, depth) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(array, depth); + } + + /** + * The inverse of `_.toPairs`; this method returns an object composed + * from key-value `pairs`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} pairs The key-value pairs. + * @returns {Object} Returns the new object. + * @example + * + * _.fromPairs([['a', 1], ['b', 2]]); + * // => { 'a': 1, 'b': 2 } + */ + function fromPairs(pairs) { + var index = -1, + length = pairs ? pairs.length : 0, + result = {}; + + while (++index < length) { + var pair = pairs[index]; + result[pair[0]] = pair[1]; + } + return result; + } + + /** + * Gets the first element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias first + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the first element of `array`. + * @example + * + * _.head([1, 2, 3]); + * // => 1 + * + * _.head([]); + * // => undefined + */ + function head(array) { + return (array && array.length) ? array[0] : undefined; + } + + /** + * Gets the index at which the first occurrence of `value` is found in `array` + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it's used as the + * offset from the end of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.indexOf([1, 2, 1, 2], 2); + * // => 1 + * + * // Search from the `fromIndex`. + * _.indexOf([1, 2, 1, 2], 2, 2); + * // => 3 + */ + function indexOf(array, value, fromIndex) { + var length = array ? array.length : 0; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseIndexOf(array, value, index); + } + + /** + * Gets all but the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.initial([1, 2, 3]); + * // => [1, 2] + */ + function initial(array) { + var length = array ? array.length : 0; + return length ? baseSlice(array, 0, -1) : []; + } + + /** + * Creates an array of unique values that are included in all given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersection([2, 1], [2, 3]); + * // => [2] + */ + var intersection = baseRest(function(arrays) { + var mapped = arrayMap(arrays, castArrayLikeObject); + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped) + : []; + }); + + /** + * This method is like `_.intersection` except that it accepts `iteratee` + * which is invoked for each element of each `arrays` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [2.1] + * + * // The `_.property` iteratee shorthand. + * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }] + */ + var intersectionBy = baseRest(function(arrays) { + var iteratee = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + if (iteratee === last(mapped)) { + iteratee = undefined; + } else { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, getIteratee(iteratee, 2)) + : []; + }); + + /** + * This method is like `_.intersection` except that it accepts `comparator` + * which is invoked to compare elements of `arrays`. The order and references + * of result values are determined by the first array. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.intersectionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }] + */ + var intersectionWith = baseRest(function(arrays) { + var comparator = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + if (comparator === last(mapped)) { + comparator = undefined; + } else { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, undefined, comparator) + : []; + }); + + /** + * Converts all elements in `array` into a string separated by `separator`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to convert. + * @param {string} [separator=','] The element separator. + * @returns {string} Returns the joined string. + * @example + * + * _.join(['a', 'b', 'c'], '~'); + * // => 'a~b~c' + */ + function join(array, separator) { + return array ? nativeJoin.call(array, separator) : ''; + } + + /** + * Gets the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + */ + function last(array) { + var length = array ? array.length : 0; + return length ? array[length - 1] : undefined; + } + + /** + * This method is like `_.indexOf` except that it iterates over elements of + * `array` from right to left. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.lastIndexOf([1, 2, 1, 2], 2); + * // => 3 + * + * // Search from the `fromIndex`. + * _.lastIndexOf([1, 2, 1, 2], 2, 2); + * // => 1 + */ + function lastIndexOf(array, value, fromIndex) { + var length = array ? array.length : 0; + if (!length) { + return -1; + } + var index = length; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); + } + return value === value + ? strictLastIndexOf(array, value, index) + : baseFindIndex(array, baseIsNaN, index, true); + } + + /** + * Gets the element at index `n` of `array`. If `n` is negative, the nth + * element from the end is returned. + * + * @static + * @memberOf _ + * @since 4.11.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=0] The index of the element to return. + * @returns {*} Returns the nth element of `array`. + * @example + * + * var array = ['a', 'b', 'c', 'd']; + * + * _.nth(array, 1); + * // => 'b' + * + * _.nth(array, -2); + * // => 'c'; + */ + function nth(array, n) { + return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; + } + + /** + * Removes all given values from `array` using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` + * to remove elements from an array by predicate. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...*} [values] The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * + * _.pull(array, 'a', 'c'); + * console.log(array); + * // => ['b', 'b'] + */ + var pull = baseRest(pullAll); + + /** + * This method is like `_.pull` except that it accepts an array of values to remove. + * + * **Note:** Unlike `_.difference`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * + * _.pullAll(array, ['a', 'c']); + * console.log(array); + * // => ['b', 'b'] + */ + function pullAll(array, values) { + return (array && array.length && values && values.length) + ? basePullAll(array, values) + : array; + } + + /** + * This method is like `_.pullAll` except that it accepts `iteratee` which is + * invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The iteratee is invoked with one argument: (value). + * + * **Note:** Unlike `_.differenceBy`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee=_.identity] + * The iteratee invoked per element. + * @returns {Array} Returns `array`. + * @example + * + * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; + * + * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); + * console.log(array); + * // => [{ 'x': 2 }] + */ + function pullAllBy(array, values, iteratee) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, getIteratee(iteratee, 2)) + : array; + } + + /** + * This method is like `_.pullAll` except that it accepts `comparator` which + * is invoked to compare elements of `array` to `values`. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.differenceWith`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + * @example + * + * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; + * + * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); + * console.log(array); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] + */ + function pullAllWith(array, values, comparator) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, undefined, comparator) + : array; + } + + /** + * Removes elements from `array` corresponding to `indexes` and returns an + * array of removed elements. + * + * **Note:** Unlike `_.at`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...(number|number[])} [indexes] The indexes of elements to remove. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = ['a', 'b', 'c', 'd']; + * var pulled = _.pullAt(array, [1, 3]); + * + * console.log(array); + * // => ['a', 'c'] + * + * console.log(pulled); + * // => ['b', 'd'] + */ + var pullAt = flatRest(function(array, indexes) { + var length = array ? array.length : 0, + result = baseAt(array, indexes); + + basePullAt(array, arrayMap(indexes, function(index) { + return isIndex(index, length) ? +index : index; + }).sort(compareAscending)); + + return result; + }); + + /** + * Removes all elements from `array` that `predicate` returns truthy for + * and returns an array of the removed elements. The predicate is invoked + * with three arguments: (value, index, array). + * + * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` + * to pull elements from an array by value. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Function} [predicate=_.identity] + * The function invoked per iteration. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = [1, 2, 3, 4]; + * var evens = _.remove(array, function(n) { + * return n % 2 == 0; + * }); + * + * console.log(array); + * // => [1, 3] + * + * console.log(evens); + * // => [2, 4] + */ + function remove(array, predicate) { + var result = []; + if (!(array && array.length)) { + return result; + } + var index = -1, + indexes = [], + length = array.length; + + predicate = getIteratee(predicate, 3); + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result.push(value); + indexes.push(index); + } + } + basePullAt(array, indexes); + return result; + } + + /** + * Reverses `array` so that the first element becomes the last, the second + * element becomes the second to last, and so on. + * + * **Note:** This method mutates `array` and is based on + * [`Array#reverse`](https://mdn.io/Array/reverse). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.reverse(array); + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ + function reverse(array) { + return array ? nativeReverse.call(array) : array; + } + + /** + * Creates a slice of `array` from `start` up to, but not including, `end`. + * + * **Note:** This method is used instead of + * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are + * returned. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function slice(array, start, end) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { + start = 0; + end = length; + } + else { + start = start == null ? 0 : toInteger(start); + end = end === undefined ? length : toInteger(end); + } + return baseSlice(array, start, end); + } + + /** + * Uses a binary search to determine the lowest index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedIndex([30, 50], 40); + * // => 1 + */ + function sortedIndex(array, value) { + return baseSortedIndex(array, value); + } + + /** + * This method is like `_.sortedIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] + * The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * + * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); + * // => 0 + */ + function sortedIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); + } + + /** + * This method is like `_.indexOf` except that it performs a binary + * search on a sorted `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedIndexOf([4, 5, 5, 5, 6], 5); + * // => 1 + */ + function sortedIndexOf(array, value) { + var length = array ? array.length : 0; + if (length) { + var index = baseSortedIndex(array, value); + if (index < length && eq(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * This method is like `_.sortedIndex` except that it returns the highest + * index at which `value` should be inserted into `array` in order to + * maintain its sort order. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedLastIndex([4, 5, 5, 5, 6], 5); + * // => 4 + */ + function sortedLastIndex(array, value) { + return baseSortedIndex(array, value, true); + } + + /** + * This method is like `_.sortedLastIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] + * The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * + * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 1 + * + * // The `_.property` iteratee shorthand. + * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); + * // => 1 + */ + function sortedLastIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); + } + + /** + * This method is like `_.lastIndexOf` except that it performs a binary + * search on a sorted `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); + * // => 3 + */ + function sortedLastIndexOf(array, value) { + var length = array ? array.length : 0; + if (length) { + var index = baseSortedIndex(array, value, true) - 1; + if (eq(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * This method is like `_.uniq` except that it's designed and optimized + * for sorted arrays. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.sortedUniq([1, 1, 2]); + * // => [1, 2] + */ + function sortedUniq(array) { + return (array && array.length) + ? baseSortedUniq(array) + : []; + } + + /** + * This method is like `_.uniqBy` except that it's designed and optimized + * for sorted arrays. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); + * // => [1.1, 2.3] + */ + function sortedUniqBy(array, iteratee) { + return (array && array.length) + ? baseSortedUniq(array, getIteratee(iteratee, 2)) + : []; + } + + /** + * Gets all but the first element of `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.tail([1, 2, 3]); + * // => [2, 3] + */ + function tail(array) { + var length = array ? array.length : 0; + return length ? baseSlice(array, 1, length) : []; + } + + /** + * Creates a slice of `array` with `n` elements taken from the beginning. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.take([1, 2, 3]); + * // => [1] + * + * _.take([1, 2, 3], 2); + * // => [1, 2] + * + * _.take([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.take([1, 2, 3], 0); + * // => [] + */ + function take(array, n, guard) { + if (!(array && array.length)) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, 0, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` with `n` elements taken from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.takeRight([1, 2, 3]); + * // => [3] + * + * _.takeRight([1, 2, 3], 2); + * // => [2, 3] + * + * _.takeRight([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.takeRight([1, 2, 3], 0); + * // => [] + */ + function takeRight(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, n < 0 ? 0 : n, length); + } + + /** + * Creates a slice of `array` with elements taken from the end. Elements are + * taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] + * The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.takeRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeRightWhile(users, ['active', false]); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.takeRightWhile(users, 'active'); + * // => [] + */ + function takeRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), false, true) + : []; + } + + /** + * Creates a slice of `array` with elements taken from the beginning. Elements + * are taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] + * The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false}, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.takeWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matches` iteratee shorthand. + * _.takeWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeWhile(users, ['active', false]); + * // => objects for ['barney', 'fred'] + * + * // The `_.property` iteratee shorthand. + * _.takeWhile(users, 'active'); + * // => [] + */ + function takeWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3)) + : []; + } + + /** + * Creates an array of unique values, in order, from all given arrays using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.union([2], [1, 2]); + * // => [2, 1] + */ + var union = baseRest(function(arrays) { + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); + }); + + /** + * This method is like `_.union` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which uniqueness is computed. Result values are chosen from the first + * array in which the value occurs. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] + * The iteratee invoked per element. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.unionBy([2.1], [1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // The `_.property` iteratee shorthand. + * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + var unionBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); + }); + + /** + * This method is like `_.union` except that it accepts `comparator` which + * is invoked to compare elements of `arrays`. Result values are chosen from + * the first array in which the value occurs. The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of combined values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.unionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */ + var unionWith = baseRest(function(arrays) { + var comparator = last(arrays); + if (isArrayLikeObject(comparator)) { + comparator = undefined; + } + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); + }); + + /** + * Creates a duplicate-free version of an array, using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons, in which only the first occurrence of each element + * is kept. The order of result values is determined by the order they occur + * in the array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniq([2, 1, 2]); + * // => [2, 1] + */ + function uniq(array) { + return (array && array.length) + ? baseUniq(array) + : []; + } + + /** + * This method is like `_.uniq` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the criterion by which + * uniqueness is computed. The order of result values is determined by the + * order they occur in the array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee=_.identity] + * The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniqBy([2.1, 1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // The `_.property` iteratee shorthand. + * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + function uniqBy(array, iteratee) { + return (array && array.length) + ? baseUniq(array, getIteratee(iteratee, 2)) + : []; + } + + /** + * This method is like `_.uniq` except that it accepts `comparator` which + * is invoked to compare elements of `array`. The order of result values is + * determined by the order they occur in the array.The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.uniqWith(objects, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] + */ + function uniqWith(array, comparator) { + return (array && array.length) + ? baseUniq(array, undefined, comparator) + : []; + } + + /** + * This method is like `_.zip` except that it accepts an array of grouped + * elements and creates an array regrouping the elements to their pre-zip + * configuration. + * + * @static + * @memberOf _ + * @since 1.2.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] + * + * _.unzip(zipped); + * // => [['a', 'b'], [1, 2], [true, false]] + */ + function unzip(array) { + if (!(array && array.length)) { + return []; + } + var length = 0; + array = arrayFilter(array, function(group) { + if (isArrayLikeObject(group)) { + length = nativeMax(group.length, length); + return true; + } + }); + return baseTimes(length, function(index) { + return arrayMap(array, baseProperty(index)); + }); + } + + /** + * This method is like `_.unzip` except that it accepts `iteratee` to specify + * how regrouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @param {Function} [iteratee=_.identity] The function to combine + * regrouped values. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip([1, 2], [10, 20], [100, 200]); + * // => [[1, 10, 100], [2, 20, 200]] + * + * _.unzipWith(zipped, _.add); + * // => [3, 30, 300] + */ + function unzipWith(array, iteratee) { + if (!(array && array.length)) { + return []; + } + var result = unzip(array); + if (iteratee == null) { + return result; + } + return arrayMap(result, function(group) { + return apply(iteratee, undefined, group); + }); + } + + /** + * Creates an array excluding all given values using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.pull`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...*} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.xor + * @example + * + * _.without([2, 1, 2, 3], 1, 2); + * // => [3] + */ + var without = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, values) + : []; + }); + + /** + * Creates an array of unique values that is the + * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) + * of the given arrays. The order of result values is determined by the order + * they occur in the arrays. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.without + * @example + * + * _.xor([2, 1], [2, 3]); + * // => [1, 3] + */ + var xor = baseRest(function(arrays) { + return baseXor(arrayFilter(arrays, isArrayLikeObject)); + }); + + /** + * This method is like `_.xor` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which by which they're compared. The order of result values is determined + * by the order they occur in the arrays. The iteratee is invoked with one + * argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] + * The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2, 3.4] + * + * // The `_.property` iteratee shorthand. + * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */ + var xorBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); + }); + + /** + * This method is like `_.xor` except that it accepts `comparator` which is + * invoked to compare elements of `arrays`. The order of result values is + * determined by the order they occur in the arrays. The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.xorWith(objects, others, _.isEqual); + * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */ + var xorWith = baseRest(function(arrays) { + var comparator = last(arrays); + if (isArrayLikeObject(comparator)) { + comparator = undefined; + } + return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); + }); + + /** + * Creates an array of grouped elements, the first of which contains the + * first elements of the given arrays, the second of which contains the + * second elements of the given arrays, and so on. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] + */ + var zip = baseRest(unzip); + + /** + * This method is like `_.fromPairs` except that it accepts two arrays, + * one of property identifiers and one of corresponding values. + * + * @static + * @memberOf _ + * @since 0.4.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObject(['a', 'b'], [1, 2]); + * // => { 'a': 1, 'b': 2 } + */ + function zipObject(props, values) { + return baseZipObject(props || [], values || [], assignValue); + } + + /** + * This method is like `_.zipObject` except that it supports property paths. + * + * @static + * @memberOf _ + * @since 4.1.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); + * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } + */ + function zipObjectDeep(props, values) { + return baseZipObject(props || [], values || [], baseSet); + } + + /** + * This method is like `_.zip` except that it accepts `iteratee` to specify + * how grouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @param {Function} [iteratee=_.identity] The function to combine grouped values. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { + * return a + b + c; + * }); + * // => [111, 222] + */ + var zipWith = baseRest(function(arrays) { + var length = arrays.length, + iteratee = length > 1 ? arrays[length - 1] : undefined; + + iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; + return unzipWith(arrays, iteratee); + }); + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` wrapper instance that wraps `value` with explicit method + * chain sequences enabled. The result of such sequences must be unwrapped + * with `_#value`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Seq + * @param {*} value The value to wrap. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'pebbles', 'age': 1 } + * ]; + * + * var youngest = _ + * .chain(users) + * .sortBy('age') + * .map(function(o) { + * return o.user + ' is ' + o.age; + * }) + * .head() + * .value(); + * // => 'pebbles is 1' + */ + function chain(value) { + var result = lodash(value); + result.__chain__ = true; + return result; + } + + /** + * This method invokes `interceptor` and returns `value`. The interceptor + * is invoked with one argument; (value). The purpose of this method is to + * "tap into" a method chain sequence in order to modify intermediate results. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns `value`. + * @example + * + * _([1, 2, 3]) + * .tap(function(array) { + * // Mutate input array. + * array.pop(); + * }) + * .reverse() + * .value(); + * // => [2, 1] + */ + function tap(value, interceptor) { + interceptor(value); + return value; + } + + /** + * This method is like `_.tap` except that it returns the result of `interceptor`. + * The purpose of this method is to "pass thru" values replacing intermediate + * results in a method chain sequence. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns the result of `interceptor`. + * @example + * + * _(' abc ') + * .chain() + * .trim() + * .thru(function(value) { + * return [value]; + * }) + * .value(); + * // => ['abc'] + */ + function thru(value, interceptor) { + return interceptor(value); + } + + /** + * This method is the wrapper version of `_.at`. + * + * @name at + * @memberOf _ + * @since 1.0.0 + * @category Seq + * @param {...(string|string[])} [paths] The property paths of elements to pick. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _(object).at(['a[0].b.c', 'a[1]']).value(); + * // => [3, 4] + */ + var wrapperAt = flatRest(function(paths) { + var length = paths.length, + start = length ? paths[0] : 0, + value = this.__wrapped__, + interceptor = function(object) { return baseAt(object, paths); }; + + if (length > 1 || this.__actions__.length || + !(value instanceof LazyWrapper) || !isIndex(start)) { + return this.thru(interceptor); + } + value = value.slice(start, +start + (length ? 1 : 0)); + value.__actions__.push({ + 'func': thru, + 'args': [interceptor], + 'thisArg': undefined + }); + return new LodashWrapper(value, this.__chain__).thru(function(array) { + if (length && !array.length) { + array.push(undefined); + } + return array; + }); + }); + + /** + * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. + * + * @name chain + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * // A sequence without explicit chaining. + * _(users).head(); + * // => { 'user': 'barney', 'age': 36 } + * + * // A sequence with explicit chaining. + * _(users) + * .chain() + * .head() + * .pick('user') + * .value(); + * // => { 'user': 'barney' } + */ + function wrapperChain() { + return chain(this); + } + + /** + * Executes the chain sequence and returns the wrapped result. + * + * @name commit + * @memberOf _ + * @since 3.2.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2]; + * var wrapped = _(array).push(3); + * + * console.log(array); + * // => [1, 2] + * + * wrapped = wrapped.commit(); + * console.log(array); + * // => [1, 2, 3] + * + * wrapped.last(); + * // => 3 + * + * console.log(array); + * // => [1, 2, 3] + */ + function wrapperCommit() { + return new LodashWrapper(this.value(), this.__chain__); + } + + /** + * Gets the next value on a wrapped object following the + * [iterator protocol](https://mdn.io/iteration_protocols#iterator). + * + * @name next + * @memberOf _ + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the next iterator value. + * @example + * + * var wrapped = _([1, 2]); + * + * wrapped.next(); + * // => { 'done': false, 'value': 1 } + * + * wrapped.next(); + * // => { 'done': false, 'value': 2 } + * + * wrapped.next(); + * // => { 'done': true, 'value': undefined } + */ + function wrapperNext() { + if (this.__values__ === undefined) { + this.__values__ = toArray(this.value()); + } + var done = this.__index__ >= this.__values__.length, + value = done ? undefined : this.__values__[this.__index__++]; + + return { 'done': done, 'value': value }; + } + + /** + * Enables the wrapper to be iterable. + * + * @name Symbol.iterator + * @memberOf _ + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the wrapper object. + * @example + * + * var wrapped = _([1, 2]); + * + * wrapped[Symbol.iterator]() === wrapped; + * // => true + * + * Array.from(wrapped); + * // => [1, 2] + */ + function wrapperToIterator() { + return this; + } + + /** + * Creates a clone of the chain sequence planting `value` as the wrapped value. + * + * @name plant + * @memberOf _ + * @since 3.2.0 + * @category Seq + * @param {*} value The value to plant. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2]).map(square); + * var other = wrapped.plant([3, 4]); + * + * other.value(); + * // => [9, 16] + * + * wrapped.value(); + * // => [1, 4] + */ + function wrapperPlant(value) { + var result, + parent = this; + + while (parent instanceof baseLodash) { + var clone = wrapperClone(parent); + clone.__index__ = 0; + clone.__values__ = undefined; + if (result) { + previous.__wrapped__ = clone; + } else { + result = clone; + } + var previous = clone; + parent = parent.__wrapped__; + } + previous.__wrapped__ = value; + return result; + } + + /** + * This method is the wrapper version of `_.reverse`. + * + * **Note:** This method mutates the wrapped array. + * + * @name reverse + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2, 3]; + * + * _(array).reverse().value() + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ + function wrapperReverse() { + var value = this.__wrapped__; + if (value instanceof LazyWrapper) { + var wrapped = value; + if (this.__actions__.length) { + wrapped = new LazyWrapper(this); + } + wrapped = wrapped.reverse(); + wrapped.__actions__.push({ + 'func': thru, + 'args': [reverse], + 'thisArg': undefined + }); + return new LodashWrapper(wrapped, this.__chain__); + } + return this.thru(reverse); + } + + /** + * Executes the chain sequence to resolve the unwrapped value. + * + * @name value + * @memberOf _ + * @since 0.1.0 + * @alias toJSON, valueOf + * @category Seq + * @returns {*} Returns the resolved unwrapped value. + * @example + * + * _([1, 2, 3]).value(); + * // => [1, 2, 3] + */ + function wrapperValue() { + return baseWrapperValue(this.__wrapped__, this.__actions__); + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the number of times the key was returned by `iteratee`. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] + * The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.countBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': 1, '6': 2 } + * + * // The `_.property` iteratee shorthand. + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } + */ + var countBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + ++result[key]; + } else { + baseAssignValue(result, key, 1); + } + }); + + /** + * Checks if `predicate` returns truthy for **all** elements of `collection`. + * Iteration is stopped once `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * **Note:** This method returns `true` for + * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because + * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of + * elements of empty collections. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] + * The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes'], Boolean); + * // => false + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.every(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.every(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.every(users, 'active'); + * // => false + */ + function every(collection, predicate, guard) { + var func = isArray(collection) ? arrayEvery : baseEvery; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Iterates over elements of `collection`, returning an array of all elements + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * **Note:** Unlike `_.remove`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] + * The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.reject + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * _.filter(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.filter(users, { 'age': 36, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.filter(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.filter(users, 'active'); + * // => objects for ['barney'] + */ + function filter(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Iterates over elements of `collection`, returning the first element + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] + * The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } + * ]; + * + * _.find(users, function(o) { return o.age < 40; }); + * // => object for 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.find(users, { 'age': 1, 'active': true }); + * // => object for 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.find(users, ['active', false]); + * // => object for 'fred' + * + * // The `_.property` iteratee shorthand. + * _.find(users, 'active'); + * // => object for 'barney' + */ + var find = createFind(findIndex); + + /** + * This method is like `_.find` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] + * The function invoked per iteration. + * @param {number} [fromIndex=collection.length-1] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * _.findLast([1, 2, 3, 4], function(n) { + * return n % 2 == 1; + * }); + * // => 3 + */ + var findLast = createFind(findLastIndex); + + /** + * Creates a flattened array of values by running each element in `collection` + * thru `iteratee` and flattening the mapped results. The iteratee is invoked + * with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] + * The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [n, n]; + * } + * + * _.flatMap([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ + function flatMap(collection, iteratee) { + return baseFlatten(map(collection, iteratee), 1); + } + + /** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] + * The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDeep([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ + function flatMapDeep(collection, iteratee) { + return baseFlatten(map(collection, iteratee), INFINITY); + } + + /** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] + * The function invoked per iteration. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDepth([1, 2], duplicate, 2); + * // => [[1, 1], [2, 2]] + */ + function flatMapDepth(collection, iteratee, depth) { + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(map(collection, iteratee), depth); + } + + /** + * Iterates over elements of `collection` and invokes `iteratee` for each element. + * The iteratee is invoked with three arguments: (value, index|key, collection). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * **Note:** As with other "Collections" methods, objects with a "length" + * property are iterated like arrays. To avoid this behavior use `_.forIn` + * or `_.forOwn` for object iteration. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias each + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEachRight + * @example + * + * _.forEach([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `1` then `2`. + * + * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ + function forEach(collection, iteratee) { + var func = isArray(collection) ? arrayEach : baseEach; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.forEach` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @alias eachRight + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEach + * @example + * + * _.forEachRight([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `2` then `1`. + */ + function forEachRight(collection, iteratee) { + var func = isArray(collection) ? arrayEachRight : baseEachRight; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The order of grouped values + * is determined by the order they occur in `collection`. The corresponding + * value of each key is an array of elements responsible for generating the + * key. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] + * The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.groupBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': [4.2], '6': [6.1, 6.3] } + * + * // The `_.property` iteratee shorthand. + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */ + var groupBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + result[key].push(value); + } else { + baseAssignValue(result, key, [value]); + } + }); + + /** + * Checks if `value` is in `collection`. If `collection` is a string, it's + * checked for a substring of `value`, otherwise + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * is used for equality comparisons. If `fromIndex` is negative, it's used as + * the offset from the end of `collection`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {boolean} Returns `true` if `value` is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes([1, 2, 3], 1, 2); + * // => false + * + * _.includes({ 'a': 1, 'b': 2 }, 1); + * // => true + * + * _.includes('abcd', 'bc'); + * // => true + */ + function includes(collection, value, fromIndex, guard) { + collection = isArrayLike(collection) ? collection : values(collection); + fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; + + var length = collection.length; + if (fromIndex < 0) { + fromIndex = nativeMax(length + fromIndex, 0); + } + return isString(collection) + ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) + : (!!length && baseIndexOf(collection, value, fromIndex) > -1); + } + + /** + * Invokes the method at `path` of each element in `collection`, returning + * an array of the results of each invoked method. Any additional arguments + * are provided to each invoked method. If `path` is a function, it's invoked + * for, and `this` bound to, each element in `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array|Function|string} path The path of the method to invoke or + * the function invoked per iteration. + * @param {...*} [args] The arguments to invoke each method with. + * @returns {Array} Returns the array of results. + * @example + * + * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] + * + * _.invokeMap([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] + */ + var invokeMap = baseRest(function(collection, path, args) { + var index = -1, + isFunc = typeof path == 'function', + isProp = isKey(path), + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value) { + var func = isFunc ? path : ((isProp && value != null) ? value[path] : undefined); + result[++index] = func ? apply(func, value, args) : baseInvoke(value, path, args); + }); + return result; + }); + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the last element responsible for generating the key. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] + * The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * var array = [ + * { 'dir': 'left', 'code': 97 }, + * { 'dir': 'right', 'code': 100 } + * ]; + * + * _.keyBy(array, function(o) { + * return String.fromCharCode(o.code); + * }); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * + * _.keyBy(array, 'dir'); + * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + */ + var keyBy = createAggregator(function(result, value, key) { + baseAssignValue(result, key, value); + }); + + /** + * Creates an array of values by running each element in `collection` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. + * + * The guarded methods are: + * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, + * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, + * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, + * `template`, `trim`, `trimEnd`, `trimStart`, and `words` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + * @example + * + * function square(n) { + * return n * n; + * } + * + * _.map([4, 8], square); + * // => [16, 64] + * + * _.map({ 'a': 4, 'b': 8 }, square); + * // => [16, 64] (iteration order is not guaranteed) + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * // The `_.property` iteratee shorthand. + * _.map(users, 'user'); + * // => ['barney', 'fred'] + */ + function map(collection, iteratee) { + var func = isArray(collection) ? arrayMap : baseMap; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.sortBy` except that it allows specifying the sort + * orders of the iteratees to sort by. If `orders` is unspecified, all values + * are sorted in ascending order. Otherwise, specify an order of "desc" for + * descending or "asc" for ascending sort order of corresponding values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] + * The iteratees to sort by. + * @param {string[]} [orders] The sort orders of `iteratees`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 34 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 36 } + * ]; + * + * // Sort by `user` in ascending order and by `age` in descending order. + * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + */ + function orderBy(collection, iteratees, orders, guard) { + if (collection == null) { + return []; + } + if (!isArray(iteratees)) { + iteratees = iteratees == null ? [] : [iteratees]; + } + orders = guard ? undefined : orders; + if (!isArray(orders)) { + orders = orders == null ? [] : [orders]; + } + return baseOrderBy(collection, iteratees, orders); + } + + /** + * Creates an array of elements split into two groups, the first of which + * contains elements `predicate` returns truthy for, the second of which + * contains elements `predicate` returns falsey for. The predicate is + * invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the array of grouped elements. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true }, + * { 'user': 'pebbles', 'age': 1, 'active': false } + * ]; + * + * _.partition(users, function(o) { return o.active; }); + * // => objects for [['fred'], ['barney', 'pebbles']] + * + * // The `_.matches` iteratee shorthand. + * _.partition(users, { 'age': 1, 'active': false }); + * // => objects for [['pebbles'], ['barney', 'fred']] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.partition(users, ['active', false]); + * // => objects for [['barney', 'pebbles'], ['fred']] + * + * // The `_.property` iteratee shorthand. + * _.partition(users, 'active'); + * // => objects for [['fred'], ['barney', 'pebbles']] + */ + var partition = createAggregator(function(result, value, key) { + result[key ? 0 : 1].push(value); + }, function() { return [[], []]; }); + + /** + * Reduces `collection` to a value which is the accumulated result of running + * each element in `collection` thru `iteratee`, where each successive + * invocation is supplied the return value of the previous. If `accumulator` + * is not given, the first element of `collection` is used as the initial + * value. The iteratee is invoked with four arguments: + * (accumulator, value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.reduce`, `_.reduceRight`, and `_.transform`. + * + * The guarded methods are: + * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, + * and `sortBy` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduceRight + * @example + * + * _.reduce([1, 2], function(sum, n) { + * return sum + n; + * }, 0); + * // => 3 + * + * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * return result; + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) + */ + function reduce(collection, iteratee, accumulator) { + var func = isArray(collection) ? arrayReduce : baseReduce, + initAccum = arguments.length < 3; + + return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); + } + + /** + * This method is like `_.reduce` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduce + * @example + * + * var array = [[0, 1], [2, 3], [4, 5]]; + * + * _.reduceRight(array, function(flattened, other) { + * return flattened.concat(other); + * }, []); + * // => [4, 5, 2, 3, 0, 1] + */ + function reduceRight(collection, iteratee, accumulator) { + var func = isArray(collection) ? arrayReduceRight : baseReduce, + initAccum = arguments.length < 3; + + return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); + } + + /** + * The opposite of `_.filter`; this method returns the elements of `collection` + * that `predicate` does **not** return truthy for. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.filter + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true } + * ]; + * + * _.reject(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.reject(users, { 'age': 40, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.reject(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.reject(users, 'active'); + * // => objects for ['barney'] + */ + function reject(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, negate(getIteratee(predicate, 3))); + } + + /** + * Gets a random element from `collection`. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + * @example + * + * _.sample([1, 2, 3, 4]); + * // => 2 + */ + function sample(collection) { + return arraySample(isArrayLike(collection) ? collection : values(collection)); + } + + /** + * Gets `n` random elements at unique keys from `collection` up to the + * size of `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @param {number} [n=1] The number of elements to sample. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the random elements. + * @example + * + * _.sampleSize([1, 2, 3], 2); + * // => [3, 1] + * + * _.sampleSize([1, 2, 3], 4); + * // => [2, 3, 1] + */ + function sampleSize(collection, n, guard) { + if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { + n = 1; + } else { + n = toInteger(n); + } + return arraySampleSize(isArrayLike(collection) ? collection : values(collection), n); + } + + /** + * Creates an array of shuffled values, using a version of the + * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + * @example + * + * _.shuffle([1, 2, 3, 4]); + * // => [4, 1, 3, 2] + */ + function shuffle(collection) { + return shuffleSelf(isArrayLike(collection) + ? copyArray(collection) + : values(collection) + ); + } + + /** + * Gets the size of `collection` by returning its length for array-like + * values or the number of own enumerable string keyed properties for objects. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns the collection size. + * @example + * + * _.size([1, 2, 3]); + * // => 3 + * + * _.size({ 'a': 1, 'b': 2 }); + * // => 2 + * + * _.size('pebbles'); + * // => 7 + */ + function size(collection) { + if (collection == null) { + return 0; + } + if (isArrayLike(collection)) { + return isString(collection) ? stringSize(collection) : collection.length; + } + var tag = getTag(collection); + if (tag == mapTag || tag == setTag) { + return collection.size; + } + return baseKeys(collection).length; + } + + /** + * Checks if `predicate` returns truthy for **any** element of `collection`. + * Iteration is stopped once `predicate` returns truthy. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + * @example + * + * _.some([null, 0, 'yes', false], Boolean); + * // => true + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.some(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.some(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.some(users, 'active'); + * // => true + */ + function some(collection, predicate, guard) { + var func = isArray(collection) ? arraySome : baseSome; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection thru each iteratee. This method + * performs a stable sort, that is, it preserves the original sort order of + * equal elements. The iteratees are invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {...(Function|Function[])} [iteratees=[_.identity]] + * The iteratees to sort by. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 34 } + * ]; + * + * _.sortBy(users, [function(o) { return o.user; }]); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + * + * _.sortBy(users, ['user', 'age']); + * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] + */ + var sortBy = baseRest(function(collection, iteratees) { + if (collection == null) { + return []; + } + var length = iteratees.length; + if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { + iteratees = []; + } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { + iteratees = [iteratees[0]]; + } + return baseOrderBy(collection, baseFlatten(iteratees, 1), []); + }); + + /*------------------------------------------------------------------------*/ + + /** + * Gets the timestamp of the number of milliseconds that have elapsed since + * the Unix epoch (1 January 1970 00:00:00 UTC). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Date + * @returns {number} Returns the timestamp. + * @example + * + * _.defer(function(stamp) { + * console.log(_.now() - stamp); + * }, _.now()); + * // => Logs the number of milliseconds it took for the deferred invocation. + */ + var now = ctxNow || function() { + return root.Date.now(); + }; + + /*------------------------------------------------------------------------*/ + + /** + * The opposite of `_.before`; this method creates a function that invokes + * `func` once it's called `n` or more times. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {number} n The number of calls before `func` is invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var saves = ['profile', 'settings']; + * + * var done = _.after(saves.length, function() { + * console.log('done saving!'); + * }); + * + * _.forEach(saves, function(type) { + * asyncSave({ 'type': type, 'complete': done }); + * }); + * // => Logs 'done saving!' after the two async saves have completed. + */ + function after(n, func) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n < 1) { + return func.apply(this, arguments); + } + }; + } + + /** + * Creates a function that invokes `func`, with up to `n` arguments, + * ignoring any additional arguments. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @param {number} [n=func.length] The arity cap. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new capped function. + * @example + * + * _.map(['6', '8', '10'], _.ary(parseInt, 1)); + * // => [6, 8, 10] + */ + function ary(func, n, guard) { + n = guard ? undefined : n; + n = (func && n == null) ? func.length : n; + return createWrap(func, ARY_FLAG, undefined, undefined, undefined, undefined, n); + } + + /** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it's called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * jQuery(element).on('click', _.before(5, addContactToList)); + * // => Allows adding up to 4 contacts to the list. + */ + function before(n, func) { + var result; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } + if (n <= 1) { + func = undefined; + } + return result; + }; + } + + /** + * Creates a function that invokes `func` with the `this` binding of `thisArg` + * and `partials` prepended to the arguments it receives. + * + * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for partially applied arguments. + * + * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" + * property of bound functions. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * function greet(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * + * var object = { 'user': 'fred' }; + * + * var bound = _.bind(greet, object, 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * // Bound with placeholders. + * var bound = _.bind(greet, object, _, '!'); + * bound('hi'); + * // => 'hi fred!' + */ + var bind = baseRest(function(func, thisArg, partials) { + var bitmask = BIND_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bind)); + bitmask |= PARTIAL_FLAG; + } + return createWrap(func, bitmask, thisArg, partials, holders); + }); + + /** + * Creates a function that invokes the method at `object[key]` with `partials` + * prepended to the arguments it receives. + * + * This method differs from `_.bind` by allowing bound functions to reference + * methods that may be redefined or don't yet exist. See + * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) + * for more details. + * + * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Function + * @param {Object} object The object to invoke the method on. + * @param {string} key The key of the method. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var object = { + * 'user': 'fred', + * 'greet': function(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * }; + * + * var bound = _.bindKey(object, 'greet', 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * object.greet = function(greeting, punctuation) { + * return greeting + 'ya ' + this.user + punctuation; + * }; + * + * bound('!'); + * // => 'hiya fred!' + * + * // Bound with placeholders. + * var bound = _.bindKey(object, 'greet', _, '!'); + * bound('hi'); + * // => 'hiya fred!' + */ + var bindKey = baseRest(function(object, key, partials) { + var bitmask = BIND_FLAG | BIND_KEY_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bindKey)); + bitmask |= PARTIAL_FLAG; + } + return createWrap(key, bitmask, object, partials, holders); + }); + + /** + * Creates a function that accepts arguments of `func` and either invokes + * `func` returning its result, if at least `arity` number of arguments have + * been provided, or returns a function that accepts the remaining `func` + * arguments, and so on. The arity of `func` may be specified if `func.length` + * is not sufficient. + * + * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curry(abc); + * + * curried(1)(2)(3); + * // => [1, 2, 3] + * + * curried(1, 2)(3); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(1)(_, 3)(2); + * // => [1, 2, 3] + */ + function curry(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curry.placeholder; + return result; + } + + /** + * This method is like `_.curry` except that arguments are applied to `func` + * in the manner of `_.partialRight` instead of `_.partial`. + * + * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curryRight(abc); + * + * curried(3)(2)(1); + * // => [1, 2, 3] + * + * curried(2, 3)(1); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(3)(1, _)(2); + * // => [1, 2, 3] + */ + function curryRight(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curryRight.placeholder; + return result; + } + + /** + * Creates a debounced function that delays invoking `func` until after `wait` + * milliseconds have elapsed since the last time the debounced function was + * invoked. The debounced function comes with a `cancel` method to cancel + * delayed `func` invocations and a `flush` method to immediately invoke them. + * Provide `options` to indicate whether `func` should be invoked on the + * leading and/or trailing edge of the `wait` timeout. The `func` is invoked + * with the last arguments provided to the debounced function. Subsequent + * calls to the debounced function return the result of the last `func` + * invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the debounced function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.debounce` and `_.throttle`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to debounce. + * @param {number} [wait=0] The number of milliseconds to delay. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=false] + * Specify invoking on the leading edge of the timeout. + * @param {number} [options.maxWait] + * The maximum time `func` is allowed to be delayed before it's invoked. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // Avoid costly calculations while the window size is in flux. + * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); + * + * // Invoke `sendMail` when clicked, debouncing subsequent calls. + * jQuery(element).on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * })); + * + * // Ensure `batchLog` is invoked once after 1 second of debounced calls. + * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); + * var source = new EventSource('/stream'); + * jQuery(source).on('message', debounced); + * + * // Cancel the trailing debounced invocation. + * jQuery(window).on('popstate', debounced.cancel); + */ + function debounce(func, wait, options) { + var lastArgs, + lastThis, + maxWait, + result, + timerId, + lastCallTime, + lastInvokeTime = 0, + leading = false, + maxing = false, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + wait = toNumber(wait) || 0; + if (isObject(options)) { + leading = !!options.leading; + maxing = 'maxWait' in options; + maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + + function invokeFunc(time) { + var args = lastArgs, + thisArg = lastThis; + + lastArgs = lastThis = undefined; + lastInvokeTime = time; + result = func.apply(thisArg, args); + return result; + } + + function leadingEdge(time) { + // Reset any `maxWait` timer. + lastInvokeTime = time; + // Start the timer for the trailing edge. + timerId = setTimeout(timerExpired, wait); + // Invoke the leading edge. + return leading ? invokeFunc(time) : result; + } + + function remainingWait(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime, + result = wait - timeSinceLastCall; + + return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result; + } + + function shouldInvoke(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime; + + // Either this is the first call, activity has stopped and we're at the + // trailing edge, the system time has gone backwards and we're treating + // it as the trailing edge, or we've hit the `maxWait` limit. + return (lastCallTime === undefined || (timeSinceLastCall >= wait) || + (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); + } + + function timerExpired() { + var time = now(); + if (shouldInvoke(time)) { + return trailingEdge(time); + } + // Restart the timer. + timerId = setTimeout(timerExpired, remainingWait(time)); + } + + function trailingEdge(time) { + timerId = undefined; + + // Only invoke if we have `lastArgs` which means `func` has been + // debounced at least once. + if (trailing && lastArgs) { + return invokeFunc(time); + } + lastArgs = lastThis = undefined; + return result; + } + + function cancel() { + if (timerId !== undefined) { + clearTimeout(timerId); + } + lastInvokeTime = 0; + lastArgs = lastCallTime = lastThis = timerId = undefined; + } + + function flush() { + return timerId === undefined ? result : trailingEdge(now()); + } + + function debounced() { + var time = now(), + isInvoking = shouldInvoke(time); + + lastArgs = arguments; + lastThis = this; + lastCallTime = time; + + if (isInvoking) { + if (timerId === undefined) { + return leadingEdge(lastCallTime); + } + if (maxing) { + // Handle invocations in a tight loop. + timerId = setTimeout(timerExpired, wait); + return invokeFunc(lastCallTime); + } + } + if (timerId === undefined) { + timerId = setTimeout(timerExpired, wait); + } + return result; + } + debounced.cancel = cancel; + debounced.flush = flush; + return debounced; + } + + /** + * Defers invoking the `func` until the current call stack has cleared. Any + * additional arguments are provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to defer. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.defer(function(text) { + * console.log(text); + * }, 'deferred'); + * // => Logs 'deferred' after one millisecond. + */ + var defer = baseRest(function(func, args) { + return baseDelay(func, 1, args); + }); + + /** + * Invokes `func` after `wait` milliseconds. Any additional arguments are + * provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.delay(function(text) { + * console.log(text); + * }, 1000, 'later'); + * // => Logs 'later' after one second. + */ + var delay = baseRest(function(func, wait, args) { + return baseDelay(func, toNumber(wait) || 0, args); + }); + + /** + * Creates a function that invokes `func` with arguments reversed. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to flip arguments for. + * @returns {Function} Returns the new flipped function. + * @example + * + * var flipped = _.flip(function() { + * return _.toArray(arguments); + * }); + * + * flipped('a', 'b', 'c', 'd'); + * // => ['d', 'c', 'b', 'a'] + */ + function flip(func) { + return createWrap(func, FLIP_FLAG); + } + + /** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `delete`, `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; + * + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] + * + * values(other); + * // => [3, 4] + * + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */ + function memoize(func, resolver) { + if (typeof func != 'function' || (resolver && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result) || cache; + return result; + }; + memoized.cache = new (memoize.Cache || MapCache); + return memoized; + } + + // Expose `MapCache`. + memoize.Cache = MapCache; + + /** + * Creates a function that negates the result of the predicate `func`. The + * `func` predicate is invoked with the `this` binding and arguments of the + * created function. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} predicate The predicate to negate. + * @returns {Function} Returns the new negated function. + * @example + * + * function isEven(n) { + * return n % 2 == 0; + * } + * + * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); + * // => [1, 3, 5] + */ + function negate(predicate) { + if (typeof predicate != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return function() { + var args = arguments; + switch (args.length) { + case 0: return !predicate.call(this); + case 1: return !predicate.call(this, args[0]); + case 2: return !predicate.call(this, args[0], args[1]); + case 3: return !predicate.call(this, args[0], args[1], args[2]); + } + return !predicate.apply(this, args); + }; + } + + /** + * Creates a function that is restricted to invoking `func` once. Repeat calls + * to the function return the value of the first invocation. The `func` is + * invoked with the `this` binding and arguments of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // => `createApplication` is invoked once + */ + function once(func) { + return before(2, func); + } + + /** + * Creates a function that invokes `func` with its arguments transformed. + * + * @static + * @since 4.0.0 + * @memberOf _ + * @category Function + * @param {Function} func The function to wrap. + * @param {...(Function|Function[])} [transforms=[_.identity]] + * The argument transforms. + * @returns {Function} Returns the new function. + * @example + * + * function doubled(n) { + * return n * 2; + * } + * + * function square(n) { + * return n * n; + * } + * + * var func = _.overArgs(function(x, y) { + * return [x, y]; + * }, [square, doubled]); + * + * func(9, 3); + * // => [81, 6] + * + * func(10, 5); + * // => [100, 10] + */ + var overArgs = castRest(function(func, transforms) { + transforms = (transforms.length == 1 && isArray(transforms[0])) + ? arrayMap(transforms[0], baseUnary(getIteratee())) + : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); + + var funcsLength = transforms.length; + return baseRest(function(args) { + var index = -1, + length = nativeMin(args.length, funcsLength); + + while (++index < length) { + args[index] = transforms[index].call(this, args[index]); + } + return apply(func, this, args); + }); + }); + + /** + * Creates a function that invokes `func` with `partials` prepended to the + * arguments it receives. This method is like `_.bind` except it does **not** + * alter the `this` binding. + * + * The `_.partial.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method doesn't set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @since 0.2.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * function greet(greeting, name) { + * return greeting + ' ' + name; + * } + * + * var sayHelloTo = _.partial(greet, 'hello'); + * sayHelloTo('fred'); + * // => 'hello fred' + * + * // Partially applied with placeholders. + * var greetFred = _.partial(greet, _, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + */ + var partial = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partial)); + return createWrap(func, PARTIAL_FLAG, undefined, partials, holders); + }); + + /** + * This method is like `_.partial` except that partially applied arguments + * are appended to the arguments it receives. + * + * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method doesn't set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * function greet(greeting, name) { + * return greeting + ' ' + name; + * } + * + * var greetFred = _.partialRight(greet, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + * + * // Partially applied with placeholders. + * var sayHelloTo = _.partialRight(greet, 'hello', _); + * sayHelloTo('fred'); + * // => 'hello fred' + */ + var partialRight = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partialRight)); + return createWrap(func, PARTIAL_RIGHT_FLAG, undefined, partials, holders); + }); + + /** + * Creates a function that invokes `func` with arguments arranged according + * to the specified `indexes` where the argument value at the first index is + * provided as the first argument, the argument value at the second index is + * provided as the second argument, and so on. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to rearrange arguments for. + * @param {...(number|number[])} indexes The arranged argument indexes. + * @returns {Function} Returns the new function. + * @example + * + * var rearged = _.rearg(function(a, b, c) { + * return [a, b, c]; + * }, [2, 0, 1]); + * + * rearged('b', 'c', 'a') + * // => ['a', 'b', 'c'] + */ + var rearg = flatRest(function(func, indexes) { + return createWrap(func, REARG_FLAG, undefined, undefined, undefined, indexes); + }); + + /** + * Creates a function that invokes `func` with the `this` binding of the + * created function and arguments from `start` and beyond provided as + * an array. + * + * **Note:** This method is based on the + * [rest parameter](https://mdn.io/rest_parameters). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.rest(function(what, names) { + * return what + ' ' + _.initial(names).join(', ') + + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); + * }); + * + * say('hello', 'fred', 'barney', 'pebbles'); + * // => 'hello fred, barney, & pebbles' + */ + function rest(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start === undefined ? start : toInteger(start); + return baseRest(func, start); + } + + /** + * Creates a function that invokes `func` with the `this` binding of the + * create function and an array of arguments much like + * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). + * + * **Note:** This method is based on the + * [spread operator](https://mdn.io/spread_operator). + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Function + * @param {Function} func The function to spread arguments over. + * @param {number} [start=0] The start position of the spread. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.spread(function(who, what) { + * return who + ' says ' + what; + * }); + * + * say(['fred', 'hello']); + * // => 'fred says hello' + * + * var numbers = Promise.all([ + * Promise.resolve(40), + * Promise.resolve(36) + * ]); + * + * numbers.then(_.spread(function(x, y) { + * return x + y; + * })); + * // => a Promise of 76 + */ + function spread(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start === undefined ? 0 : nativeMax(toInteger(start), 0); + return baseRest(function(args) { + var array = args[start], + otherArgs = castSlice(args, 0, start); + + if (array) { + arrayPush(otherArgs, array); + } + return apply(func, this, otherArgs); + }); + } + + /** + * Creates a throttled function that only invokes `func` at most once per + * every `wait` milliseconds. The throttled function comes with a `cancel` + * method to cancel delayed `func` invocations and a `flush` method to + * immediately invoke them. Provide `options` to indicate whether `func` + * should be invoked on the leading and/or trailing edge of the `wait` + * timeout. The `func` is invoked with the last arguments provided to the + * throttled function. Subsequent calls to the throttled function return the + * result of the last `func` invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the throttled function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.throttle` and `_.debounce`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to throttle. + * @param {number} [wait=0] The number of milliseconds to throttle invocations to. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=true] + * Specify invoking on the leading edge of the timeout. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new throttled function. + * @example + * + * // Avoid excessively updating the position while scrolling. + * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); + * + * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. + * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); + * jQuery(element).on('click', throttled); + * + * // Cancel the trailing throttled invocation. + * jQuery(window).on('popstate', throttled.cancel); + */ + function throttle(func, wait, options) { + var leading = true, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (isObject(options)) { + leading = 'leading' in options ? !!options.leading : leading; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + return debounce(func, wait, { + 'leading': leading, + 'maxWait': wait, + 'trailing': trailing + }); + } + + /** + * Creates a function that accepts up to one argument, ignoring any + * additional arguments. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + * @example + * + * _.map(['6', '8', '10'], _.unary(parseInt)); + * // => [6, 8, 10] + */ + function unary(func) { + return ary(func, 1); + } + + /** + * Creates a function that provides `value` to `wrapper` as its first + * argument. Any additional arguments provided to the function are appended + * to those provided to the `wrapper`. The wrapper is invoked with the `this` + * binding of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {*} value The value to wrap. + * @param {Function} [wrapper=identity] The wrapper function. + * @returns {Function} Returns the new function. + * @example + * + * var p = _.wrap(_.escape, function(func, text) { + * return '

' + func(text) + '

'; + * }); + * + * p('fred, barney, & pebbles'); + * // => '

fred, barney, & pebbles

' + */ + function wrap(value, wrapper) { + wrapper = wrapper == null ? identity : wrapper; + return partial(wrapper, value); + } + + /*------------------------------------------------------------------------*/ + + /** + * Casts `value` as an array if it's not one. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Lang + * @param {*} value The value to inspect. + * @returns {Array} Returns the cast array. + * @example + * + * _.castArray(1); + * // => [1] + * + * _.castArray({ 'a': 1 }); + * // => [{ 'a': 1 }] + * + * _.castArray('abc'); + * // => ['abc'] + * + * _.castArray(null); + * // => [null] + * + * _.castArray(undefined); + * // => [undefined] + * + * _.castArray(); + * // => [] + * + * var array = [1, 2, 3]; + * console.log(_.castArray(array) === array); + * // => true + */ + function castArray() { + if (!arguments.length) { + return []; + } + var value = arguments[0]; + return isArray(value) ? value : [value]; + } + + /** + * Creates a shallow clone of `value`. + * + * **Note:** This method is loosely based on the + * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) + * and supports cloning arrays, array buffers, booleans, date objects, maps, + * numbers, `Object` objects, regexes, sets, strings, symbols, and typed + * arrays. The own enumerable properties of `arguments` objects are cloned + * as plain objects. An empty object is returned for uncloneable values such + * as error objects, functions, DOM nodes, and WeakMaps. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to clone. + * @returns {*} Returns the cloned value. + * @see _.cloneDeep + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var shallow = _.clone(objects); + * console.log(shallow[0] === objects[0]); + * // => true + */ + function clone(value) { + return baseClone(value, false, true); + } + + /** + * This method is like `_.clone` except that it accepts `customizer` which + * is invoked to produce the cloned value. If `customizer` returns `undefined`, + * cloning is handled by the method instead. The `customizer` is invoked with + * up to four arguments; (value [, index|key, object, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the cloned value. + * @see _.cloneDeepWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(false); + * } + * } + * + * var el = _.cloneWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 0 + */ + function cloneWith(value, customizer) { + return baseClone(value, false, true, customizer); + } + + /** + * This method is like `_.clone` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @returns {*} Returns the deep cloned value. + * @see _.clone + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var deep = _.cloneDeep(objects); + * console.log(deep[0] === objects[0]); + * // => false + */ + function cloneDeep(value) { + return baseClone(value, true, true); + } + + /** + * This method is like `_.cloneWith` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the deep cloned value. + * @see _.cloneWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(true); + * } + * } + * + * var el = _.cloneDeepWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 20 + */ + function cloneDeepWith(value, customizer) { + return baseClone(value, true, true, customizer); + } + + /** + * Checks if `object` conforms to `source` by invoking the predicate + * properties of `source` with the corresponding property values of `object`. + * + * **Note:** This method is equivalent to `_.conforms` when `source` is + * partially applied. + * + * @static + * @memberOf _ + * @since 4.14.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); + * // => true + * + * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); + * // => false + */ + function conformsTo(object, source) { + return source == null || baseConformsTo(object, source, keys(source)); + } + + /** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ + function eq(value, other) { + return value === other || (value !== value && other !== other); + } + + /** + * Checks if `value` is greater than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + * @see _.lt + * @example + * + * _.gt(3, 1); + * // => true + * + * _.gt(3, 3); + * // => false + * + * _.gt(1, 3); + * // => false + */ + var gt = createRelationalOperation(baseGt); + + /** + * Checks if `value` is greater than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than or equal to + * `other`, else `false`. + * @see _.lte + * @example + * + * _.gte(3, 1); + * // => true + * + * _.gte(3, 3); + * // => true + * + * _.gte(1, 3); + * // => false + */ + var gte = createRelationalOperation(function(value, other) { + return value >= other; + }); + + /** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); + } + + /** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ + var isArray = Array.isArray; + + /** + * Checks if `value` is classified as an `ArrayBuffer` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + * @example + * + * _.isArrayBuffer(new ArrayBuffer(2)); + * // => true + * + * _.isArrayBuffer(new Array(2)); + * // => false + */ + var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; + + /** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); + } + + /** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ + function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); + } + + /** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ + function isBoolean(value) { + return value === true || value === false || + (isObjectLike(value) && objectToString.call(value) == boolTag); + } + + /** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ + var isBuffer = nativeIsBuffer || stubFalse; + + /** + * Checks if `value` is classified as a `Date` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + * @example + * + * _.isDate(new Date); + * // => true + * + * _.isDate('Mon April 23 2012'); + * // => false + */ + var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; + + /** + * Checks if `value` is likely a DOM element. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. + * @example + * + * _.isElement(document.body); + * // => true + * + * _.isElement(''); + * // => false + */ + function isElement(value) { + return value != null && value.nodeType === 1 && isObjectLike(value) && !isPlainObject(value); + } + + /** + * Checks if `value` is an empty object, collection, map, or set. + * + * Objects are considered empty if they have no own enumerable string keyed + * properties. + * + * Array-like values such as `arguments` objects, arrays, buffers, strings, or + * jQuery-like collections are considered empty if they have a `length` of `0`. + * Similarly, maps and sets are considered empty if they have a `size` of `0`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is empty, else `false`. + * @example + * + * _.isEmpty(null); + * // => true + * + * _.isEmpty(true); + * // => true + * + * _.isEmpty(1); + * // => true + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({ 'a': 1 }); + * // => false + */ + function isEmpty(value) { + if (isArrayLike(value) && + (isArray(value) || typeof value == 'string' || + typeof value.splice == 'function' || isBuffer(value) || isArguments(value))) { + return !value.length; + } + var tag = getTag(value); + if (tag == mapTag || tag == setTag) { + return !value.size; + } + if (isPrototype(value)) { + return !nativeKeys(value).length; + } + for (var key in value) { + if (hasOwnProperty.call(value, key)) { + return false; + } + } + return true; + } + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are **not** supported. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ + function isEqual(value, other) { + return baseIsEqual(value, other); + } + + /** + * This method is like `_.isEqual` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with up to + * six arguments: (objValue, othValue [, index|key, object, other, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, othValue) { + * if (isGreeting(objValue) && isGreeting(othValue)) { + * return true; + * } + * } + * + * var array = ['hello', 'goodbye']; + * var other = ['hi', 'goodbye']; + * + * _.isEqualWith(array, other, customizer); + * // => true + */ + function isEqualWith(value, other, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + var result = customizer ? customizer(value, other) : undefined; + return result === undefined ? baseIsEqual(value, other, customizer) : !!result; + } + + /** + * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, + * `SyntaxError`, `TypeError`, or `URIError` object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an error object, else `false`. + * @example + * + * _.isError(new Error); + * // => true + * + * _.isError(Error); + * // => false + */ + function isError(value) { + if (!isObjectLike(value)) { + return false; + } + return (objectToString.call(value) == errorTag) || + (typeof value.message == 'string' && typeof value.name == 'string'); + } + + /** + * Checks if `value` is a finite primitive number. + * + * **Note:** This method is based on + * [`Number.isFinite`](https://mdn.io/Number/isFinite). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. + * @example + * + * _.isFinite(3); + * // => true + * + * _.isFinite(Number.MIN_VALUE); + * // => true + * + * _.isFinite(Infinity); + * // => false + * + * _.isFinite('3'); + * // => false + */ + function isFinite(value) { + return typeof value == 'number' && nativeIsFinite(value); + } + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; + } + + /** + * Checks if `value` is an integer. + * + * **Note:** This method is based on + * [`Number.isInteger`](https://mdn.io/Number/isInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an integer, else `false`. + * @example + * + * _.isInteger(3); + * // => true + * + * _.isInteger(Number.MIN_VALUE); + * // => false + * + * _.isInteger(Infinity); + * // => false + * + * _.isInteger('3'); + * // => false + */ + function isInteger(value) { + return typeof value == 'number' && value == toInteger(value); + } + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); + } + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return value != null && typeof value == 'object'; + } + + /** + * Checks if `value` is classified as a `Map` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + * @example + * + * _.isMap(new Map); + * // => true + * + * _.isMap(new WeakMap); + * // => false + */ + var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; + + /** + * Performs a partial deep comparison between `object` and `source` to + * determine if `object` contains equivalent property values. + * + * **Note:** This method is equivalent to `_.matches` when `source` is + * partially applied. + * + * Partial comparisons will match empty array and empty object `source` + * values against any array or object value, respectively. See `_.isEqual` + * for a list of supported value comparisons. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.isMatch(object, { 'b': 2 }); + * // => true + * + * _.isMatch(object, { 'b': 1 }); + * // => false + */ + function isMatch(object, source) { + return object === source || baseIsMatch(object, source, getMatchData(source)); + } + + /** + * This method is like `_.isMatch` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with five + * arguments: (objValue, srcValue, index|key, object, source). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, srcValue) { + * if (isGreeting(objValue) && isGreeting(srcValue)) { + * return true; + * } + * } + * + * var object = { 'greeting': 'hello' }; + * var source = { 'greeting': 'hi' }; + * + * _.isMatchWith(object, source, customizer); + * // => true + */ + function isMatchWith(object, source, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseIsMatch(object, source, getMatchData(source), customizer); + } + + /** + * Checks if `value` is `NaN`. + * + * **Note:** This method is based on + * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as + * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for + * `undefined` and other non-number values. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ + function isNaN(value) { + // An `NaN` primitive is the only value that is not equal to itself. + // Perform the `toStringTag` check first to avoid errors with some + // ActiveX objects in IE. + return isNumber(value) && value != +value; + } + + /** + * Checks if `value` is a pristine native function. + * + * **Note:** This method can't reliably detect native functions in the presence + * of the core-js package because core-js circumvents this kind of detection. + * Despite multiple requests, the core-js maintainer has made it clear: any + * attempt to fix the detection will be obstructed. As a result, we're left + * with little choice but to throw an error. Unfortunately, this also affects + * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), + * which rely on core-js. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + * @example + * + * _.isNative(Array.prototype.push); + * // => true + * + * _.isNative(_); + * // => false + */ + function isNative(value) { + if (isMaskable(value)) { + throw new Error('This method is not supported with core-js. Try https://github.com/es-shims.'); + } + return baseIsNative(value); + } + + /** + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(void 0); + * // => false + */ + function isNull(value) { + return value === null; + } + + /** + * Checks if `value` is `null` or `undefined`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is nullish, else `false`. + * @example + * + * _.isNil(null); + * // => true + * + * _.isNil(void 0); + * // => true + * + * _.isNil(NaN); + * // => false + */ + function isNil(value) { + return value == null; + } + + /** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are + * classified as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a number, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ + function isNumber(value) { + return typeof value == 'number' || + (isObjectLike(value) && objectToString.call(value) == numberTag); + } + + /** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ + function isPlainObject(value) { + if (!isObjectLike(value) || objectToString.call(value) != objectTag) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; + return (typeof Ctor == 'function' && + Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString); + } + + /** + * Checks if `value` is classified as a `RegExp` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + * @example + * + * _.isRegExp(/abc/); + * // => true + * + * _.isRegExp('/abc/'); + * // => false + */ + var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; + + /** + * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 + * double precision number which isn't the result of a rounded unsafe integer. + * + * **Note:** This method is based on + * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. + * @example + * + * _.isSafeInteger(3); + * // => true + * + * _.isSafeInteger(Number.MIN_VALUE); + * // => false + * + * _.isSafeInteger(Infinity); + * // => false + * + * _.isSafeInteger('3'); + * // => false + */ + function isSafeInteger(value) { + return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is classified as a `Set` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + * @example + * + * _.isSet(new Set); + * // => true + * + * _.isSet(new WeakSet); + * // => false + */ + var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; + + /** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ + function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); + } + + /** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ + function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); + } + + /** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ + var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + + /** + * Checks if `value` is `undefined`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + * + * _.isUndefined(null); + * // => false + */ + function isUndefined(value) { + return value === undefined; + } + + /** + * Checks if `value` is classified as a `WeakMap` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. + * @example + * + * _.isWeakMap(new WeakMap); + * // => true + * + * _.isWeakMap(new Map); + * // => false + */ + function isWeakMap(value) { + return isObjectLike(value) && getTag(value) == weakMapTag; + } + + /** + * Checks if `value` is classified as a `WeakSet` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. + * @example + * + * _.isWeakSet(new WeakSet); + * // => true + * + * _.isWeakSet(new Set); + * // => false + */ + function isWeakSet(value) { + return isObjectLike(value) && objectToString.call(value) == weakSetTag; + } + + /** + * Checks if `value` is less than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + * @see _.gt + * @example + * + * _.lt(1, 3); + * // => true + * + * _.lt(3, 3); + * // => false + * + * _.lt(3, 1); + * // => false + */ + var lt = createRelationalOperation(baseLt); + + /** + * Checks if `value` is less than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than or equal to + * `other`, else `false`. + * @see _.gte + * @example + * + * _.lte(1, 3); + * // => true + * + * _.lte(3, 3); + * // => true + * + * _.lte(3, 1); + * // => false + */ + var lte = createRelationalOperation(function(value, other) { + return value <= other; + }); + + /** + * Converts `value` to an array. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to convert. + * @returns {Array} Returns the converted array. + * @example + * + * _.toArray({ 'a': 1, 'b': 2 }); + * // => [1, 2] + * + * _.toArray('abc'); + * // => ['a', 'b', 'c'] + * + * _.toArray(1); + * // => [] + * + * _.toArray(null); + * // => [] + */ + function toArray(value) { + if (!value) { + return []; + } + if (isArrayLike(value)) { + return isString(value) ? stringToArray(value) : copyArray(value); + } + if (iteratorSymbol && value[iteratorSymbol]) { + return iteratorToArray(value[iteratorSymbol]()); + } + var tag = getTag(value), + func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); + + return func(value); + } + + /** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ + function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; + } + + /** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ + function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; + + return result === result ? (remainder ? result - remainder : result) : 0; + } + + /** + * Converts `value` to an integer suitable for use as the length of an + * array-like object. + * + * **Note:** This method is based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toLength(3.2); + * // => 3 + * + * _.toLength(Number.MIN_VALUE); + * // => 0 + * + * _.toLength(Infinity); + * // => 4294967295 + * + * _.toLength('3.2'); + * // => 3 + */ + function toLength(value) { + return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; + } + + /** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ + function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); + } + + /** + * Converts `value` to a plain object flattening inherited enumerable string + * keyed properties of `value` to own properties of the plain object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {Object} Returns the converted plain object. + * @example + * + * function Foo() { + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.assign({ 'a': 1 }, new Foo); + * // => { 'a': 1, 'b': 2 } + * + * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); + * // => { 'a': 1, 'b': 2, 'c': 3 } + */ + function toPlainObject(value) { + return copyObject(value, keysIn(value)); + } + + /** + * Converts `value` to a safe integer. A safe integer can be compared and + * represented correctly. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toSafeInteger(3.2); + * // => 3 + * + * _.toSafeInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toSafeInteger(Infinity); + * // => 9007199254740991 + * + * _.toSafeInteger('3.2'); + * // => 3 + */ + function toSafeInteger(value) { + return baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + } + + /** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {string} Returns the string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ + function toString(value) { + return value == null ? '' : baseToString(value); + } + + /*------------------------------------------------------------------------*/ + + /** + * Assigns own enumerable string keyed properties of source objects to the + * destination object. Source objects are applied from left to right. + * Subsequent sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object` and is loosely based on + * [`Object.assign`](https://mdn.io/Object/assign). + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assignIn + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assign({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'c': 3 } + */ + var assign = createAssigner(function(object, source) { + if (isPrototype(source) || isArrayLike(source)) { + copyObject(source, keys(source), object); + return; + } + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + assignValue(object, key, source[key]); + } + } + }); + + /** + * This method is like `_.assign` except that it iterates over own and + * inherited source properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extend + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assign + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assignIn({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } + */ + var assignIn = createAssigner(function(object, source) { + copyObject(source, keysIn(source), object); + }); + + /** + * This method is like `_.assignIn` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extendWith + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignInWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keysIn(source), object, customizer); + }); + + /** + * This method is like `_.assign` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignInWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var assignWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keys(source), object, customizer); + }); + + /** + * Creates an array of values corresponding to `paths` of `object`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {...(string|string[])} [paths] The property paths of elements to pick. + * @returns {Array} Returns the picked values. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _.at(object, ['a[0].b.c', 'a[1]']); + * // => [3, 4] + */ + var at = flatRest(baseAt); + + /** + * Creates an object that inherits from the `prototype` object. If a + * `properties` object is given, its own enumerable string keyed properties + * are assigned to the created object. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Object + * @param {Object} prototype The object to inherit from. + * @param {Object} [properties] The properties to assign to the object. + * @returns {Object} Returns the new object. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * function Circle() { + * Shape.call(this); + * } + * + * Circle.prototype = _.create(Shape.prototype, { + * 'constructor': Circle + * }); + * + * var circle = new Circle; + * circle instanceof Circle; + * // => true + * + * circle instanceof Shape; + * // => true + */ + function create(prototype, properties) { + var result = baseCreate(prototype); + return properties ? baseAssign(result, properties) : result; + } + + /** + * Assigns own and inherited enumerable string keyed properties of source + * objects to the destination object for all destination properties that + * resolve to `undefined`. Source objects are applied from left to right. + * Once a property is set, additional values of the same property are ignored. + * + * **Note:** This method mutates `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaultsDeep + * @example + * + * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var defaults = baseRest(function(args) { + args.push(undefined, assignInDefaults); + return apply(assignInWith, undefined, args); + }); + + /** + * This method is like `_.defaults` except that it recursively assigns + * default properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaults + * @example + * + * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); + * // => { 'a': { 'b': 2, 'c': 3 } } + */ + var defaultsDeep = baseRest(function(args) { + args.push(undefined, mergeDefaults); + return apply(mergeWith, undefined, args); + }); + + /** + * This method is like `_.find` except that it returns the key of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findKey(users, function(o) { return o.age < 40; }); + * // => 'barney' (iteration order is not guaranteed) + * + * // The `_.matches` iteratee shorthand. + * _.findKey(users, { 'age': 1, 'active': true }); + * // => 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findKey(users, 'active'); + * // => 'barney' + */ + function findKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); + } + + /** + * This method is like `_.findKey` except that it iterates over elements of + * a collection in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findLastKey(users, function(o) { return o.age < 40; }); + * // => returns 'pebbles' assuming `_.findKey` returns 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.findLastKey(users, { 'age': 36, 'active': true }); + * // => 'barney' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findLastKey(users, 'active'); + * // => 'pebbles' + */ + function findLastKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); + } + + /** + * Iterates over own and inherited enumerable string keyed properties of an + * object and invokes `iteratee` for each property. The iteratee is invoked + * with three arguments: (value, key, object). Iteratee functions may exit + * iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forInRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forIn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). + */ + function forIn(object, iteratee) { + return object == null + ? object + : baseFor(object, getIteratee(iteratee, 3), keysIn); + } + + /** + * This method is like `_.forIn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forIn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forInRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. + */ + function forInRight(object, iteratee) { + return object == null + ? object + : baseForRight(object, getIteratee(iteratee, 3), keysIn); + } + + /** + * Iterates over own enumerable string keyed properties of an object and + * invokes `iteratee` for each property. The iteratee is invoked with three + * arguments: (value, key, object). Iteratee functions may exit iteration + * early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwnRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ + function forOwn(object, iteratee) { + return object && baseForOwn(object, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.forOwn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwnRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. + */ + function forOwnRight(object, iteratee) { + return object && baseForOwnRight(object, getIteratee(iteratee, 3)); + } + + /** + * Creates an array of function property names from own enumerable properties + * of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functionsIn + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functions(new Foo); + * // => ['a', 'b'] + */ + function functions(object) { + return object == null ? [] : baseFunctions(object, keys(object)); + } + + /** + * Creates an array of function property names from own and inherited + * enumerable properties of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functions + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functionsIn(new Foo); + * // => ['a', 'b', 'c'] + */ + function functionsIn(object) { + return object == null ? [] : baseFunctions(object, keysIn(object)); + } + + /** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ + function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, path); + return result === undefined ? defaultValue : result; + } + + /** + * Checks if `path` is a direct property of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = { 'a': { 'b': 2 } }; + * var other = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.has(object, 'a'); + * // => true + * + * _.has(object, 'a.b'); + * // => true + * + * _.has(object, ['a', 'b']); + * // => true + * + * _.has(other, 'a'); + * // => false + */ + function has(object, path) { + return object != null && hasPath(object, path, baseHas); + } + + /** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ + function hasIn(object, path) { + return object != null && hasPath(object, path, baseHasIn); + } + + /** + * Creates an object composed of the inverted keys and values of `object`. + * If `object` contains duplicate values, subsequent values overwrite + * property assignments of previous values. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Object + * @param {Object} object The object to invert. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invert(object); + * // => { '1': 'c', '2': 'b' } + */ + var invert = createInverter(function(result, value, key) { + result[value] = key; + }, constant(identity)); + + /** + * This method is like `_.invert` except that the inverted object is generated + * from the results of running each element of `object` thru `iteratee`. The + * corresponding inverted value of each inverted key is an array of keys + * responsible for generating the inverted value. The iteratee is invoked + * with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.1.0 + * @category Object + * @param {Object} object The object to invert. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invertBy(object); + * // => { '1': ['a', 'c'], '2': ['b'] } + * + * _.invertBy(object, function(value) { + * return 'group' + value; + * }); + * // => { 'group1': ['a', 'c'], 'group2': ['b'] } + */ + var invertBy = createInverter(function(result, value, key) { + if (hasOwnProperty.call(result, value)) { + result[value].push(key); + } else { + result[value] = [key]; + } + }, getIteratee); + + /** + * Invokes the method at `path` of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {...*} [args] The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + * @example + * + * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; + * + * _.invoke(object, 'a[0].b.c.slice', 1, 3); + * // => [2, 3] + */ + var invoke = baseRest(baseInvoke); + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + } + + /** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ + function keysIn(object) { + return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + } + + /** + * The opposite of `_.mapValues`; this method creates an object with the + * same values as `object` and keys generated by running each own enumerable + * string keyed property of `object` thru `iteratee`. The iteratee is invoked + * with three arguments: (value, key, object). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapValues + * @example + * + * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { + * return key + value; + * }); + * // => { 'a1': 1, 'b2': 2 } + */ + function mapKeys(object, iteratee) { + var result = {}; + iteratee = getIteratee(iteratee, 3); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, iteratee(value, key, object), value); + }); + return result; + } + + /** + * Creates an object with the same keys as `object` and values generated + * by running each own enumerable string keyed property of `object` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, key, object). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapKeys + * @example + * + * var users = { + * 'fred': { 'user': 'fred', 'age': 40 }, + * 'pebbles': { 'user': 'pebbles', 'age': 1 } + * }; + * + * _.mapValues(users, function(o) { return o.age; }); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * + * // The `_.property` iteratee shorthand. + * _.mapValues(users, 'age'); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + */ + function mapValues(object, iteratee) { + var result = {}; + iteratee = getIteratee(iteratee, 3); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, key, iteratee(value, key, object)); + }); + return result; + } + + /** + * This method is like `_.assign` except that it recursively merges own and + * inherited enumerable string keyed properties of source objects into the + * destination object. Source properties that resolve to `undefined` are + * skipped if a destination value exists. Array and plain object properties + * are merged recursively. Other objects and value types are overridden by + * assignment. Source objects are applied from left to right. Subsequent + * sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @example + * + * var object = { + * 'a': [{ 'b': 2 }, { 'd': 4 }] + * }; + * + * var other = { + * 'a': [{ 'c': 3 }, { 'e': 5 }] + * }; + * + * _.merge(object, other); + * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } + */ + var merge = createAssigner(function(object, source, srcIndex) { + baseMerge(object, source, srcIndex); + }); + + /** + * This method is like `_.merge` except that it accepts `customizer` which + * is invoked to produce the merged values of the destination and source + * properties. If `customizer` returns `undefined`, merging is handled by the + * method instead. The `customizer` is invoked with six arguments: + * (objValue, srcValue, key, object, source, stack). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} customizer The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * function customizer(objValue, srcValue) { + * if (_.isArray(objValue)) { + * return objValue.concat(srcValue); + * } + * } + * + * var object = { 'a': [1], 'b': [2] }; + * var other = { 'a': [3], 'b': [4] }; + * + * _.mergeWith(object, other, customizer); + * // => { 'a': [1, 3], 'b': [2, 4] } + */ + var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { + baseMerge(object, source, srcIndex, customizer); + }); + + /** + * The opposite of `_.pick`; this method creates an object composed of the + * own and inherited enumerable string keyed properties of `object` that are + * not omitted. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [props] The property identifiers to omit. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omit(object, ['a', 'c']); + * // => { 'b': '2' } + */ + var omit = flatRest(function(object, props) { + if (object == null) { + return {}; + } + props = arrayMap(props, toKey); + return basePick(object, baseDifference(getAllKeysIn(object), props)); + }); + + /** + * The opposite of `_.pickBy`; this method creates an object composed of + * the own and inherited enumerable string keyed properties of `object` that + * `predicate` doesn't return truthy for. The predicate is invoked with two + * arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omitBy(object, _.isNumber); + * // => { 'b': '2' } + */ + function omitBy(object, predicate) { + return pickBy(object, negate(getIteratee(predicate))); + } + + /** + * Creates an object composed of the picked `object` properties. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [props] The property identifiers to pick. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pick(object, ['a', 'c']); + * // => { 'a': 1, 'c': 3 } + */ + var pick = flatRest(function(object, props) { + return object == null ? {} : basePick(object, arrayMap(props, toKey)); + }); + + /** + * Creates an object composed of the `object` properties `predicate` returns + * truthy for. The predicate is invoked with two arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pickBy(object, _.isNumber); + * // => { 'a': 1, 'c': 3 } + */ + function pickBy(object, predicate) { + return object == null ? {} : basePickBy(object, getAllKeysIn(object), getIteratee(predicate)); + } + + /** + * This method is like `_.get` except that if the resolved value is a + * function it's invoked with the `this` binding of its parent object and + * its result is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to resolve. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; + * + * _.result(object, 'a[0].b.c1'); + * // => 3 + * + * _.result(object, 'a[0].b.c2'); + * // => 4 + * + * _.result(object, 'a[0].b.c3', 'default'); + * // => 'default' + * + * _.result(object, 'a[0].b.c3', _.constant('default')); + * // => 'default' + */ + function result(object, path, defaultValue) { + path = isKey(path, object) ? [path] : castPath(path); + + var index = -1, + length = path.length; + + // Ensure the loop is entered when path is empty. + if (!length) { + object = undefined; + length = 1; + } + while (++index < length) { + var value = object == null ? undefined : object[toKey(path[index])]; + if (value === undefined) { + index = length; + value = defaultValue; + } + object = isFunction(value) ? value.call(object) : value; + } + return object; + } + + /** + * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, + * it's created. Arrays are created for missing index properties while objects + * are created for all other missing properties. Use `_.setWith` to customize + * `path` creation. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.set(object, 'a[0].b.c', 4); + * console.log(object.a[0].b.c); + * // => 4 + * + * _.set(object, ['x', '0', 'y', 'z'], 5); + * console.log(object.x[0].y.z); + * // => 5 + */ + function set(object, path, value) { + return object == null ? object : baseSet(object, path, value); + } + + /** + * This method is like `_.set` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * var object = {}; + * + * _.setWith(object, '[0][1]', 'a', Object); + * // => { '0': { '1': 'a' } } + */ + function setWith(object, path, value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return object == null ? object : baseSet(object, path, value, customizer); + } + + /** + * Creates an array of own enumerable string keyed-value pairs for `object` + * which can be consumed by `_.fromPairs`. If `object` is a map or set, its + * entries are returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias entries + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairs(new Foo); + * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) + */ + var toPairs = createToPairs(keys); + + /** + * Creates an array of own and inherited enumerable string keyed-value pairs + * for `object` which can be consumed by `_.fromPairs`. If `object` is a map + * or set, its entries are returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias entriesIn + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairsIn(new Foo); + * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) + */ + var toPairsIn = createToPairs(keysIn); + + /** + * An alternative to `_.reduce`; this method transforms `object` to a new + * `accumulator` object which is the result of running each of its own + * enumerable string keyed properties thru `iteratee`, with each invocation + * potentially mutating the `accumulator` object. If `accumulator` is not + * provided, a new object with the same `[[Prototype]]` will be used. The + * iteratee is invoked with four arguments: (accumulator, value, key, object). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The custom accumulator value. + * @returns {*} Returns the accumulated value. + * @example + * + * _.transform([2, 3, 4], function(result, n) { + * result.push(n *= n); + * return n % 2 == 0; + * }, []); + * // => [4, 9] + * + * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } + */ + function transform(object, iteratee, accumulator) { + var isArr = isArray(object) || isTypedArray(object); + iteratee = getIteratee(iteratee, 4); + + if (accumulator == null) { + if (isArr || isObject(object)) { + var Ctor = object.constructor; + if (isArr) { + accumulator = isArray(object) ? new Ctor : []; + } else { + accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; + } + } else { + accumulator = {}; + } + } + (isArr ? arrayEach : baseForOwn)(object, function(value, index, object) { + return iteratee(accumulator, value, index, object); + }); + return accumulator; + } + + /** + * Removes the property at `path` of `object`. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 7 } }] }; + * _.unset(object, 'a[0].b.c'); + * // => true + * + * console.log(object); + * // => { 'a': [{ 'b': {} }] }; + * + * _.unset(object, ['a', '0', 'b', 'c']); + * // => true + * + * console.log(object); + * // => { 'a': [{ 'b': {} }] }; + */ + function unset(object, path) { + return object == null ? true : baseUnset(object, path); + } + + /** + * This method is like `_.set` except that accepts `updater` to produce the + * value to set. Use `_.updateWith` to customize `path` creation. The `updater` + * is invoked with one argument: (value). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {Function} updater The function to produce the updated value. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.update(object, 'a[0].b.c', function(n) { return n * n; }); + * console.log(object.a[0].b.c); + * // => 9 + * + * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); + * console.log(object.x[0].y.z); + * // => 0 + */ + function update(object, path, updater) { + return object == null ? object : baseUpdate(object, path, castFunction(updater)); + } + + /** + * This method is like `_.update` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * var object = {}; + * + * _.updateWith(object, '[0][1]', _.constant('a'), Object); + * // => { '0': { '1': 'a' } } + */ + function updateWith(object, path, updater, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); + } + + /** + * Creates an array of the own enumerable string keyed property values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.values(new Foo); + * // => [1, 2] (iteration order is not guaranteed) + * + * _.values('hi'); + * // => ['h', 'i'] + */ + function values(object) { + return object ? baseValues(object, keys(object)) : []; + } + + /** + * Creates an array of the own and inherited enumerable string keyed property + * values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.valuesIn(new Foo); + * // => [1, 2, 3] (iteration order is not guaranteed) + */ + function valuesIn(object) { + return object == null ? [] : baseValues(object, keysIn(object)); + } + + /*------------------------------------------------------------------------*/ + + /** + * Clamps `number` within the inclusive `lower` and `upper` bounds. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Number + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. + * @example + * + * _.clamp(-10, -5, 5); + * // => -5 + * + * _.clamp(10, -5, 5); + * // => 5 + */ + function clamp(number, lower, upper) { + if (upper === undefined) { + upper = lower; + lower = undefined; + } + if (upper !== undefined) { + upper = toNumber(upper); + upper = upper === upper ? upper : 0; + } + if (lower !== undefined) { + lower = toNumber(lower); + lower = lower === lower ? lower : 0; + } + return baseClamp(toNumber(number), lower, upper); + } + + /** + * Checks if `n` is between `start` and up to, but not including, `end`. If + * `end` is not specified, it's set to `start` with `start` then set to `0`. + * If `start` is greater than `end` the params are swapped to support + * negative ranges. + * + * @static + * @memberOf _ + * @since 3.3.0 + * @category Number + * @param {number} number The number to check. + * @param {number} [start=0] The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + * @see _.range, _.rangeRight + * @example + * + * _.inRange(3, 2, 4); + * // => true + * + * _.inRange(4, 8); + * // => true + * + * _.inRange(4, 2); + * // => false + * + * _.inRange(2, 2); + * // => false + * + * _.inRange(1.2, 2); + * // => true + * + * _.inRange(5.2, 4); + * // => false + * + * _.inRange(-3, -2, -6); + * // => true + */ + function inRange(number, start, end) { + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + number = toNumber(number); + return baseInRange(number, start, end); + } + + /** + * Produces a random number between the inclusive `lower` and `upper` bounds. + * If only one argument is provided a number between `0` and the given number + * is returned. If `floating` is `true`, or either `lower` or `upper` are + * floats, a floating-point number is returned instead of an integer. + * + * **Note:** JavaScript follows the IEEE-754 standard for resolving + * floating-point values which can produce unexpected results. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Number + * @param {number} [lower=0] The lower bound. + * @param {number} [upper=1] The upper bound. + * @param {boolean} [floating] Specify returning a floating-point number. + * @returns {number} Returns the random number. + * @example + * + * _.random(0, 5); + * // => an integer between 0 and 5 + * + * _.random(5); + * // => also an integer between 0 and 5 + * + * _.random(5, true); + * // => a floating-point number between 0 and 5 + * + * _.random(1.2, 5.2); + * // => a floating-point number between 1.2 and 5.2 + */ + function random(lower, upper, floating) { + if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { + upper = floating = undefined; + } + if (floating === undefined) { + if (typeof upper == 'boolean') { + floating = upper; + upper = undefined; + } + else if (typeof lower == 'boolean') { + floating = lower; + lower = undefined; + } + } + if (lower === undefined && upper === undefined) { + lower = 0; + upper = 1; + } + else { + lower = toFinite(lower); + if (upper === undefined) { + upper = lower; + lower = 0; + } else { + upper = toFinite(upper); + } + } + if (lower > upper) { + var temp = lower; + lower = upper; + upper = temp; + } + if (floating || lower % 1 || upper % 1) { + var rand = nativeRandom(); + return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); + } + return baseRandom(lower, upper); + } + + /*------------------------------------------------------------------------*/ + + /** + * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the camel cased string. + * @example + * + * _.camelCase('Foo Bar'); + * // => 'fooBar' + * + * _.camelCase('--foo-bar--'); + * // => 'fooBar' + * + * _.camelCase('__FOO_BAR__'); + * // => 'fooBar' + */ + var camelCase = createCompounder(function(result, word, index) { + word = word.toLowerCase(); + return result + (index ? capitalize(word) : word); + }); + + /** + * Converts the first character of `string` to upper case and the remaining + * to lower case. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to capitalize. + * @returns {string} Returns the capitalized string. + * @example + * + * _.capitalize('FRED'); + * // => 'Fred' + */ + function capitalize(string) { + return upperFirst(toString(string).toLowerCase()); + } + + /** + * Deburrs `string` by converting + * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) + * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) + * letters to basic Latin letters and removing + * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to deburr. + * @returns {string} Returns the deburred string. + * @example + * + * _.deburr('déjà vu'); + * // => 'deja vu' + */ + function deburr(string) { + string = toString(string); + return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); + } + + /** + * Checks if `string` ends with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=string.length] The position to search up to. + * @returns {boolean} Returns `true` if `string` ends with `target`, + * else `false`. + * @example + * + * _.endsWith('abc', 'c'); + * // => true + * + * _.endsWith('abc', 'b'); + * // => false + * + * _.endsWith('abc', 'b', 2); + * // => true + */ + function endsWith(string, target, position) { + string = toString(string); + target = baseToString(target); + + var length = string.length; + position = position === undefined + ? length + : baseClamp(toInteger(position), 0, length); + + var end = position; + position -= target.length; + return position >= 0 && string.slice(position, end) == target; + } + + /** + * Converts the characters "&", "<", ">", '"', and "'" in `string` to their + * corresponding HTML entities. + * + * **Note:** No other characters are escaped. To escape additional + * characters use a third-party library like [_he_](https://mths.be/he). + * + * Though the ">" character is escaped for symmetry, characters like + * ">" and "/" don't need escaping in HTML and have no special meaning + * unless they're part of a tag or unquoted attribute value. See + * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) + * (under "semi-related fun fact") for more details. + * + * When working with HTML you should always + * [quote attribute values](http://wonko.com/post/html-escaping) to reduce + * XSS vectors. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escape('fred, barney, & pebbles'); + * // => 'fred, barney, & pebbles' + */ + function escape(string) { + string = toString(string); + return (string && reHasUnescapedHtml.test(string)) + ? string.replace(reUnescapedHtml, escapeHtmlChar) + : string; + } + + /** + * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", + * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escapeRegExp('[lodash](https://lodash.com/)'); + * // => '\[lodash\]\(https://lodash\.com/\)' + */ + function escapeRegExp(string) { + string = toString(string); + return (string && reHasRegExpChar.test(string)) + ? string.replace(reRegExpChar, '\\$&') + : string; + } + + /** + * Converts `string` to + * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the kebab cased string. + * @example + * + * _.kebabCase('Foo Bar'); + * // => 'foo-bar' + * + * _.kebabCase('fooBar'); + * // => 'foo-bar' + * + * _.kebabCase('__FOO_BAR__'); + * // => 'foo-bar' + */ + var kebabCase = createCompounder(function(result, word, index) { + return result + (index ? '-' : '') + word.toLowerCase(); + }); + + /** + * Converts `string`, as space separated words, to lower case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the lower cased string. + * @example + * + * _.lowerCase('--Foo-Bar--'); + * // => 'foo bar' + * + * _.lowerCase('fooBar'); + * // => 'foo bar' + * + * _.lowerCase('__FOO_BAR__'); + * // => 'foo bar' + */ + var lowerCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + word.toLowerCase(); + }); + + /** + * Converts the first character of `string` to lower case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.lowerFirst('Fred'); + * // => 'fred' + * + * _.lowerFirst('FRED'); + * // => 'fRED' + */ + var lowerFirst = createCaseFirst('toLowerCase'); + + /** + * Pads `string` on the left and right sides if it's shorter than `length`. + * Padding characters are truncated if they can't be evenly divided by `length`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.pad('abc', 8); + * // => ' abc ' + * + * _.pad('abc', 8, '_-'); + * // => '_-abc_-_' + * + * _.pad('abc', 3); + * // => 'abc' + */ + function pad(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + if (!length || strLength >= length) { + return string; + } + var mid = (length - strLength) / 2; + return ( + createPadding(nativeFloor(mid), chars) + + string + + createPadding(nativeCeil(mid), chars) + ); + } + + /** + * Pads `string` on the right side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padEnd('abc', 6); + * // => 'abc ' + * + * _.padEnd('abc', 6, '_-'); + * // => 'abc_-_' + * + * _.padEnd('abc', 3); + * // => 'abc' + */ + function padEnd(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + return (length && strLength < length) + ? (string + createPadding(length - strLength, chars)) + : string; + } + + /** + * Pads `string` on the left side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padStart('abc', 6); + * // => ' abc' + * + * _.padStart('abc', 6, '_-'); + * // => '_-_abc' + * + * _.padStart('abc', 3); + * // => 'abc' + */ + function padStart(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + return (length && strLength < length) + ? (createPadding(length - strLength, chars) + string) + : string; + } + + /** + * Converts `string` to an integer of the specified radix. If `radix` is + * `undefined` or `0`, a `radix` of `10` is used unless `value` is a + * hexadecimal, in which case a `radix` of `16` is used. + * + * **Note:** This method aligns with the + * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category String + * @param {string} string The string to convert. + * @param {number} [radix=10] The radix to interpret `value` by. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {number} Returns the converted integer. + * @example + * + * _.parseInt('08'); + * // => 8 + * + * _.map(['6', '08', '10'], _.parseInt); + * // => [6, 8, 10] + */ + function parseInt(string, radix, guard) { + if (guard || radix == null) { + radix = 0; + } else if (radix) { + radix = +radix; + } + return nativeParseInt(toString(string), radix || 0); + } + + /** + * Repeats the given string `n` times. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to repeat. + * @param {number} [n=1] The number of times to repeat the string. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {string} Returns the repeated string. + * @example + * + * _.repeat('*', 3); + * // => '***' + * + * _.repeat('abc', 2); + * // => 'abcabc' + * + * _.repeat('abc', 0); + * // => '' + */ + function repeat(string, n, guard) { + if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { + n = 1; + } else { + n = toInteger(n); + } + return baseRepeat(toString(string), n); + } + + /** + * Replaces matches for `pattern` in `string` with `replacement`. + * + * **Note:** This method is based on + * [`String#replace`](https://mdn.io/String/replace). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to modify. + * @param {RegExp|string} pattern The pattern to replace. + * @param {Function|string} replacement The match replacement. + * @returns {string} Returns the modified string. + * @example + * + * _.replace('Hi Fred', 'Fred', 'Barney'); + * // => 'Hi Barney' + */ + function replace() { + var args = arguments, + string = toString(args[0]); + + return args.length < 3 ? string : string.replace(args[1], args[2]); + } + + /** + * Converts `string` to + * [snake case](https://en.wikipedia.org/wiki/Snake_case). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the snake cased string. + * @example + * + * _.snakeCase('Foo Bar'); + * // => 'foo_bar' + * + * _.snakeCase('fooBar'); + * // => 'foo_bar' + * + * _.snakeCase('--FOO-BAR--'); + * // => 'foo_bar' + */ + var snakeCase = createCompounder(function(result, word, index) { + return result + (index ? '_' : '') + word.toLowerCase(); + }); + + /** + * Splits `string` by `separator`. + * + * **Note:** This method is based on + * [`String#split`](https://mdn.io/String/split). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to split. + * @param {RegExp|string} separator The separator pattern to split by. + * @param {number} [limit] The length to truncate results to. + * @returns {Array} Returns the string segments. + * @example + * + * _.split('a-b-c', '-', 2); + * // => ['a', 'b'] + */ + function split(string, separator, limit) { + if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { + separator = limit = undefined; + } + limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; + if (!limit) { + return []; + } + string = toString(string); + if (string && ( + typeof separator == 'string' || + (separator != null && !isRegExp(separator)) + )) { + separator = baseToString(separator); + if (!separator && hasUnicode(string)) { + return castSlice(stringToArray(string), 0, limit); + } + } + return string.split(separator, limit); + } + + /** + * Converts `string` to + * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). + * + * @static + * @memberOf _ + * @since 3.1.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the start cased string. + * @example + * + * _.startCase('--foo-bar--'); + * // => 'Foo Bar' + * + * _.startCase('fooBar'); + * // => 'Foo Bar' + * + * _.startCase('__FOO_BAR__'); + * // => 'FOO BAR' + */ + var startCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + upperFirst(word); + }); + + /** + * Checks if `string` starts with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=0] The position to search from. + * @returns {boolean} Returns `true` if `string` starts with `target`, + * else `false`. + * @example + * + * _.startsWith('abc', 'a'); + * // => true + * + * _.startsWith('abc', 'b'); + * // => false + * + * _.startsWith('abc', 'b', 1); + * // => true + */ + function startsWith(string, target, position) { + string = toString(string); + position = baseClamp(toInteger(position), 0, string.length); + target = baseToString(target); + return string.slice(position, position + target.length) == target; + } + + /** + * Creates a compiled template function that can interpolate data properties + * in "interpolate" delimiters, HTML-escape interpolated data properties in + * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data + * properties may be accessed as free variables in the template. If a setting + * object is given, it takes precedence over `_.templateSettings` values. + * + * **Note:** In the development build `_.template` utilizes + * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) + * for easier debugging. + * + * For more information on precompiling templates see + * [lodash's custom builds documentation](https://lodash.com/custom-builds). + * + * For more information on Chrome extension sandboxes see + * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The template string. + * @param {Object} [options={}] The options object. + * @param {RegExp} [options.escape=_.templateSettings.escape] + * The HTML "escape" delimiter. + * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] + * The "evaluate" delimiter. + * @param {Object} [options.imports=_.templateSettings.imports] + * An object to import into the template as free variables. + * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] + * The "interpolate" delimiter. + * @param {string} [options.sourceURL='lodash.templateSources[n]'] + * The sourceURL of the compiled template. + * @param {string} [options.variable='obj'] + * The data object variable name. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the compiled template function. + * @example + * + * // Use the "interpolate" delimiter to create a compiled template. + * var compiled = _.template('hello <%= user %>!'); + * compiled({ 'user': 'fred' }); + * // => 'hello fred!' + * + * // Use the HTML "escape" delimiter to escape data property values. + * var compiled = _.template('<%- value %>'); + * compiled({ 'value': ' + - diff --git a/tests/mocha/test.js b/tests/mocha/test.js index 67ea550..cb7a20b 100644 --- a/tests/mocha/test.js +++ b/tests/mocha/test.js @@ -101,6 +101,111 @@ describe('UsergridError', function() { done(); }); }); +describe('UsergridQuery', function() { + + describe('_type', function() { + it('_type should equal "cats" when passing "type" as a parameter to UsergridQuery', function() { + var query = new UsergridQuery('cats') + query.should.have.property('_type').equal('cats') + }) + + it('_type should equal "cats" when calling .type() builder method', function() { + var query = new UsergridQuery().type('cats') + query.should.have.property('_type').equal('cats') + }) + + it('_type should equal "cats" when calling .collection() builder method', function() { + var query = new UsergridQuery().collection('cats') + query.should.have.property('_type').equal('cats') + }) + }) + + describe('_limit', function() { + it('_limit should equal 2 when setting .limit(2)', function() { + var query = new UsergridQuery('cats').limit(2) + query.should.have.property('_limit').equal(2) + }) + + it('_limit should equal 10 when setting .limit(10)', function() { + var query = new UsergridQuery('cats').limit(10) + query.should.have.property('_limit').equal(10) + }) + }) + + describe('_ql', function() { + it('should be an empty string if query or sort are empty or underfined', function() { + var query = new UsergridQuery('cats') + query.should.have.property('_ql').equal("") + }) + + it('should support complex builder pattern syntax (chained constructor methods)', function() { + var query = new UsergridQuery('cats') + .gt('weight', 2.4) + .contains('color', 'bl*') + .not + .eq('color', 'blue') + .or + .eq('color', 'orange') + query.should.have.property('_ql').equal("select * where weight > 2.4 and color contains 'bl*' and not color = 'blue' or color = 'orange'") + }) + + it('and operator should be implied when joining multiple conditions', function() { + var query1 = new UsergridQuery('cats') + .gt('weight', 2.4) + .contains('color', 'bl*') + query1.should.have.property('_ql').equal("select * where weight > 2.4 and color contains 'bl*'") + var query2 = new UsergridQuery('cats') + .gt('weight', 2.4) + .and + .contains('color', 'bl*') + query2.should.have.property('_ql').equal("select * where weight > 2.4 and color contains 'bl*'") + }) + + it('not operator should precede conditional statement', function() { + var query = new UsergridQuery('cats') + .not + .eq('color', 'white') + query.should.have.property('_ql').equal("select * where not color = 'white'") + }) + + it('fromString should set _ql directly, bypassing builder pattern methods', function() { + var q = "where color = 'black' or color = 'orange'" + var query = new UsergridQuery('cats') + .fromString(q) + query.should.have.property('_ql').equal(q) + }) + + it('string values should be contained in single quotes', function() { + var query = new UsergridQuery('cats') + .eq('color', 'black') + query.should.have.property('_ql').equal("select * where color = 'black'") + }) + + it('boolean values should not be contained in single quotes', function() { + var query = new UsergridQuery('cats') + .eq('longHair', true) + query.should.have.property('_ql').equal("select * where longHair = true") + }) + + it('float values should not be contained in single quotes', function() { + var query = new UsergridQuery('cats') + .lt('weight', 18) + query.should.have.property('_ql').equal("select * where weight < 18") + }) + + it('integer values should not be contained in single quotes', function() { + var query = new UsergridQuery('cats') + .gte('weight', 2) + query.should.have.property('_ql').equal("select * where weight >= 2") + }) + + it('uuid values should not be contained in single quotes', function() { + var query = new UsergridQuery('cats') + .eq('uuid', 'a61e29ba-944f-11e5-8690-fbb14f62c803') + query.should.have.property('_ql').equal("select * where uuid = a61e29ba-944f-11e5-8690-fbb14f62c803") + }) + }) +}); describe('Usergrid', function(){ describe('SDK Version', function(){ it('should contain a minimum SDK version',function(){ diff --git a/tests/resources/js/should.js b/tests/resources/js/should.js new file mode 100644 index 0000000..4422bff --- /dev/null +++ b/tests/resources/js/should.js @@ -0,0 +1,4062 @@ +/*! + * should - test framework agnostic BDD-style assertions + * @version v11.1.0 + * @author TJ Holowaychuk , Denis Bardadym and other contributors + * @link https://github.com/shouldjs/should.js + * @license MIT + */ + +(function (root) { + 'use strict'; + + var types = { + NUMBER: 'number', + UNDEFINED: 'undefined', + STRING: 'string', + BOOLEAN: 'boolean', + OBJECT: 'object', + FUNCTION: 'function', + NULL: 'null', + ARRAY: 'array', + REGEXP: 'regexp', + DATE: 'date', + ERROR: 'error', + ARGUMENTS: 'arguments', + SYMBOL: 'symbol', + ARRAY_BUFFER: 'array-buffer', + TYPED_ARRAY: 'typed-array', + DATA_VIEW: 'data-view', + MAP: 'map', + SET: 'set', + WEAK_SET: 'weak-set', + WEAK_MAP: 'weak-map', + PROMISE: 'promise', + + // node buffer + BUFFER: 'buffer', + + // dom html element + HTML_ELEMENT: 'html-element', + HTML_ELEMENT_TEXT: 'html-element-text', + DOCUMENT: 'document', + WINDOW: 'window', + FILE: 'file', + FILE_LIST: 'file-list', + BLOB: 'blob', + + HOST: 'host', + + XHR: 'xhr', + + // simd + SIMD: 'simd' + }; + + /* + * Simple data function to store type information + * @param {string} type Usually what is returned from typeof + * @param {string} cls Sanitized @Class via Object.prototype.toString + * @param {string} sub If type and cls the same, and need to specify somehow + * @private + * @example + * + * //for null + * new Type('null'); + * + * //for Date + * new Type('object', 'date'); + * + * //for Uint8Array + * + * new Type('object', 'typed-array', 'uint8'); + */ + function Type(type, cls, sub) { + if (!type) { + throw new Error('Type class must be initialized at least with `type` information'); + } + this.type = type; + this.cls = cls; + this.sub = sub; + } + + Type.prototype = { + toString: function(sep) { + sep = sep || ';'; + var str = [this.type]; + if (this.cls) { + str.push(this.cls); + } + if (this.sub) { + str.push(this.sub); + } + return str.join(sep); + }, + + toTryTypes: function() { + var _types = []; + if (this.sub) { + _types.push(new Type(this.type, this.cls, this.sub)); + } + if (this.cls) { + _types.push(new Type(this.type, this.cls)); + } + _types.push(new Type(this.type)); + + return _types; + } + }; + + var toString = Object.prototype.toString; + + + + /** + * Function to store type checks + * @private + */ + function TypeChecker() { + this.checks = []; + } + + TypeChecker.prototype = { + add: function(func) { + this.checks.push(func); + return this; + }, + + addBeforeFirstMatch: function(obj, func) { + var match = this.getFirstMatch(obj); + if (match) { + this.checks.splice(match.index, 0, func); + } else { + this.add(func); + } + }, + + addTypeOf: function(type, res) { + return this.add(function(obj, tpeOf) { + if (tpeOf === type) { + return new Type(res); + } + }); + }, + + addClass: function(cls, res, sub) { + return this.add(function(obj, tpeOf, objCls) { + if (objCls === cls) { + return new Type(types.OBJECT, res, sub); + } + }); + }, + + getFirstMatch: function(obj) { + var typeOf = typeof obj; + var cls = toString.call(obj); + + for (var i = 0, l = this.checks.length; i < l; i++) { + var res = this.checks[i].call(this, obj, typeOf, cls); + if (typeof res !== 'undefined') { + return { result: res, func: this.checks[i], index: i }; + } + } + }, + + getType: function(obj) { + var match = this.getFirstMatch(obj); + return match && match.result; + } + }; + + var main = new TypeChecker(); + + //TODO add iterators + + main + .addTypeOf(types.NUMBER, types.NUMBER) + .addTypeOf(types.UNDEFINED, types.UNDEFINED) + .addTypeOf(types.STRING, types.STRING) + .addTypeOf(types.BOOLEAN, types.BOOLEAN) + .addTypeOf(types.FUNCTION, types.FUNCTION) + .addTypeOf(types.SYMBOL, types.SYMBOL) + .add(function(obj) { + if (obj === null) { + return new Type(types.NULL); + } + }) + .addClass('[object String]', types.STRING) + .addClass('[object Boolean]', types.BOOLEAN) + .addClass('[object Number]', types.NUMBER) + .addClass('[object Array]', types.ARRAY) + .addClass('[object RegExp]', types.REGEXP) + .addClass('[object Error]', types.ERROR) + .addClass('[object Date]', types.DATE) + .addClass('[object Arguments]', types.ARGUMENTS) + + .addClass('[object ArrayBuffer]', types.ARRAY_BUFFER) + .addClass('[object Int8Array]', types.TYPED_ARRAY, 'int8') + .addClass('[object Uint8Array]', types.TYPED_ARRAY, 'uint8') + .addClass('[object Uint8ClampedArray]', types.TYPED_ARRAY, 'uint8clamped') + .addClass('[object Int16Array]', types.TYPED_ARRAY, 'int16') + .addClass('[object Uint16Array]', types.TYPED_ARRAY, 'uint16') + .addClass('[object Int32Array]', types.TYPED_ARRAY, 'int32') + .addClass('[object Uint32Array]', types.TYPED_ARRAY, 'uint32') + .addClass('[object Float32Array]', types.TYPED_ARRAY, 'float32') + .addClass('[object Float64Array]', types.TYPED_ARRAY, 'float64') + + .addClass('[object Bool16x8]', types.SIMD, 'bool16x8') + .addClass('[object Bool32x4]', types.SIMD, 'bool32x4') + .addClass('[object Bool8x16]', types.SIMD, 'bool8x16') + .addClass('[object Float32x4]', types.SIMD, 'float32x4') + .addClass('[object Int16x8]', types.SIMD, 'int16x8') + .addClass('[object Int32x4]', types.SIMD, 'int32x4') + .addClass('[object Int8x16]', types.SIMD, 'int8x16') + .addClass('[object Uint16x8]', types.SIMD, 'uint16x8') + .addClass('[object Uint32x4]', types.SIMD, 'uint32x4') + .addClass('[object Uint8x16]', types.SIMD, 'uint8x16') + + .addClass('[object DataView]', types.DATA_VIEW) + .addClass('[object Map]', types.MAP) + .addClass('[object WeakMap]', types.WEAK_MAP) + .addClass('[object Set]', types.SET) + .addClass('[object WeakSet]', types.WEAK_SET) + .addClass('[object Promise]', types.PROMISE) + .addClass('[object Blob]', types.BLOB) + .addClass('[object File]', types.FILE) + .addClass('[object FileList]', types.FILE_LIST) + .addClass('[object XMLHttpRequest]', types.XHR) + .add(function(obj) { + if ((typeof Promise === types.FUNCTION && obj instanceof Promise) || + (typeof obj.then === types.FUNCTION)) { + return new Type(types.OBJECT, types.PROMISE); + } + }) + .add(function(obj) { + if (typeof Buffer !== 'undefined' && obj instanceof Buffer) {// eslint-disable-line no-undef + return new Type(types.OBJECT, types.BUFFER); + } + }) + .add(function(obj) { + if (typeof Node !== 'undefined' && obj instanceof Node) { + return new Type(types.OBJECT, types.HTML_ELEMENT, obj.nodeName); + } + }) + .add(function(obj) { + // probably at the begginging should be enough these checks + if (obj.Boolean === Boolean && obj.Number === Number && obj.String === String && obj.Date === Date) { + return new Type(types.OBJECT, types.HOST); + } + }) + .add(function() { + return new Type(types.OBJECT); + }); + + /** + * Get type information of anything + * + * @param {any} obj Anything that could require type information + * @return {Type} type info + * @private + */ + function getGlobalType(obj) { + return main.getType(obj); + } + + getGlobalType.checker = main; + getGlobalType.TypeChecker = TypeChecker; + getGlobalType.Type = Type; + + Object.keys(types).forEach(function(typeName) { + getGlobalType[typeName] = types[typeName]; + }); + + function format$1(msg) { + var args = arguments; + for (var i = 1, l = args.length; i < l; i++) { + msg = msg.replace(/%s/, args[i]); + } + return msg; + } + + var hasOwnProperty = Object.prototype.hasOwnProperty; + + function EqualityFail(a, b, reason, path) { + this.a = a; + this.b = b; + this.reason = reason; + this.path = path; + } + + function typeToString(tp) { + return tp.type + (tp.cls ? '(' + tp.cls + (tp.sub ? ' ' + tp.sub : '') + ')' : ''); + } + + var PLUS_0_AND_MINUS_0 = '+0 is not equal to -0'; + var DIFFERENT_TYPES = 'A has type %s and B has type %s'; + var EQUALITY = 'A is not equal to B'; + var EQUALITY_PROTOTYPE = 'A and B have different prototypes'; + var WRAPPED_VALUE = 'A wrapped value is not equal to B wrapped value'; + var FUNCTION_SOURCES = 'function A is not equal to B by source code value (via .toString call)'; + var MISSING_KEY = '%s has no key %s'; + var SET_MAP_MISSING_KEY = 'Set/Map missing key %s'; + + + var DEFAULT_OPTIONS = { + checkProtoEql: true, + checkSubType: true, + plusZeroAndMinusZeroEqual: true, + collectAllFails: false + }; + + function setBooleanDefault(property, obj, opts, defaults) { + obj[property] = typeof opts[property] !== 'boolean' ? defaults[property] : opts[property]; + } + + var METHOD_PREFIX = '_check_'; + + function EQ(opts, a, b, path) { + opts = opts || {}; + + setBooleanDefault('checkProtoEql', this, opts, DEFAULT_OPTIONS); + setBooleanDefault('plusZeroAndMinusZeroEqual', this, opts, DEFAULT_OPTIONS); + setBooleanDefault('checkSubType', this, opts, DEFAULT_OPTIONS); + setBooleanDefault('collectAllFails', this, opts, DEFAULT_OPTIONS); + + this.a = a; + this.b = b; + + this._meet = opts._meet || []; + + this.fails = opts.fails || []; + + this.path = path || []; + } + + function ShortcutError(fail) { + this.name = 'ShortcutError'; + this.message = 'fail fast'; + this.fail = fail; + } + + ShortcutError.prototype = Object.create(Error.prototype); + + EQ.checkStrictEquality = function(a, b) { + this.collectFail(a !== b, EQUALITY); + }; + + EQ.add = function add(type, cls, sub, f) { + var args = Array.prototype.slice.call(arguments); + f = args.pop(); + EQ.prototype[METHOD_PREFIX + args.join('_')] = f; + }; + + EQ.prototype = { + check: function() { + try { + this.check0(); + } catch (e) { + if (e instanceof ShortcutError) { + return [e.fail]; + } + throw e; + } + return this.fails; + }, + + check0: function() { + var a = this.a; + var b = this.b; + + // equal a and b exit early + if (a === b) { + // check for +0 !== -0; + return this.collectFail(a === 0 && (1 / a !== 1 / b) && !this.plusZeroAndMinusZeroEqual, PLUS_0_AND_MINUS_0); + } + + var typeA = getGlobalType(a); + var typeB = getGlobalType(b); + + // if objects has different types they are not equal + if (typeA.type !== typeB.type || typeA.cls !== typeB.cls || typeA.sub !== typeB.sub) { + return this.collectFail(true, format$1(DIFFERENT_TYPES, typeToString(typeA), typeToString(typeB))); + } + + // as types the same checks type specific things + var name1 = typeA.type, name2 = typeA.type; + if (typeA.cls) { + name1 += '_' + typeA.cls; + name2 += '_' + typeA.cls; + } + if (typeA.sub) { + name2 += '_' + typeA.sub; + } + + var f = this[METHOD_PREFIX + name2] || this[METHOD_PREFIX + name1] || this[METHOD_PREFIX + typeA.type] || this.defaultCheck; + + f.call(this, this.a, this.b); + }, + + collectFail: function(comparison, reason, showReason) { + if (comparison) { + var res = new EqualityFail(this.a, this.b, reason, this.path); + res.showReason = !!showReason; + + this.fails.push(res); + + if (!this.collectAllFails) { + throw new ShortcutError(res); + } + } + }, + + checkPlainObjectsEquality: function(a, b) { + // compare deep objects and arrays + // stacks contain references only + // + var meet = this._meet; + var m = this._meet.length; + while (m--) { + var st = meet[m]; + if (st[0] === a && st[1] === b) { + return; + } + } + + // add `a` and `b` to the stack of traversed objects + meet.push([a, b]); + + // TODO maybe something else like getOwnPropertyNames + var key; + for (key in b) { + if (hasOwnProperty.call(b, key)) { + if (hasOwnProperty.call(a, key)) { + this.checkPropertyEquality(key); + } else { + this.collectFail(true, format$1(MISSING_KEY, 'A', key)); + } + } + } + + // ensure both objects have the same number of properties + for (key in a) { + if (hasOwnProperty.call(a, key)) { + this.collectFail(!hasOwnProperty.call(b, key), format$1(MISSING_KEY, 'B', key)); + } + } + + meet.pop(); + + if (this.checkProtoEql) { + //TODO should i check prototypes for === or use eq? + this.collectFail(Object.getPrototypeOf(a) !== Object.getPrototypeOf(b), EQUALITY_PROTOTYPE, true); + } + + }, + + checkPropertyEquality: function(propertyName) { + var _eq = new EQ(this, this.a[propertyName], this.b[propertyName], this.path.concat([propertyName])); + _eq.check0(); + }, + + defaultCheck: EQ.checkStrictEquality + }; + + + EQ.add(getGlobalType.NUMBER, function(a, b) { + this.collectFail((a !== a && b === b) || (b !== b && a === a) || (a !== b && a === a && b === b), EQUALITY); + }); + + [getGlobalType.SYMBOL, getGlobalType.BOOLEAN, getGlobalType.STRING].forEach(function(tp) { + EQ.add(tp, EQ.checkStrictEquality); + }); + + EQ.add(getGlobalType.FUNCTION, function(a, b) { + // functions are compared by their source code + this.collectFail(a.toString() !== b.toString(), FUNCTION_SOURCES); + // check user properties + this.checkPlainObjectsEquality(a, b); + }); + + EQ.add(getGlobalType.OBJECT, getGlobalType.REGEXP, function(a, b) { + // check regexp flags + var flags = ['source', 'global', 'multiline', 'lastIndex', 'ignoreCase', 'sticky', 'unicode']; + while (flags.length) { + this.checkPropertyEquality(flags.shift()); + } + // check user properties + this.checkPlainObjectsEquality(a, b); + }); + + EQ.add(getGlobalType.OBJECT, getGlobalType.DATE, function(a, b) { + //check by timestamp only (using .valueOf) + this.collectFail(+a !== +b, EQUALITY); + // check user properties + this.checkPlainObjectsEquality(a, b); + }); + + [getGlobalType.NUMBER, getGlobalType.BOOLEAN, getGlobalType.STRING].forEach(function(tp) { + EQ.add(getGlobalType.OBJECT, tp, function(a, b) { + //primitive type wrappers + this.collectFail(a.valueOf() !== b.valueOf(), WRAPPED_VALUE); + // check user properties + this.checkPlainObjectsEquality(a, b); + }); + }); + + EQ.add(getGlobalType.OBJECT, function(a, b) { + this.checkPlainObjectsEquality(a, b); + }); + + [getGlobalType.ARRAY, getGlobalType.ARGUMENTS, getGlobalType.TYPED_ARRAY].forEach(function(tp) { + EQ.add(getGlobalType.OBJECT, tp, function(a, b) { + this.checkPropertyEquality('length'); + + this.checkPlainObjectsEquality(a, b); + }); + }); + + EQ.add(getGlobalType.OBJECT, getGlobalType.ARRAY_BUFFER, function(a, b) { + this.checkPropertyEquality('byteLength'); + + this.checkPlainObjectsEquality(a, b); + }); + + EQ.add(getGlobalType.OBJECT, getGlobalType.ERROR, function(a, b) { + this.checkPropertyEquality('name'); + this.checkPropertyEquality('message'); + + this.checkPlainObjectsEquality(a, b); + }); + + EQ.add(getGlobalType.OBJECT, getGlobalType.BUFFER, function(a) { + this.checkPropertyEquality('length'); + + var l = a.length; + while (l--) { + this.checkPropertyEquality(l); + } + + //we do not check for user properties because + //node Buffer have some strange hidden properties + }); + + [getGlobalType.MAP, getGlobalType.SET, getGlobalType.WEAK_MAP, getGlobalType.WEAK_SET].forEach(function(tp) { + EQ.add(getGlobalType.OBJECT, tp, function(a, b) { + this._meet.push([a, b]); + + var iteratorA = a.entries(); + for (var nextA = iteratorA.next(); !nextA.done; nextA = iteratorA.next()) { + + var iteratorB = b.entries(); + var keyFound = false; + for (var nextB = iteratorB.next(); !nextB.done; nextB = iteratorB.next()) { + // try to check keys first + var r = eq(nextA.value[0], nextB.value[0], { collectAllFails: false, _meet: this._meet }); + + if (r.length === 0) { + keyFound = true; + + // check values also + eq(nextA.value[1], nextB.value[1], this); + } + } + + if (!keyFound) { + // no such key at all + this.collectFail(true, format$1(SET_MAP_MISSING_KEY, nextA.value[0])); + } + } + + this._meet.pop(); + + this.checkPlainObjectsEquality(a, b); + }); + }); + + + function eq(a, b, opts) { + return new EQ(opts, a, b).check(); + } + + eq.EQ = EQ; + + var _hasOwnProperty = Object.prototype.hasOwnProperty; + var _propertyIsEnumerable = Object.prototype.propertyIsEnumerable; + + function hasOwnProperty$1(obj, key) { + return _hasOwnProperty.call(obj, key); + } + + function propertyIsEnumerable(obj, key) { + return _propertyIsEnumerable.call(obj, key); + } + + function merge(a, b) { + if (a && b) { + for (var key in b) { + a[key] = b[key]; + } + } + return a; + } + + function isIterator(obj) { + if (!obj) { + return false; + } + + if (obj.__shouldIterator__) { + return true; + } + + return typeof obj.next === 'function' && + typeof Symbol === 'function' && + typeof Symbol.iterator === 'symbol' && + typeof obj[Symbol.iterator] === 'function' && + obj[Symbol.iterator]() === obj; + } + + //TODO find better way + function isGeneratorFunction(f) { + return typeof f === 'function' && /^function\s*\*\s*/.test(f.toString()); + } + + // TODO in future add generators instead of forEach and iterator implementation + + + function ObjectIterator(obj) { + this._obj = obj; + } + + ObjectIterator.prototype = { + __shouldIterator__: true, // special marker + + next: function() { + if (this._done) { + throw new Error('Iterator already reached the end'); + } + + if (!this._keys) { + this._keys = Object.keys(this._obj); + this._index = 0; + } + + var key = this._keys[this._index]; + this._done = this._index === this._keys.length; + this._index += 1; + + return { + value: this._done ? void 0: [key, this._obj[key]], + done: this._done + }; + } + }; + + if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { + ObjectIterator.prototype[Symbol.iterator] = function() { + return this; + }; + } + + + function TypeAdaptorStorage() { + this._typeAdaptors = []; + this._iterableTypes = {}; + } + + TypeAdaptorStorage.prototype = { + add: function(type, cls, sub, adaptor) { + return this.addType(new getGlobalType.Type(type, cls, sub), adaptor); + }, + + addType: function(type, adaptor) { + this._typeAdaptors[type.toString()] = adaptor; + }, + + getAdaptor: function(tp, funcName) { + var tries = tp.toTryTypes(); + while (tries.length) { + var toTry = tries.shift(); + var ad = this._typeAdaptors[toTry]; + if (ad && ad[funcName]) { + return ad[funcName]; + } + } + }, + + requireAdaptor: function(tp, funcName) { + var a = this.getAdaptor(tp, funcName); + if (!a) { + throw new Error('There is no type adaptor `' + funcName + '` for ' + tp.toString()); + } + return a; + }, + + addIterableType: function(tp) { + this._iterableTypes[tp.toString()] = true; + }, + + isIterableType: function(tp) { + return !!this._iterableTypes[tp.toString()]; + } + }; + + var defaultTypeAdaptorStorage = new TypeAdaptorStorage(); + + // default for objects + defaultTypeAdaptorStorage.addType(new getGlobalType.Type(getGlobalType.OBJECT), { + forEach: function(obj, f, context) { + for (var prop in obj) { + if (hasOwnProperty$1(obj, prop) && propertyIsEnumerable(obj, prop)) { + if (f.call(context, obj[prop], prop, obj) === false) { + return; + } + } + } + }, + + has: function(obj, prop) { + return hasOwnProperty$1(obj, prop); + }, + + get: function(obj, prop) { + return obj[prop]; + }, + + iterator: function(obj) { + return new ObjectIterator(obj); + } + }); + + var mapAdaptor = { + has: function(obj, key) { + return obj.has(key); + }, + + get: function(obj, key) { + return obj.get(key); + }, + + forEach: function(obj, f, context) { + var iter = obj.entries(); + forEach(iter, function(value) { + return f.call(context, value[1], value[0], obj); + }); + }, + + size: function(obj) { + return obj.size; + }, + + isEmpty: function(obj) { + return obj.size === 0; + }, + + iterator: function(obj) { + return obj.entries(); + } + }; + + var setAdaptor = merge({}, mapAdaptor); + setAdaptor.get = function(obj, key) { + if (obj.has(key)) { + return key; + } + }; + + defaultTypeAdaptorStorage.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.MAP), mapAdaptor); + defaultTypeAdaptorStorage.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.SET), setAdaptor); + defaultTypeAdaptorStorage.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.WEAK_SET), setAdaptor); + defaultTypeAdaptorStorage.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.WEAK_MAP), mapAdaptor); + + defaultTypeAdaptorStorage.addType(new getGlobalType.Type(getGlobalType.STRING), { + isEmpty: function(obj) { + return obj === ''; + }, + + size: function(obj) { + return obj.length; + } + }); + + defaultTypeAdaptorStorage.addIterableType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.ARRAY)); + defaultTypeAdaptorStorage.addIterableType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.ARGUMENTS)); + + function forEach(obj, f, context) { + if (isGeneratorFunction(obj)) { + return forEach(obj(), f, context); + } else if (isIterator(obj)) { + var value = obj.next(); + while (!value.done) { + if (f.call(context, value.value, 'value', obj) === false) { + return; + } + value = obj.next(); + } + } else { + var type = getGlobalType(obj); + var func = defaultTypeAdaptorStorage.requireAdaptor(type, 'forEach'); + func(obj, f, context); + } + } + + + function size(obj) { + var type = getGlobalType(obj); + var func = defaultTypeAdaptorStorage.getAdaptor(type, 'size'); + if (func) { + return func(obj); + } else { + var len = 0; + forEach(obj, function() { + len += 1; + }); + return len; + } + } + + function isEmpty(obj) { + var type = getGlobalType(obj); + var func = defaultTypeAdaptorStorage.getAdaptor(type, 'isEmpty'); + if (func) { + return func(obj); + } else { + var res = true; + forEach(obj, function() { + res = false; + return false; + }); + return res; + } + } + + // return boolean if obj has such 'key' + function has(obj, key) { + var type = getGlobalType(obj); + var func = defaultTypeAdaptorStorage.requireAdaptor(type, 'has'); + return func(obj, key); + } + + // return value for given key + function get(obj, key) { + var type = getGlobalType(obj); + var func = defaultTypeAdaptorStorage.requireAdaptor(type, 'get'); + return func(obj, key); + } + + function some(obj, f, context) { + var res = false; + forEach(obj, function(value, key) { + if (f.call(context, value, key, obj)) { + res = true; + return false; + } + }, context); + return res; + } + + function isIterable(obj) { + return defaultTypeAdaptorStorage.isIterableType(getGlobalType(obj)); + } + + function iterator(obj) { + return defaultTypeAdaptorStorage.requireAdaptor(getGlobalType(obj), 'iterator')(obj); + } + + function looksLikeANumber(n) { + return !!n.match(/\d+/); + } + + function keyCompare(a, b) { + var aNum = looksLikeANumber(a); + var bNum = looksLikeANumber(b); + if (aNum && bNum) { + return 1*a - 1*b; + } else if (aNum && !bNum) { + return -1; + } else if (!aNum && bNum) { + return 1; + } else { + return a.localeCompare(b); + } + } + + function genKeysFunc(f) { + return function(value) { + var k = f(value); + k.sort(keyCompare); + return k; + }; + } + + function Formatter(opts) { + opts = opts || {}; + + this.seen = []; + + var keysFunc; + if (typeof opts.keysFunc === 'function') { + keysFunc = opts.keysFunc; + } else if (opts.keys === false) { + keysFunc = Object.getOwnPropertyNames; + } else { + keysFunc = Object.keys; + } + + this.getKeys = genKeysFunc(keysFunc); + + this.maxLineLength = typeof opts.maxLineLength === 'number' ? opts.maxLineLength : 60; + this.propSep = opts.propSep || ','; + + this.isUTCdate = !!opts.isUTCdate; + } + + + + Formatter.prototype = { + constructor: Formatter, + + format: function(value) { + var tp = getGlobalType(value); + + if (tp.type === getGlobalType.OBJECT && this.alreadySeen(value)) { + return '[Circular]'; + } + + var tries = tp.toTryTypes(); + var f = this.defaultFormat; + while (tries.length) { + var toTry = tries.shift(); + var name = Formatter.formatterFunctionName(toTry); + if (this[name]) { + f = this[name]; + break; + } + } + return f.call(this, value).trim(); + }, + + defaultFormat: function(obj) { + return String(obj); + }, + + alreadySeen: function(value) { + return this.seen.indexOf(value) >= 0; + } + + }; + + Formatter.addType = function addType(tp, f) { + Formatter.prototype[Formatter.formatterFunctionName(tp)] = f; + }; + + Formatter.formatterFunctionName = function formatterFunctionName(tp) { + return '_format_' + tp.toString('_'); + }; + + var EOL = '\n'; + + function indent$1(v, indentation) { + return v + .split(EOL) + .map(function(vv) { + return indentation + vv; + }) + .join(EOL); + } + + function pad(str, value, filler) { + str = String(str); + var isRight = false; + + if (value < 0) { + isRight = true; + value = -value; + } + + if (str.length < value) { + var padding = new Array(value - str.length + 1).join(filler); + return isRight ? str + padding : padding + str; + } else { + return str; + } + } + + function pad0(str, value) { + return pad(str, value, '0'); + } + + var functionNameRE = /^\s*function\s*(\S*)\s*\(/; + + function functionName$1(f) { + if (f.name) { + return f.name; + } + var matches = f.toString().match(functionNameRE); + if (matches === null) { + // `functionNameRE` doesn't match arrow functions. + return ''; + } + var name = matches[1]; + return name; + } + + function constructorName(obj) { + while (obj) { + var descriptor = Object.getOwnPropertyDescriptor(obj, 'constructor'); + if (descriptor !== undefined && typeof descriptor.value === 'function') { + var name = functionName$1(descriptor.value); + if (name !== '') { + return name; + } + } + + obj = Object.getPrototypeOf(obj); + } + } + + var INDENT = ' '; + + function addSpaces(str) { + return indent$1(str, INDENT); + } + + function typeAdaptorForEachFormat(obj, opts) { + opts = opts || {}; + var filterKey = opts.filterKey || function() { return true; }; + + var formatKey = opts.formatKey || this.format; + var formatValue = opts.formatValue || this.format; + + var keyValueSep = typeof opts.keyValueSep !== 'undefined' ? opts.keyValueSep : ': '; + + this.seen.push(obj); + + var formatLength = 0; + var pairs = []; + + forEach(obj, function(value, key) { + if (!filterKey(key)) { + return; + } + + var formattedKey = formatKey.call(this, key); + var formattedValue = formatValue.call(this, value, key); + + var pair = formattedKey ? (formattedKey + keyValueSep + formattedValue) : formattedValue; + + formatLength += pair.length; + pairs.push(pair); + }, this); + + this.seen.pop(); + + (opts.additionalKeys || []).forEach(function(keyValue) { + var pair = keyValue[0] + keyValueSep + this.format(keyValue[1]); + formatLength += pair.length; + pairs.push(pair); + }, this); + + var prefix = opts.prefix || constructorName(obj) || ''; + if (prefix.length > 0) { + prefix += ' '; + } + + var lbracket, rbracket; + if (Array.isArray(opts.brackets)) { + lbracket = opts.brackets[0]; + rbracket = opts.brackets[1]; + } else { + lbracket = '{'; + rbracket = '}'; + } + + var rootValue = opts.value || ''; + + if (pairs.length === 0) { + return rootValue || (prefix + lbracket + rbracket); + } + + if (formatLength <= this.maxLineLength) { + return prefix + lbracket + ' ' + (rootValue ? rootValue + ' ' : '') + pairs.join(this.propSep + ' ') + ' ' + rbracket; + } else { + return prefix + lbracket + '\n' + (rootValue ? ' ' + rootValue + '\n' : '') + pairs.map(addSpaces).join(this.propSep + '\n') + '\n' + rbracket; + } + } + + function formatPlainObjectKey(key) { + return typeof key === 'string' && key.match(/^[a-zA-Z_$][a-zA-Z_$0-9]*$/) ? key : this.format(key); + } + + function getPropertyDescriptor(obj, key) { + var desc; + try { + desc = Object.getOwnPropertyDescriptor(obj, key) || { value: obj[key] }; + } catch (e) { + desc = { value: e }; + } + return desc; + } + + function formatPlainObjectValue(obj, key) { + var desc = getPropertyDescriptor(obj, key); + if (desc.get && desc.set) { + return '[Getter/Setter]'; + } + if (desc.get) { + return '[Getter]'; + } + if (desc.set) { + return '[Setter]'; + } + + return this.format(desc.value); + } + + function formatPlainObject(obj, opts) { + opts = opts || {}; + opts.keyValueSep = ': '; + opts.formatKey = opts.formatKey || formatPlainObjectKey; + opts.formatValue = opts.formatValue || function(value, key) { + return formatPlainObjectValue.call(this, obj, key); + }; + return typeAdaptorForEachFormat.call(this, obj, opts); + } + + function formatWrapper1(value) { + return formatPlainObject.call(this, value, { + additionalKeys: [['[[PrimitiveValue]]', value.valueOf()]] + }); + } + + + function formatWrapper2(value) { + var realValue = value.valueOf(); + + return formatPlainObject.call(this, value, { + filterKey: function(key) { + //skip useless indexed properties + return !(key.match(/\d+/) && parseInt(key, 10) < realValue.length); + }, + additionalKeys: [['[[PrimitiveValue]]', realValue]] + }); + } + + function formatRegExp(value) { + return formatPlainObject.call(this, value, { + value: String(value) + }); + } + + function formatFunction(value) { + var obj = {}; + Object.keys(value).forEach(function(key) { + obj[key] = value[key]; + }); + return formatPlainObject.call(this, obj, { + prefix: 'Function', + additionalKeys: [['name', functionName$1(value)]] + }); + } + + function formatArray(value) { + return formatPlainObject.call(this, value, { + formatKey: function(key) { + if (!key.match(/\d+/)) { + return formatPlainObjectKey.call(this, key); + } + }, + brackets: ['[', ']'] + }); + } + + function formatArguments(value) { + return formatPlainObject.call(this, value, { + formatKey: function(key) { + if (!key.match(/\d+/)) { + return formatPlainObjectKey.call(this, key); + } + }, + brackets: ['[', ']'], + prefix: 'Arguments' + }); + } + + function _formatDate(value, isUTC) { + var prefix = isUTC ? 'UTC' : ''; + + var date = value['get' + prefix + 'FullYear']() + + '-' + + pad0(value['get' + prefix + 'Month']() + 1, 2) + + '-' + + pad0(value['get' + prefix + 'Date'](), 2); + + var time = pad0(value['get' + prefix + 'Hours'](), 2) + + ':' + + pad0(value['get' + prefix + 'Minutes'](), 2) + + ':' + + pad0(value['get' + prefix + 'Seconds'](), 2) + + '.' + + pad0(value['get' + prefix + 'Milliseconds'](), 3); + + var to = value.getTimezoneOffset(); + var absTo = Math.abs(to); + var hours = Math.floor(absTo / 60); + var minutes = absTo - hours * 60; + var tzFormat = (to < 0 ? '+' : '-') + pad0(hours, 2) + pad0(minutes, 2); + + return date + ' ' + time + (isUTC ? '' : ' ' + tzFormat); + } + + function formatDate(value) { + return formatPlainObject.call(this, value, { value: _formatDate(value, this.isUTCdate) }); + } + + function formatError(value) { + return formatPlainObject.call(this, value, { + prefix: value.name, + additionalKeys: [['message', value.message]] + }); + } + + function generateFormatForNumberArray(lengthProp, name, padding) { + return function(value) { + var max = this.byteArrayMaxLength || 50; + var length = value[lengthProp]; + var formattedValues = []; + var len = 0; + for (var i = 0; i < max && i < length; i++) { + var b = value[i] || 0; + var v = pad0(b.toString(16), padding); + len += v.length; + formattedValues.push(v); + } + var prefix = value.constructor.name || name || ''; + if (prefix) { + prefix += ' '; + } + + if (formattedValues.length === 0) { + return prefix + '[]'; + } + + if (len <= this.maxLineLength) { + return prefix + '[ ' + formattedValues.join(this.propSep + ' ') + ' ' + ']'; + } else { + return prefix + '[\n' + formattedValues.map(addSpaces).join(this.propSep + '\n') + '\n' + ']'; + } + }; + } + + function formatMap(obj) { + return typeAdaptorForEachFormat.call(this, obj, { + keyValueSep: ' => ' + }); + } + + function formatSet(obj) { + return typeAdaptorForEachFormat.call(this, obj, { + keyValueSep: '', + formatKey: function() { return ''; } + }); + } + + function genSimdVectorFormat(constructorName, length) { + return function(value) { + var Constructor = value.constructor; + var extractLane = Constructor.extractLane; + + var len = 0; + var props = []; + + for (var i = 0; i < length; i ++) { + var key = this.format(extractLane(value, i)); + len += key.length; + props.push(key); + } + + if (len <= this.maxLineLength) { + return constructorName + ' [ ' + props.join(this.propSep + ' ') + ' ]'; + } else { + return constructorName + ' [\n' + props.map(addSpaces).join(this.propSep + '\n') + '\n' + ']'; + } + }; + } + + function defaultFormat(value, opts) { + return new Formatter(opts).format(value); + } + + defaultFormat.Formatter = Formatter; + defaultFormat.addSpaces = addSpaces; + defaultFormat.pad0 = pad0; + defaultFormat.functionName = functionName$1; + defaultFormat.constructorName = constructorName; + defaultFormat.formatPlainObjectKey = formatPlainObjectKey; + defaultFormat.typeAdaptorForEachFormat = typeAdaptorForEachFormat; + // adding primitive types + Formatter.addType(new getGlobalType.Type(getGlobalType.UNDEFINED), function() { + return 'undefined'; + }); + Formatter.addType(new getGlobalType.Type(getGlobalType.NULL), function() { + return 'null'; + }); + Formatter.addType(new getGlobalType.Type(getGlobalType.BOOLEAN), function(value) { + return value ? 'true': 'false'; + }); + Formatter.addType(new getGlobalType.Type(getGlobalType.SYMBOL), function(value) { + return value.toString(); + }); + Formatter.addType(new getGlobalType.Type(getGlobalType.NUMBER), function(value) { + if (value === 0 && 1 / value < 0) { + return '-0'; + } + return String(value); + }); + + Formatter.addType(new getGlobalType.Type(getGlobalType.STRING), function(value) { + return '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + }); + + Formatter.addType(new getGlobalType.Type(getGlobalType.FUNCTION), formatFunction); + + // plain object + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT), formatPlainObject); + + // type wrappers + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.NUMBER), formatWrapper1); + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.BOOLEAN), formatWrapper1); + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.STRING), formatWrapper2); + + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.REGEXP), formatRegExp); + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.ARRAY), formatArray); + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.ARGUMENTS), formatArguments); + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.DATE), formatDate); + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.ERROR), formatError); + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.SET), formatSet); + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.MAP), formatMap); + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.WEAK_MAP), formatMap); + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.WEAK_SET), formatSet); + + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.BUFFER), generateFormatForNumberArray('length', 'Buffer', 2)); + + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.ARRAY_BUFFER), generateFormatForNumberArray('byteLength', 'ArrayBuffer', 2)); + + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.TYPED_ARRAY, 'int8'), generateFormatForNumberArray('length', 'Int8Array', 2)); + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.TYPED_ARRAY, 'uint8'), generateFormatForNumberArray('length', 'Uint8Array', 2)); + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.TYPED_ARRAY, 'uint8clamped'), generateFormatForNumberArray('length', 'Uint8ClampedArray', 2)); + + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.TYPED_ARRAY, 'int16'), generateFormatForNumberArray('length', 'Int16Array', 4)); + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.TYPED_ARRAY, 'uint16'), generateFormatForNumberArray('length', 'Uint16Array', 4)); + + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.TYPED_ARRAY, 'int32'), generateFormatForNumberArray('length', 'Int32Array', 8)); + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.TYPED_ARRAY, 'uint32'), generateFormatForNumberArray('length', 'Uint32Array', 8)); + + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.SIMD, 'bool16x8'), genSimdVectorFormat('Bool16x8', 8)); + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.SIMD, 'bool32x4'), genSimdVectorFormat('Bool32x4', 4)); + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.SIMD, 'bool8x16'), genSimdVectorFormat('Bool8x16', 16)); + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.SIMD, 'float32x4'), genSimdVectorFormat('Float32x4', 4)); + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.SIMD, 'int16x8'), genSimdVectorFormat('Int16x8', 8)); + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.SIMD, 'int32x4'), genSimdVectorFormat('Int32x4', 4)); + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.SIMD, 'int8x16'), genSimdVectorFormat('Int8x16', 16)); + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.SIMD, 'uint16x8'), genSimdVectorFormat('Uint16x8', 8)); + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.SIMD, 'uint32x4'), genSimdVectorFormat('Uint32x4', 4)); + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.SIMD, 'uint8x16'), genSimdVectorFormat('Uint8x16', 16)); + + + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.PROMISE), function() { + return '[Promise]';//TODO it could be nice to inspect its state and value + }); + + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.XHR), function() { + return '[XMLHttpRequest]';//TODO it could be nice to inspect its state + }); + + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.HTML_ELEMENT), function(value) { + return value.outerHTML; + }); + + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.HTML_ELEMENT, '#text'), function(value) { + return value.nodeValue; + }); + + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.HTML_ELEMENT, '#document'), function(value) { + return value.documentElement.outerHTML; + }); + + Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.HOST), function() { + return '[Host]'; + }); + + function isWrapperType(obj) { + return obj instanceof Number || + obj instanceof String || + obj instanceof Boolean; + } + + function convertPropertyName(name) { + return (typeof name === 'symbol') ? name : String(name); + } + + var functionName = defaultFormat.functionName; + + var config = { + typeAdaptors: defaultTypeAdaptorStorage, + + getFormatter: function(opts) { + return new defaultFormat.Formatter(opts || config); + } + }; + + function format(value, opts) { + return config.getFormatter(opts).format(value); + } + + function formatProp(value) { + var formatter = config.getFormatter(); + return defaultFormat.formatPlainObjectKey.call(formatter, value); + } + + /** + * should AssertionError + * @param {Object} options + * @constructor + * @memberOf should + * @static + */ + function AssertionError(options) { + merge(this, options); + + if (!options.message) { + Object.defineProperty(this, 'message', { + get: function() { + if (!this._message) { + this._message = this.generateMessage(); + this.generatedMessage = true; + } + return this._message; + }, + configurable: true, + enumerable: false + } + ); + } + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.stackStartFunction); + } else { + // non v8 browsers so we can have a stacktrace + var err = new Error(); + if (err.stack) { + var out = err.stack; + + if (this.stackStartFunction) { + // try to strip useless frames + var fn_name = functionName(this.stackStartFunction); + var idx = out.indexOf('\n' + fn_name); + if (idx >= 0) { + // once we have located the function frame + // we need to strip out everything before it (and its line) + var next_line = out.indexOf('\n', idx + 1); + out = out.substring(next_line + 1); + } + } + + this.stack = out; + } + } + } + + + var indent = ' '; + function prependIndent(line) { + return indent + line; + } + + function indentLines(text) { + return text.split('\n').map(prependIndent).join('\n'); + } + + + // assert.AssertionError instanceof Error + AssertionError.prototype = Object.create(Error.prototype, { + name: { + value: 'AssertionError' + }, + + generateMessage: { + value: function() { + if (!this.operator && this.previous) { + return this.previous.message; + } + var actual = format(this.actual); + var expected = 'expected' in this ? ' ' + format(this.expected) : ''; + var details = 'details' in this && this.details ? ' (' + this.details + ')' : ''; + + var previous = this.previous ? '\n' + indentLines(this.previous.message) : ''; + + return 'expected ' + actual + (this.negate ? ' not ' : ' ') + this.operator + expected + details + previous; + } + } + }); + + /** + * should Assertion + * @param {*} obj Given object for assertion + * @constructor + * @memberOf should + * @static + */ + function Assertion(obj) { + this.obj = obj; + + this.anyOne = false; + this.negate = false; + + this.params = {actual: obj}; + } + + Assertion.prototype = { + constructor: Assertion, + + /** + * Base method for assertions. + * + * Before calling this method need to fill Assertion#params object. This method usually called from other assertion methods. + * `Assertion#params` can contain such properties: + * * `operator` - required string containing description of this assertion + * * `obj` - optional replacement for this.obj, it usefull if you prepare more clear object then given + * * `message` - if this property filled with string any others will be ignored and this one used as assertion message + * * `expected` - any object used when you need to assert relation between given object and expected. Like given == expected (== is a relation) + * * `details` - additional string with details to generated message + * + * @memberOf Assertion + * @category assertion + * @param {*} expr Any expression that will be used as a condition for asserting. + * @example + * + * var a = new should.Assertion(42); + * + * a.params = { + * operator: 'to be magic number', + * } + * + * a.assert(false); + * //throws AssertionError: expected 42 to be magic number + */ + assert: function(expr) { + if (expr) { + return this; + } + + var params = this.params; + + if ('obj' in params && !('actual' in params)) { + params.actual = params.obj; + } else if (!('obj' in params) && !('actual' in params)) { + params.actual = this.obj; + } + + params.stackStartFunction = params.stackStartFunction || this.assert; + params.negate = this.negate; + + params.assertion = this; + + throw new AssertionError(params); + }, + + /** + * Shortcut for `Assertion#assert(false)`. + * + * @memberOf Assertion + * @category assertion + * @example + * + * var a = new should.Assertion(42); + * + * a.params = { + * operator: 'to be magic number', + * } + * + * a.fail(); + * //throws AssertionError: expected 42 to be magic number + */ + fail: function() { + return this.assert(false); + } + }; + + + + /** + * Assertion used to delegate calls of Assertion methods inside of Promise. + * It has almost all methods of Assertion.prototype + * + * @param {Promise} obj + */ + function PromisedAssertion(/* obj */) { + Assertion.apply(this, arguments); + } + + /** + * Make PromisedAssertion to look like promise. Delegate resolve and reject to given promise. + * + * @private + * @returns {Promise} + */ + PromisedAssertion.prototype.then = function(resolve, reject) { + return this.obj.then(resolve, reject); + }; + + /** + * Way to extend Assertion function. It uses some logic + * to define only positive assertions and itself rule with negative assertion. + * + * All actions happen in subcontext and this method take care about negation. + * Potentially we can add some more modifiers that does not depends from state of assertion. + * + * @memberOf Assertion + * @static + * @param {String} name Name of assertion. It will be used for defining method or getter on Assertion.prototype + * @param {Function} func Function that will be called on executing assertion + * @example + * + * Assertion.add('asset', function() { + * this.params = { operator: 'to be asset' } + * + * this.obj.should.have.property('id').which.is.a.Number() + * this.obj.should.have.property('path') + * }) + */ + Assertion.add = function(name, func) { + Object.defineProperty(Assertion.prototype, name, { + enumerable: true, + configurable: true, + value: function() { + var context = new Assertion(this.obj, this, name); + context.anyOne = this.anyOne; + + try { + func.apply(context, arguments); + } catch (e) { + // check for fail + if (e instanceof AssertionError) { + // negative fail + if (this.negate) { + this.obj = context.obj; + this.negate = false; + return this; + } + + if (context !== e.assertion) { + context.params.previous = e; + } + + // positive fail + context.negate = false; + context.fail(); + } + // throw if it is another exception + throw e; + } + + // negative pass + if (this.negate) { + context.negate = true; // because .fail will set negate + context.params.details = 'false negative fail'; + context.fail(); + } + + // positive pass + if (!this.params.operator) { + this.params = context.params; // shortcut + } + this.obj = context.obj; + this.negate = false; + return this; + } + }); + + Object.defineProperty(PromisedAssertion.prototype, name, { + enumerable: true, + configurable: true, + value: function() { + var args = arguments; + this.obj = this.obj.then(function(a) { + return a[name].apply(a, args); + }); + + return this; + } + }); + }; + + /** + * Add chaining getter to Assertion like .a, .which etc + * + * @memberOf Assertion + * @static + * @param {string} name name of getter + * @param {function} [onCall] optional function to call + */ + Assertion.addChain = function(name, onCall) { + onCall = onCall || function() {}; + Object.defineProperty(Assertion.prototype, name, { + get: function() { + onCall.call(this); + return this; + }, + enumerable: true + }); + + Object.defineProperty(PromisedAssertion.prototype, name, { + enumerable: true, + configurable: true, + get: function() { + this.obj = this.obj.then(function(a) { + return a[name]; + }); + + return this; + } + }); + }; + + /** + * Create alias for some `Assertion` property + * + * @memberOf Assertion + * @static + * @param {String} from Name of to map + * @param {String} to Name of alias + * @example + * + * Assertion.alias('true', 'True') + */ + Assertion.alias = function(from, to) { + var desc = Object.getOwnPropertyDescriptor(Assertion.prototype, from); + if (!desc) { + throw new Error('Alias ' + from + ' -> ' + to + ' could not be created as ' + from + ' not defined'); + } + Object.defineProperty(Assertion.prototype, to, desc); + + var desc2 = Object.getOwnPropertyDescriptor(PromisedAssertion.prototype, from); + if (desc2) { + Object.defineProperty(PromisedAssertion.prototype, to, desc2); + } + }; + /** + * Negation modifier. Current assertion chain become negated. Each call invert negation on current assertion. + * + * @name not + * @property + * @memberOf Assertion + * @category assertion + */ + Assertion.addChain('not', function() { + this.negate = !this.negate; + }); + + /** + * Any modifier - it affect on execution of sequenced assertion to do not `check all`, but `check any of`. + * + * @name any + * @property + * @memberOf Assertion + * @category assertion + */ + Assertion.addChain('any', function() { + this.anyOne = true; + }); + + var pSlice = Array.prototype.slice; + + // 1. The assert module provides functions that throw + // AssertionError's when particular conditions are not met. The + // assert module must conform to the following interface. + + var assert = ok; + // 3. All of the following functions must throw an AssertionError + // when a corresponding condition is not met, with a message that + // may be undefined if not provided. All assertion methods provide + // both the actual and expected values to the assertion error for + // display purposes. + /** + * Node.js standard [`assert.fail`](http://nodejs.org/api/assert.html#assert_assert_fail_actual_expected_message_operator). + * @static + * @memberOf should + * @category assertion assert + * @param {*} actual Actual object + * @param {*} expected Expected object + * @param {string} message Message for assertion + * @param {string} operator Operator text + */ + function fail(actual, expected, message, operator, stackStartFunction) { + var a = new Assertion(actual); + a.params = { + operator: operator, + expected: expected, + message: message, + stackStartFunction: stackStartFunction || fail + }; + + a.fail(); + } + + // EXTENSION! allows for well behaved errors defined elsewhere. + assert.fail = fail; + + // 4. Pure assertion tests whether a value is truthy, as determined + // by !!guard. + // assert.ok(guard, message_opt); + // This statement is equivalent to assert.equal(true, !!guard, + // message_opt);. To test strictly for the value true, use + // assert.strictEqual(true, guard, message_opt);. + /** + * Node.js standard [`assert.ok`](http://nodejs.org/api/assert.html#assert_assert_value_message_assert_ok_value_message). + * @static + * @memberOf should + * @category assertion assert + * @param {*} value + * @param {string} [message] + */ + function ok(value, message) { + if (!value) { + fail(value, true, message, '==', assert.ok); + } + } + assert.ok = ok; + + // 5. The equality assertion tests shallow, coercive equality with + // ==. + // assert.equal(actual, expected, message_opt); + + /** + * Node.js standard [`assert.equal`](http://nodejs.org/api/assert.html#assert_assert_equal_actual_expected_message). + * @static + * @memberOf should + * @category assertion assert + * @param {*} actual + * @param {*} expected + * @param {string} [message] + */ + assert.equal = function equal(actual, expected, message) { + if (actual != expected) { + fail(actual, expected, message, '==', assert.equal); + } + }; + + // 6. The non-equality assertion tests for whether two objects are not equal + // with != assert.notEqual(actual, expected, message_opt); + /** + * Node.js standard [`assert.notEqual`](http://nodejs.org/api/assert.html#assert_assert_notequal_actual_expected_message). + * @static + * @memberOf should + * @category assertion assert + * @param {*} actual + * @param {*} expected + * @param {string} [message] + */ + assert.notEqual = function notEqual(actual, expected, message) { + if (actual == expected) { + fail(actual, expected, message, '!=', assert.notEqual); + } + }; + + // 7. The equivalence assertion tests a deep equality relation. + // assert.deepEqual(actual, expected, message_opt); + /** + * Node.js standard [`assert.deepEqual`](http://nodejs.org/api/assert.html#assert_assert_deepequal_actual_expected_message). + * But uses should.js .eql implementation instead of Node.js own deepEqual. + * + * @static + * @memberOf should + * @category assertion assert + * @param {*} actual + * @param {*} expected + * @param {string} [message] + */ + assert.deepEqual = function deepEqual(actual, expected, message) { + if (eq(actual, expected).length !== 0) { + fail(actual, expected, message, 'deepEqual', assert.deepEqual); + } + }; + + + // 8. The non-equivalence assertion tests for any deep inequality. + // assert.notDeepEqual(actual, expected, message_opt); + /** + * Node.js standard [`assert.notDeepEqual`](http://nodejs.org/api/assert.html#assert_assert_notdeepequal_actual_expected_message). + * But uses should.js .eql implementation instead of Node.js own deepEqual. + * + * @static + * @memberOf should + * @category assertion assert + * @param {*} actual + * @param {*} expected + * @param {string} [message] + */ + assert.notDeepEqual = function notDeepEqual(actual, expected, message) { + if (eq(actual, expected).result) { + fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); + } + }; + + // 9. The strict equality assertion tests strict equality, as determined by ===. + // assert.strictEqual(actual, expected, message_opt); + /** + * Node.js standard [`assert.strictEqual`](http://nodejs.org/api/assert.html#assert_assert_strictequal_actual_expected_message). + * @static + * @memberOf should + * @category assertion assert + * @param {*} actual + * @param {*} expected + * @param {string} [message] + */ + assert.strictEqual = function strictEqual(actual, expected, message) { + if (actual !== expected) { + fail(actual, expected, message, '===', assert.strictEqual); + } + }; + + // 10. The strict non-equality assertion tests for strict inequality, as + // determined by !==. assert.notStrictEqual(actual, expected, message_opt); + /** + * Node.js standard [`assert.notStrictEqual`](http://nodejs.org/api/assert.html#assert_assert_notstrictequal_actual_expected_message). + * @static + * @memberOf should + * @category assertion assert + * @param {*} actual + * @param {*} expected + * @param {string} [message] + */ + assert.notStrictEqual = function notStrictEqual(actual, expected, message) { + if (actual === expected) { + fail(actual, expected, message, '!==', assert.notStrictEqual); + } + }; + + function expectedException(actual, expected) { + if (!actual || !expected) { + return false; + } + + if (Object.prototype.toString.call(expected) == '[object RegExp]') { + return expected.test(actual); + } else if (actual instanceof expected) { + return true; + } else if (expected.call({}, actual) === true) { + return true; + } + + return false; + } + + function _throws(shouldThrow, block, expected, message) { + var actual; + + if (typeof expected == 'string') { + message = expected; + expected = null; + } + + try { + block(); + } catch (e) { + actual = e; + } + + message = (expected && expected.name ? ' (' + expected.name + ')' : '.') + + (message ? ' ' + message : '.'); + + if (shouldThrow && !actual) { + fail(actual, expected, 'Missing expected exception' + message); + } + + if (!shouldThrow && expectedException(actual, expected)) { + fail(actual, expected, 'Got unwanted exception' + message); + } + + if ((shouldThrow && actual && expected && !expectedException(actual, expected)) || (!shouldThrow && actual)) { + throw actual; + } + } + + // 11. Expected to throw an error: + // assert.throws(block, Error_opt, message_opt); + /** + * Node.js standard [`assert.throws`](http://nodejs.org/api/assert.html#assert_assert_throws_block_error_message). + * @static + * @memberOf should + * @category assertion assert + * @param {Function} block + * @param {Function} [error] + * @param {String} [message] + */ + assert.throws = function(/*block, error, message*/) { + _throws.apply(this, [true].concat(pSlice.call(arguments))); + }; + + // EXTENSION! This is annoying to write outside this module. + /** + * Node.js standard [`assert.doesNotThrow`](http://nodejs.org/api/assert.html#assert_assert_doesnotthrow_block_message). + * @static + * @memberOf should + * @category assertion assert + * @param {Function} block + * @param {String} [message] + */ + assert.doesNotThrow = function(/*block, message*/) { + _throws.apply(this, [false].concat(pSlice.call(arguments))); + }; + + /** + * Node.js standard [`assert.ifError`](http://nodejs.org/api/assert.html#assert_assert_iferror_value). + * @static + * @memberOf should + * @category assertion assert + * @param {Error} err + */ + assert.ifError = function(err) { + if (err) { + throw err; + } + }; + + function assertExtensions(should) { + var i = should.format; + + /* + * Expose assert to should + * + * This allows you to do things like below + * without require()ing the assert module. + * + * should.equal(foo.bar, undefined); + * + */ + merge(should, assert); + + /** + * Assert _obj_ exists, with optional message. + * + * @static + * @memberOf should + * @category assertion assert + * @alias should.exists + * @param {*} obj + * @param {String} [msg] + * @example + * + * should.exist(1); + * should.exist(new Date()); + */ + should.exist = should.exists = function(obj, msg) { + if (null == obj) { + throw new AssertionError({ + message: msg || ('expected ' + i(obj) + ' to exist'), stackStartFunction: should.exist + }); + } + }; + + should.not = {}; + /** + * Asserts _obj_ does not exist, with optional message. + * + * @name not.exist + * @static + * @memberOf should + * @category assertion assert + * @alias should.not.exists + * @param {*} obj + * @param {String} [msg] + * @example + * + * should.not.exist(null); + * should.not.exist(void 0); + */ + should.not.exist = should.not.exists = function(obj, msg) { + if (null != obj) { + throw new AssertionError({ + message: msg || ('expected ' + i(obj) + ' to not exist'), stackStartFunction: should.not.exist + }); + } + }; + } + + /* + * should.js - assertion library + * Copyright(c) 2010-2013 TJ Holowaychuk + * Copyright(c) 2013-2016 Denis Bardadym + * MIT Licensed + */ + + function chainAssertions(should, Assertion) { + /** + * Simple chaining. It actually do nothing. + * + * @memberOf Assertion + * @name be + * @property {should.Assertion} be + * @alias Assertion#an + * @alias Assertion#of + * @alias Assertion#a + * @alias Assertion#and + * @alias Assertion#have + * @alias Assertion#has + * @alias Assertion#with + * @alias Assertion#is + * @alias Assertion#which + * @alias Assertion#the + * @alias Assertion#it + * @category assertion chaining + */ + ['an', 'of', 'a', 'and', 'be', 'has', 'have', 'with', 'is', 'which', 'the', 'it'].forEach(function(name) { + Assertion.addChain(name); + }); + } + + /* + * should.js - assertion library + * Copyright(c) 2010-2013 TJ Holowaychuk + * Copyright(c) 2013-2016 Denis Bardadym + * MIT Licensed + */ + + function booleanAssertions(should, Assertion) { + /** + * Assert given object is exactly `true`. + * + * @name true + * @memberOf Assertion + * @category assertion bool + * @alias Assertion#True + * @param {string} [message] Optional message + * @example + * + * (true).should.be.true(); + * false.should.not.be.true(); + * + * ({ a: 10}).should.not.be.true(); + */ + Assertion.add('true', function(message) { + this.is.exactly(true, message); + }); + + Assertion.alias('true', 'True'); + + /** + * Assert given object is exactly `false`. + * + * @name false + * @memberOf Assertion + * @category assertion bool + * @alias Assertion#False + * @param {string} [message] Optional message + * @example + * + * (true).should.not.be.false(); + * false.should.be.false(); + */ + Assertion.add('false', function(message) { + this.is.exactly(false, message); + }); + + Assertion.alias('false', 'False'); + + /** + * Assert given object is truthy according javascript type conversions. + * + * @name ok + * @memberOf Assertion + * @category assertion bool + * @example + * + * (true).should.be.ok(); + * ''.should.not.be.ok(); + * should(null).not.be.ok(); + * should(void 0).not.be.ok(); + * + * (10).should.be.ok(); + * (0).should.not.be.ok(); + */ + Assertion.add('ok', function() { + this.params = { operator: 'to be truthy' }; + + this.assert(this.obj); + }); + } + + /* + * should.js - assertion library + * Copyright(c) 2010-2013 TJ Holowaychuk + * Copyright(c) 2013-2016 Denis Bardadym + * MIT Licensed + */ + + function numberAssertions(should, Assertion) { + + /** + * Assert given object is NaN + * @name NaN + * @memberOf Assertion + * @category assertion numbers + * @example + * + * (10).should.not.be.NaN(); + * NaN.should.be.NaN(); + */ + Assertion.add('NaN', function() { + this.params = { operator: 'to be NaN' }; + + this.assert(this.obj !== this.obj); + }); + + /** + * Assert given object is not finite (positive or negative) + * + * @name Infinity + * @memberOf Assertion + * @category assertion numbers + * @example + * + * (10).should.not.be.Infinity(); + * NaN.should.not.be.Infinity(); + */ + Assertion.add('Infinity', function() { + this.params = { operator: 'to be Infinity' }; + + this.is.a.Number() + .and.not.a.NaN() + .and.assert(!isFinite(this.obj)); + }); + + /** + * Assert given number between `start` and `finish` or equal one of them. + * + * @name within + * @memberOf Assertion + * @category assertion numbers + * @param {number} start Start number + * @param {number} finish Finish number + * @param {string} [description] Optional message + * @example + * + * (10).should.be.within(0, 20); + */ + Assertion.add('within', function(start, finish, description) { + this.params = { operator: 'to be within ' + start + '..' + finish, message: description }; + + this.assert(this.obj >= start && this.obj <= finish); + }); + + /** + * Assert given number near some other `value` within `delta` + * + * @name approximately + * @memberOf Assertion + * @category assertion numbers + * @param {number} value Center number + * @param {number} delta Radius + * @param {string} [description] Optional message + * @example + * + * (9.99).should.be.approximately(10, 0.1); + */ + Assertion.add('approximately', function(value, delta, description) { + this.params = { operator: 'to be approximately ' + value + ' ±' + delta, message: description }; + + this.assert(Math.abs(this.obj - value) <= delta); + }); + + /** + * Assert given number above `n`. + * + * @name above + * @alias Assertion#greaterThan + * @memberOf Assertion + * @category assertion numbers + * @param {number} n Margin number + * @param {string} [description] Optional message + * @example + * + * (10).should.be.above(0); + */ + Assertion.add('above', function(n, description) { + this.params = { operator: 'to be above ' + n, message: description }; + + this.assert(this.obj > n); + }); + + /** + * Assert given number below `n`. + * + * @name below + * @alias Assertion#lessThan + * @memberOf Assertion + * @category assertion numbers + * @param {number} n Margin number + * @param {string} [description] Optional message + * @example + * + * (0).should.be.below(10); + */ + Assertion.add('below', function(n, description) { + this.params = { operator: 'to be below ' + n, message: description }; + + this.assert(this.obj < n); + }); + + Assertion.alias('above', 'greaterThan'); + Assertion.alias('below', 'lessThan'); + + /** + * Assert given number above `n`. + * + * @name aboveOrEqual + * @alias Assertion#greaterThanOrEqual + * @memberOf Assertion + * @category assertion numbers + * @param {number} n Margin number + * @param {string} [description] Optional message + * @example + * + * (10).should.be.aboveOrEqual(0); + * (10).should.be.aboveOrEqual(10); + */ + Assertion.add('aboveOrEqual', function(n, description) { + this.params = { operator: 'to be above or equal' + n, message: description }; + + this.assert(this.obj >= n); + }); + + /** + * Assert given number below `n`. + * + * @name belowOrEqual + * @alias Assertion#lessThanOrEqual + * @memberOf Assertion + * @category assertion numbers + * @param {number} n Margin number + * @param {string} [description] Optional message + * @example + * + * (0).should.be.belowOrEqual(10); + * (0).should.be.belowOrEqual(0); + */ + Assertion.add('belowOrEqual', function(n, description) { + this.params = { operator: 'to be below or equal' + n, message: description }; + + this.assert(this.obj <= n); + }); + + Assertion.alias('aboveOrEqual', 'greaterThanOrEqual'); + Assertion.alias('belowOrEqual', 'lessThanOrEqual'); + + } + + function typeAssertions(should, Assertion) { + /** + * Assert given object is number + * @name Number + * @memberOf Assertion + * @category assertion types + */ + Assertion.add('Number', function() { + this.params = {operator: 'to be a number'}; + + this.have.type('number'); + }); + + /** + * Assert given object is arguments + * @name arguments + * @alias Assertion#Arguments + * @memberOf Assertion + * @category assertion types + */ + Assertion.add('arguments', function() { + this.params = {operator: 'to be arguments'}; + + this.have.class('Arguments'); + }); + + Assertion.alias('arguments', 'Arguments'); + + /** + * Assert given object has some type using `typeof` + * @name type + * @memberOf Assertion + * @param {string} type Type name + * @param {string} [description] Optional message + * @category assertion types + */ + Assertion.add('type', function(type, description) { + this.params = {operator: 'to have type ' + type, message: description}; + + should(typeof this.obj).be.exactly(type); + }); + + /** + * Assert given object is instance of `constructor` + * @name instanceof + * @alias Assertion#instanceOf + * @memberOf Assertion + * @param {Function} constructor Constructor function + * @param {string} [description] Optional message + * @category assertion types + */ + Assertion.add('instanceof', function(constructor, description) { + this.params = {operator: 'to be an instance of ' + functionName(constructor), message: description}; + + this.assert(Object(this.obj) instanceof constructor); + }); + + Assertion.alias('instanceof', 'instanceOf'); + + /** + * Assert given object is function + * @name Function + * @memberOf Assertion + * @category assertion types + */ + Assertion.add('Function', function() { + this.params = {operator: 'to be a function'}; + + this.have.type('function'); + }); + + /** + * Assert given object is object + * @name Object + * @memberOf Assertion + * @category assertion types + */ + Assertion.add('Object', function() { + this.params = {operator: 'to be an object'}; + + this.is.not.null().and.have.type('object'); + }); + + /** + * Assert given object is string + * @name String + * @memberOf Assertion + * @category assertion types + */ + Assertion.add('String', function() { + this.params = {operator: 'to be a string'}; + + this.have.type('string'); + }); + + /** + * Assert given object is array + * @name Array + * @memberOf Assertion + * @category assertion types + */ + Assertion.add('Array', function() { + this.params = {operator: 'to be an array'}; + + this.have.class('Array'); + }); + + /** + * Assert given object is boolean + * @name Boolean + * @memberOf Assertion + * @category assertion types + */ + Assertion.add('Boolean', function() { + this.params = {operator: 'to be a boolean'}; + + this.have.type('boolean'); + }); + + /** + * Assert given object is error + * @name Error + * @memberOf Assertion + * @category assertion types + */ + Assertion.add('Error', function() { + this.params = {operator: 'to be an error'}; + + this.have.instanceOf(Error); + }); + + /** + * Assert given object is a date + * @name Date + * @memberOf Assertion + * @category assertion types + */ + Assertion.add('Date', function() { + this.params = {operator: 'to be a date'}; + + this.have.instanceOf(Date); + }); + + /** + * Assert given object is null + * @name null + * @alias Assertion#Null + * @memberOf Assertion + * @category assertion types + */ + Assertion.add('null', function() { + this.params = {operator: 'to be null'}; + + this.assert(this.obj === null); + }); + + Assertion.alias('null', 'Null'); + + /** + * Assert given object has some internal [[Class]], via Object.prototype.toString call + * @name class + * @alias Assertion#Class + * @memberOf Assertion + * @category assertion types + */ + Assertion.add('class', function(cls) { + this.params = {operator: 'to have [[Class]] ' + cls}; + + this.assert(Object.prototype.toString.call(this.obj) === '[object ' + cls + ']'); + }); + + Assertion.alias('class', 'Class'); + + /** + * Assert given object is undefined + * @name undefined + * @alias Assertion#Undefined + * @memberOf Assertion + * @category assertion types + */ + Assertion.add('undefined', function() { + this.params = {operator: 'to be undefined'}; + + this.assert(this.obj === void 0); + }); + + Assertion.alias('undefined', 'Undefined'); + + /** + * Assert given object supports es6 iterable protocol (just check + * that object has property Symbol.iterator, which is a function) + * @name iterable + * @memberOf Assertion + * @category assertion es6 + */ + Assertion.add('iterable', function() { + this.params = {operator: 'to be iterable'}; + + should(this.obj).have.property(Symbol.iterator).which.is.a.Function(); + }); + + /** + * Assert given object supports es6 iterator protocol (just check + * that object has property next, which is a function) + * @name iterator + * @memberOf Assertion + * @category assertion es6 + */ + Assertion.add('iterator', function() { + this.params = {operator: 'to be iterator'}; + + should(this.obj).have.property('next').which.is.a.Function(); + }); + + /** + * Assert given object is a generator object + * @name generator + * @memberOf Assertion + * @category assertion es6 + */ + Assertion.add('generator', function() { + this.params = {operator: 'to be generator'}; + + should(this.obj).be.iterable + .and.iterator + .and.it.is.equal(this.obj[Symbol.iterator]()); + }); + } + + function formatEqlResult(r, a, b) { + return ((r.path.length > 0 ? 'at ' + r.path.map(formatProp).join(' -> ') : '') + + (r.a === a ? '' : ', A has ' + format(r.a)) + + (r.b === b ? '' : ' and B has ' + format(r.b)) + + (r.showReason ? ' because ' + r.reason : '')).trim(); + } + + function equalityAssertions(should, Assertion) { + + + /** + * Deep object equality comparison. For full spec see [`should-equal tests`](https://github.com/shouldjs/equal/blob/master/test.js). + * + * @name eql + * @memberOf Assertion + * @category assertion equality + * @alias Assertion#deepEqual + * @param {*} val Expected value + * @param {string} [description] Optional message + * @example + * + * (10).should.be.eql(10); + * ('10').should.not.be.eql(10); + * (-0).should.not.be.eql(+0); + * + * NaN.should.be.eql(NaN); + * + * ({ a: 10}).should.be.eql({ a: 10 }); + * [ 'a' ].should.not.be.eql({ '0': 'a' }); + */ + Assertion.add('eql', function(val, description) { + this.params = {operator: 'to equal', expected: val, message: description}; + var obj = this.obj; + var fails = eq(this.obj, val, should.config); + this.params.details = fails.map(function(fail) { + return formatEqlResult(fail, obj, val); + }).join(', '); + + this.params.showDiff = eq(getGlobalType(obj), getGlobalType(val)).length === 0; + + this.assert(fails.length === 0); + }); + + /** + * Exact comparison using ===. + * + * @name equal + * @memberOf Assertion + * @category assertion equality + * @alias Assertion#exactly + * @param {*} val Expected value + * @param {string} [description] Optional message + * @example + * + * 10.should.be.equal(10); + * 'a'.should.be.exactly('a'); + * + * should(null).be.exactly(null); + */ + Assertion.add('equal', function(val, description) { + this.params = {operator: 'to be', expected: val, message: description}; + + this.params.showDiff = eq(getGlobalType(this.obj), getGlobalType(val)).length === 0; + + this.assert(val === this.obj); + }); + + Assertion.alias('equal', 'exactly'); + Assertion.alias('eql', 'deepEqual'); + + function addOneOf(name, message, method) { + Assertion.add(name, function(vals) { + if (arguments.length !== 1) { + vals = Array.prototype.slice.call(arguments); + } else { + should(vals).be.Array(); + } + + this.params = {operator: message, expected: vals}; + + var obj = this.obj; + var found = false; + + forEach(vals, function(val) { + try { + should(val)[method](obj); + found = true; + return false; + } catch (e) { + if (e instanceof should.AssertionError) { + return;//do nothing + } + throw e; + } + }); + + this.assert(found); + }); + } + + /** + * Exact comparison using === to be one of supplied objects. + * + * @name equalOneOf + * @memberOf Assertion + * @category assertion equality + * @param {Array|*} vals Expected values + * @example + * + * 'ab'.should.be.equalOneOf('a', 10, 'ab'); + * 'ab'.should.be.equalOneOf(['a', 10, 'ab']); + */ + addOneOf('equalOneOf', 'to be equals one of', 'equal'); + + /** + * Exact comparison using .eql to be one of supplied objects. + * + * @name oneOf + * @memberOf Assertion + * @category assertion equality + * @param {Array|*} vals Expected values + * @example + * + * ({a: 10}).should.be.oneOf('a', 10, 'ab', {a: 10}); + * ({a: 10}).should.be.oneOf(['a', 10, 'ab', {a: 10}]); + */ + addOneOf('oneOf', 'to be one of', 'eql'); + + } + + function promiseAssertions(should, Assertion) { + /** + * Assert given object is a Promise + * + * @name Promise + * @memberOf Assertion + * @category assertion promises + * @example + * + * promise.should.be.Promise() + * (new Promise(function(resolve, reject) { resolve(10); })).should.be.a.Promise() + * (10).should.not.be.a.Promise() + */ + Assertion.add('Promise', function() { + this.params = {operator: 'to be promise'}; + + var obj = this.obj; + + should(obj).have.property('then') + .which.is.a.Function(); + }); + + /** + * Assert given promise will be fulfilled. Result of assertion is still .thenable and should be handled accordingly. + * + * @name fulfilled + * @memberOf Assertion + * @returns {Promise} + * @category assertion promises + * @example + * + * // don't forget to handle async nature + * (new Promise(function(resolve, reject) { resolve(10); })).should.be.fulfilled(); + * + * // test example with mocha it is possible to return promise + * it('is async', () => { + * return new Promise(resolve => resolve(10)) + * .should.be.fulfilled(); + * }); + */ + Assertion.prototype.fulfilled = function Assertion$fulfilled() { + this.params = {operator: 'to be fulfilled'}; + + should(this.obj).be.a.Promise(); + + var that = this; + return this.obj.then(function next$onResolve(value) { + if (that.negate) { + that.fail(); + } + return value; + }, function next$onReject(err) { + if (!that.negate) { + that.params.operator += ', but it was rejected with ' + should.format(err); + that.fail(); + } + return err; + }); + }; + + /** + * Assert given promise will be rejected. Result of assertion is still .thenable and should be handled accordingly. + * + * @name rejected + * @memberOf Assertion + * @category assertion promises + * @returns {Promise} + * @example + * + * // don't forget to handle async nature + * (new Promise(function(resolve, reject) { resolve(10); })) + * .should.not.be.rejected(); + * + * // test example with mocha it is possible to return promise + * it('is async', () => { + * return new Promise((resolve, reject) => reject(new Error('boom'))) + * .should.be.rejected(); + * }); + */ + Assertion.prototype.rejected = function() { + this.params = {operator: 'to be rejected'}; + + should(this.obj).be.a.Promise(); + + var that = this; + return this.obj.then(function(value) { + if (!that.negate) { + that.params.operator += ', but it was fulfilled'; + if (arguments.length != 0) { + that.params.operator += ' with ' + should.format(value); + } + that.fail(); + } + return value; + }, function next$onError(err) { + if (that.negate) { + that.fail(); + } + return err; + }); + }; + + /** + * Assert given promise will be fulfilled with some expected value (value compared using .eql). + * Result of assertion is still .thenable and should be handled accordingly. + * + * @name fulfilledWith + * @memberOf Assertion + * @category assertion promises + * @returns {Promise} + * @example + * + * // don't forget to handle async nature + * (new Promise(function(resolve, reject) { resolve(10); })) + * .should.be.fulfilledWith(10); + * + * // test example with mocha it is possible to return promise + * it('is async', () => { + * return new Promise((resolve, reject) => resolve(10)) + * .should.be.fulfilledWith(10); + * }); + */ + Assertion.prototype.fulfilledWith = function(expectedValue) { + this.params = {operator: 'to be fulfilled with ' + should.format(expectedValue)}; + + should(this.obj).be.a.Promise(); + + var that = this; + return this.obj.then(function(value) { + if (that.negate) { + that.fail(); + } + should(value).eql(expectedValue); + return value; + }, function next$onError(err) { + if (!that.negate) { + that.params.operator += ', but it was rejected with ' + should.format(err); + that.fail(); + } + return err; + }); + }; + + /** + * Assert given promise will be rejected with some sort of error. Arguments is the same for Assertion#throw. + * Result of assertion is still .thenable and should be handled accordingly. + * + * @name rejectedWith + * @memberOf Assertion + * @category assertion promises + * @returns {Promise} + * @example + * + * function failedPromise() { + * return new Promise(function(resolve, reject) { + * reject(new Error('boom')) + * }) + * } + * failedPromise().should.be.rejectedWith(Error); + * failedPromise().should.be.rejectedWith('boom'); + * failedPromise().should.be.rejectedWith(/boom/); + * failedPromise().should.be.rejectedWith(Error, { message: 'boom' }); + * failedPromise().should.be.rejectedWith({ message: 'boom' }); + * + * // test example with mocha it is possible to return promise + * it('is async', () => { + * return failedPromise().should.be.rejectedWith({ message: 'boom' }); + * }); + */ + Assertion.prototype.rejectedWith = function(message, properties) { + this.params = {operator: 'to be rejected'}; + + should(this.obj).be.a.Promise(); + + var that = this; + return this.obj.then(function(value) { + if (!that.negate) { + that.fail(); + } + return value; + }, function next$onError(err) { + if (that.negate) { + that.fail(); + } + + var errorMatched = true; + var errorInfo = ''; + + if ('string' === typeof message) { + errorMatched = message === err.message; + } else if (message instanceof RegExp) { + errorMatched = message.test(err.message); + } else if ('function' === typeof message) { + errorMatched = err instanceof message; + } else if (message !== null && typeof message === 'object') { + try { + should(err).match(message); + } catch (e) { + if (e instanceof should.AssertionError) { + errorInfo = ': ' + e.message; + errorMatched = false; + } else { + throw e; + } + } + } + + if (!errorMatched) { + if ( typeof message === 'string' || message instanceof RegExp) { + errorInfo = ' with a message matching ' + should.format(message) + ", but got '" + err.message + "'"; + } else if ('function' === typeof message) { + errorInfo = ' of type ' + functionName(message) + ', but got ' + functionName(err.constructor); + } + } else if ('function' === typeof message && properties) { + try { + should(err).match(properties); + } catch (e) { + if (e instanceof should.AssertionError) { + errorInfo = ': ' + e.message; + errorMatched = false; + } else { + throw e; + } + } + } + + that.params.operator += errorInfo; + + that.assert(errorMatched); + + return err; + }); + }; + + /** + * Assert given object is promise and wrap it in PromisedAssertion, which has all properties of Assertion. + * That means you can chain as with usual Assertion. + * Result of assertion is still .thenable and should be handled accordingly. + * + * @name finally + * @memberOf Assertion + * @alias Assertion#eventually + * @category assertion promises + * @returns {PromisedAssertion} Like Assertion, but .then this.obj in Assertion + * @example + * + * (new Promise(function(resolve, reject) { resolve(10); })) + * .should.be.eventually.equal(10); + * + * // test example with mocha it is possible to return promise + * it('is async', () => { + * return new Promise(resolve => resolve(10)) + * .should.be.finally.equal(10); + * }); + */ + Object.defineProperty(Assertion.prototype, 'finally', { + get: function() { + should(this.obj).be.a.Promise(); + + var that = this; + + return new PromisedAssertion(this.obj.then(function(obj) { + var a = should(obj); + + a.negate = that.negate; + a.anyOne = that.anyOne; + + return a; + })); + } + }); + + Assertion.alias('finally', 'eventually'); + } + + /* + * should.js - assertion library + * Copyright(c) 2010-2013 TJ Holowaychuk + * Copyright(c) 2013-2016 Denis Bardadym + * MIT Licensed + */ + + function stringAssertions(should, Assertion) { + /** + * Assert given string starts with prefix + * @name startWith + * @memberOf Assertion + * @category assertion strings + * @param {string} str Prefix + * @param {string} [description] Optional message + * @example + * + * 'abc'.should.startWith('a'); + */ + Assertion.add('startWith', function(str, description) { + this.params = { operator: 'to start with ' + should.format(str), message: description }; + + this.assert(0 === this.obj.indexOf(str)); + }); + + /** + * Assert given string ends with prefix + * @name endWith + * @memberOf Assertion + * @category assertion strings + * @param {string} str Prefix + * @param {string} [description] Optional message + * @example + * + * 'abca'.should.endWith('a'); + */ + Assertion.add('endWith', function(str, description) { + this.params = { operator: 'to end with ' + should.format(str), message: description }; + + this.assert(this.obj.indexOf(str, this.obj.length - str.length) >= 0); + }); + } + + function containAssertions(should, Assertion) { + var i = should.format; + + /** + * Assert that given object contain something that equal to `other`. It uses `should-equal` for equality checks. + * If given object is array it search that one of elements was equal to `other`. + * If given object is string it checks if `other` is a substring - expected that `other` is a string. + * If given object is Object it checks that `other` is a subobject - expected that `other` is a object. + * + * @name containEql + * @memberOf Assertion + * @category assertion contain + * @param {*} other Nested object + * @example + * + * [1, 2, 3].should.containEql(1); + * [{ a: 1 }, 'a', 10].should.containEql({ a: 1 }); + * + * 'abc'.should.containEql('b'); + * 'ab1c'.should.containEql(1); + * + * ({ a: 10, c: { d: 10 }}).should.containEql({ a: 10 }); + * ({ a: 10, c: { d: 10 }}).should.containEql({ c: { d: 10 }}); + * ({ a: 10, c: { d: 10 }}).should.containEql({ b: 10 }); + * // throws AssertionError: expected { a: 10, c: { d: 10 } } to contain { b: 10 } + * // expected { a: 10, c: { d: 10 } } to have property b + */ + Assertion.add('containEql', function(other) { + this.params = { operator: 'to contain ' + i(other) }; + + this.is.not.null().and.not.undefined(); + + var obj = this.obj; + + if (typeof obj == 'string') { + this.assert(obj.indexOf(String(other)) >= 0); + } else if (isIterable(obj)) { + this.assert(some(obj, function(v) { + return eq(v, other).length === 0; + })); + } else { + forEach(other, function(value, key) { + should(obj).have.value(key, value); + }, this); + } + }); + + /** + * Assert that given object is contain equally structured object on the same depth level. + * If given object is an array and `other` is an array it checks that the eql elements is going in the same sequence in given array (recursive) + * If given object is an object it checks that the same keys contain deep equal values (recursive) + * On other cases it try to check with `.eql` + * + * @name containDeepOrdered + * @memberOf Assertion + * @category assertion contain + * @param {*} other Nested object + * @example + * + * [ 1, 2, 3].should.containDeepOrdered([1, 2]); + * [ 1, 2, [ 1, 2, 3 ]].should.containDeepOrdered([ 1, [ 2, 3 ]]); + * + * ({ a: 10, b: { c: 10, d: [1, 2, 3] }}).should.containDeepOrdered({a: 10}); + * ({ a: 10, b: { c: 10, d: [1, 2, 3] }}).should.containDeepOrdered({b: {c: 10}}); + * ({ a: 10, b: { c: 10, d: [1, 2, 3] }}).should.containDeepOrdered({b: {d: [1, 3]}}); + */ + Assertion.add('containDeepOrdered', function(other) { + this.params = {operator: 'to contain ' + i(other)}; + + var obj = this.obj; + if (typeof obj == 'string') {// expect other to be string + this.is.equal(String(other)); + } else if (isIterable(obj) && isIterable(other)) { + var objIterator = iterator(obj); + var otherIterator = iterator(other); + + var nextObj = objIterator.next(); + var nextOther = otherIterator.next(); + while (!nextObj.done && !nextOther.done) { + try { + should(nextObj.value[1]).containDeepOrdered(nextOther.value[1]); + nextOther = otherIterator.next(); + } catch (e) { + if (!(e instanceof should.AssertionError)) { + throw e; + } + } + nextObj = objIterator.next(); + } + + this.assert(nextOther.done); + } else if (obj != null && other != null && typeof obj == 'object' && typeof other == 'object') {//TODO compare types object contains object case + forEach(other, function(value, key) { + should(obj[key]).containDeepOrdered(value); + }); + + // if both objects is empty means we finish traversing - and we need to compare for hidden values + if (isEmpty(other)) { + this.eql(other); + } + } else { + this.eql(other); + } + }); + + /** + * The same like `Assertion#containDeepOrdered` but all checks on arrays without order. + * + * @name containDeep + * @memberOf Assertion + * @category assertion contain + * @param {*} other Nested object + * @example + * + * [ 1, 2, 3].should.containDeep([2, 1]); + * [ 1, 2, [ 1, 2, 3 ]].should.containDeep([ 1, [ 3, 1 ]]); + */ + Assertion.add('containDeep', function(other) { + this.params = {operator: 'to contain ' + i(other)}; + + var obj = this.obj; + if (typeof obj == 'string') {// expect other to be string + this.is.equal(String(other)); + } else if (isIterable(obj) && isIterable(other)) { + var usedKeys = {}; + forEach(other, function(otherItem) { + this.assert(some(obj, function(item, index) { + if (index in usedKeys) { + return false; + } + + try { + should(item).containDeep(otherItem); + usedKeys[index] = true; + return true; + } catch (e) { + if (e instanceof should.AssertionError) { + return false; + } + throw e; + } + })); + }, this); + } else if (obj != null && other != null && typeof obj == 'object' && typeof other == 'object') {// object contains object case + forEach(other, function(value, key) { + should(obj[key]).containDeep(value); + }); + + // if both objects is empty means we finish traversing - and we need to compare for hidden values + if (isEmpty(other)) { + this.eql(other); + } + } else { + this.eql(other); + } + }); + + } + + var aSlice = Array.prototype.slice; + + function propertyAssertions(should, Assertion) { + var i = should.format; + /** + * Asserts given object has some descriptor. **On success it change given object to be value of property**. + * + * @name propertyWithDescriptor + * @memberOf Assertion + * @category assertion property + * @param {string} name Name of property + * @param {Object} desc Descriptor like used in Object.defineProperty (not required to add all properties) + * @example + * + * ({ a: 10 }).should.have.propertyWithDescriptor('a', { enumerable: true }); + */ + Assertion.add('propertyWithDescriptor', function(name, desc) { + this.params = {actual: this.obj, operator: 'to have own property with descriptor ' + i(desc)}; + var obj = this.obj; + this.have.ownProperty(name); + should(Object.getOwnPropertyDescriptor(Object(obj), name)).have.properties(desc); + }); + + function processPropsArgs() { + var args = {}; + if (arguments.length > 1) { + args.names = aSlice.call(arguments); + } else { + var arg = arguments[0]; + if (typeof arg === 'string') { + args.names = [arg]; + } else if (Array.isArray(arg)) { + args.names = arg; + } else { + args.names = Object.keys(arg); + args.values = arg; + } + } + return args; + } + + + /** + * Asserts given object has enumerable property with optionally value. **On success it change given object to be value of property**. + * + * @name enumerable + * @memberOf Assertion + * @category assertion property + * @param {string} name Name of property + * @param {*} [val] Optional property value to check + * @example + * + * ({ a: 10 }).should.have.enumerable('a'); + */ + Assertion.add('enumerable', function(name, val) { + name = convertPropertyName(name); + + this.params = { + operator: "to have enumerable property " + formatProp(name) + (arguments.length > 1 ? " equal to " + i(val): "") + }; + + var desc = { enumerable: true }; + if (arguments.length > 1) { + desc.value = val; + } + this.have.propertyWithDescriptor(name, desc); + }); + + /** + * Asserts given object has enumerable properties + * + * @name enumerables + * @memberOf Assertion + * @category assertion property + * @param {Array|...string|Object} names Names of property + * @example + * + * ({ a: 10, b: 10 }).should.have.enumerables('a'); + */ + Assertion.add('enumerables', function(/*names*/) { + var args = processPropsArgs.apply(null, arguments); + + this.params = { + operator: "to have enumerables " + args.names.map(formatProp) + }; + + var obj = this.obj; + args.names.forEach(function(name) { + should(obj).have.enumerable(name); + }); + }); + + /** + * Asserts given object has property with optionally value. **On success it change given object to be value of property**. + * + * @name property + * @memberOf Assertion + * @category assertion property + * @param {string} name Name of property + * @param {*} [val] Optional property value to check + * @example + * + * ({ a: 10 }).should.have.property('a'); + */ + Assertion.add('property', function(name, val) { + name = convertPropertyName(name); + if (arguments.length > 1) { + var p = {}; + p[name] = val; + this.have.properties(p); + } else { + this.have.properties(name); + } + this.obj = this.obj[name]; + }); + + /** + * Asserts given object has properties. On this method affect .any modifier, which allow to check not all properties. + * + * @name properties + * @memberOf Assertion + * @category assertion property + * @param {Array|...string|Object} names Names of property + * @example + * + * ({ a: 10 }).should.have.properties('a'); + * ({ a: 10, b: 20 }).should.have.properties([ 'a' ]); + * ({ a: 10, b: 20 }).should.have.properties({ b: 20 }); + */ + Assertion.add('properties', function(names) { + var values = {}; + if (arguments.length > 1) { + names = aSlice.call(arguments); + } else if (!Array.isArray(names)) { + if (typeof names == 'string' || typeof names == 'symbol') { + names = [names]; + } else { + values = names; + names = Object.keys(names); + } + } + + var obj = Object(this.obj), missingProperties = []; + + //just enumerate properties and check if they all present + names.forEach(function(name) { + if (!(name in obj)) { + missingProperties.push(formatProp(name)); + } + }); + + var props = missingProperties; + if (props.length === 0) { + props = names.map(formatProp); + } else if (this.anyOne) { + props = names.filter(function(name) { + return missingProperties.indexOf(formatProp(name)) < 0; + }).map(formatProp); + } + + var operator = (props.length === 1 ? + 'to have property ' : 'to have ' + (this.anyOne ? 'any of ' : '') + 'properties ') + props.join(', '); + + this.params = {obj: this.obj, operator: operator}; + + //check that all properties presented + //or if we request one of them that at least one them presented + this.assert(missingProperties.length === 0 || (this.anyOne && missingProperties.length != names.length)); + + // check if values in object matched expected + var valueCheckNames = Object.keys(values); + if (valueCheckNames.length) { + var wrongValues = []; + props = []; + + // now check values, as there we have all properties + valueCheckNames.forEach(function(name) { + var value = values[name]; + if (eq(obj[name], value).length !== 0) { + wrongValues.push(formatProp(name) + ' of ' + i(value) + ' (got ' + i(obj[name]) + ')'); + } else { + props.push(formatProp(name) + ' of ' + i(value)); + } + }); + + if ((wrongValues.length !== 0 && !this.anyOne) || (this.anyOne && props.length === 0)) { + props = wrongValues; + } + + operator = (props.length === 1 ? + 'to have property ' : 'to have ' + (this.anyOne ? 'any of ' : '') + 'properties ') + props.join(', '); + + this.params = {obj: this.obj, operator: operator}; + + //if there is no not matched values + //or there is at least one matched + this.assert(wrongValues.length === 0 || (this.anyOne && wrongValues.length != valueCheckNames.length)); + } + }); + + /** + * Asserts given object has property `length` with given value `n` + * + * @name length + * @alias Assertion#lengthOf + * @memberOf Assertion + * @category assertion property + * @param {number} n Expected length + * @param {string} [description] Optional message + * @example + * + * [1, 2].should.have.length(2); + */ + Assertion.add('length', function(n, description) { + this.have.property('length', n, description); + }); + + Assertion.alias('length', 'lengthOf'); + + /** + * Asserts given object has own property. **On success it change given object to be value of property**. + * + * @name ownProperty + * @alias Assertion#hasOwnProperty + * @memberOf Assertion + * @category assertion property + * @param {string} name Name of property + * @param {string} [description] Optional message + * @example + * + * ({ a: 10 }).should.have.ownProperty('a'); + */ + Assertion.add('ownProperty', function(name, description) { + name = convertPropertyName(name); + this.params = { + actual: this.obj, + operator: 'to have own property ' + formatProp(name), + message: description + }; + + this.assert(hasOwnProperty$1(this.obj, name)); + + this.obj = this.obj[name]; + }); + + Assertion.alias('ownProperty', 'hasOwnProperty'); + + /** + * Asserts given object is empty. For strings, arrays and arguments it checks .length property, for objects it checks keys. + * + * @name empty + * @memberOf Assertion + * @category assertion property + * @example + * + * ''.should.be.empty(); + * [].should.be.empty(); + * ({}).should.be.empty(); + */ + Assertion.add('empty', function() { + this.params = {operator: 'to be empty'}; + this.assert(isEmpty(this.obj)); + }, true); + + /** + * Asserts given object has such keys. Compared to `properties`, `keys` does not accept Object as a argument. + * When calling via .key current object in assertion changed to value of this key + * + * @name keys + * @alias Assertion#key + * @memberOf Assertion + * @category assertion property + * @param {...*} keys Keys to check + * @example + * + * ({ a: 10 }).should.have.keys('a'); + * ({ a: 10, b: 20 }).should.have.keys('a', 'b'); + * (new Map([[1, 2]])).should.have.key(1); + */ + Assertion.add('keys', function(keys) { + keys = aSlice.call(arguments); + + var obj = Object(this.obj); + + // first check if some keys are missing + var missingKeys = keys.filter(function(key) { + return !has(obj, key); + }); + + var verb = 'to have ' + (keys.length === 1 ? 'key ' : 'keys '); + + this.params = {operator: verb + keys.join(', ')}; + + if (missingKeys.length > 0) { + this.params.operator += '\n\tmissing keys: ' + missingKeys.join(', '); + } + + this.assert(missingKeys.length === 0); + }); + + + Assertion.add('key', function(key) { + this.have.keys(key); + this.obj = get(this.obj, key); + }); + + /** + * Asserts given object has such value for given key + * + * @name value + * @memberOf Assertion + * @category assertion property + * @param {*} key Key to check + * @param {*} value Value to check + * @example + * + * ({ a: 10 }).should.have.value('a', 10); + * (new Map([[1, 2]])).should.have.value(1, 2); + */ + Assertion.add('value', function(key, value) { + this.have.key(key).which.is.eql(value); + }); + + /** + * Asserts given object has such size. + * + * @name size + * @memberOf Assertion + * @category assertion property + * @param {number} s Size to check + * @example + * + * ({ a: 10 }).should.have.size(1); + * (new Map([[1, 2]])).should.have.size(1); + */ + Assertion.add('size', function(s) { + this.params = { operator: 'to have size ' + s }; + size(this.obj).should.be.exactly(s); + }); + + /** + * Asserts given object has nested property in depth by path. **On success it change given object to be value of final property**. + * + * @name propertyByPath + * @memberOf Assertion + * @category assertion property + * @param {Array|...string} properties Properties path to search + * @example + * + * ({ a: {b: 10}}).should.have.propertyByPath('a', 'b').eql(10); + */ + Assertion.add('propertyByPath', function(properties) { + if (arguments.length > 1) { + properties = aSlice.call(arguments); + } else if (arguments.length === 1 && typeof properties == 'string') { + properties = [properties]; + } else if (arguments.length === 0) { + properties = []; + } + + var allProps = properties.map(formatProp); + + properties = properties.map(String); + + var obj = should(Object(this.obj)); + + var foundProperties = []; + + var currentProperty; + while (properties.length) { + currentProperty = properties.shift(); + this.params = {operator: 'to have property by path ' + allProps.join(', ') + ' - failed on ' + formatProp(currentProperty)}; + obj = obj.have.property(currentProperty); + foundProperties.push(currentProperty); + } + + this.params = {obj: this.obj, operator: 'to have property by path ' + allProps.join(', ')}; + + this.obj = obj.obj; + }); + } + + function errorAssertions(should, Assertion) { + var i = should.format; + + /** + * Assert given function throws error with such message. + * + * @name throw + * @memberOf Assertion + * @category assertion errors + * @alias Assertion#throwError + * @param {string|RegExp|Function|Object|GeneratorFunction|GeneratorObject} [message] Message to match or properties + * @param {Object} [properties] Optional properties that will be matched to thrown error + * @example + * + * (function(){ throw new Error('fail') }).should.throw(); + * (function(){ throw new Error('fail') }).should.throw('fail'); + * (function(){ throw new Error('fail') }).should.throw(/fail/); + * + * (function(){ throw new Error('fail') }).should.throw(Error); + * var error = new Error(); + * error.a = 10; + * (function(){ throw error; }).should.throw(Error, { a: 10 }); + * (function(){ throw error; }).should.throw({ a: 10 }); + * (function*() { + * yield throwError(); + * }).should.throw(); + */ + Assertion.add('throw', function(message, properties) { + var fn = this.obj; + var err = {}; + var errorInfo = ''; + var thrown = false; + + if (isGeneratorFunction(fn)) { + return should(fn()).throw(message, properties); + } else if (isIterator(fn)) { + return should(fn.next.bind(fn)).throw(message, properties); + } + + this.is.a.Function(); + + var errorMatched = true; + + try { + fn(); + } catch (e) { + thrown = true; + err = e; + } + + if (thrown) { + if (message) { + if ('string' == typeof message) { + errorMatched = message == err.message; + } else if (message instanceof RegExp) { + errorMatched = message.test(err.message); + } else if ('function' == typeof message) { + errorMatched = err instanceof message; + } else if (null != message) { + try { + should(err).match(message); + } catch (e) { + if (e instanceof should.AssertionError) { + errorInfo = ": " + e.message; + errorMatched = false; + } else { + throw e; + } + } + } + + if (!errorMatched) { + if ('string' == typeof message || message instanceof RegExp) { + errorInfo = " with a message matching " + i(message) + ", but got '" + err.message + "'"; + } else if ('function' == typeof message) { + errorInfo = " of type " + functionName(message) + ", but got " + functionName(err.constructor); + } + } else if ('function' == typeof message && properties) { + try { + should(err).match(properties); + } catch (e) { + if (e instanceof should.AssertionError) { + errorInfo = ": " + e.message; + errorMatched = false; + } else { + throw e; + } + } + } + } else { + errorInfo = " (got " + i(err) + ")"; + } + } + + this.params = { operator: 'to throw exception' + errorInfo }; + + this.assert(thrown); + this.assert(errorMatched); + }); + + Assertion.alias('throw', 'throwError'); + } + + function matchingAssertions(should, Assertion) { + var i = should.format; + + /** + * Asserts if given object match `other` object, using some assumptions: + * First object matched if they are equal, + * If `other` is a regexp and given object is a string check on matching with regexp + * If `other` is a regexp and given object is an array check if all elements matched regexp + * If `other` is a regexp and given object is an object check values on matching regexp + * If `other` is a function check if this function throws AssertionError on given object or return false - it will be assumed as not matched + * If `other` is an object check if the same keys matched with above rules + * All other cases failed. + * + * Usually it is right idea to add pre type assertions, like `.String()` or `.Object()` to be sure assertions will do what you are expecting. + * Object iteration happen by keys (properties with enumerable: true), thus some objects can cause small pain. Typical example is js + * Error - it by default has 2 properties `name` and `message`, but they both non-enumerable. In this case make sure you specify checking props (see examples). + * + * @name match + * @memberOf Assertion + * @category assertion matching + * @param {*} other Object to match + * @param {string} [description] Optional message + * @example + * 'foobar'.should.match(/^foo/); + * 'foobar'.should.not.match(/^bar/); + * + * ({ a: 'foo', c: 'barfoo' }).should.match(/foo$/); + * + * ['a', 'b', 'c'].should.match(/[a-z]/); + * + * (5).should.not.match(function(n) { + * return n < 0; + * }); + * (5).should.not.match(function(it) { + * it.should.be.an.Array(); + * }); + * ({ a: 10, b: 'abc', c: { d: 10 }, d: 0 }).should + * .match({ a: 10, b: /c$/, c: function(it) { + * return it.should.have.property('d', 10); + * }}); + * + * [10, 'abc', { d: 10 }, 0].should + * .match({ '0': 10, '1': /c$/, '2': function(it) { + * return it.should.have.property('d', 10); + * }}); + * + * var myString = 'abc'; + * + * myString.should.be.a.String().and.match(/abc/); + * + * myString = {}; + * + * myString.should.match(/abc/); //yes this will pass + * //better to do + * myString.should.be.an.Object().and.not.empty().and.match(/abc/);//fixed + * + * (new Error('boom')).should.match(/abc/);//passed because no keys + * (new Error('boom')).should.not.match({ message: /abc/ });//check specified property + */ + Assertion.add('match', function(other, description) { + this.params = {operator: 'to match ' + i(other), message: description}; + + if (eq(this.obj, other).length !== 0) { + if (other instanceof RegExp) { // something - regex + + if (typeof this.obj == 'string') { + + this.assert(other.exec(this.obj)); + } else if (null != this.obj && typeof this.obj == 'object') { + + var notMatchedProps = [], matchedProps = []; + forEach(this.obj, function(value, name) { + if (other.exec(value)) { + matchedProps.push(formatProp(name)); + } else { + notMatchedProps.push(formatProp(name) + ' (' + i(value) + ')'); + } + }, this); + + if (notMatchedProps.length) { + this.params.operator += '\n not matched properties: ' + notMatchedProps.join(', '); + } + if (matchedProps.length) { + this.params.operator += '\n matched properties: ' + matchedProps.join(', '); + } + + this.assert(notMatchedProps.length === 0); + } // should we try to convert to String and exec? + } else if (typeof other == 'function') { + var res; + + res = other(this.obj); + + //if we throw exception ok - it is used .should inside + if (typeof res == 'boolean') { + this.assert(res); // if it is just boolean function assert on it + } + } else if (other != null && this.obj != null && typeof other == 'object' && typeof this.obj == 'object') { // try to match properties (for Object and Array) + notMatchedProps = []; + matchedProps = []; + + forEach(other, function(value, key) { + try { + should(this.obj).have.property(key).which.match(value); + matchedProps.push(formatProp(key)); + } catch (e) { + if (e instanceof should.AssertionError) { + notMatchedProps.push(formatProp(key) + ' (' + i(this.obj[key]) + ')'); + } else { + throw e; + } + } + }, this); + + if (notMatchedProps.length) { + this.params.operator += '\n not matched properties: ' + notMatchedProps.join(', '); + } + if (matchedProps.length) { + this.params.operator += '\n matched properties: ' + matchedProps.join(', '); + } + + this.assert(notMatchedProps.length === 0); + } else { + this.assert(false); + } + } + }); + + /** + * Asserts if given object values or array elements all match `other` object, using some assumptions: + * First object matched if they are equal, + * If `other` is a regexp - matching with regexp + * If `other` is a function check if this function throws AssertionError on given object or return false - it will be assumed as not matched + * All other cases check if this `other` equal to each element + * + * @name matchEach + * @memberOf Assertion + * @category assertion matching + * @alias Assertion#matchEvery + * @param {*} other Object to match + * @param {string} [description] Optional message + * @example + * [ 'a', 'b', 'c'].should.matchEach(/\w+/); + * [ 'a', 'a', 'a'].should.matchEach('a'); + * + * [ 'a', 'a', 'a'].should.matchEach(function(value) { value.should.be.eql('a') }); + * + * { a: 'a', b: 'a', c: 'a' }.should.matchEach(function(value) { value.should.be.eql('a') }); + */ + Assertion.add('matchEach', function(other, description) { + this.params = {operator: 'to match each ' + i(other), message: description}; + + forEach(this.obj, function(value) { + should(value).match(other); + }, this); + }); + + /** + * Asserts if any of given object values or array elements match `other` object, using some assumptions: + * First object matched if they are equal, + * If `other` is a regexp - matching with regexp + * If `other` is a function check if this function throws AssertionError on given object or return false - it will be assumed as not matched + * All other cases check if this `other` equal to each element + * + * @name matchAny + * @memberOf Assertion + * @category assertion matching + * @param {*} other Object to match + * @alias Assertion#matchSome + * @param {string} [description] Optional message + * @example + * [ 'a', 'b', 'c'].should.matchAny(/\w+/); + * [ 'a', 'b', 'c'].should.matchAny('a'); + * + * [ 'a', 'b', 'c'].should.matchAny(function(value) { value.should.be.eql('a') }); + * + * { a: 'a', b: 'b', c: 'c' }.should.matchAny(function(value) { value.should.be.eql('a') }); + */ + Assertion.add('matchAny', function(other, description) { + this.params = {operator: 'to match any ' + i(other), message: description}; + + this.assert(some(this.obj, function(value) { + try { + should(value).match(other); + return true; + } catch (e) { + if (e instanceof should.AssertionError) { + // Caught an AssertionError, return false to the iterator + return false; + } + throw e; + } + })); + }); + + Assertion.alias('matchAny', 'matchSome'); + Assertion.alias('matchEach', 'matchEvery'); + } + + /** + * Our function should + * + * @param {*} obj Object to assert + * @returns {should.Assertion} Returns new Assertion for beginning assertion chain + * @example + * + * var should = require('should'); + * should('abc').be.a.String(); + */ + function should(obj) { + return (new Assertion(obj)); + } + + should.AssertionError = AssertionError; + should.Assertion = Assertion; + + // exposing modules dirty way + should.modules = { + format: defaultFormat, + type: getGlobalType, + equal: eq + }; + should.format = format; + + /** + * Object with configuration. + * It contains such properties: + * * `checkProtoEql` boolean - Affect if `.eql` will check objects prototypes + * * `plusZeroAndMinusZeroEqual` boolean - Affect if `.eql` will treat +0 and -0 as equal + * Also it can contain options for should-format. + * + * @type {Object} + * @memberOf should + * @static + * @example + * + * var a = { a: 10 }, b = Object.create(null); + * b.a = 10; + * + * a.should.be.eql(b); + * //not throws + * + * should.config.checkProtoEql = true; + * a.should.be.eql(b); + * //throws AssertionError: expected { a: 10 } to equal { a: 10 } (because A and B have different prototypes) + */ + should.config = config; + + /** + * Allow to extend given prototype with should property using given name. This getter will **unwrap** all standard wrappers like `Number`, `Boolean`, `String`. + * Using `should(obj)` is the equivalent of using `obj.should` with known issues (like nulls and method calls etc). + * + * To add new assertions, need to use Assertion.add method. + * + * @param {string} [propertyName] Name of property to add. Default is `'should'`. + * @param {Object} [proto] Prototype to extend with. Default is `Object.prototype`. + * @memberOf should + * @returns {{ name: string, descriptor: Object, proto: Object }} Descriptor enough to return all back + * @static + * @example + * + * var prev = should.extend('must', Object.prototype); + * + * 'abc'.must.startWith('a'); + * + * var should = should.noConflict(prev); + * should.not.exist(Object.prototype.must); + */ + should.extend = function(propertyName, proto) { + propertyName = propertyName || 'should'; + proto = proto || Object.prototype; + + var prevDescriptor = Object.getOwnPropertyDescriptor(proto, propertyName); + + Object.defineProperty(proto, propertyName, { + set: function() { + }, + get: function() { + return should(isWrapperType(this) ? this.valueOf() : this); + }, + configurable: true + }); + + return { name: propertyName, descriptor: prevDescriptor, proto: proto }; + }; + + /** + * Delete previous extension. If `desc` missing it will remove default extension. + * + * @param {{ name: string, descriptor: Object, proto: Object }} [desc] Returned from `should.extend` object + * @memberOf should + * @returns {Function} Returns should function + * @static + * @example + * + * var should = require('should').noConflict(); + * + * should(Object.prototype).not.have.property('should'); + * + * var prev = should.extend('must', Object.prototype); + * 'abc'.must.startWith('a'); + * should.noConflict(prev); + * + * should(Object.prototype).not.have.property('must'); + */ + should.noConflict = function(desc) { + desc = desc || should._prevShould; + + if (desc) { + delete desc.proto[desc.name]; + + if (desc.descriptor) { + Object.defineProperty(desc.proto, desc.name, desc.descriptor); + } + } + return should; + }; + + /** + * Simple utility function for a bit more easier should assertion extension + * @param {Function} f So called plugin function. It should accept 2 arguments: `should` function and `Assertion` constructor + * @memberOf should + * @returns {Function} Returns `should` function + * @static + * @example + * + * should.use(function(should, Assertion) { + * Assertion.add('asset', function() { + * this.params = { operator: 'to be asset' }; + * + * this.obj.should.have.property('id').which.is.a.Number(); + * this.obj.should.have.property('path'); + * }) + * }) + */ + should.use = function(f) { + f(should, should.Assertion); + return this; + }; + + should + .use(assertExtensions) + .use(chainAssertions) + .use(booleanAssertions) + .use(numberAssertions) + .use(equalityAssertions) + .use(typeAssertions) + .use(stringAssertions) + .use(propertyAssertions) + .use(errorAssertions) + .use(matchingAssertions) + .use(containAssertions) + .use(promiseAssertions); + + var defaultProto = Object.prototype; + var defaultProperty = 'should'; + + //Expose api via `Object#should`. + try { + var prevShould = should.extend(defaultProperty, defaultProto); + should._prevShould = prevShould; + } catch (e) { + //ignore errors + } + + + if (typeof define === 'function' && define.amd) { + define([], function() { return should }); + } else if (typeof module === 'object' && module.exports) { + module.exports = should; + } else { + var _root = root; + + _root.Should = should; + + Object.defineProperty(_root, 'should', { + enumerable: false, + configurable: true, + value: should + }); + } + +}(this)); \ No newline at end of file diff --git a/usergrid.js b/usergrid.js index b578f63..5df4f0f 100644 --- a/usergrid.js +++ b/usergrid.js @@ -17,7 +17,7 @@ *under the License. * * - * usergrid@0.11.0 2016-09-20 + * usergrid@0.11.0 2016-09-21 */ var UsergridAuthMode = Object.freeze({ NONE: "none", @@ -15518,6 +15518,142 @@ function configureTempAuth(auth) { } } +function useQuotesIfRequired(value) { + return _.isFinite(value) || isUUID(value) || _.isBoolean(value) || _.isObject(value) && !_.isFunction(value) || _.isArray(value) ? value : "'" + value + "'"; +} + +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ +"use strict"; + +var UsergridQuery = function(type) { + var self = this; + var query = "", queryString, sort, __nextIsNot = false; + _.assign(self, { + type: function(value) { + self._type = value; + return self; + }, + collection: function(value) { + self._type = value; + return self; + }, + limit: function(value) { + self._limit = value; + return self; + }, + cursor: function(value) { + self._cursor = value; + return self; + }, + eq: function(key, value) { + query = self.andJoin(key + " = " + useQuotesIfRequired(value)); + return self; + }, + equal: this.eq, + gt: function(key, value) { + query = self.andJoin(key + " > " + useQuotesIfRequired(value)); + return self; + }, + greaterThan: this.gt, + gte: function(key, value) { + query = self.andJoin(key + " >= " + useQuotesIfRequired(value)); + return self; + }, + greaterThanOrEqual: this.gte, + lt: function(key, value) { + query = self.andJoin(key + " < " + useQuotesIfRequired(value)); + return self; + }, + lessThan: this.lt, + lte: function(key, value) { + query = self.andJoin(key + " <= " + useQuotesIfRequired(value)); + return self; + }, + lessThanOrEqual: this.lte, + contains: function(key, value) { + query = self.andJoin(key + " contains " + useQuotesIfRequired(value)); + return self; + }, + locationWithin: function(distanceInMeters, lat, lng) { + query = self.andJoin("location within " + distanceInMeters + " of " + lat + ", " + lng); + return self; + }, + asc: function(key) { + self.sort(key, "asc"); + return self; + }, + desc: function(key) { + self.sort(key, "desc"); + return self; + }, + sort: function(key, order) { + sort = key && order ? " order by " + key + " " + order : ""; + return self; + }, + fromString: function(string) { + queryString = string; + return self; + }, + andJoin: function(append) { + if (__nextIsNot) { + append = "not " + append; + __nextIsNot = false; + } + if (!append) { + return query; + } else if (query.length === 0) { + return append; + } else { + return _.endsWith(query, "and") || _.endsWith(query, "or") ? query + " " + append : query + " and " + append; + } + }, + orJoin: function() { + return query.length > 0 && !_.endsWith(query, "or") ? query + " or" : query; + } + }); + self._type = self._type || type; + Object.defineProperty(self, "_ql", { + get: function() { + if (queryString !== undefined) { + return queryString; + } else { + return query.length > 0 || sort !== undefined ? "select * where " + (query || "") + (sort || "") : ""; + } + } + }); + Object.defineProperty(self, "and", { + get: function() { + query = self.andJoin(""); + return self; + } + }); + Object.defineProperty(self, "or", { + get: function() { + query = self.orJoin(); + return self; + } + }); + Object.defineProperty(self, "not", { + get: function() { + __nextIsNot = true; + return self; + } + }); + return self; +}; + /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18645,17 +18781,16 @@ var UsergridAuth = function(token, expiry) { configurable: true, writable: true }); + _.assign(self, { + destroy: function() { + self.token = undefined; + self.expiry = 0; + self.tokenTtl = undefined; + } + }); return self; }; -UsergridAuth.prototype = { - destroy: function() { - this.token = undefined; - this.expiry = 0; - this.tokenTtl = undefined; - } -}; - var UsergridAppAuth = function() { var self = this; var args = flattenArgs(arguments); @@ -18679,14 +18814,14 @@ var UsergridUserAuth = function() { var self = this; var args = flattenArgs(arguments); if (_.isPlainObject(args[0])) { - options = args[0]; - } - self.username = options.username || args[0]; - self.email = options.email; - if (options.password || args[1]) { - self.password = options.password || args[1]; + self.username = args[0].username; + self.email = args[0].email; + self.tokenTtl = args[0].tokenTtl; + } else { + self.username = args[0]; + self.email = args[1]; + self.tokenTtl = args[2]; } - self.tokenTtl = options.tokenTtl || args[2]; UsergridAuth.call(self); _.assign(self, UsergridAuth); return self; diff --git a/usergrid.min.js b/usergrid.min.js index 3f07159..6c12b8d 100644 --- a/usergrid.min.js +++ b/usergrid.min.js @@ -17,12 +17,12 @@ *under the License. * * - * usergrid@0.11.0 2016-09-20 + * usergrid@0.11.0 2016-09-21 */ -"use strict";function inherits(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})}function flattenArgs(args){return _.flattenDeep(Array.prototype.slice.call(args))}function validateAndRetrieveClient(args){var client=void 0;if(args instanceof UsergridClient)client=args;else if(args[0]instanceof UsergridClient)client=args[0];else{if(!Usergrid.isInitialized)throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument");client=Usergrid.getInstance()}return client}function configureTempAuth(auth){return _.isString(auth)&&auth!==UsergridAuthMode.NONE?new UsergridAuth(auth):auth&&auth!==UsergridAuthMode.NONE&&auth instanceof UsergridAuth?auth:void 0}function extend(subClass,superClass){var F=function(){};return F.prototype=superClass.prototype,subClass.prototype=new F,subClass.prototype.constructor=subClass,subClass.superclass=superClass.prototype,superClass.prototype.constructor==Object.prototype.constructor&&(superClass.prototype.constructor=superClass),subClass}function propCopy(from,to){for(var prop in from)from.hasOwnProperty(prop)&&("object"==typeof from[prop]&&"object"==typeof to[prop]?to[prop]=propCopy(from[prop],to[prop]):to[prop]=from[prop]);return to}function NOOP(){}function isValidUrl(url){if(!url)return!1;var doc,base,anchor,isValid=!1;try{doc=document.implementation.createHTMLDocument(""),base=doc.createElement("base"),base.href=base||window.lo,doc.head.appendChild(base),anchor=doc.createElement("a"),anchor.href=url,doc.body.appendChild(anchor),isValid=!(""===anchor.href)}catch(e){console.error(e)}finally{return doc.head.removeChild(base),doc.body.removeChild(anchor),base=null,anchor=null,doc=null,isValid}}function isUUID(uuid){return uuid?uuidValueRegex.test(uuid):!1}function encodeParams(params){var queryString;return params&&Object.keys(params)&&(queryString=[].slice.call(arguments).reduce(function(a,b){return a.concat(b instanceof Array?b:[b])},[]).filter(function(c){return"object"==typeof c}).reduce(function(p,c){return c instanceof Array?p.push(c):p=p.concat(Object.keys(c).map(function(key){return[key,c[key]]})),p},[]).reduce(function(p,c){return 2===c.length?p.push(c):p=p.concat(c),p},[]).reduce(function(p,c){return c[1]instanceof Array?c[1].forEach(function(v){p.push([c[0],v])}):p.push(c),p},[]).map(function(c){return c[1]=encodeURIComponent(c[1]),c.join("=")}).join("&")),queryString}function isFunction(f){return f&&null!==f&&"function"==typeof f}function doCallback(callback,params,context){var returnValue;return isFunction(callback)&&(params||(params=[]),context||(context=this),params.push(context),returnValue=callback.apply(context,params)),returnValue}function getSafeTime(prop){var time;switch(typeof prop){case"undefined":time=Date.now();break;case"number":time=prop;break;case"string":time=isNaN(prop)?Date.parse(prop):parseInt(prop);break;default:time=Date.parse(prop.toString())}return time}var UsergridAuthMode=Object.freeze({NONE:"none",USER:"user",APP:"app"}),UsergridDirection=Object.freeze({IN:"connecting",OUT:"connections"}),UsergridHttpMethod=Object.freeze({GET:"GET",PUT:"PUT",POST:"POST",DELETE:"DELETE"}),UsergridQueryOperator=Object.freeze({EQUAL:"=",GREATER_THAN:">",GREATER_THAN_EQUAL_TO:">=",LESS_THAN:"<",LESS_THAN_EQUAL_TO:"<="}),UsergridQuerySortOrder=Object.freeze({ASC:"asc",DESC:"desc"}),UsergridEventable=function(){throw Error("'UsergridEventable' is not intended to be invoked directly")};UsergridEventable.prototype={bind:function(event,fn){this._events=this._events||{},this._events[event]=this._events[event]||[],this._events[event].push(fn)},unbind:function(event,fn){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fn),1)},trigger:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;ii;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,error,result){var p=new Promise;return null===promises||0===promises.length?p.done(error,result):promises[0](error,result).then(function(res,err){promises.splice(0,1),promises?Promise.chain(promises,res,err).then(function(r,e){p.done(r,e)}):p.done(res,err)}),p},global[name]=Promise,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Promise},global[name]}(this),function(){function partial(){var args=Array.prototype.slice.call(arguments),fn=args.shift();return fn.bind(this,args)}function Ajax(){function encode(data){var result="";if("string"==typeof data)result=data;else{var e=encodeURIComponent;for(var i in data)data.hasOwnProperty(i)&&(result+="&"+e(i)+"="+e(data[i]))}return result}function request(m,u,d){var timeout,p=new Promise;return self.logger.time(m+" "+u),function(xhr){xhr.onreadystatechange=function(){4===this.readyState&&(self.logger.timeEnd(m+" "+u),clearTimeout(timeout),p.done(null,this))},xhr.onerror=function(response){clearTimeout(timeout),p.done(response,null)},xhr.oncomplete=function(response){clearTimeout(timeout),self.logger.timeEnd(m+" "+u),self.info("%s request to %s returned %s",m,u,this.status)},xhr.open(m,u),d&&("object"==typeof d&&(d=JSON.stringify(d)),xhr.setRequestHeader("Content-Type","application/json"),xhr.setRequestHeader("Accept","application/json")),timeout=setTimeout(function(){xhr.abort(),p.done("API Call timed out.",null)},3e4),xhr.send(encode(d))}(new XMLHttpRequest),p}this.logger=new global.Logger(name);var self=this;this.request=request,this.get=partial(request,"GET"),this.post=partial(request,"POST"),this.put=partial(request,"PUT"),this["delete"]=partial(request,"DELETE")}var exports,name="Ajax",global=this,overwrittenName=global[name];return global[name]=new Ajax,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}(),function(){function addMapEntry(map,pair){return map.set(pair[0],pair[1]),map}function addSetEntry(set,value){return set.add(value),set}function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}function arrayAggregator(array,setter,iteratee,accumulator){for(var index=-1,length=array?array.length:0;++index-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1;);return index}function charsEndIndex(strSymbols,chrSymbols){for(var index=strSymbols.length;index--&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1;);return index}function countHolders(array,placeholder){for(var length=array.length,result=0;length--;)array[length]===placeholder&&++result;return result}function escapeStringChar(chr){return"\\"+stringEscapes[chr]}function getValue(object,key){return null==object?undefined:object[key]}function hasUnicode(string){return reHasUnicode.test(string)}function hasUnicodeWord(string){return reHasUnicodeWord.test(string)}function iteratorToArray(iterator){for(var data,result=[];!(data=iterator.next()).done;)result.push(data.value);return result}function mapToArray(map){var index=-1,result=Array(map.size);return map.forEach(function(value,key){result[++index]=[key,value]}),result}function overArg(func,transform){return function(arg){return func(transform(arg))}}function replaceHolders(array,placeholder){for(var index=-1,length=array.length,resIndex=0,result=[];++indexdir,arrLength=isArr?array.length:0,view=getView(0,arrLength,this.__views__),start=view.start,end=view.end,length=end-start,index=isRight?end:start-1,iteratees=this.__iteratees__,iterLength=iteratees.length,resIndex=0,takeCount=nativeMin(length,this.__takeCount__);if(!isArr||LARGE_ARRAY_SIZE>arrLength||arrLength==length&&takeCount==length)return baseWrapperValue(array,this.__actions__);var result=[];outer:for(;length--&&takeCount>resIndex;){index+=dir;for(var iterIndex=-1,value=array[index];++iterIndexindex)return!1;var lastIndex=data.length-1;return index==lastIndex?data.pop():splice.call(data,index,1),--this.size,!0}function listCacheGet(key){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?undefined:data[index][1]}function listCacheHas(key){return assocIndexOf(this.__data__,key)>-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?(++this.size,data.push([key,value])):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index=number?number:upper),lower!==undefined&&(number=number>=lower?number:lower)),number}function baseClone(value,isDeep,isFull,customizer,key,object,stack){var result;if(customizer&&(result=object?customizer(value,key,object,stack):customizer(value)),result!==undefined)return result;if(!isObject(value))return value;var isArr=isArray(value);if(isArr){if(result=initCloneArray(value),!isDeep)return copyArray(value,result)}else{var tag=getTag(value),isFunc=tag==funcTag||tag==genTag;if(isBuffer(value))return cloneBuffer(value,isDeep);if(tag==objectTag||tag==argsTag||isFunc&&!object){if(result=initCloneObject(isFunc?{}:value),!isDeep)return copySymbols(value,baseAssign(result,value))}else{if(!cloneableTags[tag])return object?value:{};result=initCloneByTag(value,tag,baseClone,isDeep)}}stack||(stack=new Stack);var stacked=stack.get(value);if(stacked)return stacked;if(stack.set(value,result),!isArr)var props=isFull?getAllKeys(value):keys(value);return arrayEach(props||value,function(subValue,key){props&&(key=subValue,subValue=value[key]),assignValue(result,key,baseClone(subValue,isDeep,isFull,customizer,key,value,stack))}),result}function baseConforms(source){var props=keys(source);return function(object){return baseConformsTo(object,source,props)}}function baseConformsTo(object,source,props){var length=props.length;if(null==object)return!length;for(object=Object(object);length--;){var key=props[length],predicate=source[key],value=object[key];if(value===undefined&&!(key in object)||!predicate(value))return!1}return!0}function baseCreate(proto){return isObject(proto)?objectCreate(proto):{}}function baseDelay(func,wait,args){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return setTimeout(function(){func.apply(undefined,args)},wait)}function baseDifference(array,values,iteratee,comparator){var index=-1,includes=arrayIncludes,isCommon=!0,length=array.length,result=[],valuesLength=values.length;if(!length)return result;iteratee&&(values=arrayMap(values,baseUnary(iteratee))),comparator?(includes=arrayIncludesWith,isCommon=!1):values.length>=LARGE_ARRAY_SIZE&&(includes=cacheHas,isCommon=!1,values=new SetCache(values));outer:for(;++indexstart&&(start=-start>length?0:length+start),end=end===undefined||end>length?length:toInteger(end),0>end&&(end+=length),end=start>end?0:toLength(end);end>start;)array[start++]=value;return array}function baseFilter(collection,predicate){var result=[];return baseEach(collection,function(value,index,collection){predicate(value,index,collection)&&result.push(value)}),result}function baseFlatten(array,depth,predicate,isStrict,result){var index=-1,length=array.length;for(predicate||(predicate=isFlattenable),result||(result=[]);++index0&&predicate(value)?depth>1?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}function baseForOwn(object,iteratee){return object&&baseFor(object,iteratee,keys)}function baseForOwnRight(object,iteratee){return object&&baseForRight(object,iteratee,keys)}function baseFunctions(object,props){return arrayFilter(props,function(key){return isFunction(object[key])})}function baseGet(object,path){path=isKey(path,object)?[path]:castPath(path);for(var index=0,length=path.length;null!=object&&length>index;)object=object[toKey(path[index++])];return index&&index==length?object:undefined}function baseGetAllKeys(object,keysFunc,symbolsFunc){var result=keysFunc(object);return isArray(object)?result:arrayPush(result,symbolsFunc(object))}function baseGetTag(value){return objectToString.call(value)}function baseGt(value,other){return value>other}function baseHas(object,key){return null!=object&&hasOwnProperty.call(object,key)}function baseHasIn(object,key){return null!=object&&key in Object(object)}function baseInRange(number,start,end){return number>=nativeMin(start,end)&&number=120&&array.length>=120)?new SetCache(othIndex&&array):undefined}array=arrays[0];var index=-1,seen=caches[0];outer:for(;++indexvalue}function baseMap(collection,iteratee){var index=-1,result=isArrayLike(collection)?Array(collection.length):[];return baseEach(collection,function(value,key,collection){result[++index]=iteratee(value,key,collection)}),result}function baseMatches(source){var matchData=getMatchData(source);return 1==matchData.length&&matchData[0][2]?matchesStrictComparable(matchData[0][0],matchData[0][1]):function(object){return object===source||baseIsMatch(object,source,matchData)}}function baseMatchesProperty(path,srcValue){return isKey(path)&&isStrictComparable(srcValue)?matchesStrictComparable(toKey(path),srcValue):function(object){var objValue=get(object,path);return objValue===undefined&&objValue===srcValue?hasIn(object,path):baseIsEqual(srcValue,objValue,undefined,UNORDERED_COMPARE_FLAG|PARTIAL_COMPARE_FLAG)}}function baseMerge(object,source,srcIndex,customizer,stack){if(object!==source){if(!isArray(source)&&!isTypedArray(source))var props=baseKeysIn(source);arrayEach(props||source,function(srcValue,key){if(props&&(key=srcValue,srcValue=source[key]),isObject(srcValue))stack||(stack=new Stack),baseMergeDeep(object,source,key,srcIndex,baseMerge,customizer,stack);else{var newValue=customizer?customizer(object[key],srcValue,key+"",object,source,stack):undefined;newValue===undefined&&(newValue=srcValue),assignMergeValue(object,key,newValue)}})}}function baseMergeDeep(object,source,key,srcIndex,mergeFunc,customizer,stack){var objValue=object[key],srcValue=source[key],stacked=stack.get(srcValue);if(stacked)return void assignMergeValue(object,key,stacked);var newValue=customizer?customizer(objValue,srcValue,key+"",object,source,stack):undefined,isCommon=newValue===undefined;isCommon&&(newValue=srcValue,isArray(srcValue)||isTypedArray(srcValue)?isArray(objValue)?newValue=objValue:isArrayLikeObject(objValue)?newValue=copyArray(objValue):(isCommon=!1,newValue=baseClone(srcValue,!0)):isPlainObject(srcValue)||isArguments(srcValue)?isArguments(objValue)?newValue=toPlainObject(objValue):!isObject(objValue)||srcIndex&&isFunction(objValue)?(isCommon=!1,newValue=baseClone(srcValue,!0)):newValue=objValue:isCommon=!1),isCommon&&(stack.set(srcValue,newValue),mergeFunc(newValue,srcValue,srcIndex,customizer,stack),stack["delete"](srcValue)),assignMergeValue(object,key,newValue)}function baseNth(array,n){var length=array.length;if(length)return n+=0>n?length:0,isIndex(n,length)?array[n]:undefined}function baseOrderBy(collection,iteratees,orders){var index=-1;iteratees=arrayMap(iteratees.length?iteratees:[identity],baseUnary(getIteratee()));var result=baseMap(collection,function(value,key,collection){var criteria=arrayMap(iteratees,function(iteratee){return iteratee(value)});return{criteria:criteria,index:++index,value:value}});return baseSortBy(result,function(object,other){return compareMultiple(object,other,orders)})}function basePick(object,props){return object=Object(object),basePickBy(object,props,function(value,key){return key in object})}function basePickBy(object,props,predicate){for(var index=-1,length=props.length,result={};++index-1;)seen!==array&&splice.call(seen,fromIndex,1),splice.call(array,fromIndex,1);return array}function basePullAt(array,indexes){for(var length=array?indexes.length:0,lastIndex=length-1;length--;){var index=indexes[length];if(length==lastIndex||index!==previous){var previous=index;if(isIndex(index))splice.call(array,index,1);else if(isKey(index,array))delete array[toKey(index)];else{var path=castPath(index),object=parent(array,path);null!=object&&delete object[toKey(last(path))]}}}return array}function baseRandom(lower,upper){return lower+nativeFloor(nativeRandom()*(upper-lower+1))}function baseRange(start,end,step,fromRight){for(var index=-1,length=nativeMax(nativeCeil((end-start)/(step||1)),0),result=Array(length);length--;)result[fromRight?length:++index]=start,start+=step;return result}function baseRepeat(string,n){var result="";if(!string||1>n||n>MAX_SAFE_INTEGER)return result;do n%2&&(result+=string),n=nativeFloor(n/2),n&&(string+=string);while(n);return result}function baseRest(func,start){return setToString(overRest(func,start,identity),func+"")}function baseSet(object,path,value,customizer){if(!isObject(object))return object;path=isKey(path,object)?[path]:castPath(path);for(var index=-1,length=path.length,lastIndex=length-1,nested=object;null!=nested&&++indexstart&&(start=-start>length?0:length+start),end=end>length?length:end,0>end&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index=high){for(;high>low;){var mid=low+high>>>1,computed=array[mid];null!==computed&&!isSymbol(computed)&&(retHighest?value>=computed:value>computed)?low=mid+1:high=mid}return high}return baseSortedIndexBy(array,value,identity,retHighest)}function baseSortedIndexBy(array,value,iteratee,retHighest){value=iteratee(value);for(var low=0,high=array?array.length:0,valIsNaN=value!==value,valIsNull=null===value,valIsSymbol=isSymbol(value),valIsUndefined=value===undefined;high>low;){var mid=nativeFloor((low+high)/2),computed=iteratee(array[mid]),othIsDefined=computed!==undefined,othIsNull=null===computed,othIsReflexive=computed===computed,othIsSymbol=isSymbol(computed);if(valIsNaN)var setLow=retHighest||othIsReflexive;else setLow=valIsUndefined?othIsReflexive&&(retHighest||othIsDefined):valIsNull?othIsReflexive&&othIsDefined&&(retHighest||!othIsNull):valIsSymbol?othIsReflexive&&othIsDefined&&!othIsNull&&(retHighest||!othIsSymbol):othIsNull||othIsSymbol?!1:retHighest?value>=computed:value>computed;setLow?low=mid+1:high=mid}return nativeMin(high,MAX_ARRAY_INDEX)}function baseSortedUniq(array,iteratee){for(var index=-1,length=array.length,resIndex=0,result=[];++index=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++indexindex?values[index]:undefined;assignFunc(result,props[index],value)}return result}function castArrayLikeObject(value){return isArrayLikeObject(value)?value:[]}function castFunction(value){return"function"==typeof value?value:identity}function castPath(value){return isArray(value)?value:stringToPath(value)}function castSlice(array,start,end){var length=array.length;return end=end===undefined?length:end,!start&&end>=length?array:baseSlice(array,start,end)}function cloneBuffer(buffer,isDeep){if(isDeep)return buffer.slice();var result=new buffer.constructor(buffer.length);return buffer.copy(result),result}function cloneArrayBuffer(arrayBuffer){var result=new arrayBuffer.constructor(arrayBuffer.byteLength);return new Uint8Array(result).set(new Uint8Array(arrayBuffer)),result}function cloneDataView(dataView,isDeep){var buffer=isDeep?cloneArrayBuffer(dataView.buffer):dataView.buffer;return new dataView.constructor(buffer,dataView.byteOffset,dataView.byteLength)}function cloneMap(map,isDeep,cloneFunc){var array=isDeep?cloneFunc(mapToArray(map),!0):mapToArray(map);return arrayReduce(array,addMapEntry,new map.constructor)}function cloneRegExp(regexp){var result=new regexp.constructor(regexp.source,reFlags.exec(regexp));return result.lastIndex=regexp.lastIndex,result}function cloneSet(set,isDeep,cloneFunc){var array=isDeep?cloneFunc(setToArray(set),!0):setToArray(set);return arrayReduce(array,addSetEntry,new set.constructor)}function cloneSymbol(symbol){return symbolValueOf?Object(symbolValueOf.call(symbol)):{}}function cloneTypedArray(typedArray,isDeep){var buffer=isDeep?cloneArrayBuffer(typedArray.buffer):typedArray.buffer;return new typedArray.constructor(buffer,typedArray.byteOffset,typedArray.length)}function compareAscending(value,other){if(value!==other){var valIsDefined=value!==undefined,valIsNull=null===value,valIsReflexive=value===value,valIsSymbol=isSymbol(value),othIsDefined=other!==undefined,othIsNull=null===other,othIsReflexive=other===other,othIsSymbol=isSymbol(other);if(!othIsNull&&!othIsSymbol&&!valIsSymbol&&value>other||valIsSymbol&&othIsDefined&&othIsReflexive&&!othIsNull&&!othIsSymbol||valIsNull&&othIsDefined&&othIsReflexive||!valIsDefined&&othIsReflexive||!valIsReflexive)return 1;if(!valIsNull&&!valIsSymbol&&!othIsSymbol&&other>value||othIsSymbol&&valIsDefined&&valIsReflexive&&!valIsNull&&!valIsSymbol||othIsNull&&valIsDefined&&valIsReflexive||!othIsDefined&&valIsReflexive||!othIsReflexive)return-1}return 0}function compareMultiple(object,other,orders){for(var index=-1,objCriteria=object.criteria,othCriteria=other.criteria,length=objCriteria.length,ordersLength=orders.length;++index=ordersLength)return result;var order=orders[index];return result*("desc"==order?-1:1)}}return object.index-other.index}function composeArgs(args,partials,holders,isCurried){for(var argsIndex=-1,argsLength=args.length,holdersLength=holders.length,leftIndex=-1,leftLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(leftLength+rangeLength),isUncurried=!isCurried;++leftIndexargsIndex)&&(result[holders[argsIndex]]=args[argsIndex]);for(;rangeLength--;)result[leftIndex++]=args[argsIndex++];return result}function composeArgsRight(args,partials,holders,isCurried){for(var argsIndex=-1,argsLength=args.length,holdersIndex=-1,holdersLength=holders.length,rightIndex=-1,rightLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(rangeLength+rightLength),isUncurried=!isCurried;++argsIndexargsIndex)&&(result[offset+holders[holdersIndex]]=args[argsIndex++]);return result}function copyArray(source,array){var index=-1,length=source.length;for(array||(array=Array(length));++index1?sources[length-1]:undefined,guard=length>2?sources[2]:undefined;for(customizer=assigner.length>3&&"function"==typeof customizer?(length--,customizer):undefined,guard&&isIterateeCall(sources[0],sources[1],guard)&&(customizer=3>length?undefined:customizer,length=1),object=Object(object);++indexlength&&args[0]!==placeholder&&args[length-1]!==placeholder?[]:replaceHolders(args,placeholder);if(length-=holders.length,arity>length)return createRecurry(func,bitmask,createHybrid,wrapper.placeholder,undefined,args,holders,undefined,undefined,arity-length);var fn=this&&this!==root&&this instanceof wrapper?Ctor:func;return apply(fn,this,args)}var Ctor=createCtor(func);return wrapper}function createFind(findIndexFunc){return function(collection,predicate,fromIndex){var iterable=Object(collection);if(!isArrayLike(collection)){var iteratee=getIteratee(predicate,3);collection=keys(collection),predicate=function(key){return iteratee(iterable[key],key,iterable)}}var index=findIndexFunc(collection,predicate,fromIndex);return index>-1?iterable[iteratee?collection[index]:index]:undefined}}function createFlow(fromRight){return flatRest(function(funcs){var length=funcs.length,index=length,prereq=LodashWrapper.prototype.thru;for(fromRight&&funcs.reverse();index--;){var func=funcs[index];if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);if(prereq&&!wrapper&&"wrapper"==getFuncName(func))var wrapper=new LodashWrapper([],!0)}for(index=wrapper?index:length;++index=LARGE_ARRAY_SIZE)return wrapper.plant(value).value();for(var index=0,result=length?funcs[index].apply(this,args):value;++indexlength){var newHolders=replaceHolders(args,placeholder);return createRecurry(func,bitmask,createHybrid,wrapper.placeholder,thisArg,args,newHolders,argPos,ary,arity-length)}var thisBinding=isBind?thisArg:this,fn=isBindKey?thisBinding[func]:func;return length=args.length,argPos?args=reorder(args,argPos):isFlip&&length>1&&args.reverse(),isAry&&length>ary&&(args.length=ary),this&&this!==root&&this instanceof wrapper&&(fn=Ctor||createCtor(fn)),fn.apply(thisBinding,args)}var isAry=bitmask&ARY_FLAG,isBind=bitmask&BIND_FLAG,isBindKey=bitmask&BIND_KEY_FLAG,isCurried=bitmask&(CURRY_FLAG|CURRY_RIGHT_FLAG),isFlip=bitmask&FLIP_FLAG,Ctor=isBindKey?undefined:createCtor(func);return wrapper}function createInverter(setter,toIteratee){return function(object,iteratee){return baseInverter(object,setter,toIteratee(iteratee),{})}}function createMathOperation(operator,defaultValue){return function(value,other){var result;if(value===undefined&&other===undefined)return defaultValue;if(value!==undefined&&(result=value),other!==undefined){if(result===undefined)return other;"string"==typeof value||"string"==typeof other?(value=baseToString(value),other=baseToString(other)):(value=baseToNumber(value),other=baseToNumber(other)),result=operator(value,other)}return result}}function createOver(arrayFunc){return flatRest(function(iteratees){return iteratees=arrayMap(iteratees,baseUnary(getIteratee())),baseRest(function(args){var thisArg=this;return arrayFunc(iteratees,function(iteratee){return apply(iteratee,thisArg,args)})})})}function createPadding(length,chars){chars=chars===undefined?" ":baseToString(chars);var charsLength=chars.length;if(2>charsLength)return charsLength?baseRepeat(chars,length):chars;var result=baseRepeat(chars,nativeCeil(length/stringSize(chars)));return hasUnicode(chars)?castSlice(stringToArray(result),0,length).join(""):result.slice(0,length)}function createPartial(func,bitmask,thisArg,partials){function wrapper(){for(var argsIndex=-1,argsLength=arguments.length,leftIndex=-1,leftLength=partials.length,args=Array(leftLength+argsLength),fn=this&&this!==root&&this instanceof wrapper?Ctor:func;++leftIndexstart?1:-1:toFinite(step),baseRange(start,end,step,fromRight)}}function createRelationalOperation(operator){return function(value,other){return("string"!=typeof value||"string"!=typeof other)&&(value=toNumber(value),other=toNumber(other)),operator(value,other)}}function createRecurry(func,bitmask,wrapFunc,placeholder,thisArg,partials,holders,argPos,ary,arity){var isCurry=bitmask&CURRY_FLAG,newHolders=isCurry?holders:undefined,newHoldersRight=isCurry?undefined:holders,newPartials=isCurry?partials:undefined,newPartialsRight=isCurry?undefined:partials;bitmask|=isCurry?PARTIAL_FLAG:PARTIAL_RIGHT_FLAG,bitmask&=~(isCurry?PARTIAL_RIGHT_FLAG:PARTIAL_FLAG),bitmask&CURRY_BOUND_FLAG||(bitmask&=~(BIND_FLAG|BIND_KEY_FLAG));var newData=[func,bitmask,thisArg,newPartials,newHolders,newPartialsRight,newHoldersRight,argPos,ary,arity],result=wrapFunc.apply(undefined,newData);return isLaziable(func)&&setData(result,newData),result.placeholder=placeholder,setWrapToString(result,func,bitmask)}function createRound(methodName){var func=Math[methodName];return function(number,precision){if(number=toNumber(number),precision=nativeMin(toInteger(precision),292)){var pair=(toString(number)+"e").split("e"),value=func(pair[0]+"e"+(+pair[1]+precision));return pair=(toString(value)+"e").split("e"),+(pair[0]+"e"+(+pair[1]-precision))}return func(number)}}function createToPairs(keysFunc){return function(object){var tag=getTag(object);return tag==mapTag?mapToArray(object):tag==setTag?setToPairs(object):baseToPairs(object,keysFunc(object))}}function createWrap(func,bitmask,thisArg,partials,holders,argPos,ary,arity){var isBindKey=bitmask&BIND_KEY_FLAG;if(!isBindKey&&"function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);var length=partials?partials.length:0;if(length||(bitmask&=~(PARTIAL_FLAG|PARTIAL_RIGHT_FLAG),partials=holders=undefined),ary=ary===undefined?ary:nativeMax(toInteger(ary),0),arity=arity===undefined?arity:toInteger(arity),length-=holders?holders.length:0,bitmask&PARTIAL_RIGHT_FLAG){var partialsRight=partials,holdersRight=holders;partials=holders=undefined}var data=isBindKey?undefined:getData(func),newData=[func,bitmask,thisArg,partials,holders,partialsRight,holdersRight,argPos,ary,arity];if(data&&mergeData(newData,data),func=newData[0],bitmask=newData[1],thisArg=newData[2],partials=newData[3],holders=newData[4],arity=newData[9]=null==newData[9]?isBindKey?0:func.length:nativeMax(newData[9]-length,0),!arity&&bitmask&(CURRY_FLAG|CURRY_RIGHT_FLAG)&&(bitmask&=~(CURRY_FLAG|CURRY_RIGHT_FLAG)),bitmask&&bitmask!=BIND_FLAG)result=bitmask==CURRY_FLAG||bitmask==CURRY_RIGHT_FLAG?createCurry(func,bitmask,arity):bitmask!=PARTIAL_FLAG&&bitmask!=(BIND_FLAG|PARTIAL_FLAG)||holders.length?createHybrid.apply(undefined,newData):createPartial(func,bitmask,thisArg,partials);else var result=createBind(func,bitmask,thisArg);var setter=data?baseSetData:setData;return setWrapToString(setter(result,newData),func,bitmask)}function equalArrays(array,other,equalFunc,customizer,bitmask,stack){var isPartial=bitmask&PARTIAL_COMPARE_FLAG,arrLength=array.length,othLength=other.length;if(arrLength!=othLength&&!(isPartial&&othLength>arrLength))return!1;var stacked=stack.get(array);if(stacked&&stack.get(other))return stacked==other;var index=-1,result=!0,seen=bitmask&UNORDERED_COMPARE_FLAG?new SetCache:undefined;for(stack.set(array,other),stack.set(other,array);++index1?"& ":"")+details[lastIndex],details=details.join(length>2?", ":" "),source.replace(reWrapComment,"{\n/* [wrapped with "+details+"] */\n")}function isFlattenable(value){return isArray(value)||isArguments(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol])}function isIndex(value,length){return length=null==length?MAX_SAFE_INTEGER:length,!!length&&("number"==typeof value||reIsUint.test(value))&&value>-1&&value%1==0&&length>value}function isIterateeCall(value,index,object){if(!isObject(object))return!1;var type=typeof index;return("number"==type?isArrayLike(object)&&isIndex(index,object.length):"string"==type&&index in object)?eq(object[index],value):!1}function isKey(value,object){if(isArray(value))return!1;var type=typeof value;return"number"==type||"symbol"==type||"boolean"==type||null==value||isSymbol(value)?!0:reIsPlainProp.test(value)||!reIsDeepProp.test(value)||null!=object&&value in Object(object)}function isKeyable(value){var type=typeof value;return"string"==type||"number"==type||"symbol"==type||"boolean"==type?"__proto__"!==value:null===value}function isLaziable(func){var funcName=getFuncName(func),other=lodash[funcName];if("function"!=typeof other||!(funcName in LazyWrapper.prototype))return!1;if(func===other)return!0;var data=getData(other);return!!data&&func===data[0]}function isMasked(func){return!!maskSrcKey&&maskSrcKey in func}function isPrototype(value){var Ctor=value&&value.constructor,proto="function"==typeof Ctor&&Ctor.prototype||objectProto;return value===proto}function isStrictComparable(value){return value===value&&!isObject(value)}function matchesStrictComparable(key,srcValue){return function(object){return null==object?!1:object[key]===srcValue&&(srcValue!==undefined||key in Object(object))}}function memoizeCapped(func){var result=memoize(func,function(key){return cache.size===MAX_MEMOIZE_SIZE&&cache.clear(),key}),cache=result.cache;return result}function mergeData(data,source){var bitmask=data[1],srcBitmask=source[1],newBitmask=bitmask|srcBitmask,isCommon=(BIND_FLAG|BIND_KEY_FLAG|ARY_FLAG)>newBitmask,isCombo=srcBitmask==ARY_FLAG&&bitmask==CURRY_FLAG||srcBitmask==ARY_FLAG&&bitmask==REARG_FLAG&&data[7].length<=source[8]||srcBitmask==(ARY_FLAG|REARG_FLAG)&&source[7].length<=source[8]&&bitmask==CURRY_FLAG;if(!isCommon&&!isCombo)return data;srcBitmask&BIND_FLAG&&(data[2]=source[2],newBitmask|=bitmask&BIND_FLAG?0:CURRY_BOUND_FLAG);var value=source[3];if(value){var partials=data[3];data[3]=partials?composeArgs(partials,value,source[4]):value,data[4]=partials?replaceHolders(data[3],PLACEHOLDER):source[4]}return value=source[5],value&&(partials=data[5],data[5]=partials?composeArgsRight(partials,value,source[6]):value,data[6]=partials?replaceHolders(data[5],PLACEHOLDER):source[6]),value=source[7],value&&(data[7]=value),srcBitmask&ARY_FLAG&&(data[8]=null==data[8]?source[8]:nativeMin(data[8],source[8])),null==data[9]&&(data[9]=source[9]),data[0]=source[0],data[1]=newBitmask,data}function mergeDefaults(objValue,srcValue,key,object,source,stack){return isObject(objValue)&&isObject(srcValue)&&(stack.set(srcValue,objValue),baseMerge(objValue,srcValue,undefined,mergeDefaults,stack),stack["delete"](srcValue)),objValue}function nativeKeysIn(object){var result=[];if(null!=object)for(var key in Object(object))result.push(key);return result}function overRest(func,start,transform){return start=nativeMax(start===undefined?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index0){if(++count>=HOT_COUNT)return arguments[0]}else count=0;return func.apply(undefined,arguments)}}function shuffleSelf(array){for(var index=-1,length=array.length,lastIndex=length-1;++indexsize)return[];for(var index=0,resIndex=0,result=Array(nativeCeil(length/size));length>index;)result[resIndex++]=baseSlice(array,index,index+=size);return result}function compact(array){for(var index=-1,length=array?array.length:0,resIndex=0,result=[];++indexn?0:n,length)):[]}function dropRight(array,n,guard){var length=array?array.length:0;return length?(n=guard||n===undefined?1:toInteger(n),n=length-n,baseSlice(array,0,0>n?0:n)):[]}function dropRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!0,!0):[]}function dropWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!0):[]}function fill(array,value,start,end){var length=array?array.length:0;return length?(start&&"number"!=typeof start&&isIterateeCall(array,value,start)&&(start=0,end=length),baseFill(array,value,start,end)):[]}function findIndex(array,predicate,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=null==fromIndex?0:toInteger(fromIndex);return 0>index&&(index=nativeMax(length+index,0)),baseFindIndex(array,getIteratee(predicate,3),index)}function findLastIndex(array,predicate,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=length-1;return fromIndex!==undefined&&(index=toInteger(fromIndex),index=0>fromIndex?nativeMax(length+index,0):nativeMin(index,length-1)),baseFindIndex(array,getIteratee(predicate,3),index,!0)}function flatten(array){var length=array?array.length:0;return length?baseFlatten(array,1):[]}function flattenDeep(array){var length=array?array.length:0;return length?baseFlatten(array,INFINITY):[]}function flattenDepth(array,depth){var length=array?array.length:0;return length?(depth=depth===undefined?1:toInteger(depth),baseFlatten(array,depth)):[]}function fromPairs(pairs){for(var index=-1,length=pairs?pairs.length:0,result={};++indexindex&&(index=nativeMax(length+index,0)),baseIndexOf(array,value,index)}function initial(array){var length=array?array.length:0;return length?baseSlice(array,0,-1):[]}function join(array,separator){return array?nativeJoin.call(array,separator):""}function last(array){var length=array?array.length:0;return length?array[length-1]:undefined}function lastIndexOf(array,value,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=length;return fromIndex!==undefined&&(index=toInteger(fromIndex),index=0>index?nativeMax(length+index,0):nativeMin(index,length-1)),value===value?strictLastIndexOf(array,value,index):baseFindIndex(array,baseIsNaN,index,!0)}function nth(array,n){return array&&array.length?baseNth(array,toInteger(n)):undefined}function pullAll(array,values){return array&&array.length&&values&&values.length?basePullAll(array,values):array}function pullAllBy(array,values,iteratee){return array&&array.length&&values&&values.length?basePullAll(array,values,getIteratee(iteratee,2)):array}function pullAllWith(array,values,comparator){return array&&array.length&&values&&values.length?basePullAll(array,values,undefined,comparator):array}function remove(array,predicate){var result=[];if(!array||!array.length)return result;var index=-1,indexes=[],length=array.length;for(predicate=getIteratee(predicate,3);++indexindex&&eq(array[index],value))return index}return-1}function sortedLastIndex(array,value){return baseSortedIndex(array,value,!0)}function sortedLastIndexBy(array,value,iteratee){return baseSortedIndexBy(array,value,getIteratee(iteratee,2),!0)}function sortedLastIndexOf(array,value){var length=array?array.length:0;if(length){var index=baseSortedIndex(array,value,!0)-1;if(eq(array[index],value))return index}return-1}function sortedUniq(array){return array&&array.length?baseSortedUniq(array):[]}function sortedUniqBy(array,iteratee){return array&&array.length?baseSortedUniq(array,getIteratee(iteratee,2)):[]}function tail(array){var length=array?array.length:0;return length?baseSlice(array,1,length):[]}function take(array,n,guard){return array&&array.length?(n=guard||n===undefined?1:toInteger(n),baseSlice(array,0,0>n?0:n)):[]}function takeRight(array,n,guard){var length=array?array.length:0;return length?(n=guard||n===undefined?1:toInteger(n),n=length-n,baseSlice(array,0>n?0:n,length)):[]}function takeRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!1,!0):[]}function takeWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3)):[]}function uniq(array){return array&&array.length?baseUniq(array):[]}function uniqBy(array,iteratee){return array&&array.length?baseUniq(array,getIteratee(iteratee,2)):[]}function uniqWith(array,comparator){return array&&array.length?baseUniq(array,undefined,comparator):[]}function unzip(array){if(!array||!array.length)return[];var length=0;return array=arrayFilter(array,function(group){return isArrayLikeObject(group)?(length=nativeMax(group.length,length),!0):void 0}),baseTimes(length,function(index){return arrayMap(array,baseProperty(index))})}function unzipWith(array,iteratee){if(!array||!array.length)return[];var result=unzip(array);return null==iteratee?result:arrayMap(result,function(group){return apply(iteratee,undefined,group)})}function zipObject(props,values){return baseZipObject(props||[],values||[],assignValue)}function zipObjectDeep(props,values){return baseZipObject(props||[],values||[],baseSet)}function chain(value){var result=lodash(value);return result.__chain__=!0,result}function tap(value,interceptor){return interceptor(value),value}function thru(value,interceptor){return interceptor(value)}function wrapperChain(){return chain(this)}function wrapperCommit(){return new LodashWrapper(this.value(),this.__chain__)}function wrapperNext(){this.__values__===undefined&&(this.__values__=toArray(this.value()));var done=this.__index__>=this.__values__.length,value=done?undefined:this.__values__[this.__index__++];return{done:done,value:value}}function wrapperToIterator(){return this}function wrapperPlant(value){for(var result,parent=this;parent instanceof baseLodash;){var clone=wrapperClone(parent);clone.__index__=0,clone.__values__=undefined,result?previous.__wrapped__=clone:result=clone;var previous=clone;parent=parent.__wrapped__}return previous.__wrapped__=value,result}function wrapperReverse(){var value=this.__wrapped__;if(value instanceof LazyWrapper){var wrapped=value;return this.__actions__.length&&(wrapped=new LazyWrapper(this)),wrapped=wrapped.reverse(),wrapped.__actions__.push({func:thru,args:[reverse],thisArg:undefined}),new LodashWrapper(wrapped,this.__chain__)}return this.thru(reverse)}function wrapperValue(){return baseWrapperValue(this.__wrapped__,this.__actions__)}function every(collection,predicate,guard){var func=isArray(collection)?arrayEvery:baseEvery;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=undefined),func(collection,getIteratee(predicate,3))}function filter(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,getIteratee(predicate,3))}function flatMap(collection,iteratee){return baseFlatten(map(collection,iteratee),1)}function flatMapDeep(collection,iteratee){return baseFlatten(map(collection,iteratee),INFINITY)}function flatMapDepth(collection,iteratee,depth){return depth=depth===undefined?1:toInteger(depth),baseFlatten(map(collection,iteratee),depth)}function forEach(collection,iteratee){var func=isArray(collection)?arrayEach:baseEach;return func(collection,getIteratee(iteratee,3))}function forEachRight(collection,iteratee){var func=isArray(collection)?arrayEachRight:baseEachRight;return func(collection,getIteratee(iteratee,3))}function includes(collection,value,fromIndex,guard){collection=isArrayLike(collection)?collection:values(collection),fromIndex=fromIndex&&!guard?toInteger(fromIndex):0;var length=collection.length;return 0>fromIndex&&(fromIndex=nativeMax(length+fromIndex,0)),isString(collection)?length>=fromIndex&&collection.indexOf(value,fromIndex)>-1:!!length&&baseIndexOf(collection,value,fromIndex)>-1}function map(collection,iteratee){var func=isArray(collection)?arrayMap:baseMap;return func(collection,getIteratee(iteratee,3))}function orderBy(collection,iteratees,orders,guard){return null==collection?[]:(isArray(iteratees)||(iteratees=null==iteratees?[]:[iteratees]),orders=guard?undefined:orders,isArray(orders)||(orders=null==orders?[]:[orders]),baseOrderBy(collection,iteratees,orders))}function reduce(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduce:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEach)}function reduceRight(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduceRight:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEachRight)}function reject(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,negate(getIteratee(predicate,3)))}function sample(collection){return arraySample(isArrayLike(collection)?collection:values(collection))}function sampleSize(collection,n,guard){return n=(guard?isIterateeCall(collection,n,guard):n===undefined)?1:toInteger(n),arraySampleSize(isArrayLike(collection)?collection:values(collection),n)}function shuffle(collection){return shuffleSelf(isArrayLike(collection)?copyArray(collection):values(collection))}function size(collection){if(null==collection)return 0;if(isArrayLike(collection))return isString(collection)?stringSize(collection):collection.length;var tag=getTag(collection);return tag==mapTag||tag==setTag?collection.size:baseKeys(collection).length}function some(collection,predicate,guard){var func=isArray(collection)?arraySome:baseSome;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=undefined),func(collection,getIteratee(predicate,3))}function after(n,func){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return n=toInteger(n),function(){return--n<1?func.apply(this,arguments):void 0}}function ary(func,n,guard){return n=guard?undefined:n,n=func&&null==n?func.length:n,createWrap(func,ARY_FLAG,undefined,undefined,undefined,undefined,n)}function before(n,func){var result;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return n=toInteger(n),function(){return--n>0&&(result=func.apply(this,arguments)),1>=n&&(func=undefined),result}}function curry(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,CURRY_FLAG,undefined,undefined,undefined,undefined,undefined,arity);return result.placeholder=curry.placeholder,result}function curryRight(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,CURRY_RIGHT_FLAG,undefined,undefined,undefined,undefined,undefined,arity);return result.placeholder=curryRight.placeholder,result}function debounce(func,wait,options){function invokeFunc(time){var args=lastArgs,thisArg=lastThis;return lastArgs=lastThis=undefined,lastInvokeTime=time,result=func.apply(thisArg,args)}function leadingEdge(time){return lastInvokeTime=time,timerId=setTimeout(timerExpired,wait),leading?invokeFunc(time):result}function remainingWait(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime,result=wait-timeSinceLastCall;return maxing?nativeMin(result,maxWait-timeSinceLastInvoke):result}function shouldInvoke(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime;return lastCallTime===undefined||timeSinceLastCall>=wait||0>timeSinceLastCall||maxing&&timeSinceLastInvoke>=maxWait}function timerExpired(){var time=now();return shouldInvoke(time)?trailingEdge(time):void(timerId=setTimeout(timerExpired,remainingWait(time)))}function trailingEdge(time){return timerId=undefined,trailing&&lastArgs?invokeFunc(time):(lastArgs=lastThis=undefined,result)}function cancel(){timerId!==undefined&&clearTimeout(timerId),lastInvokeTime=0,lastArgs=lastCallTime=lastThis=timerId=undefined}function flush(){return timerId===undefined?result:trailingEdge(now())}function debounced(){var time=now(),isInvoking=shouldInvoke(time);if(lastArgs=arguments,lastThis=this,lastCallTime=time,isInvoking){if(timerId===undefined)return leadingEdge(lastCallTime);if(maxing)return timerId=setTimeout(timerExpired,wait),invokeFunc(lastCallTime)}return timerId===undefined&&(timerId=setTimeout(timerExpired,wait)),result}var lastArgs,lastThis,maxWait,result,timerId,lastCallTime,lastInvokeTime=0,leading=!1,maxing=!1,trailing=!0;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return wait=toNumber(wait)||0,isObject(options)&&(leading=!!options.leading,maxing="maxWait"in options,maxWait=maxing?nativeMax(toNumber(options.maxWait)||0,wait):maxWait,trailing="trailing"in options?!!options.trailing:trailing),debounced.cancel=cancel,debounced.flush=flush,debounced}function flip(func){return createWrap(func,FLIP_FLAG)}function memoize(func,resolver){if("function"!=typeof func||resolver&&"function"!=typeof resolver)throw new TypeError(FUNC_ERROR_TEXT);var memoized=function(){var args=arguments,key=resolver?resolver.apply(this,args):args[0],cache=memoized.cache;if(cache.has(key))return cache.get(key);var result=func.apply(this,args);return memoized.cache=cache.set(key,result)||cache,result};return memoized.cache=new(memoize.Cache||MapCache),memoized}function negate(predicate){if("function"!=typeof predicate)throw new TypeError(FUNC_ERROR_TEXT);return function(){var args=arguments;switch(args.length){case 0:return!predicate.call(this);case 1:return!predicate.call(this,args[0]);case 2:return!predicate.call(this,args[0],args[1]);case 3:return!predicate.call(this,args[0],args[1],args[2])}return!predicate.apply(this,args)}}function once(func){return before(2,func)}function rest(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=start===undefined?start:toInteger(start),baseRest(func,start)}function spread(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=start===undefined?0:nativeMax(toInteger(start),0),baseRest(function(args){var array=args[start],otherArgs=castSlice(args,0,start);return array&&arrayPush(otherArgs,array),apply(func,this,otherArgs)})}function throttle(func,wait,options){var leading=!0,trailing=!0;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return isObject(options)&&(leading="leading"in options?!!options.leading:leading,trailing="trailing"in options?!!options.trailing:trailing),debounce(func,wait,{leading:leading,maxWait:wait,trailing:trailing})}function unary(func){return ary(func,1)}function wrap(value,wrapper){return wrapper=null==wrapper?identity:wrapper,partial(wrapper,value)}function castArray(){if(!arguments.length)return[];var value=arguments[0];return isArray(value)?value:[value]}function clone(value){return baseClone(value,!1,!0)}function cloneWith(value,customizer){return baseClone(value,!1,!0,customizer)}function cloneDeep(value){return baseClone(value,!0,!0)}function cloneDeepWith(value,customizer){return baseClone(value,!0,!0,customizer)}function conformsTo(object,source){return null==source||baseConformsTo(object,source,keys(source))}function eq(value,other){return value===other||value!==value&&other!==other}function isArguments(value){return isArrayLikeObject(value)&&hasOwnProperty.call(value,"callee")&&(!propertyIsEnumerable.call(value,"callee")||objectToString.call(value)==argsTag)}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value)}function isBoolean(value){return value===!0||value===!1||isObjectLike(value)&&objectToString.call(value)==boolTag}function isElement(value){return null!=value&&1===value.nodeType&&isObjectLike(value)&&!isPlainObject(value)}function isEmpty(value){if(isArrayLike(value)&&(isArray(value)||"string"==typeof value||"function"==typeof value.splice||isBuffer(value)||isArguments(value)))return!value.length;var tag=getTag(value);if(tag==mapTag||tag==setTag)return!value.size;if(isPrototype(value))return!nativeKeys(value).length;for(var key in value)if(hasOwnProperty.call(value,key))return!1;return!0}function isEqual(value,other){return baseIsEqual(value,other)}function isEqualWith(value,other,customizer){customizer="function"==typeof customizer?customizer:undefined;var result=customizer?customizer(value,other):undefined;return result===undefined?baseIsEqual(value,other,customizer):!!result}function isError(value){return isObjectLike(value)?objectToString.call(value)==errorTag||"string"==typeof value.message&&"string"==typeof value.name:!1}function isFinite(value){return"number"==typeof value&&nativeIsFinite(value)}function isFunction(value){var tag=isObject(value)?objectToString.call(value):"";return tag==funcTag||tag==genTag}function isInteger(value){return"number"==typeof value&&value==toInteger(value)}function isLength(value){return"number"==typeof value&&value>-1&&value%1==0&&MAX_SAFE_INTEGER>=value}function isObject(value){var type=typeof value;return null!=value&&("object"==type||"function"==type)}function isObjectLike(value){return null!=value&&"object"==typeof value}function isMatch(object,source){return object===source||baseIsMatch(object,source,getMatchData(source))}function isMatchWith(object,source,customizer){return customizer="function"==typeof customizer?customizer:undefined,baseIsMatch(object,source,getMatchData(source),customizer)}function isNaN(value){return isNumber(value)&&value!=+value}function isNative(value){if(isMaskable(value))throw new Error("This method is not supported with core-js. Try https://github.com/es-shims.");return baseIsNative(value)}function isNull(value){return null===value}function isNil(value){return null==value}function isNumber(value){return"number"==typeof value||isObjectLike(value)&&objectToString.call(value)==numberTag}function isPlainObject(value){if(!isObjectLike(value)||objectToString.call(value)!=objectTag)return!1;var proto=getPrototype(value);if(null===proto)return!0;var Ctor=hasOwnProperty.call(proto,"constructor")&&proto.constructor;return"function"==typeof Ctor&&Ctor instanceof Ctor&&funcToString.call(Ctor)==objectCtorString}function isSafeInteger(value){return isInteger(value)&&value>=-MAX_SAFE_INTEGER&&MAX_SAFE_INTEGER>=value}function isString(value){return"string"==typeof value||!isArray(value)&&isObjectLike(value)&&objectToString.call(value)==stringTag}function isSymbol(value){return"symbol"==typeof value||isObjectLike(value)&&objectToString.call(value)==symbolTag}function isUndefined(value){return value===undefined}function isWeakMap(value){return isObjectLike(value)&&getTag(value)==weakMapTag}function isWeakSet(value){return isObjectLike(value)&&objectToString.call(value)==weakSetTag}function toArray(value){if(!value)return[];if(isArrayLike(value))return isString(value)?stringToArray(value):copyArray(value);if(iteratorSymbol&&value[iteratorSymbol])return iteratorToArray(value[iteratorSymbol]());var tag=getTag(value),func=tag==mapTag?mapToArray:tag==setTag?setToArray:values;return func(value)}function toFinite(value){if(!value)return 0===value?value:0;if(value=toNumber(value),value===INFINITY||value===-INFINITY){var sign=0>value?-1:1;return sign*MAX_INTEGER}return value===value?value:0}function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0}function toLength(value){return value?baseClamp(toInteger(value),0,MAX_ARRAY_LENGTH):0}function toNumber(value){if("number"==typeof value)return value;if(isSymbol(value))return NAN;if(isObject(value)){var other="function"==typeof value.valueOf?value.valueOf():value;value=isObject(other)?other+"":other}if("string"!=typeof value)return 0===value?value:+value;value=value.replace(reTrim,"");var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value}function toPlainObject(value){return copyObject(value,keysIn(value))}function toSafeInteger(value){return baseClamp(toInteger(value),-MAX_SAFE_INTEGER,MAX_SAFE_INTEGER)}function toString(value){return null==value?"":baseToString(value)}function create(prototype,properties){var result=baseCreate(prototype);return properties?baseAssign(result,properties):result}function findKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwn)}function findLastKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwnRight)}function forIn(object,iteratee){return null==object?object:baseFor(object,getIteratee(iteratee,3),keysIn)}function forInRight(object,iteratee){return null==object?object:baseForRight(object,getIteratee(iteratee,3),keysIn)}function forOwn(object,iteratee){return object&&baseForOwn(object,getIteratee(iteratee,3))}function forOwnRight(object,iteratee){return object&&baseForOwnRight(object,getIteratee(iteratee,3))}function functions(object){return null==object?[]:baseFunctions(object,keys(object))}function functionsIn(object){return null==object?[]:baseFunctions(object,keysIn(object))}function get(object,path,defaultValue){var result=null==object?undefined:baseGet(object,path);return result===undefined?defaultValue:result}function has(object,path){return null!=object&&hasPath(object,path,baseHas)}function hasIn(object,path){return null!=object&&hasPath(object,path,baseHasIn)}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function keysIn(object){return isArrayLike(object)?arrayLikeKeys(object,!0):baseKeysIn(object)}function mapKeys(object,iteratee){var result={};return iteratee=getIteratee(iteratee,3),baseForOwn(object,function(value,key,object){baseAssignValue(result,iteratee(value,key,object),value)}),result}function mapValues(object,iteratee){var result={};return iteratee=getIteratee(iteratee,3),baseForOwn(object,function(value,key,object){baseAssignValue(result,key,iteratee(value,key,object))}),result}function omitBy(object,predicate){return pickBy(object,negate(getIteratee(predicate)))}function pickBy(object,predicate){return null==object?{}:basePickBy(object,getAllKeysIn(object),getIteratee(predicate))}function result(object,path,defaultValue){path=isKey(path,object)?[path]:castPath(path);var index=-1,length=path.length;for(length||(object=undefined,length=1);++indexupper){var temp=lower;lower=upper,upper=temp}if(floating||lower%1||upper%1){var rand=nativeRandom();return nativeMin(lower+rand*(upper-lower+freeParseFloat("1e-"+((rand+"").length-1))),upper)}return baseRandom(lower,upper)}function capitalize(string){return upperFirst(toString(string).toLowerCase())}function deburr(string){return string=toString(string),string&&string.replace(reLatin,deburrLetter).replace(reComboMark,"")}function endsWith(string,target,position){string=toString(string),target=baseToString(target);var length=string.length;position=position===undefined?length:baseClamp(toInteger(position),0,length);var end=position;return position-=target.length,position>=0&&string.slice(position,end)==target}function escape(string){return string=toString(string),string&&reHasUnescapedHtml.test(string)?string.replace(reUnescapedHtml,escapeHtmlChar):string}function escapeRegExp(string){return string=toString(string),string&&reHasRegExpChar.test(string)?string.replace(reRegExpChar,"\\$&"):string}function pad(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;if(!length||strLength>=length)return string;var mid=(length-strLength)/2;return createPadding(nativeFloor(mid),chars)+string+createPadding(nativeCeil(mid),chars)}function padEnd(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;return length&&length>strLength?string+createPadding(length-strLength,chars):string}function padStart(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;return length&&length>strLength?createPadding(length-strLength,chars)+string:string}function parseInt(string,radix,guard){return guard||null==radix?radix=0:radix&&(radix=+radix),nativeParseInt(toString(string),radix||0)}function repeat(string,n,guard){return n=(guard?isIterateeCall(string,n,guard):n===undefined)?1:toInteger(n),baseRepeat(toString(string),n)}function replace(){var args=arguments,string=toString(args[0]);return args.length<3?string:string.replace(args[1],args[2])}function split(string,separator,limit){return limit&&"number"!=typeof limit&&isIterateeCall(string,separator,limit)&&(separator=limit=undefined),(limit=limit===undefined?MAX_ARRAY_LENGTH:limit>>>0)?(string=toString(string),string&&("string"==typeof separator||null!=separator&&!isRegExp(separator))&&(separator=baseToString(separator),!separator&&hasUnicode(string))?castSlice(stringToArray(string),0,limit):string.split(separator,limit)):[]}function startsWith(string,target,position){return string=toString(string),position=baseClamp(toInteger(position),0,string.length),target=baseToString(target),string.slice(position,position+target.length)==target}function template(string,options,guard){var settings=lodash.templateSettings;guard&&isIterateeCall(string,options,guard)&&(options=undefined),string=toString(string),options=assignInWith({},options,settings,assignInDefaults);var isEscaping,isEvaluating,imports=assignInWith({},options.imports,settings.imports,assignInDefaults),importsKeys=keys(imports),importsValues=baseValues(imports,importsKeys),index=0,interpolate=options.interpolate||reNoMatch,source="__p += '",reDelimiters=RegExp((options.escape||reNoMatch).source+"|"+interpolate.source+"|"+(interpolate===reInterpolate?reEsTemplate:reNoMatch).source+"|"+(options.evaluate||reNoMatch).source+"|$","g"),sourceURL="//# sourceURL="+("sourceURL"in options?options.sourceURL:"lodash.templateSources["+ ++templateCounter+"]")+"\n";string.replace(reDelimiters,function(match,escapeValue,interpolateValue,esTemplateValue,evaluateValue,offset){return interpolateValue||(interpolateValue=esTemplateValue),source+=string.slice(index,offset).replace(reUnescapedString,escapeStringChar),escapeValue&&(isEscaping=!0,source+="' +\n__e("+escapeValue+") +\n'"),evaluateValue&&(isEvaluating=!0,source+="';\n"+evaluateValue+";\n__p += '"),interpolateValue&&(source+="' +\n((__t = ("+interpolateValue+")) == null ? '' : __t) +\n'"),index=offset+match.length,match}),source+="';\n";var variable=options.variable;variable||(source="with (obj) {\n"+source+"\n}\n"),source=(isEvaluating?source.replace(reEmptyStringLeading,""):source).replace(reEmptyStringMiddle,"$1").replace(reEmptyStringTrailing,"$1;"),source="function("+(variable||"obj")+") {\n"+(variable?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(isEscaping?", __e = _.escape":"")+(isEvaluating?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+source+"return __p\n}";var result=attempt(function(){return Function(importsKeys,sourceURL+"return "+source).apply(undefined,importsValues)});if(result.source=source,isError(result))throw result;return result}function toLower(value){return toString(value).toLowerCase()}function toUpper(value){return toString(value).toUpperCase()}function trim(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrim,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),chrSymbols=stringToArray(chars),start=charsStartIndex(strSymbols,chrSymbols),end=charsEndIndex(strSymbols,chrSymbols)+1;return castSlice(strSymbols,start,end).join("")}function trimEnd(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrimEnd,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),end=charsEndIndex(strSymbols,stringToArray(chars))+1;return castSlice(strSymbols,0,end).join("")}function trimStart(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrimStart,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),start=charsStartIndex(strSymbols,stringToArray(chars));return castSlice(strSymbols,start).join("")}function truncate(string,options){var length=DEFAULT_TRUNC_LENGTH,omission=DEFAULT_TRUNC_OMISSION;if(isObject(options)){var separator="separator"in options?options.separator:separator;length="length"in options?toInteger(options.length):length,omission="omission"in options?baseToString(options.omission):omission}string=toString(string);var strLength=string.length;if(hasUnicode(string)){var strSymbols=stringToArray(string);strLength=strSymbols.length}if(length>=strLength)return string;var end=length-stringSize(omission);if(1>end)return omission;var result=strSymbols?castSlice(strSymbols,0,end).join(""):string.slice(0,end);if(separator===undefined)return result+omission;if(strSymbols&&(end+=result.length-end),isRegExp(separator)){if(string.slice(end).search(separator)){var match,substring=result;for(separator.global||(separator=RegExp(separator.source,toString(reFlags.exec(separator))+"g")),separator.lastIndex=0;match=separator.exec(substring);)var newEnd=match.index;result=result.slice(0,newEnd===undefined?end:newEnd)}}else if(string.indexOf(baseToString(separator),end)!=end){var index=result.lastIndexOf(separator);index>-1&&(result=result.slice(0,index))}return result+omission}function unescape(string){return string=toString(string),string&&reHasEscapedHtml.test(string)?string.replace(reEscapedHtml,unescapeHtmlChar):string}function words(string,pattern,guard){return string=toString(string),pattern=guard?undefined:pattern,pattern===undefined?hasUnicodeWord(string)?unicodeWords(string):asciiWords(string):string.match(pattern)||[]}function cond(pairs){var length=pairs?pairs.length:0,toIteratee=getIteratee();return pairs=length?arrayMap(pairs,function(pair){if("function"!=typeof pair[1])throw new TypeError(FUNC_ERROR_TEXT);return[toIteratee(pair[0]),pair[1]]}):[],baseRest(function(args){for(var index=-1;++indexn||n>MAX_SAFE_INTEGER)return[];var index=MAX_ARRAY_LENGTH,length=nativeMin(n,MAX_ARRAY_LENGTH);iteratee=getIteratee(iteratee),n-=MAX_ARRAY_LENGTH;for(var result=baseTimes(length,iteratee);++index1?arrays[length-1]:undefined;return iteratee="function"==typeof iteratee?(arrays.pop(),iteratee):undefined,unzipWith(arrays,iteratee)}),wrapperAt=flatRest(function(paths){var length=paths.length,start=length?paths[0]:0,value=this.__wrapped__,interceptor=function(object){return baseAt(object,paths)};return!(length>1||this.__actions__.length)&&value instanceof LazyWrapper&&isIndex(start)?(value=value.slice(start,+start+(length?1:0)),value.__actions__.push({func:thru,args:[interceptor],thisArg:undefined}),new LodashWrapper(value,this.__chain__).thru(function(array){return length&&!array.length&&array.push(undefined),array})):this.thru(interceptor)}),countBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?++result[key]:baseAssignValue(result,key,1)}),find=createFind(findIndex),findLast=createFind(findLastIndex),groupBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?result[key].push(value):baseAssignValue(result,key,[value])}),invokeMap=baseRest(function(collection,path,args){var index=-1,isFunc="function"==typeof path,isProp=isKey(path),result=isArrayLike(collection)?Array(collection.length):[];return baseEach(collection,function(value){var func=isFunc?path:isProp&&null!=value?value[path]:undefined;result[++index]=func?apply(func,value,args):baseInvoke(value,path,args)}),result}),keyBy=createAggregator(function(result,value,key){baseAssignValue(result,key,value)}),partition=createAggregator(function(result,value,key){result[key?0:1].push(value)},function(){return[[],[]]}),sortBy=baseRest(function(collection,iteratees){if(null==collection)return[];var length=iteratees.length;return length>1&&isIterateeCall(collection,iteratees[0],iteratees[1])?iteratees=[]:length>2&&isIterateeCall(iteratees[0],iteratees[1],iteratees[2])&&(iteratees=[iteratees[0]]),baseOrderBy(collection,baseFlatten(iteratees,1),[])}),now=ctxNow||function(){return root.Date.now()},bind=baseRest(function(func,thisArg,partials){var bitmask=BIND_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bind));bitmask|=PARTIAL_FLAG}return createWrap(func,bitmask,thisArg,partials,holders)}),bindKey=baseRest(function(object,key,partials){var bitmask=BIND_FLAG|BIND_KEY_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bindKey));bitmask|=PARTIAL_FLAG}return createWrap(key,bitmask,object,partials,holders)}),defer=baseRest(function(func,args){return baseDelay(func,1,args)}),delay=baseRest(function(func,wait,args){return baseDelay(func,toNumber(wait)||0,args)});memoize.Cache=MapCache;var overArgs=castRest(function(func,transforms){transforms=1==transforms.length&&isArray(transforms[0])?arrayMap(transforms[0],baseUnary(getIteratee())):arrayMap(baseFlatten(transforms,1),baseUnary(getIteratee()));var funcsLength=transforms.length;return baseRest(function(args){for(var index=-1,length=nativeMin(args.length,funcsLength);++index=other}),isArray=Array.isArray,isArrayBuffer=nodeIsArrayBuffer?baseUnary(nodeIsArrayBuffer):baseIsArrayBuffer,isBuffer=nativeIsBuffer||stubFalse,isDate=nodeIsDate?baseUnary(nodeIsDate):baseIsDate,isMap=nodeIsMap?baseUnary(nodeIsMap):baseIsMap,isRegExp=nodeIsRegExp?baseUnary(nodeIsRegExp):baseIsRegExp,isSet=nodeIsSet?baseUnary(nodeIsSet):baseIsSet,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray,lt=createRelationalOperation(baseLt),lte=createRelationalOperation(function(value,other){return other>=value}),assign=createAssigner(function(object,source){if(isPrototype(source)||isArrayLike(source))return void copyObject(source,keys(source),object);for(var key in source)hasOwnProperty.call(source,key)&&assignValue(object,key,source[key])}),assignIn=createAssigner(function(object,source){copyObject(source,keysIn(source),object)}),assignInWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keysIn(source),object,customizer)}),assignWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keys(source),object,customizer)}),at=flatRest(baseAt),defaults=baseRest(function(args){return args.push(undefined,assignInDefaults),apply(assignInWith,undefined,args)}),defaultsDeep=baseRest(function(args){return args.push(undefined,mergeDefaults),apply(mergeWith,undefined,args)}),invert=createInverter(function(result,value,key){result[value]=key},constant(identity)),invertBy=createInverter(function(result,value,key){hasOwnProperty.call(result,value)?result[value].push(key):result[value]=[key]},getIteratee),invoke=baseRest(baseInvoke),merge=createAssigner(function(object,source,srcIndex){baseMerge(object,source,srcIndex)}),mergeWith=createAssigner(function(object,source,srcIndex,customizer){baseMerge(object,source,srcIndex,customizer)}),omit=flatRest(function(object,props){return null==object?{}:(props=arrayMap(props,toKey),basePick(object,baseDifference(getAllKeysIn(object),props)))}),pick=flatRest(function(object,props){return null==object?{}:basePick(object,arrayMap(props,toKey))}),toPairs=createToPairs(keys),toPairsIn=createToPairs(keysIn),camelCase=createCompounder(function(result,word,index){return word=word.toLowerCase(),result+(index?capitalize(word):word)}),kebabCase=createCompounder(function(result,word,index){return result+(index?"-":"")+word.toLowerCase()}),lowerCase=createCompounder(function(result,word,index){return result+(index?" ":"")+word.toLowerCase()}),lowerFirst=createCaseFirst("toLowerCase"),snakeCase=createCompounder(function(result,word,index){return result+(index?"_":"")+word.toLowerCase()}),startCase=createCompounder(function(result,word,index){return result+(index?" ":"")+upperFirst(word)}),upperCase=createCompounder(function(result,word,index){return result+(index?" ":"")+word.toUpperCase()}),upperFirst=createCaseFirst("toUpperCase"),attempt=baseRest(function(func,args){try{return apply(func,undefined,args)}catch(e){return isError(e)?e:new Error(e)}}),bindAll=flatRest(function(object,methodNames){return arrayEach(methodNames,function(key){key=toKey(key),baseAssignValue(object,key,bind(object[key],object))}),object}),flow=createFlow(),flowRight=createFlow(!0),method=baseRest(function(path,args){return function(object){return baseInvoke(object,path,args)}}),methodOf=baseRest(function(object,args){return function(path){return baseInvoke(object,path,args)}}),over=createOver(arrayMap),overEvery=createOver(arrayEvery),overSome=createOver(arraySome),range=createRange(),rangeRight=createRange(!0),add=createMathOperation(function(augend,addend){return augend+addend},0),ceil=createRound("ceil"),divide=createMathOperation(function(dividend,divisor){return dividend/divisor},1),floor=createRound("floor"),multiply=createMathOperation(function(multiplier,multiplicand){return multiplier*multiplicand},1),round=createRound("round"),subtract=createMathOperation(function(minuend,subtrahend){return minuend-subtrahend},0);return lodash.after=after,lodash.ary=ary,lodash.assign=assign,lodash.assignIn=assignIn,lodash.assignInWith=assignInWith,lodash.assignWith=assignWith,lodash.at=at,lodash.before=before,lodash.bind=bind,lodash.bindAll=bindAll,lodash.bindKey=bindKey,lodash.castArray=castArray,lodash.chain=chain,lodash.chunk=chunk,lodash.compact=compact,lodash.concat=concat,lodash.cond=cond,lodash.conforms=conforms,lodash.constant=constant,lodash.countBy=countBy,lodash.create=create,lodash.curry=curry,lodash.curryRight=curryRight,lodash.debounce=debounce,lodash.defaults=defaults,lodash.defaultsDeep=defaultsDeep,lodash.defer=defer,lodash.delay=delay,lodash.difference=difference,lodash.differenceBy=differenceBy,lodash.differenceWith=differenceWith,lodash.drop=drop,lodash.dropRight=dropRight,lodash.dropRightWhile=dropRightWhile,lodash.dropWhile=dropWhile,lodash.fill=fill,lodash.filter=filter,lodash.flatMap=flatMap,lodash.flatMapDeep=flatMapDeep,lodash.flatMapDepth=flatMapDepth,lodash.flatten=flatten,lodash.flattenDeep=flattenDeep,lodash.flattenDepth=flattenDepth,lodash.flip=flip,lodash.flow=flow,lodash.flowRight=flowRight,lodash.fromPairs=fromPairs,lodash.functions=functions,lodash.functionsIn=functionsIn,lodash.groupBy=groupBy,lodash.initial=initial,lodash.intersection=intersection,lodash.intersectionBy=intersectionBy,lodash.intersectionWith=intersectionWith,lodash.invert=invert,lodash.invertBy=invertBy,lodash.invokeMap=invokeMap,lodash.iteratee=iteratee,lodash.keyBy=keyBy,lodash.keys=keys,lodash.keysIn=keysIn,lodash.map=map,lodash.mapKeys=mapKeys,lodash.mapValues=mapValues,lodash.matches=matches,lodash.matchesProperty=matchesProperty,lodash.memoize=memoize,lodash.merge=merge,lodash.mergeWith=mergeWith,lodash.method=method,lodash.methodOf=methodOf,lodash.mixin=mixin,lodash.negate=negate,lodash.nthArg=nthArg,lodash.omit=omit,lodash.omitBy=omitBy,lodash.once=once,lodash.orderBy=orderBy,lodash.over=over,lodash.overArgs=overArgs,lodash.overEvery=overEvery,lodash.overSome=overSome,lodash.partial=partial,lodash.partialRight=partialRight,lodash.partition=partition,lodash.pick=pick,lodash.pickBy=pickBy,lodash.property=property,lodash.propertyOf=propertyOf,lodash.pull=pull,lodash.pullAll=pullAll,lodash.pullAllBy=pullAllBy,lodash.pullAllWith=pullAllWith,lodash.pullAt=pullAt,lodash.range=range,lodash.rangeRight=rangeRight,lodash.rearg=rearg,lodash.reject=reject,lodash.remove=remove,lodash.rest=rest,lodash.reverse=reverse,lodash.sampleSize=sampleSize,lodash.set=set,lodash.setWith=setWith,lodash.shuffle=shuffle,lodash.slice=slice,lodash.sortBy=sortBy,lodash.sortedUniq=sortedUniq,lodash.sortedUniqBy=sortedUniqBy,lodash.split=split,lodash.spread=spread,lodash.tail=tail,lodash.take=take,lodash.takeRight=takeRight,lodash.takeRightWhile=takeRightWhile,lodash.takeWhile=takeWhile,lodash.tap=tap,lodash.throttle=throttle,lodash.thru=thru,lodash.toArray=toArray,lodash.toPairs=toPairs,lodash.toPairsIn=toPairsIn,lodash.toPath=toPath,lodash.toPlainObject=toPlainObject,lodash.transform=transform,lodash.unary=unary,lodash.union=union,lodash.unionBy=unionBy,lodash.unionWith=unionWith,lodash.uniq=uniq,lodash.uniqBy=uniqBy,lodash.uniqWith=uniqWith,lodash.unset=unset,lodash.unzip=unzip,lodash.unzipWith=unzipWith,lodash.update=update,lodash.updateWith=updateWith,lodash.values=values,lodash.valuesIn=valuesIn,lodash.without=without,lodash.words=words,lodash.wrap=wrap,lodash.xor=xor,lodash.xorBy=xorBy,lodash.xorWith=xorWith,lodash.zip=zip,lodash.zipObject=zipObject,lodash.zipObjectDeep=zipObjectDeep,lodash.zipWith=zipWith,lodash.entries=toPairs,lodash.entriesIn=toPairsIn,lodash.extend=assignIn,lodash.extendWith=assignInWith,mixin(lodash,lodash),lodash.add=add,lodash.attempt=attempt,lodash.camelCase=camelCase,lodash.capitalize=capitalize,lodash.ceil=ceil,lodash.clamp=clamp,lodash.clone=clone,lodash.cloneDeep=cloneDeep,lodash.cloneDeepWith=cloneDeepWith,lodash.cloneWith=cloneWith,lodash.conformsTo=conformsTo,lodash.deburr=deburr,lodash.defaultTo=defaultTo,lodash.divide=divide,lodash.endsWith=endsWith,lodash.eq=eq,lodash.escape=escape,lodash.escapeRegExp=escapeRegExp,lodash.every=every,lodash.find=find,lodash.findIndex=findIndex,lodash.findKey=findKey,lodash.findLast=findLast,lodash.findLastIndex=findLastIndex,lodash.findLastKey=findLastKey,lodash.floor=floor,lodash.forEach=forEach,lodash.forEachRight=forEachRight,lodash.forIn=forIn,lodash.forInRight=forInRight,lodash.forOwn=forOwn,lodash.forOwnRight=forOwnRight,lodash.get=get,lodash.gt=gt, -lodash.gte=gte,lodash.has=has,lodash.hasIn=hasIn,lodash.head=head,lodash.identity=identity,lodash.includes=includes,lodash.indexOf=indexOf,lodash.inRange=inRange,lodash.invoke=invoke,lodash.isArguments=isArguments,lodash.isArray=isArray,lodash.isArrayBuffer=isArrayBuffer,lodash.isArrayLike=isArrayLike,lodash.isArrayLikeObject=isArrayLikeObject,lodash.isBoolean=isBoolean,lodash.isBuffer=isBuffer,lodash.isDate=isDate,lodash.isElement=isElement,lodash.isEmpty=isEmpty,lodash.isEqual=isEqual,lodash.isEqualWith=isEqualWith,lodash.isError=isError,lodash.isFinite=isFinite,lodash.isFunction=isFunction,lodash.isInteger=isInteger,lodash.isLength=isLength,lodash.isMap=isMap,lodash.isMatch=isMatch,lodash.isMatchWith=isMatchWith,lodash.isNaN=isNaN,lodash.isNative=isNative,lodash.isNil=isNil,lodash.isNull=isNull,lodash.isNumber=isNumber,lodash.isObject=isObject,lodash.isObjectLike=isObjectLike,lodash.isPlainObject=isPlainObject,lodash.isRegExp=isRegExp,lodash.isSafeInteger=isSafeInteger,lodash.isSet=isSet,lodash.isString=isString,lodash.isSymbol=isSymbol,lodash.isTypedArray=isTypedArray,lodash.isUndefined=isUndefined,lodash.isWeakMap=isWeakMap,lodash.isWeakSet=isWeakSet,lodash.join=join,lodash.kebabCase=kebabCase,lodash.last=last,lodash.lastIndexOf=lastIndexOf,lodash.lowerCase=lowerCase,lodash.lowerFirst=lowerFirst,lodash.lt=lt,lodash.lte=lte,lodash.max=max,lodash.maxBy=maxBy,lodash.mean=mean,lodash.meanBy=meanBy,lodash.min=min,lodash.minBy=minBy,lodash.stubArray=stubArray,lodash.stubFalse=stubFalse,lodash.stubObject=stubObject,lodash.stubString=stubString,lodash.stubTrue=stubTrue,lodash.multiply=multiply,lodash.nth=nth,lodash.noConflict=noConflict,lodash.noop=noop,lodash.now=now,lodash.pad=pad,lodash.padEnd=padEnd,lodash.padStart=padStart,lodash.parseInt=parseInt,lodash.random=random,lodash.reduce=reduce,lodash.reduceRight=reduceRight,lodash.repeat=repeat,lodash.replace=replace,lodash.result=result,lodash.round=round,lodash.runInContext=runInContext,lodash.sample=sample,lodash.size=size,lodash.snakeCase=snakeCase,lodash.some=some,lodash.sortedIndex=sortedIndex,lodash.sortedIndexBy=sortedIndexBy,lodash.sortedIndexOf=sortedIndexOf,lodash.sortedLastIndex=sortedLastIndex,lodash.sortedLastIndexBy=sortedLastIndexBy,lodash.sortedLastIndexOf=sortedLastIndexOf,lodash.startCase=startCase,lodash.startsWith=startsWith,lodash.subtract=subtract,lodash.sum=sum,lodash.sumBy=sumBy,lodash.template=template,lodash.times=times,lodash.toFinite=toFinite,lodash.toInteger=toInteger,lodash.toLength=toLength,lodash.toLower=toLower,lodash.toNumber=toNumber,lodash.toSafeInteger=toSafeInteger,lodash.toString=toString,lodash.toUpper=toUpper,lodash.trim=trim,lodash.trimEnd=trimEnd,lodash.trimStart=trimStart,lodash.truncate=truncate,lodash.unescape=unescape,lodash.uniqueId=uniqueId,lodash.upperCase=upperCase,lodash.upperFirst=upperFirst,lodash.each=forEach,lodash.eachRight=forEachRight,lodash.first=head,mixin(lodash,function(){var source={};return baseForOwn(lodash,function(func,methodName){hasOwnProperty.call(lodash.prototype,methodName)||(source[methodName]=func)}),source}(),{chain:!1}),lodash.VERSION=VERSION,arrayEach(["bind","bindKey","curry","curryRight","partial","partialRight"],function(methodName){lodash[methodName].placeholder=lodash}),arrayEach(["drop","take"],function(methodName,index){LazyWrapper.prototype[methodName]=function(n){var filtered=this.__filtered__;if(filtered&&!index)return new LazyWrapper(this);n=n===undefined?1:nativeMax(toInteger(n),0);var result=this.clone();return filtered?result.__takeCount__=nativeMin(n,result.__takeCount__):result.__views__.push({size:nativeMin(n,MAX_ARRAY_LENGTH),type:methodName+(result.__dir__<0?"Right":"")}),result},LazyWrapper.prototype[methodName+"Right"]=function(n){return this.reverse()[methodName](n).reverse()}}),arrayEach(["filter","map","takeWhile"],function(methodName,index){var type=index+1,isFilter=type==LAZY_FILTER_FLAG||type==LAZY_WHILE_FLAG;LazyWrapper.prototype[methodName]=function(iteratee){var result=this.clone();return result.__iteratees__.push({iteratee:getIteratee(iteratee,3),type:type}),result.__filtered__=result.__filtered__||isFilter,result}}),arrayEach(["head","last"],function(methodName,index){var takeName="take"+(index?"Right":"");LazyWrapper.prototype[methodName]=function(){return this[takeName](1).value()[0]}}),arrayEach(["initial","tail"],function(methodName,index){var dropName="drop"+(index?"":"Right");LazyWrapper.prototype[methodName]=function(){return this.__filtered__?new LazyWrapper(this):this[dropName](1)}}),LazyWrapper.prototype.compact=function(){return this.filter(identity)},LazyWrapper.prototype.find=function(predicate){return this.filter(predicate).head()},LazyWrapper.prototype.findLast=function(predicate){return this.reverse().find(predicate)},LazyWrapper.prototype.invokeMap=baseRest(function(path,args){return"function"==typeof path?new LazyWrapper(this):this.map(function(value){return baseInvoke(value,path,args)})}),LazyWrapper.prototype.reject=function(predicate){return this.filter(negate(getIteratee(predicate)))},LazyWrapper.prototype.slice=function(start,end){start=toInteger(start);var result=this;return result.__filtered__&&(start>0||0>end)?new LazyWrapper(result):(0>start?result=result.takeRight(-start):start&&(result=result.drop(start)),end!==undefined&&(end=toInteger(end),result=0>end?result.dropRight(-end):result.take(end-start)),result)},LazyWrapper.prototype.takeRightWhile=function(predicate){return this.reverse().takeWhile(predicate).reverse()},LazyWrapper.prototype.toArray=function(){return this.take(MAX_ARRAY_LENGTH)},baseForOwn(LazyWrapper.prototype,function(func,methodName){var checkIteratee=/^(?:filter|find|map|reject)|While$/.test(methodName),isTaker=/^(?:head|last)$/.test(methodName),lodashFunc=lodash[isTaker?"take"+("last"==methodName?"Right":""):methodName],retUnwrapped=isTaker||/^find/.test(methodName);lodashFunc&&(lodash.prototype[methodName]=function(){var value=this.__wrapped__,args=isTaker?[1]:arguments,isLazy=value instanceof LazyWrapper,iteratee=args[0],useLazy=isLazy||isArray(value),interceptor=function(value){var result=lodashFunc.apply(lodash,arrayPush([value],args));return isTaker&&chainAll?result[0]:result};useLazy&&checkIteratee&&"function"==typeof iteratee&&1!=iteratee.length&&(isLazy=useLazy=!1);var chainAll=this.__chain__,isHybrid=!!this.__actions__.length,isUnwrapped=retUnwrapped&&!chainAll,onlyLazy=isLazy&&!isHybrid;if(!retUnwrapped&&useLazy){value=onlyLazy?value:new LazyWrapper(this);var result=func.apply(value,args);return result.__actions__.push({func:thru,args:[interceptor],thisArg:undefined}),new LodashWrapper(result,chainAll)}return isUnwrapped&&onlyLazy?func.apply(this,args):(result=this.thru(interceptor),isUnwrapped?isTaker?result.value()[0]:result.value():result)})}),arrayEach(["pop","push","shift","sort","splice","unshift"],function(methodName){var func=arrayProto[methodName],chainName=/^(?:push|sort|unshift)$/.test(methodName)?"tap":"thru",retUnwrapped=/^(?:pop|shift)$/.test(methodName);lodash.prototype[methodName]=function(){var args=arguments;if(retUnwrapped&&!this.__chain__){var value=this.value();return func.apply(isArray(value)?value:[],args)}return this[chainName](function(value){return func.apply(isArray(value)?value:[],args)})}}),baseForOwn(LazyWrapper.prototype,function(func,methodName){var lodashFunc=lodash[methodName];if(lodashFunc){var key=lodashFunc.name+"",names=realNames[key]||(realNames[key]=[]);names.push({name:methodName,func:lodashFunc})}}),realNames[createHybrid(undefined,BIND_KEY_FLAG).name]=[{name:"wrapper",func:undefined}],LazyWrapper.prototype.clone=lazyClone,LazyWrapper.prototype.reverse=lazyReverse,LazyWrapper.prototype.value=lazyValue,lodash.prototype.at=wrapperAt,lodash.prototype.chain=wrapperChain,lodash.prototype.commit=wrapperCommit,lodash.prototype.next=wrapperNext,lodash.prototype.plant=wrapperPlant,lodash.prototype.reverse=wrapperReverse,lodash.prototype.toJSON=lodash.prototype.valueOf=lodash.prototype.value=wrapperValue,lodash.prototype.first=lodash.prototype.head,iteratorSymbol&&(lodash.prototype[iteratorSymbol]=wrapperToIterator),lodash}var undefined,VERSION="4.16.0",LARGE_ARRAY_SIZE=200,FUNC_ERROR_TEXT="Expected a function",HASH_UNDEFINED="__lodash_hash_undefined__",MAX_MEMOIZE_SIZE=500,PLACEHOLDER="__lodash_placeholder__",BIND_FLAG=1,BIND_KEY_FLAG=2,CURRY_BOUND_FLAG=4,CURRY_FLAG=8,CURRY_RIGHT_FLAG=16,PARTIAL_FLAG=32,PARTIAL_RIGHT_FLAG=64,ARY_FLAG=128,REARG_FLAG=256,FLIP_FLAG=512,UNORDERED_COMPARE_FLAG=1,PARTIAL_COMPARE_FLAG=2,DEFAULT_TRUNC_LENGTH=30,DEFAULT_TRUNC_OMISSION="...",HOT_COUNT=500,HOT_SPAN=16,LAZY_FILTER_FLAG=1,LAZY_MAP_FLAG=2,LAZY_WHILE_FLAG=3,INFINITY=1/0,MAX_SAFE_INTEGER=9007199254740991,MAX_INTEGER=1.7976931348623157e308,NAN=NaN,MAX_ARRAY_LENGTH=4294967295,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH-1,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH>>>1,wrapFlags=[["ary",ARY_FLAG],["bind",BIND_FLAG],["bindKey",BIND_KEY_FLAG],["curry",CURRY_FLAG],["curryRight",CURRY_RIGHT_FLAG],["flip",FLIP_FLAG],["partial",PARTIAL_FLAG],["partialRight",PARTIAL_RIGHT_FLAG],["rearg",REARG_FLAG]],argsTag="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",genTag="[object GeneratorFunction]",mapTag="[object Map]",numberTag="[object Number]",objectTag="[object Object]",promiseTag="[object Promise]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]",weakMapTag="[object WeakMap]",weakSetTag="[object WeakSet]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]",reEmptyStringLeading=/\b__p \+= '';/g,reEmptyStringMiddle=/\b(__p \+=) '' \+/g,reEmptyStringTrailing=/(__e\(.*?\)|\b__t\)) \+\n'';/g,reEscapedHtml=/&(?:amp|lt|gt|quot|#39|#96);/g,reUnescapedHtml=/[&<>"'`]/g,reHasEscapedHtml=RegExp(reEscapedHtml.source),reHasUnescapedHtml=RegExp(reUnescapedHtml.source),reEscape=/<%-([\s\S]+?)%>/g,reEvaluate=/<%([\s\S]+?)%>/g,reInterpolate=/<%=([\s\S]+?)%>/g,reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/,reLeadingDot=/^\./,rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reHasRegExpChar=RegExp(reRegExpChar.source),reTrim=/^\s+|\s+$/g,reTrimStart=/^\s+/,reTrimEnd=/\s+$/,reWrapComment=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,reWrapDetails=/\{\n\/\* \[wrapped with (.+)\] \*/,reSplitDetails=/,? & /,reAsciiWord=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,reEscapeChar=/\\(\\)?/g,reEsTemplate=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,reFlags=/\w*$/,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsHostCtor=/^\[object .+?Constructor\]$/,reIsOctal=/^0o[0-7]+$/i,reIsUint=/^(?:0|[1-9]\d*)$/,reLatin=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,reNoMatch=/($^)/,reUnescapedString=/['\n\r\u2028\u2029\\]/g,rsAstralRange="\\ud800-\\udfff",rsComboMarksRange="\\u0300-\\u036f\\ufe20-\\ufe23",rsComboSymbolsRange="\\u20d0-\\u20f0",rsDingbatRange="\\u2700-\\u27bf",rsLowerRange="a-z\\xdf-\\xf6\\xf8-\\xff",rsMathOpRange="\\xac\\xb1\\xd7\\xf7",rsNonCharRange="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",rsPunctuationRange="\\u2000-\\u206f",rsSpaceRange=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",rsUpperRange="A-Z\\xc0-\\xd6\\xd8-\\xde",rsVarRange="\\ufe0e\\ufe0f",rsBreakRange=rsMathOpRange+rsNonCharRange+rsPunctuationRange+rsSpaceRange,rsApos="['’]",rsAstral="["+rsAstralRange+"]",rsBreak="["+rsBreakRange+"]",rsCombo="["+rsComboMarksRange+rsComboSymbolsRange+"]",rsDigits="\\d+",rsDingbat="["+rsDingbatRange+"]",rsLower="["+rsLowerRange+"]",rsMisc="[^"+rsAstralRange+rsBreakRange+rsDigits+rsDingbatRange+rsLowerRange+rsUpperRange+"]",rsFitz="\\ud83c[\\udffb-\\udfff]",rsModifier="(?:"+rsCombo+"|"+rsFitz+")",rsNonAstral="[^"+rsAstralRange+"]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",rsUpper="["+rsUpperRange+"]",rsZWJ="\\u200d",rsLowerMisc="(?:"+rsLower+"|"+rsMisc+")",rsUpperMisc="(?:"+rsUpper+"|"+rsMisc+")",rsOptLowerContr="(?:"+rsApos+"(?:d|ll|m|re|s|t|ve))?",rsOptUpperContr="(?:"+rsApos+"(?:D|LL|M|RE|S|T|VE))?",reOptMod=rsModifier+"?",rsOptVar="["+rsVarRange+"]?",rsOptJoin="(?:"+rsZWJ+"(?:"+[rsNonAstral,rsRegional,rsSurrPair].join("|")+")"+rsOptVar+reOptMod+")*",rsSeq=rsOptVar+reOptMod+rsOptJoin,rsEmoji="(?:"+[rsDingbat,rsRegional,rsSurrPair].join("|")+")"+rsSeq,rsSymbol="(?:"+[rsNonAstral+rsCombo+"?",rsCombo,rsRegional,rsSurrPair,rsAstral].join("|")+")",reApos=RegExp(rsApos,"g"),reComboMark=RegExp(rsCombo,"g"),reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g"),reUnicodeWord=RegExp([rsUpper+"?"+rsLower+"+"+rsOptLowerContr+"(?="+[rsBreak,rsUpper,"$"].join("|")+")",rsUpperMisc+"+"+rsOptUpperContr+"(?="+[rsBreak,rsUpper+rsLowerMisc,"$"].join("|")+")",rsUpper+"?"+rsLowerMisc+"+"+rsOptLowerContr,rsUpper+"+"+rsOptUpperContr,rsDigits,rsEmoji].join("|"),"g"),reHasUnicode=RegExp("["+rsZWJ+rsAstralRange+rsComboMarksRange+rsComboSymbolsRange+rsVarRange+"]"),reHasUnicodeWord=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,contextProps=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],templateCounter=-1,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[dataViewTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[mapTag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[setTag]=cloneableTags[stringTag]=cloneableTags[symbolTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=!0,cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[weakMapTag]=!1;var deburredLetters={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"},htmlEscapes={"&":"&","<":"<",">":">",'"':""","'":"'"},htmlUnescapes={"&":"&","<":"<",">":">",""":'"',"'":"'"},stringEscapes={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},freeParseFloat=parseFloat,freeParseInt=parseInt,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,freeProcess=moduleExports&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding("util")}catch(e){}}(),nodeIsArrayBuffer=nodeUtil&&nodeUtil.isArrayBuffer,nodeIsDate=nodeUtil&&nodeUtil.isDate,nodeIsMap=nodeUtil&&nodeUtil.isMap,nodeIsRegExp=nodeUtil&&nodeUtil.isRegExp,nodeIsSet=nodeUtil&&nodeUtil.isSet,nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,asciiSize=baseProperty("length"),deburrLetter=basePropertyOf(deburredLetters),escapeHtmlChar=basePropertyOf(htmlEscapes),unescapeHtmlChar=basePropertyOf(htmlUnescapes),_=runInContext();"function"==typeof define&&"object"==typeof define.amd&&define.amd?(root._=_,define(function(){return _})):freeModule?((freeModule.exports=_)._=_,freeExports._=_):root._=_}.call(this),window.console=window.console||{},window.console.log=window.console.log||function(){};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;!function(global){function Usergrid(){this.logger=new Logger(name)}var name="Usergrid",overwrittenName=global[name],VALID_REQUEST_METHODS=["GET","POST","PUT","DELETE"];return Usergrid.initSharedInstance=function(options){return console.warn("TRYING TO INITIALIZING SHARED INSTANCE"),this.isInitialized||(console.warn("INITIALIZING SHARED INSTANCE"),this.__sharedInstance=new Usergrid.Client(options),this.isInitialized=!0),this.__sharedInstance},Usergrid.getInstance=function(){return this.__sharedInstance},Usergrid.isValidEndpoint=function(endpoint){return!0},Usergrid.Request=function(method,endpoint,query_params,data,callback){var p=new Promise;if(this.logger=new global.Logger("Usergrid.Request"),this.logger.time("process request "+method+" "+endpoint),this.endpoint=endpoint+"?"+encodeParams(query_params),this.method=method.toUpperCase(),this.data="object"==typeof data?JSON.stringify(data):data,-1===VALID_REQUEST_METHODS.indexOf(this.method))throw new UsergridInvalidHTTPMethodError("invalid request method '"+this.method+"'");if(!isValidUrl(this.endpoint))throw this.logger.error(endpoint,this.endpoint,/^https:\/\//.test(endpoint)),new UsergridInvalidURIError("The provided endpoint is not valid: "+this.endpoint);var request=function(){return Ajax.request(this.method,this.endpoint,this.data)}.bind(this),response=function(err,request){return new Usergrid.Response(err,request)}.bind(this),oncomplete=function(err,response){p.done(err,response),this.logger.info("REQUEST",err,response),doCallback(callback,[err,response]),this.logger.timeEnd("process request "+method+" "+endpoint)}.bind(this);return Promise.chain([request,response]).then(oncomplete),p},Usergrid.Response=function(err,response){var p=new Promise,data=null;try{data=JSON.parse(response.responseText)}catch(e){data={}}switch(Object.keys(data).forEach(function(key){Object.defineProperty(this,key,{value:data[key],enumerable:!0})}.bind(this)),Object.defineProperty(this,"logger",{enumerable:!1,configurable:!1,writable:!1,value:new global.Logger(name)}),Object.defineProperty(this,"success",{enumerable:!1,configurable:!1,writable:!0,value:!0}),Object.defineProperty(this,"err",{enumerable:!1,configurable:!1,writable:!0,value:err}),Object.defineProperty(this,"status",{enumerable:!1,configurable:!1,writable:!0,value:parseInt(response.status)}),Object.defineProperty(this,"statusGroup",{enumerable:!1,configurable:!1,writable:!0,value:this.status-this.status%100}),this.statusGroup){case 200:this.success=!0;break;case 400:case 500:case 300:case 100:default:this.success=!1}return this.success?p.done(null,this):p.done(UsergridError.fromResponse(data),this),p},Usergrid.Response.prototype.getEntities=function(){var entities;return this.success&&(entities=this.data?this.data.entities:this.entities),entities||[]},Usergrid.Response.prototype.getEntity=function(){var entities=this.getEntities();return entities[0]},Usergrid.VERSION=Usergrid.USERGRID_SDK_VERSION="0.11.0",global[name]=Usergrid,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Usergrid},global[name]}(this);var defaultOptions={baseUrl:"https://api.usergrid.com",authMode:UsergridAuthMode.USER};!function(){var exports,name="Client",global=this,overwrittenName=global[name];return Usergrid.Client=function(options){var self=this;if(!options.orgId||!options.appId)throw new Error('"orgId" and "appId" parameters are required when instantiating UsergridClient');_.defaults(this,options,defaultOptions),self.clientAppURL=[self.baseUrl,self.orgId,self.appId].join("/"),self.isSharedInstance=!1,self.currentUser=void 0,self.__appAuth=void 0,Object.defineProperty(self,"appAuth",{get:function(){return self.__appAuth},set:function(options){options instanceof UsergridAppAuth?self.__appAuth=options:"undefined"!=typeof options&&(self.__appAuth=new UsergridAppAuth(options))}}),this.userAuth=void 0,options.qs&&this.setObject("default_qs",options.qs),this.buildCurl=options.buildCurl||!1,this.logging=options.logging||!1},Usergrid.Client.prototype.request=function(options,callback){var uri,method=options.method||"GET",endpoint=options.endpoint,body=options.body||{},qs=options.qs||{},mQuery=options.mQuery||!1,orgId=this.get("orgId"),appId=this.get("appId"),default_qs=this.getObject("default_qs");if(!mQuery&&!orgId&&!appId)return logoutCallback();uri=mQuery?this.baseUrl+"/"+endpoint:this.baseUrl+"/"+orgId+"/"+appId+"/"+endpoint,this.getToken()&&(qs.access_token=this.getToken()),default_qs&&(qs=propCopy(qs,default_qs));var self=this;new Usergrid.Request(method,uri,qs,body,function(err,response){err?doCallback(callback,[err,response,self],self):doCallback(callback,[null,response,self],self)})},Usergrid.Client.prototype.buildAssetURL=function(uuid){var self=this,qs={},assetURL=this.baseUrl+"/"+this.orgId+"/"+this.appId+"/assets/"+uuid+"/data";self.getToken()&&(qs.access_token=self.getToken());var encoded_params=encodeParams(qs);return encoded_params&&(assetURL+="?"+encoded_params),assetURL},Usergrid.Client.prototype.createGroup=function(options,callback){var group=new Usergrid.Group({path:options.path,client:this,data:options});group.save(function(err,response){doCallback(callback,[err,response,group],group)})},Usergrid.Client.prototype.createEntity=function(options,callback){var entity=new Usergrid.Entity({client:this,data:options});entity.save(function(err,response){doCallback(callback,[err,response,entity],entity)})},Usergrid.Client.prototype.getEntity=function(options,callback){var entity=new Usergrid.Entity({client:this,data:options});entity.fetch(function(err,response){doCallback(callback,[err,response,entity],entity)})},Usergrid.Client.prototype.restoreEntity=function(serializedObject){var data=JSON.parse(serializedObject),options={client:this,data:data},entity=new Usergrid.Entity(options);return entity},Usergrid.Client.prototype.createCounter=function(options,callback){var counter=new Usergrid.Counter({client:this,data:options});counter.save(callback)},Usergrid.Client.prototype.createAsset=function(options,callback){var file=options.file;file&&(options.name=options.name||file.name,options["content-type"]=options["content-type"]||file.type,options.path=options.path||"/",delete options.file);var asset=new Usergrid.Asset({client:this,data:options});asset.save(function(err,response,asset){file&&!err?asset.upload(file,callback):doCallback(callback,[err,response,asset],asset)})},Usergrid.Client.prototype.createCollection=function(options,callback){options.client=this;var collection=new Usergrid.Collection(options);this.request({method:"POST",endpoint:options.type},function(err,data){err?doCallback(callback,[err,data,collection],self):collection.fetch(function(err,response,collection){doCallback(callback,[err,response,collection],self)})})},Usergrid.Client.prototype.restoreCollection=function(serializedObject){var data=JSON.parse(serializedObject);data.client=this;var collection=new Usergrid.Collection(data);return collection},Usergrid.Client.prototype.getFeedForUser=function(username,callback){var options={method:"GET",endpoint:"users/"+username+"/feed"};this.request(options,function(err,data){err?doCallback(callback,[err]):doCallback(callback,[err,data,data.getEntities()])})},Usergrid.Client.prototype.createUserActivity=function(user,options,callback){options.type="users/"+user+"/activities",options={client:this,data:options};var entity=new Usergrid.Entity(options);entity.save(function(err,data){doCallback(callback,[err,data,entity])})},Usergrid.Client.prototype.createUserActivityWithEntity=function(user,content,callback){var username=user.get("username"),options={actor:{displayName:username,uuid:user.get("uuid"),username:username,email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80}},verb:"post",content:content};this.createUserActivity(username,options,callback)},Usergrid.Client.prototype.calcTimeDiff=function(){var seconds=0,time=this._end-this._start;try{seconds=(time/10/60).toFixed(2)}catch(e){return 0}return seconds},Usergrid.Client.prototype.setToken=function(token){this.set("token",token)},Usergrid.Client.prototype.getToken=function(){return this.get("token")},Usergrid.Client.prototype.setObject=function(key,value){value&&(value=JSON.stringify(value)),this.set(key,value)},Usergrid.Client.prototype.set=function(key,value){var keyStore="apigee_"+key;this[key]=value,"undefined"!=typeof Storage&&(value?localStorage.setItem(keyStore,value):localStorage.removeItem(keyStore))},Usergrid.Client.prototype.getObject=function(key){return JSON.parse(this.get(key))},Usergrid.Client.prototype.get=function(key){var keyStore="apigee_"+key,value=null;return this[key]?value=this[key]:"undefined"!=typeof Storage&&(value=localStorage.getItem(keyStore)),value},Usergrid.Client.prototype.signup=function(username,password,email,name,callback){var options={type:"users",username:username,password:password,email:email,name:name};this.createEntity(options,callback)},Usergrid.Client.prototype.login=function(username,password,callback){var self=this,options={method:"POST",endpoint:"token",body:{username:username,password:password,grant_type:"password"}};self.request(options,function(err,response){var user={};if(err)self.logging&&console.log("error trying to log user in");else{var options={client:self,data:response.user};user=new Usergrid.Entity(options),self.setToken(response.access_token)}doCallback(callback,[err,response,user])})},Usergrid.Client.prototype.adminlogin=function(username,password,callback){var self=this,options={method:"POST",endpoint:"management/token",body:{username:username,password:password,grant_type:"password"},mQuery:!0};self.request(options,function(err,response){var user={};if(err)self.logging&&console.log("error trying to log adminuser in");else{var options={client:self,data:response.user};user=new Usergrid.Entity(options),self.setToken(response.access_token)}doCallback(callback,[err,response,user])})},Usergrid.Client.prototype.reAuthenticateLite=function(callback){var self=this,options={method:"GET",endpoint:"management/me",mQuery:!0};this.request(options,function(err,response){err&&self.logging?console.log("error trying to re-authenticate user"):self.setToken(response.data.access_token),doCallback(callback,[err])})},Usergrid.Client.prototype.reAuthenticate=function(email,callback){var self=this,options={method:"GET",endpoint:"management/users/"+email,mQuery:!0};this.request(options,function(err,response){var data,organizations={},applications={},user={};if(err&&self.logging)console.log("error trying to full authenticate user");else{data=response.data,self.setToken(data.token),self.set("email",data.email),localStorage.setItem("accessToken",data.token),localStorage.setItem("userUUID",data.uuid),localStorage.setItem("userEmail",data.email);var userData={username:data.username,email:data.email,name:data.name,uuid:data.uuid},options={client:self,data:userData};user=new Usergrid.Entity(options),organizations=data.organizations;var org="";try{var existingOrg=self.get("orgName");org=organizations[existingOrg]?organizations[existingOrg]:organizations[Object.keys(organizations)[0]],self.set("orgName",org.name)}catch(e){err=!0,self.logging&&console.log("error selecting org")}applications=self.parseApplicationsArray(org),self.selectFirstApp(applications),self.setObject("organizations",organizations),self.setObject("applications",applications)}doCallback(callback,[err,data,user,organizations,applications],self)})},Usergrid.Client.prototype.loginFacebook=function(facebookToken,callback){var self=this,options={method:"GET",endpoint:"auth/facebook",qs:{fb_access_token:facebookToken}};this.request(options,function(err,data){var user={};if(err&&self.logging)console.log("error trying to log user in");else{var options={client:self,data:data.user};user=new Usergrid.Entity(options),self.setToken(data.access_token)}doCallback(callback,[err,data,user],self)})},Usergrid.Client.prototype.getLoggedInUser=function(callback){var self=this;if(this.getToken()){var options={method:"GET",endpoint:"users/me"};this.request(options,function(err,response){if(err)self.logging&&console.log("error trying to log user in"),console.error(err,response),doCallback(callback,[err,response,self],self);else{var options={client:self,data:response.getEntity()},user=new Usergrid.Entity(options);doCallback(callback,[null,response,user],self)}})}else doCallback(callback,[new UsergridError("Access Token not set"),null,self],self)},Usergrid.Client.prototype.isLoggedIn=function(){var token=this.getToken();return"undefined"!=typeof token&&null!==token},Usergrid.Client.prototype.logout=function(){this.setToken()},Usergrid.Client.prototype.destroyToken=function(username,token,revokeAll,callback){var options={client:self,method:"PUT"};revokeAll===!0?options.endpoint="users/"+username+"/revoketokens":null===token?options.endpoint="users/"+username+"/revoketoken?token="+this.getToken():options.endpoint="users/"+username+"/revoketoken?token="+token,this.request(options,function(err,data){err?(self.logging&&console.log("error destroying access token"),doCallback(callback,[err,data,null],self)):(revokeAll===!0?console.log("all user tokens invalidated"):console.log("token invalidated"),doCallback(callback,[err,data,null],self))})},Usergrid.Client.prototype.logoutAndDestroyToken=function(username,token,revokeAll,callback){null===username?console.log("username required to revoke tokens"):(this.destroyToken(username,token,revokeAll,callback),(revokeAll===!0||token===this.getToken()||null===token)&&this.setToken(null))},Usergrid.Client.prototype.buildCurlCall=function(options){var curl=["curl"],method=(options.method||"GET").toUpperCase(),body=options.body,uri=options.uri; -return curl.push("-X"),curl.push(["POST","PUT","DELETE"].indexOf(method)>=0?method:"GET"),curl.push(uri),"object"==typeof body&&Object.keys(body).length>0&&-1!==["POST","PUT"].indexOf(method)&&(curl.push("-d"),curl.push("'"+JSON.stringify(body)+"'")),curl=curl.join(" "),console.log(curl),curl},Usergrid.Client.prototype.getDisplayImage=function(email,picture,size){size=size||50;var image="https://apigee.com/usergrid/images/user_profile.png";try{picture?image=picture:email.length&&(image="https://secure.gravatar.com/avatar/"+MD5(email)+"?s="+size+encodeURI("&d=https://apigee.com/usergrid/images/user_profile.png"))}catch(e){}finally{return image}},global[name]=Usergrid.Client,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}();var ENTITY_SYSTEM_PROPERTIES=["metadata","created","modified","oldpassword","newpassword","type","activated","uuid"];Usergrid.Entity=function(options){this._data={},this._client=void 0,options&&(this.set(options.data||{}),this._client=options.client||{})},Usergrid.Entity.isEntity=function(obj){return obj&&obj instanceof Usergrid.Entity},Usergrid.Entity.isPersistedEntity=function(obj){return isEntity(obj)&&isUUID(obj.get("uuid"))},Usergrid.Entity.prototype.serialize=function(){return JSON.stringify(this._data)},Usergrid.Entity.prototype.get=function(key){var value;if(0===arguments.length?value=this._data:arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c,i,a){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(value=this._data[key]);return value},Usergrid.Entity.prototype.set=function(key,value){if("object"==typeof key)for(var field in key)this._data[field]=key[field];else"string"==typeof key?null===value?delete this._data[key]:this._data[key]=value:this._data={}},Usergrid.Entity.prototype.getEndpoint=function(){var name,type=this.get("type"),nameProperties=["uuid","name"];if(void 0===type)throw new UsergridError("cannot fetch entity, no entity type specified","no_type_specified");return/^users?$/.test(type)&&nameProperties.unshift("username"),name=this.get(nameProperties).filter(function(x){return null!==x&&"undefined"!=typeof x}).shift(),name?[type,name].join("/"):type},Usergrid.Entity.prototype.save=function(callback){var self=this,type=this.get("type"),method="POST",entityId=this.get("uuid"),entityData=this.get(),options={method:method,endpoint:type};entityId&&(options.method="PUT",options.endpoint+="/"+entityId),options.body=Object.keys(entityData).filter(function(key){return-1===ENTITY_SYSTEM_PROPERTIES.indexOf(key)}).reduce(function(data,key){return data[key]=entityData[key],data},{}),self._client.request(options,function(err,response){var entity=response.getEntity();entity&&(self.set(entity),self.set("type",/^\//.test(response.path)?response.path.substring(1):response.path)),err&&self._client.logging&&console.log("could not save entity"),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.changePassword=function(oldpassword,newpassword,callback){var self=this;if("function"==typeof oldpassword&&void 0===callback&&(callback=oldpassword,oldpassword=self.get("oldpassword"),newpassword=self.get("newpassword")),self.set({password:null,oldpassword:null,newpassword:null}),!(/^users?$/.test(self.get("type"))&&oldpassword&&newpassword))throw new UsergridInvalidArgumentError("Invalid arguments passed to 'changePassword'");var options={method:"PUT",endpoint:"users/"+self.get("uuid")+"/password",body:{uuid:self.get("uuid"),username:self.get("username"),oldpassword:oldpassword,newpassword:newpassword}};self._client.request(options,function(err,response){err&&self._client.logging&&console.log("could not update user"),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.fetch=function(callback){var endpoint,self=this;endpoint=this.getEndpoint();var options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,response){var entity=response.getEntity();entity&&self.set(entity),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.destroy=function(callback){var self=this,endpoint=this.getEndpoint(),options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,response){err||self.set(null),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.connect=function(connection,entity,callback){this.addOrRemoveConnection("POST",connection,entity,callback)},Usergrid.Entity.prototype.disconnect=function(connection,entity,callback){this.addOrRemoveConnection("DELETE",connection,entity,callback)},Usergrid.Entity.prototype.addOrRemoveConnection=function(method,connection,entity,callback){var self=this;if(-1==["POST","DELETE"].indexOf(method.toUpperCase()))throw new UsergridInvalidArgumentError("invalid method for connection call. must be 'POST' or 'DELETE'");var connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)throw new UsergridInvalidArgumentError("connectee could not be identified");var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)throw new UsergridInvalidArgumentError("connector could not be identified");var endpoint=[connectorType,connector,connection,connecteeType,connectee].join("/"),options={method:method,endpoint:endpoint};this._client.request(options,function(err,response){err&&self._client.logging&&console.log("There was an error with the connection call"),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.getEntityId=function(entity){var id;return id=isUUID(entity.get("uuid"))?entity.get("uuid"):"users"===this.get("type")||"user"===this.get("type")?entity.get("username"):entity.get("name")},Usergrid.Entity.prototype.getConnections=function(connection,callback){var self=this,connectorType=this.get("type"),connector=this.getEntityId(this);if(connector){var endpoint=connectorType+"/"+connector+"/"+connection+"/",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self[connection]={};for(var length=data&&data.entities?data.entities.length:0,i=0;length>i;i++)"user"===data.entities[i].type?self[connection][data.entities[i].username]=data.entities[i]:self[connection][data.entities[i].name]=data.entities[i];doCallback(callback,[err,data,data.entities],self)})}else if("function"==typeof callback){var error="Error in getConnections - no uuid specified.";self._client.logging&&console.log(error),doCallback(callback,[!0,error],self)}},Usergrid.Entity.prototype.getGroups=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/groups",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self.groups=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Entity.prototype.getActivities=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/activities",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected");for(var entity in data.entities)data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();self.activities=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Entity.prototype.getFollowing=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/following",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user following");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.following=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Entity.prototype.getFollowers=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/followers",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user followers");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.followers=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Client.prototype.createRole=function(roleName,permissions,callback){var options={type:"role",name:roleName};this.createEntity(options,function(err,response,entity){err?doCallback(callback,[err,response,self]):entity.assignPermissions(permissions,function(err,data){err?doCallback(callback,[err,response,self]):doCallback(callback,[err,data,data.data],self)})})},Usergrid.Entity.prototype.getRoles=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/roles",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user roles"),self.roles=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Entity.prototype.assignRole=function(roleName,callback){var entityID,self=this,type=self.get("type"),collection=type+"s";"user"==type&&null!=this.get("username")?entityID=self.get("username"):"group"==type&&null!=this.get("name")?entityID=self.get("name"):null!=this.get("uuid")&&(entityID=self.get("uuid")),"users"!=type&&"groups"!=type&&doCallback(callback,[new UsergridError("entity must be a group or user","invalid_entity_type"),null,this],this);var endpoint="roles/"+roleName+"/"+collection+"/"+entityID,options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,response){err&&console.log("Could not assign role."),doCallback(callback,[err,response,self])})},Usergrid.Entity.prototype.removeRole=function(roleName,callback){var entityID,self=this,type=self.get("type"),collection=type+"s";"user"==type&&null!=this.get("username")?entityID=this.get("username"):"group"==type&&null!=this.get("name")?entityID=this.get("name"):null!=this.get("uuid")&&(entityID=this.get("uuid")),"users"!=type&&"groups"!=type&&doCallback(callback,[new UsergridError("entity must be a group or user","invalid_entity_type"),null,this],this);var endpoint="roles/"+roleName+"/"+collection+"/"+entityID,options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,response){err&&console.log("Could not assign role."),doCallback(callback,[err,response,self])})},Usergrid.Entity.prototype.assignPermissions=function(permissions,callback){var entityID,self=this,type=this.get("type");"user"!=type&&"users"!=type&&"group"!=type&&"groups"!=type&&"role"!=type&&"roles"!=type&&doCallback(callback,[new UsergridError("entity must be a group, user, or role","invalid_entity_type"),null,this],this),"user"==type&&null!=this.get("username")?entityID=this.get("username"):"group"==type&&null!=this.get("name")?entityID=this.get("name"):null!=this.get("uuid")&&(entityID=this.get("uuid"));var endpoint=type+"/"+entityID+"/permissions",options={method:"POST",endpoint:endpoint,body:{permission:permissions}};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not assign permissions"),doCallback(callback,[err,data,data.data],self)})},Usergrid.Entity.prototype.removePermissions=function(permissions,callback){var entityID,self=this,type=this.get("type");"user"!=type&&"users"!=type&&"group"!=type&&"groups"!=type&&"role"!=type&&"roles"!=type&&doCallback(callback,[new UsergridError("entity must be a group, user, or role","invalid_entity_type"),null,this],this),"user"==type&&null!=this.get("username")?entityID=this.get("username"):"group"==type&&null!=this.get("name")?entityID=this.get("name"):null!=this.get("uuid")&&(entityID=this.get("uuid"));var endpoint=type+"/"+entityID+"/permissions",options={method:"DELETE",endpoint:endpoint,qs:{permission:permissions}};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not remove permissions"),doCallback(callback,[err,data,data.params.permission],self)})},Usergrid.Entity.prototype.getPermissions=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/permissions",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user permissions");var permissions=[];if(data.data){var perms=data.data,count=0;for(var i in perms){count++;var perm=perms[i],parts=perm.split(":"),ops_part="",path_part=parts[0];parts.length>1&&(ops_part=parts[0],path_part=parts[1]),ops_part=ops_part.replace("*","get,post,put,delete");var ops=ops_part.split(","),ops_object={};ops_object.get="no",ops_object.post="no",ops_object.put="no",ops_object["delete"]="no";for(var j in ops)ops_object[ops[j]]="yes";permissions.push({operations:ops_object,path:path_part,perm:perm})}}self.permissions=permissions,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Collection=function(options){if(options&&(this._client=options.client,this._type=options.type,this.qs=options.qs||{},this._list=options.list||[],this._iterator=options.iterator||-1,this._previous=options.previous||[],this._next=options.next||null,this._cursor=options.cursor||null,options.list))for(var count=options.list.length,i=0;count>i;i++){var entity=this._client.restoreEntity(options.list[i]);this._list[i]=entity}},Usergrid.isCollection=function(obj){return obj&&obj instanceof Usergrid.Collection},Usergrid.Collection.prototype.serialize=function(){var data={};data.type=this._type,data.qs=this.qs,data.iterator=this._iterator,data.previous=this._previous,data.next=this._next,data.cursor=this._cursor,this.resetEntityPointer();var i=0;for(data.list=[];this.hasNextEntity();){var entity=this.getNextEntity();data.list[i]=entity.serialize(),i++}return data=JSON.stringify(data)},Usergrid.Collection.prototype.fetch=function(callback){var self=this,qs=this.qs;this._cursor?qs.cursor=this._cursor:delete qs.cursor;var options={method:"GET",endpoint:this._type,qs:this.qs};this._client.request(options,function(err,response){err&&self._client.logging?console.log("error getting collection"):(self.saveCursor(response.cursor||null),self.resetEntityPointer(),self._list=response.getEntities().filter(function(entity){return isUUID(entity.uuid)}).map(function(entity){var ent=new Usergrid.Entity({client:self._client});return ent.set(entity),ent.type=self._type,ent})),doCallback(callback,[err,response,self],self)})},Usergrid.Collection.prototype.addEntity=function(entityObject,callback){var self=this;entityObject.type=this._type,this._client.createEntity(entityObject,function(err,response,entity){err||self.addExistingEntity(entity),doCallback(callback,[err,response,self],self)})},Usergrid.Collection.prototype.addExistingEntity=function(entity){var count=this._list.length;this._list[count]=entity},Usergrid.Collection.prototype.destroyEntity=function(entity,callback){var self=this;entity.destroy(function(err,response){err?(self._client.logging&&console.log("could not destroy entity"),doCallback(callback,[err,response,self],self)):self.fetch(callback),self.removeEntity(entity)})},Usergrid.Collection.prototype.getEntitiesByCriteria=function(criteria){return this._list.filter(criteria)},Usergrid.Collection.prototype.getEntityByCriteria=function(criteria){return this.getEntitiesByCriteria(criteria).shift()},Usergrid.Collection.prototype.removeEntity=function(entity){var removedEntity=this.getEntityByCriteria(function(item){return entity.uuid===item.get("uuid")});return delete this._list[this._list.indexOf(removedEntity)],removedEntity},Usergrid.Collection.prototype.getEntityByUUID=function(uuid,callback){var entity=this.getEntityByCriteria(function(item){return item.get("uuid")===uuid});if(entity)doCallback(callback,[null,entity,entity],this);else{var options={data:{type:this._type,uuid:uuid},client:this._client};entity=new Usergrid.Entity(options),entity.fetch(callback)}},Usergrid.Collection.prototype.getFirstEntity=function(){var count=this._list.length;return count>0?this._list[0]:null},Usergrid.Collection.prototype.getLastEntity=function(){var count=this._list.length;return count>0?this._list[count-1]:null},Usergrid.Collection.prototype.hasNextEntity=function(){var next=this._iterator+1,hasNextElement=next>=0&&next=0&&this._iterator<=this._list.length;return hasNextElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.hasPrevEntity=function(){var previous=this._iterator-1,hasPreviousElement=previous>=0&&previous=0&&this._iterator<=this._list.length;return hasPreviousElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.resetEntityPointer=function(){this._iterator=-1},Usergrid.Collection.prototype.saveCursor=function(cursor){this._next!==cursor&&(this._next=cursor)},Usergrid.Collection.prototype.resetPaging=function(){this._previous=[],this._next=null,this._cursor=null},Usergrid.Collection.prototype.hasNextPage=function(){return this._next},Usergrid.Collection.prototype.getNextPage=function(callback){this.hasNextPage()&&(this._previous.push(this._cursor),this._cursor=this._next,this._list=[],this.fetch(callback))},Usergrid.Collection.prototype.hasPreviousPage=function(){return this._previous.length>0},Usergrid.Collection.prototype.getPreviousPage=function(callback){this.hasPreviousPage()&&(this._next=null,this._cursor=this._previous.pop(),this._list=[],this.fetch(callback))},Usergrid.Group=function(options,callback){this._path=options.path,this._list=[],this._client=options.client,this._data=options.data||{},this._data.type="groups"},Usergrid.Group.prototype=new Usergrid.Entity,Usergrid.Group.prototype.fetch=function(callback){var self=this,groupEndpoint="groups/"+this._path,memberEndpoint="groups/"+this._path+"/users",groupOptions={method:"GET",endpoint:groupEndpoint},memberOptions={method:"GET",endpoint:memberEndpoint};this._client.request(groupOptions,function(err,response){if(err)self._client.logging&&console.log("error getting group"),doCallback(callback,[err,response],self);else{var entities=response.getEntities();if(entities&&entities.length){entities.shift();self._client.request(memberOptions,function(err,response){err&&self._client.logging?console.log("error getting group users"):self._list=response.getEntities().filter(function(entity){return isUUID(entity.uuid)}).map(function(entity){return new Usergrid.Entity({type:entity.type,client:self._client,uuid:entity.uuid,response:entity})}),doCallback(callback,[err,response,self],self)})}}})},Usergrid.Group.prototype.members=function(callback){return this._list},Usergrid.Group.prototype.add=function(options,callback){var self=this;options.user?(options={method:"POST",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")},this._client.request(options,function(error,response){error?doCallback(callback,[error,response,self],self):self.fetch(callback)})):doCallback(callback,[new UsergridError("no user specified","no_user_specified"),null,this],this)},Usergrid.Group.prototype.remove=function(options,callback){var self=this;options.user?(options={method:"DELETE",endpoint:"groups/"+this._path+"/users/"+options.user.username},this._client.request(options,function(error,response){error?doCallback(callback,[error,response,self],self):self.fetch(callback)})):doCallback(callback,[new UsergridError("no user specified","no_user_specified"),null,this],this)},Usergrid.Group.prototype.feed=function(callback){var self=this,options={method:"GET",endpoint:"groups/"+this._path+"/feed"};this._client.request(options,function(err,response){doCallback(callback,[err,response,self],self)})},Usergrid.Group.prototype.createGroupActivity=function(options,callback){var self=this,user=options.user,entity=new Usergrid.Entity({client:this._client,data:{actor:{displayName:user.get("username"),uuid:user.get("uuid"),username:user.get("username"),email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80}},verb:"post",content:options.content,type:"groups/"+this._path+"/activities"}});entity.save(function(err,response,entity){doCallback(callback,[err,response,self])})},Usergrid.Counter=function(options){this._client=options.client,this._data=options.data||{},this._data.category=options.category||"UNKNOWN",this._data.timestamp=options.timestamp||0,this._data.type="events",this._data.counters=options.counters||{}};var COUNTER_RESOLUTIONS=["all","minute","five_minutes","half_hour","hour","six_day","day","week","month"];Usergrid.Counter.prototype=new Usergrid.Entity,Usergrid.Counter.prototype.fetch=function(callback){this.getData({},callback)},Usergrid.Counter.prototype.increment=function(options,callback){var self=this,name=options.name,value=options.value;return name?isNaN(value)?doCallback(callback,[new UsergridInvalidArgumentError("'value' for increment, decrement must be a number"),null,self],self):(self._data.counters[name]=parseInt(value)||1,self.save(callback)):doCallback(callback,[new UsergridInvalidArgumentError("'name' for increment, decrement must be a number"),null,self],self)},Usergrid.Counter.prototype.decrement=function(options,callback){var self=this,name=options.name,value=options.value;self.increment({name:name,value:-(parseInt(value)||1)},callback)},Usergrid.Counter.prototype.reset=function(options,callback){var self=this,name=options.name;self.increment({name:name,value:0},callback)},Usergrid.Counter.prototype.getData=function(options,callback){var start_time,end_time,start=options.start||0,end=options.end||Date.now(),resolution=(options.resolution||"all").toLowerCase(),counters=options.counters||Object.keys(this._data.counters),res=(resolution||"all").toLowerCase();-1===COUNTER_RESOLUTIONS.indexOf(res)&&(res="all"),start_time=getSafeTime(start),end_time=getSafeTime(end);var self=this,params=Object.keys(counters).map(function(counter){return["counter",encodeURIComponent(counters[counter])].join("=")});params.push("resolution="+res),params.push("start_time="+String(start_time)),params.push("end_time="+String(end_time));var endpoint="counters?"+params.join("&");this._client.request({endpoint:endpoint},function(err,data){return data.counters&&data.counters.length&&data.counters.forEach(function(counter){self._data.counters[counter.name]=counter.value||counter.values}),doCallback(callback,[err,data,self],self)})},Usergrid.Folder=function(options,callback){var self=this;console.log("FOLDER OPTIONS",options),self._client=options.client,self._data=options.data||{},self._data.type="folders";var missingData=["name","owner","path"].some(function(required){return!(required in self._data)});return missingData?doCallback(callback,[new UsergridInvalidArgumentError("Invalid asset data: 'name', 'owner', and 'path' are required properties."),null,self],self):void self.save(function(err,response){err?doCallback(callback,[new UsergridError(response),response,self],self):(response&&response.entities&&response.entities.length&&self.set(response.entities[0]),doCallback(callback,[null,response,self],self))})},Usergrid.Folder.prototype=new Usergrid.Entity,Usergrid.Folder.prototype.fetch=function(callback){var self=this;Usergrid.Entity.prototype.fetch.call(self,function(err,data){console.log("self",self.get()),console.log("data",data),err?doCallback(callback,[null,data,self],self):self.getAssets(function(err,response){err?doCallback(callback,[new UsergridError(response),resonse,self],self):doCallback(callback,[null,self],self)})})},Usergrid.Folder.prototype.addAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset,asset instanceof Usergrid.Entity||(asset=new Usergrid.Asset(asset));break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}asset&&asset instanceof Usergrid.Entity&&asset.fetch(function(err,data){if(err)doCallback(callback,[new UsergridError(data),data,self],self);else{var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/"),options={method:"POST",endpoint:endpoint};self._client.request(options,callback)}})}else doCallback(callback,[new UsergridInvalidArgumentError("No asset specified"),null,self],self)},Usergrid.Folder.prototype.removeAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset;break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}if(asset&&null!==asset){var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/");self._client.request({method:"DELETE",endpoint:endpoint},function(err,response){err?doCallback(callback,[new UsergridError(response),response,self],self):doCallback(callback,[null,response,self],self)})}}else doCallback(callback,[new UsergridInvalidArgumentError("No asset specified"),null,self],self)},Usergrid.Folder.prototype.getAssets=function(callback){return this.getConnections("assets",callback)},XMLHttpRequest.prototype.sendAsBinary||(XMLHttpRequest.prototype.sendAsBinary=function(sData){for(var nBytes=sData.length,ui8Data=new Uint8Array(nBytes),nIdx=0;nBytes>nIdx;nIdx++)ui8Data[nIdx]=255&sData.charCodeAt(nIdx);this.send(ui8Data)}),Usergrid.Asset=function(options,callback){var self=this;self._client=options.client,self._data=options.data||{},self._data.type="assets";var missingData=["name","owner","path"].some(function(required){return!(required in self._data)});missingData?doCallback(callback,[new UsergridError("Invalid asset data: 'name', 'owner', and 'path' are required properties."),null,self],self):self.save(function(err,data){err?doCallback(callback,[new UsergridError(data),data,self],self):(data&&data.entities&&data.entities.length&&self.set(data.entities[0]),doCallback(callback,[null,data,self],self))})},Usergrid.Asset.prototype=new Usergrid.Entity,Usergrid.Asset.prototype.addToFolder=function(options,callback){var self=this;if("folder"in options&&isUUID(options.folder)){Usergrid.Folder({uuid:options.folder},function(err,folder){if(err)doCallback(callback,[UsergridError.fromResponse(folder),folder,self],self);else{var endpoint=["folders",folder.get("uuid"),"assets",self.get("uuid")].join("/"),options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,response){err?doCallback(callback,[UsergridError.fromResponse(folder),response,self],self):doCallback(callback,[null,folder,self],self)})}})}else doCallback(callback,[new UsergridError("folder not specified"),null,self],self)},Usergrid.Entity.prototype.attachAsset=function(file,callback){if(!(window.File&&window.FileReader&&window.FileList&&window.Blob))return void doCallback(callback,[new UsergridError("The File APIs are not fully supported by your browser."),null,this],this);var self=this,args=arguments,type=this._data.type,attempts=self.get("attempts");if(isNaN(attempts)&&(attempts=3),"assets"!=type&&"asset"!=type)var endpoint=[this._client.clientAppURL,type,self.get("uuid")].join("/");else{self.set("content-type",file.type),self.set("size",file.size);var endpoint=[this._client.clientAppURL,"assets",self.get("uuid"),"data"].join("/")}var xhr=new XMLHttpRequest;xhr.open("POST",endpoint,!0),xhr.onerror=function(err){doCallback(callback,[new UsergridError("The File APIs are not fully supported by your browser.")],xhr,self)},xhr.onload=function(ev){xhr.status>=500&&attempts>0?(self.set("attempts",--attempts),setTimeout(function(){self.attachAsset.apply(self,args)},100)):xhr.status>=300?(self.set("attempts"),doCallback(callback,[new UsergridError(JSON.parse(xhr.responseText)),xhr,self],self)):(self.set("attempts"),self.fetch(),doCallback(callback,[null,xhr,self],self))};var fr=new FileReader;fr.onload=function(){var binary=fr.result;("assets"===type||"asset"===type)&&(xhr.overrideMimeType("application/octet-stream"),xhr.setRequestHeader("Content-Type","application/octet-stream")),xhr.sendAsBinary(binary)},fr.readAsBinaryString(file)},Usergrid.Asset.prototype.upload=function(data,callback){this.attachAsset(data,function(err,response){err?doCallback(callback,[new UsergridError(err),response,self],self):doCallback(callback,[null,response,self],self)})},Usergrid.Entity.prototype.downloadAsset=function(callback){var endpoint,self=this,type=this._data.type,xhr=new XMLHttpRequest;endpoint="assets"!=type&&"asset"!=type?[this._client.clientAppURL,type,self.get("uuid")].join("/"):[this._client.clientAppURL,"assets",self.get("uuid"),"data"].join("/"),xhr.open("GET",endpoint,!0),xhr.responseType="blob",xhr.onload=function(ev){var blob=xhr.response;"assets"!=type&&"asset"!=type?doCallback(callback,[null,blob,xhr],self):doCallback(callback,[null,xhr,self],self)},xhr.onerror=function(err){callback(!0,err),doCallback(callback,[new UsergridError(err),xhr,self],self)},"assets"!=type&&"asset"!=type?xhr.setRequestHeader("Accept",self._data["file-metadata"]["content-type"]):xhr.overrideMimeType(self.get("content-type")),xhr.send()},Usergrid.Asset.prototype.download=function(callback){this.downloadAsset(function(err,response){err?doCallback(callback,[new UsergridError(err),response,self],self):doCallback(callback,[null,response,self],self)})},function(global){function UsergridError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridHTTPResponseError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidHTTPMethodError(message,name,timestamp,duration,exception){this.message=message,this.name=name||"invalid_http_method",this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidURIError(message,name,timestamp,duration,exception){this.message=message,this.name=name||"invalid_uri",this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidArgumentError(message,name,timestamp,duration,exception){this.message=message,this.name=name||"invalid_argument",this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridKeystoreDatabaseUpgradeNeededError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}var short,name="UsergridError",_name=global[name],_short=short&&void 0!==short?global[short]:void 0;return UsergridError.prototype=new Error,UsergridError.prototype.constructor=UsergridError,UsergridError.fromResponse=function(response){return response&&"undefined"!=typeof response?new UsergridError(response.error_description,response.error,response.timestamp,response.duration,response.exception):new UsergridError},UsergridError.createSubClass=function(name){return name in global&&global[name]?global[name]:(global[name]=function(){},global[name].name=name,global[name].prototype=new UsergridError,global[name])},UsergridHTTPResponseError.prototype=new UsergridError, -UsergridInvalidHTTPMethodError.prototype=new UsergridError,UsergridInvalidURIError.prototype=new UsergridError,UsergridInvalidArgumentError.prototype=new UsergridError,UsergridKeystoreDatabaseUpgradeNeededError.prototype=new UsergridError,global.UsergridHTTPResponseError=UsergridHTTPResponseError,global.UsergridInvalidHTTPMethodError=UsergridInvalidHTTPMethodError,global.UsergridInvalidURIError=UsergridInvalidURIError,global.UsergridInvalidArgumentError=UsergridInvalidArgumentError,global.UsergridKeystoreDatabaseUpgradeNeededError=UsergridKeystoreDatabaseUpgradeNeededError,global[name]=UsergridError,void 0!==short&&(global[short]=UsergridError),global[name].noConflict=function(){return _name&&(global[name]=_name),void 0!==short&&(global[short]=_short),UsergridError},global[name]}(this);var UsergridAuth=function(token,expiry){var self=this;self.token=token,self.expiry=expiry||0;var usingToken=token?!0:!1;return Object.defineProperty(self,"hasToken",{get:function(){return self.token?!0:!1},configurable:!0}),Object.defineProperty(self,"isExpired",{get:function(){return usingToken?!1:Date.now()>=self.expiry},configurable:!0}),Object.defineProperty(self,"isValid",{get:function(){return!self.isExpired&&self.hasToken},configurable:!0}),Object.defineProperty(self,"tokenTtl",{configurable:!0,writable:!0}),self};UsergridAuth.prototype={destroy:function(){this.token=void 0,this.expiry=0,this.tokenTtl=void 0}};var UsergridAppAuth=function(){var self=this,args=flattenArgs(arguments);return _.isPlainObject(args[0])?(self.clientId=args[0].clientId,self.clientSecret=args[0].clientSecret,self.tokenTtl=args[0].tokenTtl):(self.clientId=args[0],self.clientSecret=args[1],self.tokenTtl=args[2]),UsergridAuth.call(self),_.assign(self,UsergridAuth),self};inherits(UsergridAppAuth,UsergridAuth);var UsergridUserAuth=function(){var self=this,args=flattenArgs(arguments);return _.isPlainObject(args[0])&&(options=args[0]),self.username=options.username||args[0],self.email=options.email,(options.password||args[1])&&(self.password=options.password||args[1]),self.tokenTtl=options.tokenTtl||args[2],UsergridAuth.call(self),_.assign(self,UsergridAuth),self};inherits(UsergridUserAuth,UsergridAuth); \ No newline at end of file +"use strict";function inherits(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})}function flattenArgs(args){return _.flattenDeep(Array.prototype.slice.call(args))}function validateAndRetrieveClient(args){var client=void 0;if(args instanceof UsergridClient)client=args;else if(args[0]instanceof UsergridClient)client=args[0];else{if(!Usergrid.isInitialized)throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument");client=Usergrid.getInstance()}return client}function configureTempAuth(auth){return _.isString(auth)&&auth!==UsergridAuthMode.NONE?new UsergridAuth(auth):auth&&auth!==UsergridAuthMode.NONE&&auth instanceof UsergridAuth?auth:void 0}function useQuotesIfRequired(value){return _.isFinite(value)||isUUID(value)||_.isBoolean(value)||_.isObject(value)&&!_.isFunction(value)||_.isArray(value)?value:"'"+value+"'"}function extend(subClass,superClass){var F=function(){};return F.prototype=superClass.prototype,subClass.prototype=new F,subClass.prototype.constructor=subClass,subClass.superclass=superClass.prototype,superClass.prototype.constructor==Object.prototype.constructor&&(superClass.prototype.constructor=superClass),subClass}function propCopy(from,to){for(var prop in from)from.hasOwnProperty(prop)&&("object"==typeof from[prop]&&"object"==typeof to[prop]?to[prop]=propCopy(from[prop],to[prop]):to[prop]=from[prop]);return to}function NOOP(){}function isValidUrl(url){if(!url)return!1;var doc,base,anchor,isValid=!1;try{doc=document.implementation.createHTMLDocument(""),base=doc.createElement("base"),base.href=base||window.lo,doc.head.appendChild(base),anchor=doc.createElement("a"),anchor.href=url,doc.body.appendChild(anchor),isValid=!(""===anchor.href)}catch(e){console.error(e)}finally{return doc.head.removeChild(base),doc.body.removeChild(anchor),base=null,anchor=null,doc=null,isValid}}function isUUID(uuid){return uuid?uuidValueRegex.test(uuid):!1}function encodeParams(params){var queryString;return params&&Object.keys(params)&&(queryString=[].slice.call(arguments).reduce(function(a,b){return a.concat(b instanceof Array?b:[b])},[]).filter(function(c){return"object"==typeof c}).reduce(function(p,c){return c instanceof Array?p.push(c):p=p.concat(Object.keys(c).map(function(key){return[key,c[key]]})),p},[]).reduce(function(p,c){return 2===c.length?p.push(c):p=p.concat(c),p},[]).reduce(function(p,c){return c[1]instanceof Array?c[1].forEach(function(v){p.push([c[0],v])}):p.push(c),p},[]).map(function(c){return c[1]=encodeURIComponent(c[1]),c.join("=")}).join("&")),queryString}function isFunction(f){return f&&null!==f&&"function"==typeof f}function doCallback(callback,params,context){var returnValue;return isFunction(callback)&&(params||(params=[]),context||(context=this),params.push(context),returnValue=callback.apply(context,params)),returnValue}function getSafeTime(prop){var time;switch(typeof prop){case"undefined":time=Date.now();break;case"number":time=prop;break;case"string":time=isNaN(prop)?Date.parse(prop):parseInt(prop);break;default:time=Date.parse(prop.toString())}return time}var UsergridAuthMode=Object.freeze({NONE:"none",USER:"user",APP:"app"}),UsergridDirection=Object.freeze({IN:"connecting",OUT:"connections"}),UsergridHttpMethod=Object.freeze({GET:"GET",PUT:"PUT",POST:"POST",DELETE:"DELETE"}),UsergridQueryOperator=Object.freeze({EQUAL:"=",GREATER_THAN:">",GREATER_THAN_EQUAL_TO:">=",LESS_THAN:"<",LESS_THAN_EQUAL_TO:"<="}),UsergridQuerySortOrder=Object.freeze({ASC:"asc",DESC:"desc"}),UsergridEventable=function(){throw Error("'UsergridEventable' is not intended to be invoked directly")};UsergridEventable.prototype={bind:function(event,fn){this._events=this._events||{},this._events[event]=this._events[event]||[],this._events[event].push(fn)},unbind:function(event,fn){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fn),1)},trigger:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;ii;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,error,result){var p=new Promise;return null===promises||0===promises.length?p.done(error,result):promises[0](error,result).then(function(res,err){promises.splice(0,1),promises?Promise.chain(promises,res,err).then(function(r,e){p.done(r,e)}):p.done(res,err)}),p},global[name]=Promise,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Promise},global[name]}(this),function(){function partial(){var args=Array.prototype.slice.call(arguments),fn=args.shift();return fn.bind(this,args)}function Ajax(){function encode(data){var result="";if("string"==typeof data)result=data;else{var e=encodeURIComponent;for(var i in data)data.hasOwnProperty(i)&&(result+="&"+e(i)+"="+e(data[i]))}return result}function request(m,u,d){var timeout,p=new Promise;return self.logger.time(m+" "+u),function(xhr){xhr.onreadystatechange=function(){4===this.readyState&&(self.logger.timeEnd(m+" "+u),clearTimeout(timeout),p.done(null,this))},xhr.onerror=function(response){clearTimeout(timeout),p.done(response,null)},xhr.oncomplete=function(response){clearTimeout(timeout),self.logger.timeEnd(m+" "+u),self.info("%s request to %s returned %s",m,u,this.status)},xhr.open(m,u),d&&("object"==typeof d&&(d=JSON.stringify(d)),xhr.setRequestHeader("Content-Type","application/json"),xhr.setRequestHeader("Accept","application/json")),timeout=setTimeout(function(){xhr.abort(),p.done("API Call timed out.",null)},3e4),xhr.send(encode(d))}(new XMLHttpRequest),p}this.logger=new global.Logger(name);var self=this;this.request=request,this.get=partial(request,"GET"),this.post=partial(request,"POST"),this.put=partial(request,"PUT"),this["delete"]=partial(request,"DELETE")}var exports,name="Ajax",global=this,overwrittenName=global[name];return global[name]=new Ajax,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}(),function(){function addMapEntry(map,pair){return map.set(pair[0],pair[1]),map}function addSetEntry(set,value){return set.add(value),set}function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}function arrayAggregator(array,setter,iteratee,accumulator){for(var index=-1,length=array?array.length:0;++index-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1;);return index}function charsEndIndex(strSymbols,chrSymbols){for(var index=strSymbols.length;index--&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1;);return index}function countHolders(array,placeholder){for(var length=array.length,result=0;length--;)array[length]===placeholder&&++result;return result}function escapeStringChar(chr){return"\\"+stringEscapes[chr]}function getValue(object,key){return null==object?undefined:object[key]}function hasUnicode(string){return reHasUnicode.test(string)}function hasUnicodeWord(string){return reHasUnicodeWord.test(string)}function iteratorToArray(iterator){for(var data,result=[];!(data=iterator.next()).done;)result.push(data.value);return result}function mapToArray(map){var index=-1,result=Array(map.size);return map.forEach(function(value,key){result[++index]=[key,value]}),result}function overArg(func,transform){return function(arg){return func(transform(arg))}}function replaceHolders(array,placeholder){for(var index=-1,length=array.length,resIndex=0,result=[];++indexdir,arrLength=isArr?array.length:0,view=getView(0,arrLength,this.__views__),start=view.start,end=view.end,length=end-start,index=isRight?end:start-1,iteratees=this.__iteratees__,iterLength=iteratees.length,resIndex=0,takeCount=nativeMin(length,this.__takeCount__);if(!isArr||LARGE_ARRAY_SIZE>arrLength||arrLength==length&&takeCount==length)return baseWrapperValue(array,this.__actions__);var result=[];outer:for(;length--&&takeCount>resIndex;){index+=dir;for(var iterIndex=-1,value=array[index];++iterIndexindex)return!1;var lastIndex=data.length-1;return index==lastIndex?data.pop():splice.call(data,index,1),--this.size,!0}function listCacheGet(key){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?undefined:data[index][1]}function listCacheHas(key){return assocIndexOf(this.__data__,key)>-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?(++this.size,data.push([key,value])):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index=number?number:upper),lower!==undefined&&(number=number>=lower?number:lower)),number}function baseClone(value,isDeep,isFull,customizer,key,object,stack){var result;if(customizer&&(result=object?customizer(value,key,object,stack):customizer(value)),result!==undefined)return result;if(!isObject(value))return value;var isArr=isArray(value);if(isArr){if(result=initCloneArray(value),!isDeep)return copyArray(value,result)}else{var tag=getTag(value),isFunc=tag==funcTag||tag==genTag;if(isBuffer(value))return cloneBuffer(value,isDeep);if(tag==objectTag||tag==argsTag||isFunc&&!object){if(result=initCloneObject(isFunc?{}:value),!isDeep)return copySymbols(value,baseAssign(result,value))}else{if(!cloneableTags[tag])return object?value:{};result=initCloneByTag(value,tag,baseClone,isDeep)}}stack||(stack=new Stack);var stacked=stack.get(value);if(stacked)return stacked;if(stack.set(value,result),!isArr)var props=isFull?getAllKeys(value):keys(value);return arrayEach(props||value,function(subValue,key){props&&(key=subValue,subValue=value[key]),assignValue(result,key,baseClone(subValue,isDeep,isFull,customizer,key,value,stack))}),result}function baseConforms(source){var props=keys(source);return function(object){return baseConformsTo(object,source,props)}}function baseConformsTo(object,source,props){var length=props.length;if(null==object)return!length;for(object=Object(object);length--;){var key=props[length],predicate=source[key],value=object[key];if(value===undefined&&!(key in object)||!predicate(value))return!1}return!0}function baseCreate(proto){return isObject(proto)?objectCreate(proto):{}}function baseDelay(func,wait,args){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return setTimeout(function(){func.apply(undefined,args)},wait)}function baseDifference(array,values,iteratee,comparator){var index=-1,includes=arrayIncludes,isCommon=!0,length=array.length,result=[],valuesLength=values.length;if(!length)return result;iteratee&&(values=arrayMap(values,baseUnary(iteratee))),comparator?(includes=arrayIncludesWith,isCommon=!1):values.length>=LARGE_ARRAY_SIZE&&(includes=cacheHas,isCommon=!1,values=new SetCache(values));outer:for(;++indexstart&&(start=-start>length?0:length+start),end=end===undefined||end>length?length:toInteger(end),0>end&&(end+=length),end=start>end?0:toLength(end);end>start;)array[start++]=value;return array}function baseFilter(collection,predicate){var result=[];return baseEach(collection,function(value,index,collection){predicate(value,index,collection)&&result.push(value)}),result}function baseFlatten(array,depth,predicate,isStrict,result){var index=-1,length=array.length;for(predicate||(predicate=isFlattenable),result||(result=[]);++index0&&predicate(value)?depth>1?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}function baseForOwn(object,iteratee){return object&&baseFor(object,iteratee,keys)}function baseForOwnRight(object,iteratee){return object&&baseForRight(object,iteratee,keys)}function baseFunctions(object,props){return arrayFilter(props,function(key){return isFunction(object[key])})}function baseGet(object,path){path=isKey(path,object)?[path]:castPath(path);for(var index=0,length=path.length;null!=object&&length>index;)object=object[toKey(path[index++])];return index&&index==length?object:undefined}function baseGetAllKeys(object,keysFunc,symbolsFunc){var result=keysFunc(object);return isArray(object)?result:arrayPush(result,symbolsFunc(object))}function baseGetTag(value){return objectToString.call(value)}function baseGt(value,other){return value>other}function baseHas(object,key){return null!=object&&hasOwnProperty.call(object,key)}function baseHasIn(object,key){return null!=object&&key in Object(object)}function baseInRange(number,start,end){return number>=nativeMin(start,end)&&number=120&&array.length>=120)?new SetCache(othIndex&&array):undefined}array=arrays[0];var index=-1,seen=caches[0];outer:for(;++indexvalue}function baseMap(collection,iteratee){var index=-1,result=isArrayLike(collection)?Array(collection.length):[];return baseEach(collection,function(value,key,collection){result[++index]=iteratee(value,key,collection)}),result}function baseMatches(source){var matchData=getMatchData(source);return 1==matchData.length&&matchData[0][2]?matchesStrictComparable(matchData[0][0],matchData[0][1]):function(object){return object===source||baseIsMatch(object,source,matchData)}}function baseMatchesProperty(path,srcValue){return isKey(path)&&isStrictComparable(srcValue)?matchesStrictComparable(toKey(path),srcValue):function(object){var objValue=get(object,path);return objValue===undefined&&objValue===srcValue?hasIn(object,path):baseIsEqual(srcValue,objValue,undefined,UNORDERED_COMPARE_FLAG|PARTIAL_COMPARE_FLAG)}}function baseMerge(object,source,srcIndex,customizer,stack){if(object!==source){if(!isArray(source)&&!isTypedArray(source))var props=baseKeysIn(source);arrayEach(props||source,function(srcValue,key){if(props&&(key=srcValue,srcValue=source[key]),isObject(srcValue))stack||(stack=new Stack),baseMergeDeep(object,source,key,srcIndex,baseMerge,customizer,stack);else{var newValue=customizer?customizer(object[key],srcValue,key+"",object,source,stack):undefined;newValue===undefined&&(newValue=srcValue),assignMergeValue(object,key,newValue)}})}}function baseMergeDeep(object,source,key,srcIndex,mergeFunc,customizer,stack){var objValue=object[key],srcValue=source[key],stacked=stack.get(srcValue);if(stacked)return void assignMergeValue(object,key,stacked);var newValue=customizer?customizer(objValue,srcValue,key+"",object,source,stack):undefined,isCommon=newValue===undefined;isCommon&&(newValue=srcValue,isArray(srcValue)||isTypedArray(srcValue)?isArray(objValue)?newValue=objValue:isArrayLikeObject(objValue)?newValue=copyArray(objValue):(isCommon=!1,newValue=baseClone(srcValue,!0)):isPlainObject(srcValue)||isArguments(srcValue)?isArguments(objValue)?newValue=toPlainObject(objValue):!isObject(objValue)||srcIndex&&isFunction(objValue)?(isCommon=!1,newValue=baseClone(srcValue,!0)):newValue=objValue:isCommon=!1),isCommon&&(stack.set(srcValue,newValue),mergeFunc(newValue,srcValue,srcIndex,customizer,stack),stack["delete"](srcValue)),assignMergeValue(object,key,newValue)}function baseNth(array,n){var length=array.length;if(length)return n+=0>n?length:0,isIndex(n,length)?array[n]:undefined}function baseOrderBy(collection,iteratees,orders){var index=-1;iteratees=arrayMap(iteratees.length?iteratees:[identity],baseUnary(getIteratee()));var result=baseMap(collection,function(value,key,collection){var criteria=arrayMap(iteratees,function(iteratee){return iteratee(value)});return{criteria:criteria,index:++index,value:value}});return baseSortBy(result,function(object,other){return compareMultiple(object,other,orders)})}function basePick(object,props){return object=Object(object),basePickBy(object,props,function(value,key){return key in object})}function basePickBy(object,props,predicate){for(var index=-1,length=props.length,result={};++index-1;)seen!==array&&splice.call(seen,fromIndex,1),splice.call(array,fromIndex,1);return array}function basePullAt(array,indexes){for(var length=array?indexes.length:0,lastIndex=length-1;length--;){var index=indexes[length];if(length==lastIndex||index!==previous){var previous=index;if(isIndex(index))splice.call(array,index,1);else if(isKey(index,array))delete array[toKey(index)];else{var path=castPath(index),object=parent(array,path);null!=object&&delete object[toKey(last(path))]}}}return array}function baseRandom(lower,upper){return lower+nativeFloor(nativeRandom()*(upper-lower+1))}function baseRange(start,end,step,fromRight){for(var index=-1,length=nativeMax(nativeCeil((end-start)/(step||1)),0),result=Array(length);length--;)result[fromRight?length:++index]=start,start+=step;return result}function baseRepeat(string,n){var result="";if(!string||1>n||n>MAX_SAFE_INTEGER)return result;do n%2&&(result+=string),n=nativeFloor(n/2),n&&(string+=string);while(n);return result}function baseRest(func,start){return setToString(overRest(func,start,identity),func+"")}function baseSet(object,path,value,customizer){if(!isObject(object))return object;path=isKey(path,object)?[path]:castPath(path);for(var index=-1,length=path.length,lastIndex=length-1,nested=object;null!=nested&&++indexstart&&(start=-start>length?0:length+start),end=end>length?length:end,0>end&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index=high){for(;high>low;){var mid=low+high>>>1,computed=array[mid];null!==computed&&!isSymbol(computed)&&(retHighest?value>=computed:value>computed)?low=mid+1:high=mid}return high}return baseSortedIndexBy(array,value,identity,retHighest)}function baseSortedIndexBy(array,value,iteratee,retHighest){value=iteratee(value);for(var low=0,high=array?array.length:0,valIsNaN=value!==value,valIsNull=null===value,valIsSymbol=isSymbol(value),valIsUndefined=value===undefined;high>low;){var mid=nativeFloor((low+high)/2),computed=iteratee(array[mid]),othIsDefined=computed!==undefined,othIsNull=null===computed,othIsReflexive=computed===computed,othIsSymbol=isSymbol(computed);if(valIsNaN)var setLow=retHighest||othIsReflexive;else setLow=valIsUndefined?othIsReflexive&&(retHighest||othIsDefined):valIsNull?othIsReflexive&&othIsDefined&&(retHighest||!othIsNull):valIsSymbol?othIsReflexive&&othIsDefined&&!othIsNull&&(retHighest||!othIsSymbol):othIsNull||othIsSymbol?!1:retHighest?value>=computed:value>computed;setLow?low=mid+1:high=mid}return nativeMin(high,MAX_ARRAY_INDEX)}function baseSortedUniq(array,iteratee){for(var index=-1,length=array.length,resIndex=0,result=[];++index=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++indexindex?values[index]:undefined;assignFunc(result,props[index],value)}return result}function castArrayLikeObject(value){return isArrayLikeObject(value)?value:[]}function castFunction(value){return"function"==typeof value?value:identity}function castPath(value){return isArray(value)?value:stringToPath(value)}function castSlice(array,start,end){var length=array.length;return end=end===undefined?length:end,!start&&end>=length?array:baseSlice(array,start,end)}function cloneBuffer(buffer,isDeep){if(isDeep)return buffer.slice();var result=new buffer.constructor(buffer.length);return buffer.copy(result),result}function cloneArrayBuffer(arrayBuffer){var result=new arrayBuffer.constructor(arrayBuffer.byteLength);return new Uint8Array(result).set(new Uint8Array(arrayBuffer)),result}function cloneDataView(dataView,isDeep){var buffer=isDeep?cloneArrayBuffer(dataView.buffer):dataView.buffer;return new dataView.constructor(buffer,dataView.byteOffset,dataView.byteLength)}function cloneMap(map,isDeep,cloneFunc){var array=isDeep?cloneFunc(mapToArray(map),!0):mapToArray(map);return arrayReduce(array,addMapEntry,new map.constructor)}function cloneRegExp(regexp){var result=new regexp.constructor(regexp.source,reFlags.exec(regexp));return result.lastIndex=regexp.lastIndex,result}function cloneSet(set,isDeep,cloneFunc){var array=isDeep?cloneFunc(setToArray(set),!0):setToArray(set);return arrayReduce(array,addSetEntry,new set.constructor)}function cloneSymbol(symbol){return symbolValueOf?Object(symbolValueOf.call(symbol)):{}}function cloneTypedArray(typedArray,isDeep){var buffer=isDeep?cloneArrayBuffer(typedArray.buffer):typedArray.buffer;return new typedArray.constructor(buffer,typedArray.byteOffset,typedArray.length)}function compareAscending(value,other){if(value!==other){var valIsDefined=value!==undefined,valIsNull=null===value,valIsReflexive=value===value,valIsSymbol=isSymbol(value),othIsDefined=other!==undefined,othIsNull=null===other,othIsReflexive=other===other,othIsSymbol=isSymbol(other);if(!othIsNull&&!othIsSymbol&&!valIsSymbol&&value>other||valIsSymbol&&othIsDefined&&othIsReflexive&&!othIsNull&&!othIsSymbol||valIsNull&&othIsDefined&&othIsReflexive||!valIsDefined&&othIsReflexive||!valIsReflexive)return 1;if(!valIsNull&&!valIsSymbol&&!othIsSymbol&&other>value||othIsSymbol&&valIsDefined&&valIsReflexive&&!valIsNull&&!valIsSymbol||othIsNull&&valIsDefined&&valIsReflexive||!othIsDefined&&valIsReflexive||!othIsReflexive)return-1}return 0}function compareMultiple(object,other,orders){for(var index=-1,objCriteria=object.criteria,othCriteria=other.criteria,length=objCriteria.length,ordersLength=orders.length;++index=ordersLength)return result;var order=orders[index];return result*("desc"==order?-1:1)}}return object.index-other.index}function composeArgs(args,partials,holders,isCurried){for(var argsIndex=-1,argsLength=args.length,holdersLength=holders.length,leftIndex=-1,leftLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(leftLength+rangeLength),isUncurried=!isCurried;++leftIndexargsIndex)&&(result[holders[argsIndex]]=args[argsIndex]);for(;rangeLength--;)result[leftIndex++]=args[argsIndex++];return result}function composeArgsRight(args,partials,holders,isCurried){for(var argsIndex=-1,argsLength=args.length,holdersIndex=-1,holdersLength=holders.length,rightIndex=-1,rightLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(rangeLength+rightLength),isUncurried=!isCurried;++argsIndexargsIndex)&&(result[offset+holders[holdersIndex]]=args[argsIndex++]);return result}function copyArray(source,array){var index=-1,length=source.length;for(array||(array=Array(length));++index1?sources[length-1]:undefined,guard=length>2?sources[2]:undefined;for(customizer=assigner.length>3&&"function"==typeof customizer?(length--,customizer):undefined,guard&&isIterateeCall(sources[0],sources[1],guard)&&(customizer=3>length?undefined:customizer,length=1),object=Object(object);++indexlength&&args[0]!==placeholder&&args[length-1]!==placeholder?[]:replaceHolders(args,placeholder);if(length-=holders.length,arity>length)return createRecurry(func,bitmask,createHybrid,wrapper.placeholder,undefined,args,holders,undefined,undefined,arity-length);var fn=this&&this!==root&&this instanceof wrapper?Ctor:func;return apply(fn,this,args)}var Ctor=createCtor(func);return wrapper}function createFind(findIndexFunc){return function(collection,predicate,fromIndex){var iterable=Object(collection);if(!isArrayLike(collection)){var iteratee=getIteratee(predicate,3);collection=keys(collection),predicate=function(key){return iteratee(iterable[key],key,iterable)}}var index=findIndexFunc(collection,predicate,fromIndex);return index>-1?iterable[iteratee?collection[index]:index]:undefined}}function createFlow(fromRight){return flatRest(function(funcs){var length=funcs.length,index=length,prereq=LodashWrapper.prototype.thru;for(fromRight&&funcs.reverse();index--;){var func=funcs[index];if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);if(prereq&&!wrapper&&"wrapper"==getFuncName(func))var wrapper=new LodashWrapper([],!0)}for(index=wrapper?index:length;++index=LARGE_ARRAY_SIZE)return wrapper.plant(value).value();for(var index=0,result=length?funcs[index].apply(this,args):value;++indexlength){var newHolders=replaceHolders(args,placeholder);return createRecurry(func,bitmask,createHybrid,wrapper.placeholder,thisArg,args,newHolders,argPos,ary,arity-length)}var thisBinding=isBind?thisArg:this,fn=isBindKey?thisBinding[func]:func;return length=args.length,argPos?args=reorder(args,argPos):isFlip&&length>1&&args.reverse(),isAry&&length>ary&&(args.length=ary),this&&this!==root&&this instanceof wrapper&&(fn=Ctor||createCtor(fn)),fn.apply(thisBinding,args)}var isAry=bitmask&ARY_FLAG,isBind=bitmask&BIND_FLAG,isBindKey=bitmask&BIND_KEY_FLAG,isCurried=bitmask&(CURRY_FLAG|CURRY_RIGHT_FLAG),isFlip=bitmask&FLIP_FLAG,Ctor=isBindKey?undefined:createCtor(func);return wrapper}function createInverter(setter,toIteratee){return function(object,iteratee){return baseInverter(object,setter,toIteratee(iteratee),{})}}function createMathOperation(operator,defaultValue){return function(value,other){var result;if(value===undefined&&other===undefined)return defaultValue;if(value!==undefined&&(result=value),other!==undefined){if(result===undefined)return other;"string"==typeof value||"string"==typeof other?(value=baseToString(value),other=baseToString(other)):(value=baseToNumber(value),other=baseToNumber(other)),result=operator(value,other)}return result}}function createOver(arrayFunc){return flatRest(function(iteratees){return iteratees=arrayMap(iteratees,baseUnary(getIteratee())),baseRest(function(args){var thisArg=this;return arrayFunc(iteratees,function(iteratee){return apply(iteratee,thisArg,args)})})})}function createPadding(length,chars){chars=chars===undefined?" ":baseToString(chars);var charsLength=chars.length;if(2>charsLength)return charsLength?baseRepeat(chars,length):chars;var result=baseRepeat(chars,nativeCeil(length/stringSize(chars)));return hasUnicode(chars)?castSlice(stringToArray(result),0,length).join(""):result.slice(0,length)}function createPartial(func,bitmask,thisArg,partials){function wrapper(){for(var argsIndex=-1,argsLength=arguments.length,leftIndex=-1,leftLength=partials.length,args=Array(leftLength+argsLength),fn=this&&this!==root&&this instanceof wrapper?Ctor:func;++leftIndexstart?1:-1:toFinite(step),baseRange(start,end,step,fromRight)}}function createRelationalOperation(operator){return function(value,other){return("string"!=typeof value||"string"!=typeof other)&&(value=toNumber(value),other=toNumber(other)),operator(value,other)}}function createRecurry(func,bitmask,wrapFunc,placeholder,thisArg,partials,holders,argPos,ary,arity){var isCurry=bitmask&CURRY_FLAG,newHolders=isCurry?holders:undefined,newHoldersRight=isCurry?undefined:holders,newPartials=isCurry?partials:undefined,newPartialsRight=isCurry?undefined:partials;bitmask|=isCurry?PARTIAL_FLAG:PARTIAL_RIGHT_FLAG,bitmask&=~(isCurry?PARTIAL_RIGHT_FLAG:PARTIAL_FLAG),bitmask&CURRY_BOUND_FLAG||(bitmask&=~(BIND_FLAG|BIND_KEY_FLAG));var newData=[func,bitmask,thisArg,newPartials,newHolders,newPartialsRight,newHoldersRight,argPos,ary,arity],result=wrapFunc.apply(undefined,newData);return isLaziable(func)&&setData(result,newData),result.placeholder=placeholder,setWrapToString(result,func,bitmask)}function createRound(methodName){var func=Math[methodName];return function(number,precision){if(number=toNumber(number),precision=nativeMin(toInteger(precision),292)){var pair=(toString(number)+"e").split("e"),value=func(pair[0]+"e"+(+pair[1]+precision));return pair=(toString(value)+"e").split("e"),+(pair[0]+"e"+(+pair[1]-precision))}return func(number)}}function createToPairs(keysFunc){return function(object){var tag=getTag(object);return tag==mapTag?mapToArray(object):tag==setTag?setToPairs(object):baseToPairs(object,keysFunc(object))}}function createWrap(func,bitmask,thisArg,partials,holders,argPos,ary,arity){var isBindKey=bitmask&BIND_KEY_FLAG;if(!isBindKey&&"function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);var length=partials?partials.length:0;if(length||(bitmask&=~(PARTIAL_FLAG|PARTIAL_RIGHT_FLAG),partials=holders=undefined),ary=ary===undefined?ary:nativeMax(toInteger(ary),0),arity=arity===undefined?arity:toInteger(arity),length-=holders?holders.length:0,bitmask&PARTIAL_RIGHT_FLAG){var partialsRight=partials,holdersRight=holders;partials=holders=undefined}var data=isBindKey?undefined:getData(func),newData=[func,bitmask,thisArg,partials,holders,partialsRight,holdersRight,argPos,ary,arity];if(data&&mergeData(newData,data),func=newData[0],bitmask=newData[1],thisArg=newData[2],partials=newData[3],holders=newData[4],arity=newData[9]=null==newData[9]?isBindKey?0:func.length:nativeMax(newData[9]-length,0),!arity&&bitmask&(CURRY_FLAG|CURRY_RIGHT_FLAG)&&(bitmask&=~(CURRY_FLAG|CURRY_RIGHT_FLAG)),bitmask&&bitmask!=BIND_FLAG)result=bitmask==CURRY_FLAG||bitmask==CURRY_RIGHT_FLAG?createCurry(func,bitmask,arity):bitmask!=PARTIAL_FLAG&&bitmask!=(BIND_FLAG|PARTIAL_FLAG)||holders.length?createHybrid.apply(undefined,newData):createPartial(func,bitmask,thisArg,partials);else var result=createBind(func,bitmask,thisArg);var setter=data?baseSetData:setData;return setWrapToString(setter(result,newData),func,bitmask)}function equalArrays(array,other,equalFunc,customizer,bitmask,stack){var isPartial=bitmask&PARTIAL_COMPARE_FLAG,arrLength=array.length,othLength=other.length;if(arrLength!=othLength&&!(isPartial&&othLength>arrLength))return!1;var stacked=stack.get(array);if(stacked&&stack.get(other))return stacked==other;var index=-1,result=!0,seen=bitmask&UNORDERED_COMPARE_FLAG?new SetCache:undefined;for(stack.set(array,other),stack.set(other,array);++index1?"& ":"")+details[lastIndex],details=details.join(length>2?", ":" "),source.replace(reWrapComment,"{\n/* [wrapped with "+details+"] */\n")}function isFlattenable(value){return isArray(value)||isArguments(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol])}function isIndex(value,length){return length=null==length?MAX_SAFE_INTEGER:length,!!length&&("number"==typeof value||reIsUint.test(value))&&value>-1&&value%1==0&&length>value}function isIterateeCall(value,index,object){if(!isObject(object))return!1;var type=typeof index;return("number"==type?isArrayLike(object)&&isIndex(index,object.length):"string"==type&&index in object)?eq(object[index],value):!1}function isKey(value,object){if(isArray(value))return!1;var type=typeof value;return"number"==type||"symbol"==type||"boolean"==type||null==value||isSymbol(value)?!0:reIsPlainProp.test(value)||!reIsDeepProp.test(value)||null!=object&&value in Object(object)}function isKeyable(value){var type=typeof value;return"string"==type||"number"==type||"symbol"==type||"boolean"==type?"__proto__"!==value:null===value}function isLaziable(func){var funcName=getFuncName(func),other=lodash[funcName];if("function"!=typeof other||!(funcName in LazyWrapper.prototype))return!1;if(func===other)return!0;var data=getData(other);return!!data&&func===data[0]}function isMasked(func){return!!maskSrcKey&&maskSrcKey in func}function isPrototype(value){var Ctor=value&&value.constructor,proto="function"==typeof Ctor&&Ctor.prototype||objectProto;return value===proto}function isStrictComparable(value){return value===value&&!isObject(value)}function matchesStrictComparable(key,srcValue){return function(object){return null==object?!1:object[key]===srcValue&&(srcValue!==undefined||key in Object(object))}}function memoizeCapped(func){var result=memoize(func,function(key){return cache.size===MAX_MEMOIZE_SIZE&&cache.clear(),key}),cache=result.cache;return result}function mergeData(data,source){var bitmask=data[1],srcBitmask=source[1],newBitmask=bitmask|srcBitmask,isCommon=(BIND_FLAG|BIND_KEY_FLAG|ARY_FLAG)>newBitmask,isCombo=srcBitmask==ARY_FLAG&&bitmask==CURRY_FLAG||srcBitmask==ARY_FLAG&&bitmask==REARG_FLAG&&data[7].length<=source[8]||srcBitmask==(ARY_FLAG|REARG_FLAG)&&source[7].length<=source[8]&&bitmask==CURRY_FLAG;if(!isCommon&&!isCombo)return data;srcBitmask&BIND_FLAG&&(data[2]=source[2],newBitmask|=bitmask&BIND_FLAG?0:CURRY_BOUND_FLAG);var value=source[3];if(value){var partials=data[3];data[3]=partials?composeArgs(partials,value,source[4]):value,data[4]=partials?replaceHolders(data[3],PLACEHOLDER):source[4]}return value=source[5],value&&(partials=data[5],data[5]=partials?composeArgsRight(partials,value,source[6]):value,data[6]=partials?replaceHolders(data[5],PLACEHOLDER):source[6]),value=source[7],value&&(data[7]=value),srcBitmask&ARY_FLAG&&(data[8]=null==data[8]?source[8]:nativeMin(data[8],source[8])),null==data[9]&&(data[9]=source[9]),data[0]=source[0],data[1]=newBitmask,data}function mergeDefaults(objValue,srcValue,key,object,source,stack){return isObject(objValue)&&isObject(srcValue)&&(stack.set(srcValue,objValue),baseMerge(objValue,srcValue,undefined,mergeDefaults,stack),stack["delete"](srcValue)),objValue}function nativeKeysIn(object){var result=[];if(null!=object)for(var key in Object(object))result.push(key);return result}function overRest(func,start,transform){return start=nativeMax(start===undefined?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index0){if(++count>=HOT_COUNT)return arguments[0]}else count=0;return func.apply(undefined,arguments)}}function shuffleSelf(array){for(var index=-1,length=array.length,lastIndex=length-1;++indexsize)return[];for(var index=0,resIndex=0,result=Array(nativeCeil(length/size));length>index;)result[resIndex++]=baseSlice(array,index,index+=size);return result}function compact(array){for(var index=-1,length=array?array.length:0,resIndex=0,result=[];++indexn?0:n,length)):[]}function dropRight(array,n,guard){var length=array?array.length:0;return length?(n=guard||n===undefined?1:toInteger(n),n=length-n,baseSlice(array,0,0>n?0:n)):[]}function dropRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!0,!0):[]}function dropWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!0):[]}function fill(array,value,start,end){var length=array?array.length:0;return length?(start&&"number"!=typeof start&&isIterateeCall(array,value,start)&&(start=0,end=length),baseFill(array,value,start,end)):[]}function findIndex(array,predicate,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=null==fromIndex?0:toInteger(fromIndex);return 0>index&&(index=nativeMax(length+index,0)),baseFindIndex(array,getIteratee(predicate,3),index)}function findLastIndex(array,predicate,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=length-1;return fromIndex!==undefined&&(index=toInteger(fromIndex),index=0>fromIndex?nativeMax(length+index,0):nativeMin(index,length-1)),baseFindIndex(array,getIteratee(predicate,3),index,!0)}function flatten(array){var length=array?array.length:0;return length?baseFlatten(array,1):[]}function flattenDeep(array){var length=array?array.length:0;return length?baseFlatten(array,INFINITY):[]}function flattenDepth(array,depth){var length=array?array.length:0;return length?(depth=depth===undefined?1:toInteger(depth),baseFlatten(array,depth)):[]}function fromPairs(pairs){for(var index=-1,length=pairs?pairs.length:0,result={};++indexindex&&(index=nativeMax(length+index,0)),baseIndexOf(array,value,index)}function initial(array){var length=array?array.length:0;return length?baseSlice(array,0,-1):[]}function join(array,separator){return array?nativeJoin.call(array,separator):""}function last(array){var length=array?array.length:0;return length?array[length-1]:undefined}function lastIndexOf(array,value,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=length;return fromIndex!==undefined&&(index=toInteger(fromIndex),index=0>index?nativeMax(length+index,0):nativeMin(index,length-1)),value===value?strictLastIndexOf(array,value,index):baseFindIndex(array,baseIsNaN,index,!0)}function nth(array,n){return array&&array.length?baseNth(array,toInteger(n)):undefined}function pullAll(array,values){return array&&array.length&&values&&values.length?basePullAll(array,values):array}function pullAllBy(array,values,iteratee){return array&&array.length&&values&&values.length?basePullAll(array,values,getIteratee(iteratee,2)):array}function pullAllWith(array,values,comparator){return array&&array.length&&values&&values.length?basePullAll(array,values,undefined,comparator):array}function remove(array,predicate){var result=[];if(!array||!array.length)return result;var index=-1,indexes=[],length=array.length;for(predicate=getIteratee(predicate,3);++indexindex&&eq(array[index],value))return index}return-1}function sortedLastIndex(array,value){return baseSortedIndex(array,value,!0)}function sortedLastIndexBy(array,value,iteratee){return baseSortedIndexBy(array,value,getIteratee(iteratee,2),!0)}function sortedLastIndexOf(array,value){var length=array?array.length:0;if(length){var index=baseSortedIndex(array,value,!0)-1;if(eq(array[index],value))return index}return-1}function sortedUniq(array){return array&&array.length?baseSortedUniq(array):[]}function sortedUniqBy(array,iteratee){return array&&array.length?baseSortedUniq(array,getIteratee(iteratee,2)):[]}function tail(array){var length=array?array.length:0;return length?baseSlice(array,1,length):[]}function take(array,n,guard){return array&&array.length?(n=guard||n===undefined?1:toInteger(n),baseSlice(array,0,0>n?0:n)):[]}function takeRight(array,n,guard){var length=array?array.length:0;return length?(n=guard||n===undefined?1:toInteger(n),n=length-n,baseSlice(array,0>n?0:n,length)):[]}function takeRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!1,!0):[]}function takeWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3)):[]}function uniq(array){return array&&array.length?baseUniq(array):[]}function uniqBy(array,iteratee){return array&&array.length?baseUniq(array,getIteratee(iteratee,2)):[]}function uniqWith(array,comparator){return array&&array.length?baseUniq(array,undefined,comparator):[]}function unzip(array){if(!array||!array.length)return[];var length=0;return array=arrayFilter(array,function(group){return isArrayLikeObject(group)?(length=nativeMax(group.length,length),!0):void 0}),baseTimes(length,function(index){return arrayMap(array,baseProperty(index))})}function unzipWith(array,iteratee){if(!array||!array.length)return[];var result=unzip(array);return null==iteratee?result:arrayMap(result,function(group){return apply(iteratee,undefined,group)})}function zipObject(props,values){return baseZipObject(props||[],values||[],assignValue)}function zipObjectDeep(props,values){return baseZipObject(props||[],values||[],baseSet)}function chain(value){var result=lodash(value);return result.__chain__=!0,result}function tap(value,interceptor){return interceptor(value),value}function thru(value,interceptor){return interceptor(value)}function wrapperChain(){return chain(this)}function wrapperCommit(){return new LodashWrapper(this.value(),this.__chain__)}function wrapperNext(){this.__values__===undefined&&(this.__values__=toArray(this.value()));var done=this.__index__>=this.__values__.length,value=done?undefined:this.__values__[this.__index__++];return{done:done,value:value}}function wrapperToIterator(){return this}function wrapperPlant(value){for(var result,parent=this;parent instanceof baseLodash;){var clone=wrapperClone(parent);clone.__index__=0,clone.__values__=undefined,result?previous.__wrapped__=clone:result=clone;var previous=clone;parent=parent.__wrapped__}return previous.__wrapped__=value,result}function wrapperReverse(){var value=this.__wrapped__;if(value instanceof LazyWrapper){var wrapped=value;return this.__actions__.length&&(wrapped=new LazyWrapper(this)),wrapped=wrapped.reverse(),wrapped.__actions__.push({func:thru,args:[reverse],thisArg:undefined}),new LodashWrapper(wrapped,this.__chain__)}return this.thru(reverse)}function wrapperValue(){return baseWrapperValue(this.__wrapped__,this.__actions__)}function every(collection,predicate,guard){var func=isArray(collection)?arrayEvery:baseEvery;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=undefined),func(collection,getIteratee(predicate,3))}function filter(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,getIteratee(predicate,3))}function flatMap(collection,iteratee){return baseFlatten(map(collection,iteratee),1)}function flatMapDeep(collection,iteratee){return baseFlatten(map(collection,iteratee),INFINITY)}function flatMapDepth(collection,iteratee,depth){return depth=depth===undefined?1:toInteger(depth),baseFlatten(map(collection,iteratee),depth)}function forEach(collection,iteratee){var func=isArray(collection)?arrayEach:baseEach;return func(collection,getIteratee(iteratee,3))}function forEachRight(collection,iteratee){var func=isArray(collection)?arrayEachRight:baseEachRight;return func(collection,getIteratee(iteratee,3))}function includes(collection,value,fromIndex,guard){collection=isArrayLike(collection)?collection:values(collection),fromIndex=fromIndex&&!guard?toInteger(fromIndex):0;var length=collection.length;return 0>fromIndex&&(fromIndex=nativeMax(length+fromIndex,0)),isString(collection)?length>=fromIndex&&collection.indexOf(value,fromIndex)>-1:!!length&&baseIndexOf(collection,value,fromIndex)>-1}function map(collection,iteratee){var func=isArray(collection)?arrayMap:baseMap;return func(collection,getIteratee(iteratee,3))}function orderBy(collection,iteratees,orders,guard){return null==collection?[]:(isArray(iteratees)||(iteratees=null==iteratees?[]:[iteratees]),orders=guard?undefined:orders,isArray(orders)||(orders=null==orders?[]:[orders]),baseOrderBy(collection,iteratees,orders))}function reduce(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduce:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEach)}function reduceRight(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduceRight:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEachRight)}function reject(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,negate(getIteratee(predicate,3)))}function sample(collection){return arraySample(isArrayLike(collection)?collection:values(collection))}function sampleSize(collection,n,guard){return n=(guard?isIterateeCall(collection,n,guard):n===undefined)?1:toInteger(n),arraySampleSize(isArrayLike(collection)?collection:values(collection),n)}function shuffle(collection){return shuffleSelf(isArrayLike(collection)?copyArray(collection):values(collection))}function size(collection){if(null==collection)return 0;if(isArrayLike(collection))return isString(collection)?stringSize(collection):collection.length;var tag=getTag(collection);return tag==mapTag||tag==setTag?collection.size:baseKeys(collection).length}function some(collection,predicate,guard){var func=isArray(collection)?arraySome:baseSome;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=undefined),func(collection,getIteratee(predicate,3))}function after(n,func){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return n=toInteger(n),function(){return--n<1?func.apply(this,arguments):void 0}}function ary(func,n,guard){return n=guard?undefined:n,n=func&&null==n?func.length:n,createWrap(func,ARY_FLAG,undefined,undefined,undefined,undefined,n)}function before(n,func){var result;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return n=toInteger(n),function(){return--n>0&&(result=func.apply(this,arguments)),1>=n&&(func=undefined),result}}function curry(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,CURRY_FLAG,undefined,undefined,undefined,undefined,undefined,arity);return result.placeholder=curry.placeholder,result}function curryRight(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,CURRY_RIGHT_FLAG,undefined,undefined,undefined,undefined,undefined,arity);return result.placeholder=curryRight.placeholder,result}function debounce(func,wait,options){function invokeFunc(time){var args=lastArgs,thisArg=lastThis;return lastArgs=lastThis=undefined,lastInvokeTime=time,result=func.apply(thisArg,args)}function leadingEdge(time){return lastInvokeTime=time,timerId=setTimeout(timerExpired,wait),leading?invokeFunc(time):result}function remainingWait(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime,result=wait-timeSinceLastCall;return maxing?nativeMin(result,maxWait-timeSinceLastInvoke):result}function shouldInvoke(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime;return lastCallTime===undefined||timeSinceLastCall>=wait||0>timeSinceLastCall||maxing&&timeSinceLastInvoke>=maxWait}function timerExpired(){var time=now();return shouldInvoke(time)?trailingEdge(time):void(timerId=setTimeout(timerExpired,remainingWait(time)))}function trailingEdge(time){return timerId=undefined,trailing&&lastArgs?invokeFunc(time):(lastArgs=lastThis=undefined,result)}function cancel(){timerId!==undefined&&clearTimeout(timerId),lastInvokeTime=0,lastArgs=lastCallTime=lastThis=timerId=undefined}function flush(){return timerId===undefined?result:trailingEdge(now())}function debounced(){var time=now(),isInvoking=shouldInvoke(time);if(lastArgs=arguments,lastThis=this,lastCallTime=time,isInvoking){if(timerId===undefined)return leadingEdge(lastCallTime);if(maxing)return timerId=setTimeout(timerExpired,wait),invokeFunc(lastCallTime)}return timerId===undefined&&(timerId=setTimeout(timerExpired,wait)),result}var lastArgs,lastThis,maxWait,result,timerId,lastCallTime,lastInvokeTime=0,leading=!1,maxing=!1,trailing=!0;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return wait=toNumber(wait)||0,isObject(options)&&(leading=!!options.leading,maxing="maxWait"in options,maxWait=maxing?nativeMax(toNumber(options.maxWait)||0,wait):maxWait,trailing="trailing"in options?!!options.trailing:trailing),debounced.cancel=cancel,debounced.flush=flush,debounced}function flip(func){return createWrap(func,FLIP_FLAG)}function memoize(func,resolver){if("function"!=typeof func||resolver&&"function"!=typeof resolver)throw new TypeError(FUNC_ERROR_TEXT);var memoized=function(){var args=arguments,key=resolver?resolver.apply(this,args):args[0],cache=memoized.cache;if(cache.has(key))return cache.get(key);var result=func.apply(this,args);return memoized.cache=cache.set(key,result)||cache,result};return memoized.cache=new(memoize.Cache||MapCache),memoized}function negate(predicate){if("function"!=typeof predicate)throw new TypeError(FUNC_ERROR_TEXT);return function(){var args=arguments;switch(args.length){case 0:return!predicate.call(this);case 1:return!predicate.call(this,args[0]);case 2:return!predicate.call(this,args[0],args[1]);case 3:return!predicate.call(this,args[0],args[1],args[2])}return!predicate.apply(this,args)}}function once(func){return before(2,func)}function rest(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=start===undefined?start:toInteger(start),baseRest(func,start)}function spread(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=start===undefined?0:nativeMax(toInteger(start),0),baseRest(function(args){var array=args[start],otherArgs=castSlice(args,0,start);return array&&arrayPush(otherArgs,array),apply(func,this,otherArgs)})}function throttle(func,wait,options){var leading=!0,trailing=!0;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return isObject(options)&&(leading="leading"in options?!!options.leading:leading,trailing="trailing"in options?!!options.trailing:trailing),debounce(func,wait,{leading:leading,maxWait:wait,trailing:trailing})}function unary(func){return ary(func,1)}function wrap(value,wrapper){return wrapper=null==wrapper?identity:wrapper,partial(wrapper,value)}function castArray(){if(!arguments.length)return[];var value=arguments[0];return isArray(value)?value:[value]}function clone(value){return baseClone(value,!1,!0)}function cloneWith(value,customizer){return baseClone(value,!1,!0,customizer)}function cloneDeep(value){return baseClone(value,!0,!0)}function cloneDeepWith(value,customizer){return baseClone(value,!0,!0,customizer)}function conformsTo(object,source){return null==source||baseConformsTo(object,source,keys(source))}function eq(value,other){return value===other||value!==value&&other!==other}function isArguments(value){return isArrayLikeObject(value)&&hasOwnProperty.call(value,"callee")&&(!propertyIsEnumerable.call(value,"callee")||objectToString.call(value)==argsTag)}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value)}function isBoolean(value){return value===!0||value===!1||isObjectLike(value)&&objectToString.call(value)==boolTag}function isElement(value){return null!=value&&1===value.nodeType&&isObjectLike(value)&&!isPlainObject(value)}function isEmpty(value){if(isArrayLike(value)&&(isArray(value)||"string"==typeof value||"function"==typeof value.splice||isBuffer(value)||isArguments(value)))return!value.length;var tag=getTag(value);if(tag==mapTag||tag==setTag)return!value.size;if(isPrototype(value))return!nativeKeys(value).length;for(var key in value)if(hasOwnProperty.call(value,key))return!1;return!0}function isEqual(value,other){return baseIsEqual(value,other)}function isEqualWith(value,other,customizer){customizer="function"==typeof customizer?customizer:undefined;var result=customizer?customizer(value,other):undefined;return result===undefined?baseIsEqual(value,other,customizer):!!result}function isError(value){return isObjectLike(value)?objectToString.call(value)==errorTag||"string"==typeof value.message&&"string"==typeof value.name:!1}function isFinite(value){return"number"==typeof value&&nativeIsFinite(value)}function isFunction(value){var tag=isObject(value)?objectToString.call(value):"";return tag==funcTag||tag==genTag}function isInteger(value){return"number"==typeof value&&value==toInteger(value)}function isLength(value){return"number"==typeof value&&value>-1&&value%1==0&&MAX_SAFE_INTEGER>=value}function isObject(value){var type=typeof value;return null!=value&&("object"==type||"function"==type)}function isObjectLike(value){return null!=value&&"object"==typeof value}function isMatch(object,source){return object===source||baseIsMatch(object,source,getMatchData(source))}function isMatchWith(object,source,customizer){return customizer="function"==typeof customizer?customizer:undefined,baseIsMatch(object,source,getMatchData(source),customizer)}function isNaN(value){return isNumber(value)&&value!=+value}function isNative(value){if(isMaskable(value))throw new Error("This method is not supported with core-js. Try https://github.com/es-shims.");return baseIsNative(value)}function isNull(value){return null===value}function isNil(value){return null==value}function isNumber(value){return"number"==typeof value||isObjectLike(value)&&objectToString.call(value)==numberTag}function isPlainObject(value){if(!isObjectLike(value)||objectToString.call(value)!=objectTag)return!1;var proto=getPrototype(value);if(null===proto)return!0;var Ctor=hasOwnProperty.call(proto,"constructor")&&proto.constructor;return"function"==typeof Ctor&&Ctor instanceof Ctor&&funcToString.call(Ctor)==objectCtorString}function isSafeInteger(value){return isInteger(value)&&value>=-MAX_SAFE_INTEGER&&MAX_SAFE_INTEGER>=value}function isString(value){return"string"==typeof value||!isArray(value)&&isObjectLike(value)&&objectToString.call(value)==stringTag}function isSymbol(value){return"symbol"==typeof value||isObjectLike(value)&&objectToString.call(value)==symbolTag}function isUndefined(value){return value===undefined}function isWeakMap(value){return isObjectLike(value)&&getTag(value)==weakMapTag}function isWeakSet(value){return isObjectLike(value)&&objectToString.call(value)==weakSetTag}function toArray(value){if(!value)return[];if(isArrayLike(value))return isString(value)?stringToArray(value):copyArray(value);if(iteratorSymbol&&value[iteratorSymbol])return iteratorToArray(value[iteratorSymbol]());var tag=getTag(value),func=tag==mapTag?mapToArray:tag==setTag?setToArray:values;return func(value)}function toFinite(value){if(!value)return 0===value?value:0;if(value=toNumber(value),value===INFINITY||value===-INFINITY){var sign=0>value?-1:1;return sign*MAX_INTEGER}return value===value?value:0}function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0}function toLength(value){return value?baseClamp(toInteger(value),0,MAX_ARRAY_LENGTH):0}function toNumber(value){if("number"==typeof value)return value;if(isSymbol(value))return NAN;if(isObject(value)){var other="function"==typeof value.valueOf?value.valueOf():value;value=isObject(other)?other+"":other}if("string"!=typeof value)return 0===value?value:+value;value=value.replace(reTrim,"");var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value}function toPlainObject(value){return copyObject(value,keysIn(value))}function toSafeInteger(value){return baseClamp(toInteger(value),-MAX_SAFE_INTEGER,MAX_SAFE_INTEGER)}function toString(value){return null==value?"":baseToString(value)}function create(prototype,properties){var result=baseCreate(prototype);return properties?baseAssign(result,properties):result}function findKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwn)}function findLastKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwnRight)}function forIn(object,iteratee){return null==object?object:baseFor(object,getIteratee(iteratee,3),keysIn)}function forInRight(object,iteratee){return null==object?object:baseForRight(object,getIteratee(iteratee,3),keysIn)}function forOwn(object,iteratee){return object&&baseForOwn(object,getIteratee(iteratee,3))}function forOwnRight(object,iteratee){return object&&baseForOwnRight(object,getIteratee(iteratee,3))}function functions(object){return null==object?[]:baseFunctions(object,keys(object))}function functionsIn(object){return null==object?[]:baseFunctions(object,keysIn(object))}function get(object,path,defaultValue){var result=null==object?undefined:baseGet(object,path);return result===undefined?defaultValue:result}function has(object,path){return null!=object&&hasPath(object,path,baseHas)}function hasIn(object,path){return null!=object&&hasPath(object,path,baseHasIn)}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function keysIn(object){return isArrayLike(object)?arrayLikeKeys(object,!0):baseKeysIn(object)}function mapKeys(object,iteratee){var result={};return iteratee=getIteratee(iteratee,3),baseForOwn(object,function(value,key,object){baseAssignValue(result,iteratee(value,key,object),value)}),result}function mapValues(object,iteratee){var result={};return iteratee=getIteratee(iteratee,3),baseForOwn(object,function(value,key,object){baseAssignValue(result,key,iteratee(value,key,object))}),result}function omitBy(object,predicate){return pickBy(object,negate(getIteratee(predicate)))}function pickBy(object,predicate){return null==object?{}:basePickBy(object,getAllKeysIn(object),getIteratee(predicate))}function result(object,path,defaultValue){path=isKey(path,object)?[path]:castPath(path);var index=-1,length=path.length;for(length||(object=undefined,length=1);++indexupper){var temp=lower;lower=upper,upper=temp}if(floating||lower%1||upper%1){var rand=nativeRandom();return nativeMin(lower+rand*(upper-lower+freeParseFloat("1e-"+((rand+"").length-1))),upper)}return baseRandom(lower,upper)}function capitalize(string){return upperFirst(toString(string).toLowerCase())}function deburr(string){return string=toString(string),string&&string.replace(reLatin,deburrLetter).replace(reComboMark,"")}function endsWith(string,target,position){string=toString(string),target=baseToString(target);var length=string.length;position=position===undefined?length:baseClamp(toInteger(position),0,length);var end=position;return position-=target.length,position>=0&&string.slice(position,end)==target}function escape(string){return string=toString(string),string&&reHasUnescapedHtml.test(string)?string.replace(reUnescapedHtml,escapeHtmlChar):string}function escapeRegExp(string){return string=toString(string),string&&reHasRegExpChar.test(string)?string.replace(reRegExpChar,"\\$&"):string}function pad(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;if(!length||strLength>=length)return string;var mid=(length-strLength)/2;return createPadding(nativeFloor(mid),chars)+string+createPadding(nativeCeil(mid),chars)}function padEnd(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;return length&&length>strLength?string+createPadding(length-strLength,chars):string}function padStart(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;return length&&length>strLength?createPadding(length-strLength,chars)+string:string}function parseInt(string,radix,guard){return guard||null==radix?radix=0:radix&&(radix=+radix),nativeParseInt(toString(string),radix||0)}function repeat(string,n,guard){return n=(guard?isIterateeCall(string,n,guard):n===undefined)?1:toInteger(n),baseRepeat(toString(string),n)}function replace(){var args=arguments,string=toString(args[0]);return args.length<3?string:string.replace(args[1],args[2])}function split(string,separator,limit){return limit&&"number"!=typeof limit&&isIterateeCall(string,separator,limit)&&(separator=limit=undefined),(limit=limit===undefined?MAX_ARRAY_LENGTH:limit>>>0)?(string=toString(string),string&&("string"==typeof separator||null!=separator&&!isRegExp(separator))&&(separator=baseToString(separator),!separator&&hasUnicode(string))?castSlice(stringToArray(string),0,limit):string.split(separator,limit)):[]}function startsWith(string,target,position){return string=toString(string),position=baseClamp(toInteger(position),0,string.length),target=baseToString(target),string.slice(position,position+target.length)==target}function template(string,options,guard){var settings=lodash.templateSettings;guard&&isIterateeCall(string,options,guard)&&(options=undefined),string=toString(string),options=assignInWith({},options,settings,assignInDefaults);var isEscaping,isEvaluating,imports=assignInWith({},options.imports,settings.imports,assignInDefaults),importsKeys=keys(imports),importsValues=baseValues(imports,importsKeys),index=0,interpolate=options.interpolate||reNoMatch,source="__p += '",reDelimiters=RegExp((options.escape||reNoMatch).source+"|"+interpolate.source+"|"+(interpolate===reInterpolate?reEsTemplate:reNoMatch).source+"|"+(options.evaluate||reNoMatch).source+"|$","g"),sourceURL="//# sourceURL="+("sourceURL"in options?options.sourceURL:"lodash.templateSources["+ ++templateCounter+"]")+"\n";string.replace(reDelimiters,function(match,escapeValue,interpolateValue,esTemplateValue,evaluateValue,offset){return interpolateValue||(interpolateValue=esTemplateValue),source+=string.slice(index,offset).replace(reUnescapedString,escapeStringChar),escapeValue&&(isEscaping=!0,source+="' +\n__e("+escapeValue+") +\n'"),evaluateValue&&(isEvaluating=!0,source+="';\n"+evaluateValue+";\n__p += '"),interpolateValue&&(source+="' +\n((__t = ("+interpolateValue+")) == null ? '' : __t) +\n'"),index=offset+match.length,match}),source+="';\n";var variable=options.variable;variable||(source="with (obj) {\n"+source+"\n}\n"),source=(isEvaluating?source.replace(reEmptyStringLeading,""):source).replace(reEmptyStringMiddle,"$1").replace(reEmptyStringTrailing,"$1;"),source="function("+(variable||"obj")+") {\n"+(variable?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(isEscaping?", __e = _.escape":"")+(isEvaluating?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+source+"return __p\n}";var result=attempt(function(){return Function(importsKeys,sourceURL+"return "+source).apply(undefined,importsValues)});if(result.source=source,isError(result))throw result;return result}function toLower(value){return toString(value).toLowerCase()}function toUpper(value){return toString(value).toUpperCase()}function trim(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrim,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),chrSymbols=stringToArray(chars),start=charsStartIndex(strSymbols,chrSymbols),end=charsEndIndex(strSymbols,chrSymbols)+1;return castSlice(strSymbols,start,end).join("")}function trimEnd(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrimEnd,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),end=charsEndIndex(strSymbols,stringToArray(chars))+1;return castSlice(strSymbols,0,end).join("")}function trimStart(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrimStart,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),start=charsStartIndex(strSymbols,stringToArray(chars));return castSlice(strSymbols,start).join("")}function truncate(string,options){var length=DEFAULT_TRUNC_LENGTH,omission=DEFAULT_TRUNC_OMISSION;if(isObject(options)){var separator="separator"in options?options.separator:separator;length="length"in options?toInteger(options.length):length,omission="omission"in options?baseToString(options.omission):omission}string=toString(string);var strLength=string.length;if(hasUnicode(string)){var strSymbols=stringToArray(string);strLength=strSymbols.length}if(length>=strLength)return string;var end=length-stringSize(omission);if(1>end)return omission;var result=strSymbols?castSlice(strSymbols,0,end).join(""):string.slice(0,end);if(separator===undefined)return result+omission;if(strSymbols&&(end+=result.length-end),isRegExp(separator)){if(string.slice(end).search(separator)){var match,substring=result;for(separator.global||(separator=RegExp(separator.source,toString(reFlags.exec(separator))+"g")),separator.lastIndex=0;match=separator.exec(substring);)var newEnd=match.index;result=result.slice(0,newEnd===undefined?end:newEnd)}}else if(string.indexOf(baseToString(separator),end)!=end){var index=result.lastIndexOf(separator);index>-1&&(result=result.slice(0,index))}return result+omission}function unescape(string){return string=toString(string),string&&reHasEscapedHtml.test(string)?string.replace(reEscapedHtml,unescapeHtmlChar):string}function words(string,pattern,guard){return string=toString(string),pattern=guard?undefined:pattern,pattern===undefined?hasUnicodeWord(string)?unicodeWords(string):asciiWords(string):string.match(pattern)||[]}function cond(pairs){var length=pairs?pairs.length:0,toIteratee=getIteratee();return pairs=length?arrayMap(pairs,function(pair){if("function"!=typeof pair[1])throw new TypeError(FUNC_ERROR_TEXT);return[toIteratee(pair[0]),pair[1]]}):[],baseRest(function(args){for(var index=-1;++indexn||n>MAX_SAFE_INTEGER)return[];var index=MAX_ARRAY_LENGTH,length=nativeMin(n,MAX_ARRAY_LENGTH);iteratee=getIteratee(iteratee),n-=MAX_ARRAY_LENGTH;for(var result=baseTimes(length,iteratee);++index1?arrays[length-1]:undefined;return iteratee="function"==typeof iteratee?(arrays.pop(),iteratee):undefined,unzipWith(arrays,iteratee)}),wrapperAt=flatRest(function(paths){var length=paths.length,start=length?paths[0]:0,value=this.__wrapped__,interceptor=function(object){return baseAt(object,paths)};return!(length>1||this.__actions__.length)&&value instanceof LazyWrapper&&isIndex(start)?(value=value.slice(start,+start+(length?1:0)),value.__actions__.push({func:thru,args:[interceptor],thisArg:undefined}),new LodashWrapper(value,this.__chain__).thru(function(array){return length&&!array.length&&array.push(undefined),array})):this.thru(interceptor)}),countBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?++result[key]:baseAssignValue(result,key,1)}),find=createFind(findIndex),findLast=createFind(findLastIndex),groupBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?result[key].push(value):baseAssignValue(result,key,[value])}),invokeMap=baseRest(function(collection,path,args){var index=-1,isFunc="function"==typeof path,isProp=isKey(path),result=isArrayLike(collection)?Array(collection.length):[];return baseEach(collection,function(value){var func=isFunc?path:isProp&&null!=value?value[path]:undefined;result[++index]=func?apply(func,value,args):baseInvoke(value,path,args)}),result}),keyBy=createAggregator(function(result,value,key){baseAssignValue(result,key,value)}),partition=createAggregator(function(result,value,key){result[key?0:1].push(value)},function(){return[[],[]]}),sortBy=baseRest(function(collection,iteratees){if(null==collection)return[];var length=iteratees.length;return length>1&&isIterateeCall(collection,iteratees[0],iteratees[1])?iteratees=[]:length>2&&isIterateeCall(iteratees[0],iteratees[1],iteratees[2])&&(iteratees=[iteratees[0]]),baseOrderBy(collection,baseFlatten(iteratees,1),[])}),now=ctxNow||function(){return root.Date.now()},bind=baseRest(function(func,thisArg,partials){var bitmask=BIND_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bind));bitmask|=PARTIAL_FLAG}return createWrap(func,bitmask,thisArg,partials,holders)}),bindKey=baseRest(function(object,key,partials){var bitmask=BIND_FLAG|BIND_KEY_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bindKey));bitmask|=PARTIAL_FLAG}return createWrap(key,bitmask,object,partials,holders)}),defer=baseRest(function(func,args){return baseDelay(func,1,args)}),delay=baseRest(function(func,wait,args){return baseDelay(func,toNumber(wait)||0,args)});memoize.Cache=MapCache;var overArgs=castRest(function(func,transforms){transforms=1==transforms.length&&isArray(transforms[0])?arrayMap(transforms[0],baseUnary(getIteratee())):arrayMap(baseFlatten(transforms,1),baseUnary(getIteratee()));var funcsLength=transforms.length;return baseRest(function(args){for(var index=-1,length=nativeMin(args.length,funcsLength);++index=other}),isArray=Array.isArray,isArrayBuffer=nodeIsArrayBuffer?baseUnary(nodeIsArrayBuffer):baseIsArrayBuffer,isBuffer=nativeIsBuffer||stubFalse,isDate=nodeIsDate?baseUnary(nodeIsDate):baseIsDate,isMap=nodeIsMap?baseUnary(nodeIsMap):baseIsMap,isRegExp=nodeIsRegExp?baseUnary(nodeIsRegExp):baseIsRegExp,isSet=nodeIsSet?baseUnary(nodeIsSet):baseIsSet,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray,lt=createRelationalOperation(baseLt),lte=createRelationalOperation(function(value,other){return other>=value}),assign=createAssigner(function(object,source){if(isPrototype(source)||isArrayLike(source))return void copyObject(source,keys(source),object);for(var key in source)hasOwnProperty.call(source,key)&&assignValue(object,key,source[key])}),assignIn=createAssigner(function(object,source){copyObject(source,keysIn(source),object)}),assignInWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keysIn(source),object,customizer)}),assignWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keys(source),object,customizer)}),at=flatRest(baseAt),defaults=baseRest(function(args){return args.push(undefined,assignInDefaults),apply(assignInWith,undefined,args)}),defaultsDeep=baseRest(function(args){return args.push(undefined,mergeDefaults),apply(mergeWith,undefined,args)}),invert=createInverter(function(result,value,key){result[value]=key},constant(identity)),invertBy=createInverter(function(result,value,key){hasOwnProperty.call(result,value)?result[value].push(key):result[value]=[key]},getIteratee),invoke=baseRest(baseInvoke),merge=createAssigner(function(object,source,srcIndex){baseMerge(object,source,srcIndex)}),mergeWith=createAssigner(function(object,source,srcIndex,customizer){baseMerge(object,source,srcIndex,customizer)}),omit=flatRest(function(object,props){return null==object?{}:(props=arrayMap(props,toKey),basePick(object,baseDifference(getAllKeysIn(object),props)))}),pick=flatRest(function(object,props){return null==object?{}:basePick(object,arrayMap(props,toKey))}),toPairs=createToPairs(keys),toPairsIn=createToPairs(keysIn),camelCase=createCompounder(function(result,word,index){return word=word.toLowerCase(),result+(index?capitalize(word):word)}),kebabCase=createCompounder(function(result,word,index){return result+(index?"-":"")+word.toLowerCase()}),lowerCase=createCompounder(function(result,word,index){return result+(index?" ":"")+word.toLowerCase()}),lowerFirst=createCaseFirst("toLowerCase"),snakeCase=createCompounder(function(result,word,index){return result+(index?"_":"")+word.toLowerCase()}),startCase=createCompounder(function(result,word,index){return result+(index?" ":"")+upperFirst(word)}),upperCase=createCompounder(function(result,word,index){return result+(index?" ":"")+word.toUpperCase()}),upperFirst=createCaseFirst("toUpperCase"),attempt=baseRest(function(func,args){try{return apply(func,undefined,args)}catch(e){return isError(e)?e:new Error(e)}}),bindAll=flatRest(function(object,methodNames){return arrayEach(methodNames,function(key){key=toKey(key),baseAssignValue(object,key,bind(object[key],object))}),object}),flow=createFlow(),flowRight=createFlow(!0),method=baseRest(function(path,args){return function(object){return baseInvoke(object,path,args)}}),methodOf=baseRest(function(object,args){return function(path){return baseInvoke(object,path,args)}}),over=createOver(arrayMap),overEvery=createOver(arrayEvery),overSome=createOver(arraySome),range=createRange(),rangeRight=createRange(!0),add=createMathOperation(function(augend,addend){return augend+addend},0),ceil=createRound("ceil"),divide=createMathOperation(function(dividend,divisor){return dividend/divisor},1),floor=createRound("floor"),multiply=createMathOperation(function(multiplier,multiplicand){return multiplier*multiplicand},1),round=createRound("round"),subtract=createMathOperation(function(minuend,subtrahend){return minuend-subtrahend},0);return lodash.after=after,lodash.ary=ary,lodash.assign=assign,lodash.assignIn=assignIn,lodash.assignInWith=assignInWith,lodash.assignWith=assignWith,lodash.at=at,lodash.before=before,lodash.bind=bind,lodash.bindAll=bindAll,lodash.bindKey=bindKey,lodash.castArray=castArray,lodash.chain=chain,lodash.chunk=chunk,lodash.compact=compact,lodash.concat=concat,lodash.cond=cond,lodash.conforms=conforms,lodash.constant=constant,lodash.countBy=countBy,lodash.create=create,lodash.curry=curry,lodash.curryRight=curryRight,lodash.debounce=debounce,lodash.defaults=defaults,lodash.defaultsDeep=defaultsDeep,lodash.defer=defer,lodash.delay=delay,lodash.difference=difference,lodash.differenceBy=differenceBy,lodash.differenceWith=differenceWith,lodash.drop=drop,lodash.dropRight=dropRight,lodash.dropRightWhile=dropRightWhile,lodash.dropWhile=dropWhile,lodash.fill=fill,lodash.filter=filter,lodash.flatMap=flatMap,lodash.flatMapDeep=flatMapDeep,lodash.flatMapDepth=flatMapDepth,lodash.flatten=flatten,lodash.flattenDeep=flattenDeep,lodash.flattenDepth=flattenDepth,lodash.flip=flip,lodash.flow=flow,lodash.flowRight=flowRight,lodash.fromPairs=fromPairs,lodash.functions=functions,lodash.functionsIn=functionsIn,lodash.groupBy=groupBy,lodash.initial=initial,lodash.intersection=intersection,lodash.intersectionBy=intersectionBy,lodash.intersectionWith=intersectionWith,lodash.invert=invert,lodash.invertBy=invertBy,lodash.invokeMap=invokeMap,lodash.iteratee=iteratee,lodash.keyBy=keyBy,lodash.keys=keys,lodash.keysIn=keysIn,lodash.map=map,lodash.mapKeys=mapKeys,lodash.mapValues=mapValues,lodash.matches=matches,lodash.matchesProperty=matchesProperty,lodash.memoize=memoize,lodash.merge=merge,lodash.mergeWith=mergeWith,lodash.method=method,lodash.methodOf=methodOf,lodash.mixin=mixin,lodash.negate=negate,lodash.nthArg=nthArg,lodash.omit=omit,lodash.omitBy=omitBy,lodash.once=once,lodash.orderBy=orderBy,lodash.over=over,lodash.overArgs=overArgs,lodash.overEvery=overEvery,lodash.overSome=overSome,lodash.partial=partial,lodash.partialRight=partialRight,lodash.partition=partition,lodash.pick=pick,lodash.pickBy=pickBy,lodash.property=property,lodash.propertyOf=propertyOf,lodash.pull=pull,lodash.pullAll=pullAll,lodash.pullAllBy=pullAllBy,lodash.pullAllWith=pullAllWith,lodash.pullAt=pullAt,lodash.range=range,lodash.rangeRight=rangeRight,lodash.rearg=rearg,lodash.reject=reject,lodash.remove=remove,lodash.rest=rest,lodash.reverse=reverse,lodash.sampleSize=sampleSize,lodash.set=set,lodash.setWith=setWith,lodash.shuffle=shuffle,lodash.slice=slice,lodash.sortBy=sortBy,lodash.sortedUniq=sortedUniq,lodash.sortedUniqBy=sortedUniqBy,lodash.split=split,lodash.spread=spread,lodash.tail=tail,lodash.take=take,lodash.takeRight=takeRight,lodash.takeRightWhile=takeRightWhile,lodash.takeWhile=takeWhile,lodash.tap=tap,lodash.throttle=throttle,lodash.thru=thru,lodash.toArray=toArray,lodash.toPairs=toPairs,lodash.toPairsIn=toPairsIn,lodash.toPath=toPath,lodash.toPlainObject=toPlainObject,lodash.transform=transform,lodash.unary=unary,lodash.union=union,lodash.unionBy=unionBy,lodash.unionWith=unionWith,lodash.uniq=uniq,lodash.uniqBy=uniqBy,lodash.uniqWith=uniqWith,lodash.unset=unset,lodash.unzip=unzip,lodash.unzipWith=unzipWith,lodash.update=update,lodash.updateWith=updateWith,lodash.values=values,lodash.valuesIn=valuesIn,lodash.without=without,lodash.words=words,lodash.wrap=wrap,lodash.xor=xor,lodash.xorBy=xorBy,lodash.xorWith=xorWith,lodash.zip=zip,lodash.zipObject=zipObject,lodash.zipObjectDeep=zipObjectDeep,lodash.zipWith=zipWith,lodash.entries=toPairs,lodash.entriesIn=toPairsIn,lodash.extend=assignIn,lodash.extendWith=assignInWith,mixin(lodash,lodash),lodash.add=add,lodash.attempt=attempt,lodash.camelCase=camelCase,lodash.capitalize=capitalize,lodash.ceil=ceil,lodash.clamp=clamp,lodash.clone=clone,lodash.cloneDeep=cloneDeep,lodash.cloneDeepWith=cloneDeepWith,lodash.cloneWith=cloneWith,lodash.conformsTo=conformsTo,lodash.deburr=deburr,lodash.defaultTo=defaultTo,lodash.divide=divide,lodash.endsWith=endsWith,lodash.eq=eq,lodash.escape=escape,lodash.escapeRegExp=escapeRegExp,lodash.every=every,lodash.find=find,lodash.findIndex=findIndex,lodash.findKey=findKey,lodash.findLast=findLast,lodash.findLastIndex=findLastIndex,lodash.findLastKey=findLastKey,lodash.floor=floor,lodash.forEach=forEach,lodash.forEachRight=forEachRight,lodash.forIn=forIn, +lodash.forInRight=forInRight,lodash.forOwn=forOwn,lodash.forOwnRight=forOwnRight,lodash.get=get,lodash.gt=gt,lodash.gte=gte,lodash.has=has,lodash.hasIn=hasIn,lodash.head=head,lodash.identity=identity,lodash.includes=includes,lodash.indexOf=indexOf,lodash.inRange=inRange,lodash.invoke=invoke,lodash.isArguments=isArguments,lodash.isArray=isArray,lodash.isArrayBuffer=isArrayBuffer,lodash.isArrayLike=isArrayLike,lodash.isArrayLikeObject=isArrayLikeObject,lodash.isBoolean=isBoolean,lodash.isBuffer=isBuffer,lodash.isDate=isDate,lodash.isElement=isElement,lodash.isEmpty=isEmpty,lodash.isEqual=isEqual,lodash.isEqualWith=isEqualWith,lodash.isError=isError,lodash.isFinite=isFinite,lodash.isFunction=isFunction,lodash.isInteger=isInteger,lodash.isLength=isLength,lodash.isMap=isMap,lodash.isMatch=isMatch,lodash.isMatchWith=isMatchWith,lodash.isNaN=isNaN,lodash.isNative=isNative,lodash.isNil=isNil,lodash.isNull=isNull,lodash.isNumber=isNumber,lodash.isObject=isObject,lodash.isObjectLike=isObjectLike,lodash.isPlainObject=isPlainObject,lodash.isRegExp=isRegExp,lodash.isSafeInteger=isSafeInteger,lodash.isSet=isSet,lodash.isString=isString,lodash.isSymbol=isSymbol,lodash.isTypedArray=isTypedArray,lodash.isUndefined=isUndefined,lodash.isWeakMap=isWeakMap,lodash.isWeakSet=isWeakSet,lodash.join=join,lodash.kebabCase=kebabCase,lodash.last=last,lodash.lastIndexOf=lastIndexOf,lodash.lowerCase=lowerCase,lodash.lowerFirst=lowerFirst,lodash.lt=lt,lodash.lte=lte,lodash.max=max,lodash.maxBy=maxBy,lodash.mean=mean,lodash.meanBy=meanBy,lodash.min=min,lodash.minBy=minBy,lodash.stubArray=stubArray,lodash.stubFalse=stubFalse,lodash.stubObject=stubObject,lodash.stubString=stubString,lodash.stubTrue=stubTrue,lodash.multiply=multiply,lodash.nth=nth,lodash.noConflict=noConflict,lodash.noop=noop,lodash.now=now,lodash.pad=pad,lodash.padEnd=padEnd,lodash.padStart=padStart,lodash.parseInt=parseInt,lodash.random=random,lodash.reduce=reduce,lodash.reduceRight=reduceRight,lodash.repeat=repeat,lodash.replace=replace,lodash.result=result,lodash.round=round,lodash.runInContext=runInContext,lodash.sample=sample,lodash.size=size,lodash.snakeCase=snakeCase,lodash.some=some,lodash.sortedIndex=sortedIndex,lodash.sortedIndexBy=sortedIndexBy,lodash.sortedIndexOf=sortedIndexOf,lodash.sortedLastIndex=sortedLastIndex,lodash.sortedLastIndexBy=sortedLastIndexBy,lodash.sortedLastIndexOf=sortedLastIndexOf,lodash.startCase=startCase,lodash.startsWith=startsWith,lodash.subtract=subtract,lodash.sum=sum,lodash.sumBy=sumBy,lodash.template=template,lodash.times=times,lodash.toFinite=toFinite,lodash.toInteger=toInteger,lodash.toLength=toLength,lodash.toLower=toLower,lodash.toNumber=toNumber,lodash.toSafeInteger=toSafeInteger,lodash.toString=toString,lodash.toUpper=toUpper,lodash.trim=trim,lodash.trimEnd=trimEnd,lodash.trimStart=trimStart,lodash.truncate=truncate,lodash.unescape=unescape,lodash.uniqueId=uniqueId,lodash.upperCase=upperCase,lodash.upperFirst=upperFirst,lodash.each=forEach,lodash.eachRight=forEachRight,lodash.first=head,mixin(lodash,function(){var source={};return baseForOwn(lodash,function(func,methodName){hasOwnProperty.call(lodash.prototype,methodName)||(source[methodName]=func)}),source}(),{chain:!1}),lodash.VERSION=VERSION,arrayEach(["bind","bindKey","curry","curryRight","partial","partialRight"],function(methodName){lodash[methodName].placeholder=lodash}),arrayEach(["drop","take"],function(methodName,index){LazyWrapper.prototype[methodName]=function(n){var filtered=this.__filtered__;if(filtered&&!index)return new LazyWrapper(this);n=n===undefined?1:nativeMax(toInteger(n),0);var result=this.clone();return filtered?result.__takeCount__=nativeMin(n,result.__takeCount__):result.__views__.push({size:nativeMin(n,MAX_ARRAY_LENGTH),type:methodName+(result.__dir__<0?"Right":"")}),result},LazyWrapper.prototype[methodName+"Right"]=function(n){return this.reverse()[methodName](n).reverse()}}),arrayEach(["filter","map","takeWhile"],function(methodName,index){var type=index+1,isFilter=type==LAZY_FILTER_FLAG||type==LAZY_WHILE_FLAG;LazyWrapper.prototype[methodName]=function(iteratee){var result=this.clone();return result.__iteratees__.push({iteratee:getIteratee(iteratee,3),type:type}),result.__filtered__=result.__filtered__||isFilter,result}}),arrayEach(["head","last"],function(methodName,index){var takeName="take"+(index?"Right":"");LazyWrapper.prototype[methodName]=function(){return this[takeName](1).value()[0]}}),arrayEach(["initial","tail"],function(methodName,index){var dropName="drop"+(index?"":"Right");LazyWrapper.prototype[methodName]=function(){return this.__filtered__?new LazyWrapper(this):this[dropName](1)}}),LazyWrapper.prototype.compact=function(){return this.filter(identity)},LazyWrapper.prototype.find=function(predicate){return this.filter(predicate).head()},LazyWrapper.prototype.findLast=function(predicate){return this.reverse().find(predicate)},LazyWrapper.prototype.invokeMap=baseRest(function(path,args){return"function"==typeof path?new LazyWrapper(this):this.map(function(value){return baseInvoke(value,path,args)})}),LazyWrapper.prototype.reject=function(predicate){return this.filter(negate(getIteratee(predicate)))},LazyWrapper.prototype.slice=function(start,end){start=toInteger(start);var result=this;return result.__filtered__&&(start>0||0>end)?new LazyWrapper(result):(0>start?result=result.takeRight(-start):start&&(result=result.drop(start)),end!==undefined&&(end=toInteger(end),result=0>end?result.dropRight(-end):result.take(end-start)),result)},LazyWrapper.prototype.takeRightWhile=function(predicate){return this.reverse().takeWhile(predicate).reverse()},LazyWrapper.prototype.toArray=function(){return this.take(MAX_ARRAY_LENGTH)},baseForOwn(LazyWrapper.prototype,function(func,methodName){var checkIteratee=/^(?:filter|find|map|reject)|While$/.test(methodName),isTaker=/^(?:head|last)$/.test(methodName),lodashFunc=lodash[isTaker?"take"+("last"==methodName?"Right":""):methodName],retUnwrapped=isTaker||/^find/.test(methodName);lodashFunc&&(lodash.prototype[methodName]=function(){var value=this.__wrapped__,args=isTaker?[1]:arguments,isLazy=value instanceof LazyWrapper,iteratee=args[0],useLazy=isLazy||isArray(value),interceptor=function(value){var result=lodashFunc.apply(lodash,arrayPush([value],args));return isTaker&&chainAll?result[0]:result};useLazy&&checkIteratee&&"function"==typeof iteratee&&1!=iteratee.length&&(isLazy=useLazy=!1);var chainAll=this.__chain__,isHybrid=!!this.__actions__.length,isUnwrapped=retUnwrapped&&!chainAll,onlyLazy=isLazy&&!isHybrid;if(!retUnwrapped&&useLazy){value=onlyLazy?value:new LazyWrapper(this);var result=func.apply(value,args);return result.__actions__.push({func:thru,args:[interceptor],thisArg:undefined}),new LodashWrapper(result,chainAll)}return isUnwrapped&&onlyLazy?func.apply(this,args):(result=this.thru(interceptor),isUnwrapped?isTaker?result.value()[0]:result.value():result)})}),arrayEach(["pop","push","shift","sort","splice","unshift"],function(methodName){var func=arrayProto[methodName],chainName=/^(?:push|sort|unshift)$/.test(methodName)?"tap":"thru",retUnwrapped=/^(?:pop|shift)$/.test(methodName);lodash.prototype[methodName]=function(){var args=arguments;if(retUnwrapped&&!this.__chain__){var value=this.value();return func.apply(isArray(value)?value:[],args)}return this[chainName](function(value){return func.apply(isArray(value)?value:[],args)})}}),baseForOwn(LazyWrapper.prototype,function(func,methodName){var lodashFunc=lodash[methodName];if(lodashFunc){var key=lodashFunc.name+"",names=realNames[key]||(realNames[key]=[]);names.push({name:methodName,func:lodashFunc})}}),realNames[createHybrid(undefined,BIND_KEY_FLAG).name]=[{name:"wrapper",func:undefined}],LazyWrapper.prototype.clone=lazyClone,LazyWrapper.prototype.reverse=lazyReverse,LazyWrapper.prototype.value=lazyValue,lodash.prototype.at=wrapperAt,lodash.prototype.chain=wrapperChain,lodash.prototype.commit=wrapperCommit,lodash.prototype.next=wrapperNext,lodash.prototype.plant=wrapperPlant,lodash.prototype.reverse=wrapperReverse,lodash.prototype.toJSON=lodash.prototype.valueOf=lodash.prototype.value=wrapperValue,lodash.prototype.first=lodash.prototype.head,iteratorSymbol&&(lodash.prototype[iteratorSymbol]=wrapperToIterator),lodash}var undefined,VERSION="4.16.0",LARGE_ARRAY_SIZE=200,FUNC_ERROR_TEXT="Expected a function",HASH_UNDEFINED="__lodash_hash_undefined__",MAX_MEMOIZE_SIZE=500,PLACEHOLDER="__lodash_placeholder__",BIND_FLAG=1,BIND_KEY_FLAG=2,CURRY_BOUND_FLAG=4,CURRY_FLAG=8,CURRY_RIGHT_FLAG=16,PARTIAL_FLAG=32,PARTIAL_RIGHT_FLAG=64,ARY_FLAG=128,REARG_FLAG=256,FLIP_FLAG=512,UNORDERED_COMPARE_FLAG=1,PARTIAL_COMPARE_FLAG=2,DEFAULT_TRUNC_LENGTH=30,DEFAULT_TRUNC_OMISSION="...",HOT_COUNT=500,HOT_SPAN=16,LAZY_FILTER_FLAG=1,LAZY_MAP_FLAG=2,LAZY_WHILE_FLAG=3,INFINITY=1/0,MAX_SAFE_INTEGER=9007199254740991,MAX_INTEGER=1.7976931348623157e308,NAN=NaN,MAX_ARRAY_LENGTH=4294967295,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH-1,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH>>>1,wrapFlags=[["ary",ARY_FLAG],["bind",BIND_FLAG],["bindKey",BIND_KEY_FLAG],["curry",CURRY_FLAG],["curryRight",CURRY_RIGHT_FLAG],["flip",FLIP_FLAG],["partial",PARTIAL_FLAG],["partialRight",PARTIAL_RIGHT_FLAG],["rearg",REARG_FLAG]],argsTag="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",genTag="[object GeneratorFunction]",mapTag="[object Map]",numberTag="[object Number]",objectTag="[object Object]",promiseTag="[object Promise]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]",weakMapTag="[object WeakMap]",weakSetTag="[object WeakSet]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]",reEmptyStringLeading=/\b__p \+= '';/g,reEmptyStringMiddle=/\b(__p \+=) '' \+/g,reEmptyStringTrailing=/(__e\(.*?\)|\b__t\)) \+\n'';/g,reEscapedHtml=/&(?:amp|lt|gt|quot|#39|#96);/g,reUnescapedHtml=/[&<>"'`]/g,reHasEscapedHtml=RegExp(reEscapedHtml.source),reHasUnescapedHtml=RegExp(reUnescapedHtml.source),reEscape=/<%-([\s\S]+?)%>/g,reEvaluate=/<%([\s\S]+?)%>/g,reInterpolate=/<%=([\s\S]+?)%>/g,reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/,reLeadingDot=/^\./,rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reHasRegExpChar=RegExp(reRegExpChar.source),reTrim=/^\s+|\s+$/g,reTrimStart=/^\s+/,reTrimEnd=/\s+$/,reWrapComment=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,reWrapDetails=/\{\n\/\* \[wrapped with (.+)\] \*/,reSplitDetails=/,? & /,reAsciiWord=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,reEscapeChar=/\\(\\)?/g,reEsTemplate=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,reFlags=/\w*$/,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsHostCtor=/^\[object .+?Constructor\]$/,reIsOctal=/^0o[0-7]+$/i,reIsUint=/^(?:0|[1-9]\d*)$/,reLatin=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,reNoMatch=/($^)/,reUnescapedString=/['\n\r\u2028\u2029\\]/g,rsAstralRange="\\ud800-\\udfff",rsComboMarksRange="\\u0300-\\u036f\\ufe20-\\ufe23",rsComboSymbolsRange="\\u20d0-\\u20f0",rsDingbatRange="\\u2700-\\u27bf",rsLowerRange="a-z\\xdf-\\xf6\\xf8-\\xff",rsMathOpRange="\\xac\\xb1\\xd7\\xf7",rsNonCharRange="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",rsPunctuationRange="\\u2000-\\u206f",rsSpaceRange=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",rsUpperRange="A-Z\\xc0-\\xd6\\xd8-\\xde",rsVarRange="\\ufe0e\\ufe0f",rsBreakRange=rsMathOpRange+rsNonCharRange+rsPunctuationRange+rsSpaceRange,rsApos="['’]",rsAstral="["+rsAstralRange+"]",rsBreak="["+rsBreakRange+"]",rsCombo="["+rsComboMarksRange+rsComboSymbolsRange+"]",rsDigits="\\d+",rsDingbat="["+rsDingbatRange+"]",rsLower="["+rsLowerRange+"]",rsMisc="[^"+rsAstralRange+rsBreakRange+rsDigits+rsDingbatRange+rsLowerRange+rsUpperRange+"]",rsFitz="\\ud83c[\\udffb-\\udfff]",rsModifier="(?:"+rsCombo+"|"+rsFitz+")",rsNonAstral="[^"+rsAstralRange+"]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",rsUpper="["+rsUpperRange+"]",rsZWJ="\\u200d",rsLowerMisc="(?:"+rsLower+"|"+rsMisc+")",rsUpperMisc="(?:"+rsUpper+"|"+rsMisc+")",rsOptLowerContr="(?:"+rsApos+"(?:d|ll|m|re|s|t|ve))?",rsOptUpperContr="(?:"+rsApos+"(?:D|LL|M|RE|S|T|VE))?",reOptMod=rsModifier+"?",rsOptVar="["+rsVarRange+"]?",rsOptJoin="(?:"+rsZWJ+"(?:"+[rsNonAstral,rsRegional,rsSurrPair].join("|")+")"+rsOptVar+reOptMod+")*",rsSeq=rsOptVar+reOptMod+rsOptJoin,rsEmoji="(?:"+[rsDingbat,rsRegional,rsSurrPair].join("|")+")"+rsSeq,rsSymbol="(?:"+[rsNonAstral+rsCombo+"?",rsCombo,rsRegional,rsSurrPair,rsAstral].join("|")+")",reApos=RegExp(rsApos,"g"),reComboMark=RegExp(rsCombo,"g"),reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g"),reUnicodeWord=RegExp([rsUpper+"?"+rsLower+"+"+rsOptLowerContr+"(?="+[rsBreak,rsUpper,"$"].join("|")+")",rsUpperMisc+"+"+rsOptUpperContr+"(?="+[rsBreak,rsUpper+rsLowerMisc,"$"].join("|")+")",rsUpper+"?"+rsLowerMisc+"+"+rsOptLowerContr,rsUpper+"+"+rsOptUpperContr,rsDigits,rsEmoji].join("|"),"g"),reHasUnicode=RegExp("["+rsZWJ+rsAstralRange+rsComboMarksRange+rsComboSymbolsRange+rsVarRange+"]"),reHasUnicodeWord=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,contextProps=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],templateCounter=-1,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[dataViewTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[mapTag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[setTag]=cloneableTags[stringTag]=cloneableTags[symbolTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=!0,cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[weakMapTag]=!1;var deburredLetters={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"},htmlEscapes={"&":"&","<":"<",">":">",'"':""","'":"'"},htmlUnescapes={"&":"&","<":"<",">":">",""":'"',"'":"'"},stringEscapes={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},freeParseFloat=parseFloat,freeParseInt=parseInt,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,freeProcess=moduleExports&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding("util")}catch(e){}}(),nodeIsArrayBuffer=nodeUtil&&nodeUtil.isArrayBuffer,nodeIsDate=nodeUtil&&nodeUtil.isDate,nodeIsMap=nodeUtil&&nodeUtil.isMap,nodeIsRegExp=nodeUtil&&nodeUtil.isRegExp,nodeIsSet=nodeUtil&&nodeUtil.isSet,nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,asciiSize=baseProperty("length"),deburrLetter=basePropertyOf(deburredLetters),escapeHtmlChar=basePropertyOf(htmlEscapes),unescapeHtmlChar=basePropertyOf(htmlUnescapes),_=runInContext();"function"==typeof define&&"object"==typeof define.amd&&define.amd?(root._=_,define(function(){return _})):freeModule?((freeModule.exports=_)._=_,freeExports._=_):root._=_}.call(this);var UsergridQuery=function(type){var queryString,sort,self=this,query="",__nextIsNot=!1;return _.assign(self,{type:function(value){return self._type=value,self},collection:function(value){return self._type=value,self},limit:function(value){return self._limit=value,self},cursor:function(value){return self._cursor=value,self},eq:function(key,value){return query=self.andJoin(key+" = "+useQuotesIfRequired(value)),self},equal:this.eq,gt:function(key,value){return query=self.andJoin(key+" > "+useQuotesIfRequired(value)),self},greaterThan:this.gt,gte:function(key,value){return query=self.andJoin(key+" >= "+useQuotesIfRequired(value)),self},greaterThanOrEqual:this.gte,lt:function(key,value){return query=self.andJoin(key+" < "+useQuotesIfRequired(value)),self},lessThan:this.lt,lte:function(key,value){return query=self.andJoin(key+" <= "+useQuotesIfRequired(value)),self},lessThanOrEqual:this.lte,contains:function(key,value){return query=self.andJoin(key+" contains "+useQuotesIfRequired(value)),self},locationWithin:function(distanceInMeters,lat,lng){return query=self.andJoin("location within "+distanceInMeters+" of "+lat+", "+lng),self},asc:function(key){return self.sort(key,"asc"),self},desc:function(key){return self.sort(key,"desc"),self},sort:function(key,order){return sort=key&&order?" order by "+key+" "+order:"",self},fromString:function(string){return queryString=string,self},andJoin:function(append){return __nextIsNot&&(append="not "+append,__nextIsNot=!1),append?0===query.length?append:_.endsWith(query,"and")||_.endsWith(query,"or")?query+" "+append:query+" and "+append:query},orJoin:function(){return query.length>0&&!_.endsWith(query,"or")?query+" or":query}}),self._type=self._type||type,Object.defineProperty(self,"_ql",{get:function(){return void 0!==queryString?queryString:query.length>0||void 0!==sort?"select * where "+(query||"")+(sort||""):""}}),Object.defineProperty(self,"and",{get:function(){return query=self.andJoin(""),self}}),Object.defineProperty(self,"or",{get:function(){return query=self.orJoin(),self}}),Object.defineProperty(self,"not",{get:function(){return __nextIsNot=!0,self}}),self};window.console=window.console||{},window.console.log=window.console.log||function(){};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;!function(global){function Usergrid(){this.logger=new Logger(name)}var name="Usergrid",overwrittenName=global[name],VALID_REQUEST_METHODS=["GET","POST","PUT","DELETE"];return Usergrid.initSharedInstance=function(options){return console.warn("TRYING TO INITIALIZING SHARED INSTANCE"),this.isInitialized||(console.warn("INITIALIZING SHARED INSTANCE"),this.__sharedInstance=new Usergrid.Client(options),this.isInitialized=!0),this.__sharedInstance},Usergrid.getInstance=function(){return this.__sharedInstance},Usergrid.isValidEndpoint=function(endpoint){return!0},Usergrid.Request=function(method,endpoint,query_params,data,callback){var p=new Promise;if(this.logger=new global.Logger("Usergrid.Request"),this.logger.time("process request "+method+" "+endpoint),this.endpoint=endpoint+"?"+encodeParams(query_params),this.method=method.toUpperCase(),this.data="object"==typeof data?JSON.stringify(data):data,-1===VALID_REQUEST_METHODS.indexOf(this.method))throw new UsergridInvalidHTTPMethodError("invalid request method '"+this.method+"'");if(!isValidUrl(this.endpoint))throw this.logger.error(endpoint,this.endpoint,/^https:\/\//.test(endpoint)),new UsergridInvalidURIError("The provided endpoint is not valid: "+this.endpoint);var request=function(){return Ajax.request(this.method,this.endpoint,this.data)}.bind(this),response=function(err,request){return new Usergrid.Response(err,request)}.bind(this),oncomplete=function(err,response){p.done(err,response),this.logger.info("REQUEST",err,response),doCallback(callback,[err,response]),this.logger.timeEnd("process request "+method+" "+endpoint)}.bind(this);return Promise.chain([request,response]).then(oncomplete),p},Usergrid.Response=function(err,response){var p=new Promise,data=null;try{data=JSON.parse(response.responseText)}catch(e){data={}}switch(Object.keys(data).forEach(function(key){Object.defineProperty(this,key,{value:data[key],enumerable:!0})}.bind(this)),Object.defineProperty(this,"logger",{enumerable:!1,configurable:!1,writable:!1,value:new global.Logger(name)}),Object.defineProperty(this,"success",{enumerable:!1,configurable:!1,writable:!0,value:!0}),Object.defineProperty(this,"err",{enumerable:!1,configurable:!1,writable:!0,value:err}),Object.defineProperty(this,"status",{enumerable:!1,configurable:!1,writable:!0,value:parseInt(response.status)}),Object.defineProperty(this,"statusGroup",{enumerable:!1,configurable:!1,writable:!0,value:this.status-this.status%100}),this.statusGroup){case 200:this.success=!0;break;case 400:case 500:case 300:case 100:default:this.success=!1}return this.success?p.done(null,this):p.done(UsergridError.fromResponse(data),this),p},Usergrid.Response.prototype.getEntities=function(){var entities;return this.success&&(entities=this.data?this.data.entities:this.entities),entities||[]},Usergrid.Response.prototype.getEntity=function(){var entities=this.getEntities();return entities[0]},Usergrid.VERSION=Usergrid.USERGRID_SDK_VERSION="0.11.0",global[name]=Usergrid,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Usergrid},global[name]}(this);var defaultOptions={baseUrl:"https://api.usergrid.com",authMode:UsergridAuthMode.USER};!function(){var exports,name="Client",global=this,overwrittenName=global[name];return Usergrid.Client=function(options){var self=this;if(!options.orgId||!options.appId)throw new Error('"orgId" and "appId" parameters are required when instantiating UsergridClient');_.defaults(this,options,defaultOptions),self.clientAppURL=[self.baseUrl,self.orgId,self.appId].join("/"),self.isSharedInstance=!1,self.currentUser=void 0,self.__appAuth=void 0,Object.defineProperty(self,"appAuth",{get:function(){return self.__appAuth},set:function(options){options instanceof UsergridAppAuth?self.__appAuth=options:"undefined"!=typeof options&&(self.__appAuth=new UsergridAppAuth(options))}}),this.userAuth=void 0,options.qs&&this.setObject("default_qs",options.qs),this.buildCurl=options.buildCurl||!1,this.logging=options.logging||!1},Usergrid.Client.prototype.request=function(options,callback){var uri,method=options.method||"GET",endpoint=options.endpoint,body=options.body||{},qs=options.qs||{},mQuery=options.mQuery||!1,orgId=this.get("orgId"),appId=this.get("appId"),default_qs=this.getObject("default_qs");if(!mQuery&&!orgId&&!appId)return logoutCallback();uri=mQuery?this.baseUrl+"/"+endpoint:this.baseUrl+"/"+orgId+"/"+appId+"/"+endpoint,this.getToken()&&(qs.access_token=this.getToken()),default_qs&&(qs=propCopy(qs,default_qs));var self=this;new Usergrid.Request(method,uri,qs,body,function(err,response){err?doCallback(callback,[err,response,self],self):doCallback(callback,[null,response,self],self)})},Usergrid.Client.prototype.buildAssetURL=function(uuid){var self=this,qs={},assetURL=this.baseUrl+"/"+this.orgId+"/"+this.appId+"/assets/"+uuid+"/data";self.getToken()&&(qs.access_token=self.getToken());var encoded_params=encodeParams(qs);return encoded_params&&(assetURL+="?"+encoded_params),assetURL},Usergrid.Client.prototype.createGroup=function(options,callback){var group=new Usergrid.Group({path:options.path,client:this,data:options});group.save(function(err,response){doCallback(callback,[err,response,group],group)})},Usergrid.Client.prototype.createEntity=function(options,callback){var entity=new Usergrid.Entity({client:this,data:options});entity.save(function(err,response){doCallback(callback,[err,response,entity],entity)})},Usergrid.Client.prototype.getEntity=function(options,callback){var entity=new Usergrid.Entity({client:this,data:options});entity.fetch(function(err,response){doCallback(callback,[err,response,entity],entity)})},Usergrid.Client.prototype.restoreEntity=function(serializedObject){var data=JSON.parse(serializedObject),options={client:this,data:data},entity=new Usergrid.Entity(options);return entity},Usergrid.Client.prototype.createCounter=function(options,callback){var counter=new Usergrid.Counter({client:this,data:options});counter.save(callback)},Usergrid.Client.prototype.createAsset=function(options,callback){var file=options.file;file&&(options.name=options.name||file.name,options["content-type"]=options["content-type"]||file.type,options.path=options.path||"/",delete options.file);var asset=new Usergrid.Asset({client:this,data:options});asset.save(function(err,response,asset){file&&!err?asset.upload(file,callback):doCallback(callback,[err,response,asset],asset)})},Usergrid.Client.prototype.createCollection=function(options,callback){options.client=this;var collection=new Usergrid.Collection(options);this.request({method:"POST",endpoint:options.type},function(err,data){err?doCallback(callback,[err,data,collection],self):collection.fetch(function(err,response,collection){doCallback(callback,[err,response,collection],self)})})},Usergrid.Client.prototype.restoreCollection=function(serializedObject){var data=JSON.parse(serializedObject);data.client=this;var collection=new Usergrid.Collection(data);return collection},Usergrid.Client.prototype.getFeedForUser=function(username,callback){var options={method:"GET",endpoint:"users/"+username+"/feed"};this.request(options,function(err,data){err?doCallback(callback,[err]):doCallback(callback,[err,data,data.getEntities()])})},Usergrid.Client.prototype.createUserActivity=function(user,options,callback){options.type="users/"+user+"/activities",options={client:this,data:options};var entity=new Usergrid.Entity(options);entity.save(function(err,data){doCallback(callback,[err,data,entity])})},Usergrid.Client.prototype.createUserActivityWithEntity=function(user,content,callback){var username=user.get("username"),options={actor:{displayName:username,uuid:user.get("uuid"),username:username,email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80}},verb:"post",content:content};this.createUserActivity(username,options,callback)},Usergrid.Client.prototype.calcTimeDiff=function(){var seconds=0,time=this._end-this._start;try{seconds=(time/10/60).toFixed(2)}catch(e){return 0}return seconds},Usergrid.Client.prototype.setToken=function(token){this.set("token",token)},Usergrid.Client.prototype.getToken=function(){return this.get("token")},Usergrid.Client.prototype.setObject=function(key,value){value&&(value=JSON.stringify(value)),this.set(key,value)},Usergrid.Client.prototype.set=function(key,value){var keyStore="apigee_"+key;this[key]=value,"undefined"!=typeof Storage&&(value?localStorage.setItem(keyStore,value):localStorage.removeItem(keyStore))},Usergrid.Client.prototype.getObject=function(key){return JSON.parse(this.get(key))},Usergrid.Client.prototype.get=function(key){var keyStore="apigee_"+key,value=null;return this[key]?value=this[key]:"undefined"!=typeof Storage&&(value=localStorage.getItem(keyStore)),value},Usergrid.Client.prototype.signup=function(username,password,email,name,callback){var options={type:"users",username:username,password:password,email:email,name:name};this.createEntity(options,callback)},Usergrid.Client.prototype.login=function(username,password,callback){var self=this,options={method:"POST",endpoint:"token",body:{username:username,password:password,grant_type:"password"}};self.request(options,function(err,response){var user={};if(err)self.logging&&console.log("error trying to log user in");else{var options={client:self,data:response.user};user=new Usergrid.Entity(options),self.setToken(response.access_token)}doCallback(callback,[err,response,user])})},Usergrid.Client.prototype.adminlogin=function(username,password,callback){var self=this,options={method:"POST",endpoint:"management/token",body:{username:username,password:password,grant_type:"password"},mQuery:!0};self.request(options,function(err,response){var user={};if(err)self.logging&&console.log("error trying to log adminuser in");else{var options={client:self,data:response.user};user=new Usergrid.Entity(options),self.setToken(response.access_token)}doCallback(callback,[err,response,user])})},Usergrid.Client.prototype.reAuthenticateLite=function(callback){var self=this,options={method:"GET",endpoint:"management/me",mQuery:!0};this.request(options,function(err,response){err&&self.logging?console.log("error trying to re-authenticate user"):self.setToken(response.data.access_token),doCallback(callback,[err])})},Usergrid.Client.prototype.reAuthenticate=function(email,callback){var self=this,options={method:"GET",endpoint:"management/users/"+email,mQuery:!0};this.request(options,function(err,response){var data,organizations={},applications={},user={};if(err&&self.logging)console.log("error trying to full authenticate user");else{data=response.data,self.setToken(data.token),self.set("email",data.email),localStorage.setItem("accessToken",data.token),localStorage.setItem("userUUID",data.uuid),localStorage.setItem("userEmail",data.email);var userData={username:data.username,email:data.email,name:data.name,uuid:data.uuid},options={client:self,data:userData};user=new Usergrid.Entity(options),organizations=data.organizations;var org="";try{var existingOrg=self.get("orgName");org=organizations[existingOrg]?organizations[existingOrg]:organizations[Object.keys(organizations)[0]],self.set("orgName",org.name)}catch(e){err=!0,self.logging&&console.log("error selecting org")}applications=self.parseApplicationsArray(org),self.selectFirstApp(applications),self.setObject("organizations",organizations),self.setObject("applications",applications); +}doCallback(callback,[err,data,user,organizations,applications],self)})},Usergrid.Client.prototype.loginFacebook=function(facebookToken,callback){var self=this,options={method:"GET",endpoint:"auth/facebook",qs:{fb_access_token:facebookToken}};this.request(options,function(err,data){var user={};if(err&&self.logging)console.log("error trying to log user in");else{var options={client:self,data:data.user};user=new Usergrid.Entity(options),self.setToken(data.access_token)}doCallback(callback,[err,data,user],self)})},Usergrid.Client.prototype.getLoggedInUser=function(callback){var self=this;if(this.getToken()){var options={method:"GET",endpoint:"users/me"};this.request(options,function(err,response){if(err)self.logging&&console.log("error trying to log user in"),console.error(err,response),doCallback(callback,[err,response,self],self);else{var options={client:self,data:response.getEntity()},user=new Usergrid.Entity(options);doCallback(callback,[null,response,user],self)}})}else doCallback(callback,[new UsergridError("Access Token not set"),null,self],self)},Usergrid.Client.prototype.isLoggedIn=function(){var token=this.getToken();return"undefined"!=typeof token&&null!==token},Usergrid.Client.prototype.logout=function(){this.setToken()},Usergrid.Client.prototype.destroyToken=function(username,token,revokeAll,callback){var options={client:self,method:"PUT"};revokeAll===!0?options.endpoint="users/"+username+"/revoketokens":null===token?options.endpoint="users/"+username+"/revoketoken?token="+this.getToken():options.endpoint="users/"+username+"/revoketoken?token="+token,this.request(options,function(err,data){err?(self.logging&&console.log("error destroying access token"),doCallback(callback,[err,data,null],self)):(revokeAll===!0?console.log("all user tokens invalidated"):console.log("token invalidated"),doCallback(callback,[err,data,null],self))})},Usergrid.Client.prototype.logoutAndDestroyToken=function(username,token,revokeAll,callback){null===username?console.log("username required to revoke tokens"):(this.destroyToken(username,token,revokeAll,callback),(revokeAll===!0||token===this.getToken()||null===token)&&this.setToken(null))},Usergrid.Client.prototype.buildCurlCall=function(options){var curl=["curl"],method=(options.method||"GET").toUpperCase(),body=options.body,uri=options.uri;return curl.push("-X"),curl.push(["POST","PUT","DELETE"].indexOf(method)>=0?method:"GET"),curl.push(uri),"object"==typeof body&&Object.keys(body).length>0&&-1!==["POST","PUT"].indexOf(method)&&(curl.push("-d"),curl.push("'"+JSON.stringify(body)+"'")),curl=curl.join(" "),console.log(curl),curl},Usergrid.Client.prototype.getDisplayImage=function(email,picture,size){size=size||50;var image="https://apigee.com/usergrid/images/user_profile.png";try{picture?image=picture:email.length&&(image="https://secure.gravatar.com/avatar/"+MD5(email)+"?s="+size+encodeURI("&d=https://apigee.com/usergrid/images/user_profile.png"))}catch(e){}finally{return image}},global[name]=Usergrid.Client,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}();var ENTITY_SYSTEM_PROPERTIES=["metadata","created","modified","oldpassword","newpassword","type","activated","uuid"];Usergrid.Entity=function(options){this._data={},this._client=void 0,options&&(this.set(options.data||{}),this._client=options.client||{})},Usergrid.Entity.isEntity=function(obj){return obj&&obj instanceof Usergrid.Entity},Usergrid.Entity.isPersistedEntity=function(obj){return isEntity(obj)&&isUUID(obj.get("uuid"))},Usergrid.Entity.prototype.serialize=function(){return JSON.stringify(this._data)},Usergrid.Entity.prototype.get=function(key){var value;if(0===arguments.length?value=this._data:arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c,i,a){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(value=this._data[key]);return value},Usergrid.Entity.prototype.set=function(key,value){if("object"==typeof key)for(var field in key)this._data[field]=key[field];else"string"==typeof key?null===value?delete this._data[key]:this._data[key]=value:this._data={}},Usergrid.Entity.prototype.getEndpoint=function(){var name,type=this.get("type"),nameProperties=["uuid","name"];if(void 0===type)throw new UsergridError("cannot fetch entity, no entity type specified","no_type_specified");return/^users?$/.test(type)&&nameProperties.unshift("username"),name=this.get(nameProperties).filter(function(x){return null!==x&&"undefined"!=typeof x}).shift(),name?[type,name].join("/"):type},Usergrid.Entity.prototype.save=function(callback){var self=this,type=this.get("type"),method="POST",entityId=this.get("uuid"),entityData=this.get(),options={method:method,endpoint:type};entityId&&(options.method="PUT",options.endpoint+="/"+entityId),options.body=Object.keys(entityData).filter(function(key){return-1===ENTITY_SYSTEM_PROPERTIES.indexOf(key)}).reduce(function(data,key){return data[key]=entityData[key],data},{}),self._client.request(options,function(err,response){var entity=response.getEntity();entity&&(self.set(entity),self.set("type",/^\//.test(response.path)?response.path.substring(1):response.path)),err&&self._client.logging&&console.log("could not save entity"),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.changePassword=function(oldpassword,newpassword,callback){var self=this;if("function"==typeof oldpassword&&void 0===callback&&(callback=oldpassword,oldpassword=self.get("oldpassword"),newpassword=self.get("newpassword")),self.set({password:null,oldpassword:null,newpassword:null}),!(/^users?$/.test(self.get("type"))&&oldpassword&&newpassword))throw new UsergridInvalidArgumentError("Invalid arguments passed to 'changePassword'");var options={method:"PUT",endpoint:"users/"+self.get("uuid")+"/password",body:{uuid:self.get("uuid"),username:self.get("username"),oldpassword:oldpassword,newpassword:newpassword}};self._client.request(options,function(err,response){err&&self._client.logging&&console.log("could not update user"),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.fetch=function(callback){var endpoint,self=this;endpoint=this.getEndpoint();var options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,response){var entity=response.getEntity();entity&&self.set(entity),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.destroy=function(callback){var self=this,endpoint=this.getEndpoint(),options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,response){err||self.set(null),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.connect=function(connection,entity,callback){this.addOrRemoveConnection("POST",connection,entity,callback)},Usergrid.Entity.prototype.disconnect=function(connection,entity,callback){this.addOrRemoveConnection("DELETE",connection,entity,callback)},Usergrid.Entity.prototype.addOrRemoveConnection=function(method,connection,entity,callback){var self=this;if(-1==["POST","DELETE"].indexOf(method.toUpperCase()))throw new UsergridInvalidArgumentError("invalid method for connection call. must be 'POST' or 'DELETE'");var connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)throw new UsergridInvalidArgumentError("connectee could not be identified");var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)throw new UsergridInvalidArgumentError("connector could not be identified");var endpoint=[connectorType,connector,connection,connecteeType,connectee].join("/"),options={method:method,endpoint:endpoint};this._client.request(options,function(err,response){err&&self._client.logging&&console.log("There was an error with the connection call"),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.getEntityId=function(entity){var id;return id=isUUID(entity.get("uuid"))?entity.get("uuid"):"users"===this.get("type")||"user"===this.get("type")?entity.get("username"):entity.get("name")},Usergrid.Entity.prototype.getConnections=function(connection,callback){var self=this,connectorType=this.get("type"),connector=this.getEntityId(this);if(connector){var endpoint=connectorType+"/"+connector+"/"+connection+"/",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self[connection]={};for(var length=data&&data.entities?data.entities.length:0,i=0;length>i;i++)"user"===data.entities[i].type?self[connection][data.entities[i].username]=data.entities[i]:self[connection][data.entities[i].name]=data.entities[i];doCallback(callback,[err,data,data.entities],self)})}else if("function"==typeof callback){var error="Error in getConnections - no uuid specified.";self._client.logging&&console.log(error),doCallback(callback,[!0,error],self)}},Usergrid.Entity.prototype.getGroups=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/groups",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self.groups=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Entity.prototype.getActivities=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/activities",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected");for(var entity in data.entities)data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();self.activities=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Entity.prototype.getFollowing=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/following",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user following");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.following=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Entity.prototype.getFollowers=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/followers",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user followers");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.followers=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Client.prototype.createRole=function(roleName,permissions,callback){var options={type:"role",name:roleName};this.createEntity(options,function(err,response,entity){err?doCallback(callback,[err,response,self]):entity.assignPermissions(permissions,function(err,data){err?doCallback(callback,[err,response,self]):doCallback(callback,[err,data,data.data],self)})})},Usergrid.Entity.prototype.getRoles=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/roles",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user roles"),self.roles=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Entity.prototype.assignRole=function(roleName,callback){var entityID,self=this,type=self.get("type"),collection=type+"s";"user"==type&&null!=this.get("username")?entityID=self.get("username"):"group"==type&&null!=this.get("name")?entityID=self.get("name"):null!=this.get("uuid")&&(entityID=self.get("uuid")),"users"!=type&&"groups"!=type&&doCallback(callback,[new UsergridError("entity must be a group or user","invalid_entity_type"),null,this],this);var endpoint="roles/"+roleName+"/"+collection+"/"+entityID,options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,response){err&&console.log("Could not assign role."),doCallback(callback,[err,response,self])})},Usergrid.Entity.prototype.removeRole=function(roleName,callback){var entityID,self=this,type=self.get("type"),collection=type+"s";"user"==type&&null!=this.get("username")?entityID=this.get("username"):"group"==type&&null!=this.get("name")?entityID=this.get("name"):null!=this.get("uuid")&&(entityID=this.get("uuid")),"users"!=type&&"groups"!=type&&doCallback(callback,[new UsergridError("entity must be a group or user","invalid_entity_type"),null,this],this);var endpoint="roles/"+roleName+"/"+collection+"/"+entityID,options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,response){err&&console.log("Could not assign role."),doCallback(callback,[err,response,self])})},Usergrid.Entity.prototype.assignPermissions=function(permissions,callback){var entityID,self=this,type=this.get("type");"user"!=type&&"users"!=type&&"group"!=type&&"groups"!=type&&"role"!=type&&"roles"!=type&&doCallback(callback,[new UsergridError("entity must be a group, user, or role","invalid_entity_type"),null,this],this),"user"==type&&null!=this.get("username")?entityID=this.get("username"):"group"==type&&null!=this.get("name")?entityID=this.get("name"):null!=this.get("uuid")&&(entityID=this.get("uuid"));var endpoint=type+"/"+entityID+"/permissions",options={method:"POST",endpoint:endpoint,body:{permission:permissions}};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not assign permissions"),doCallback(callback,[err,data,data.data],self)})},Usergrid.Entity.prototype.removePermissions=function(permissions,callback){var entityID,self=this,type=this.get("type");"user"!=type&&"users"!=type&&"group"!=type&&"groups"!=type&&"role"!=type&&"roles"!=type&&doCallback(callback,[new UsergridError("entity must be a group, user, or role","invalid_entity_type"),null,this],this),"user"==type&&null!=this.get("username")?entityID=this.get("username"):"group"==type&&null!=this.get("name")?entityID=this.get("name"):null!=this.get("uuid")&&(entityID=this.get("uuid"));var endpoint=type+"/"+entityID+"/permissions",options={method:"DELETE",endpoint:endpoint,qs:{permission:permissions}};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not remove permissions"),doCallback(callback,[err,data,data.params.permission],self)})},Usergrid.Entity.prototype.getPermissions=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/permissions",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user permissions");var permissions=[];if(data.data){var perms=data.data,count=0;for(var i in perms){count++;var perm=perms[i],parts=perm.split(":"),ops_part="",path_part=parts[0];parts.length>1&&(ops_part=parts[0],path_part=parts[1]),ops_part=ops_part.replace("*","get,post,put,delete");var ops=ops_part.split(","),ops_object={};ops_object.get="no",ops_object.post="no",ops_object.put="no",ops_object["delete"]="no";for(var j in ops)ops_object[ops[j]]="yes";permissions.push({operations:ops_object,path:path_part,perm:perm})}}self.permissions=permissions,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Collection=function(options){if(options&&(this._client=options.client,this._type=options.type,this.qs=options.qs||{},this._list=options.list||[],this._iterator=options.iterator||-1,this._previous=options.previous||[],this._next=options.next||null,this._cursor=options.cursor||null,options.list))for(var count=options.list.length,i=0;count>i;i++){var entity=this._client.restoreEntity(options.list[i]);this._list[i]=entity}},Usergrid.isCollection=function(obj){return obj&&obj instanceof Usergrid.Collection},Usergrid.Collection.prototype.serialize=function(){var data={};data.type=this._type,data.qs=this.qs,data.iterator=this._iterator,data.previous=this._previous,data.next=this._next,data.cursor=this._cursor,this.resetEntityPointer();var i=0;for(data.list=[];this.hasNextEntity();){var entity=this.getNextEntity();data.list[i]=entity.serialize(),i++}return data=JSON.stringify(data)},Usergrid.Collection.prototype.fetch=function(callback){var self=this,qs=this.qs;this._cursor?qs.cursor=this._cursor:delete qs.cursor;var options={method:"GET",endpoint:this._type,qs:this.qs};this._client.request(options,function(err,response){err&&self._client.logging?console.log("error getting collection"):(self.saveCursor(response.cursor||null),self.resetEntityPointer(),self._list=response.getEntities().filter(function(entity){return isUUID(entity.uuid)}).map(function(entity){var ent=new Usergrid.Entity({client:self._client});return ent.set(entity),ent.type=self._type,ent})),doCallback(callback,[err,response,self],self)})},Usergrid.Collection.prototype.addEntity=function(entityObject,callback){var self=this;entityObject.type=this._type,this._client.createEntity(entityObject,function(err,response,entity){err||self.addExistingEntity(entity),doCallback(callback,[err,response,self],self)})},Usergrid.Collection.prototype.addExistingEntity=function(entity){var count=this._list.length;this._list[count]=entity},Usergrid.Collection.prototype.destroyEntity=function(entity,callback){var self=this;entity.destroy(function(err,response){err?(self._client.logging&&console.log("could not destroy entity"),doCallback(callback,[err,response,self],self)):self.fetch(callback),self.removeEntity(entity)})},Usergrid.Collection.prototype.getEntitiesByCriteria=function(criteria){return this._list.filter(criteria)},Usergrid.Collection.prototype.getEntityByCriteria=function(criteria){return this.getEntitiesByCriteria(criteria).shift()},Usergrid.Collection.prototype.removeEntity=function(entity){var removedEntity=this.getEntityByCriteria(function(item){return entity.uuid===item.get("uuid")});return delete this._list[this._list.indexOf(removedEntity)],removedEntity},Usergrid.Collection.prototype.getEntityByUUID=function(uuid,callback){var entity=this.getEntityByCriteria(function(item){return item.get("uuid")===uuid});if(entity)doCallback(callback,[null,entity,entity],this);else{var options={data:{type:this._type,uuid:uuid},client:this._client};entity=new Usergrid.Entity(options),entity.fetch(callback)}},Usergrid.Collection.prototype.getFirstEntity=function(){var count=this._list.length;return count>0?this._list[0]:null},Usergrid.Collection.prototype.getLastEntity=function(){var count=this._list.length;return count>0?this._list[count-1]:null},Usergrid.Collection.prototype.hasNextEntity=function(){var next=this._iterator+1,hasNextElement=next>=0&&next=0&&this._iterator<=this._list.length;return hasNextElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.hasPrevEntity=function(){var previous=this._iterator-1,hasPreviousElement=previous>=0&&previous=0&&this._iterator<=this._list.length;return hasPreviousElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.resetEntityPointer=function(){this._iterator=-1},Usergrid.Collection.prototype.saveCursor=function(cursor){this._next!==cursor&&(this._next=cursor)},Usergrid.Collection.prototype.resetPaging=function(){this._previous=[],this._next=null,this._cursor=null},Usergrid.Collection.prototype.hasNextPage=function(){return this._next},Usergrid.Collection.prototype.getNextPage=function(callback){this.hasNextPage()&&(this._previous.push(this._cursor),this._cursor=this._next,this._list=[],this.fetch(callback))},Usergrid.Collection.prototype.hasPreviousPage=function(){return this._previous.length>0},Usergrid.Collection.prototype.getPreviousPage=function(callback){this.hasPreviousPage()&&(this._next=null,this._cursor=this._previous.pop(),this._list=[],this.fetch(callback))},Usergrid.Group=function(options,callback){this._path=options.path,this._list=[],this._client=options.client,this._data=options.data||{},this._data.type="groups"},Usergrid.Group.prototype=new Usergrid.Entity,Usergrid.Group.prototype.fetch=function(callback){var self=this,groupEndpoint="groups/"+this._path,memberEndpoint="groups/"+this._path+"/users",groupOptions={method:"GET",endpoint:groupEndpoint},memberOptions={method:"GET",endpoint:memberEndpoint};this._client.request(groupOptions,function(err,response){if(err)self._client.logging&&console.log("error getting group"),doCallback(callback,[err,response],self);else{var entities=response.getEntities();if(entities&&entities.length){entities.shift();self._client.request(memberOptions,function(err,response){err&&self._client.logging?console.log("error getting group users"):self._list=response.getEntities().filter(function(entity){return isUUID(entity.uuid)}).map(function(entity){return new Usergrid.Entity({type:entity.type,client:self._client,uuid:entity.uuid,response:entity})}),doCallback(callback,[err,response,self],self)})}}})},Usergrid.Group.prototype.members=function(callback){return this._list},Usergrid.Group.prototype.add=function(options,callback){var self=this;options.user?(options={method:"POST",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")},this._client.request(options,function(error,response){error?doCallback(callback,[error,response,self],self):self.fetch(callback)})):doCallback(callback,[new UsergridError("no user specified","no_user_specified"),null,this],this)},Usergrid.Group.prototype.remove=function(options,callback){var self=this;options.user?(options={method:"DELETE",endpoint:"groups/"+this._path+"/users/"+options.user.username},this._client.request(options,function(error,response){error?doCallback(callback,[error,response,self],self):self.fetch(callback)})):doCallback(callback,[new UsergridError("no user specified","no_user_specified"),null,this],this)},Usergrid.Group.prototype.feed=function(callback){var self=this,options={method:"GET",endpoint:"groups/"+this._path+"/feed"};this._client.request(options,function(err,response){doCallback(callback,[err,response,self],self)})},Usergrid.Group.prototype.createGroupActivity=function(options,callback){var self=this,user=options.user,entity=new Usergrid.Entity({client:this._client,data:{actor:{displayName:user.get("username"),uuid:user.get("uuid"),username:user.get("username"),email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80}},verb:"post",content:options.content,type:"groups/"+this._path+"/activities"}});entity.save(function(err,response,entity){doCallback(callback,[err,response,self])})},Usergrid.Counter=function(options){this._client=options.client,this._data=options.data||{},this._data.category=options.category||"UNKNOWN",this._data.timestamp=options.timestamp||0,this._data.type="events",this._data.counters=options.counters||{}};var COUNTER_RESOLUTIONS=["all","minute","five_minutes","half_hour","hour","six_day","day","week","month"];Usergrid.Counter.prototype=new Usergrid.Entity,Usergrid.Counter.prototype.fetch=function(callback){this.getData({},callback)},Usergrid.Counter.prototype.increment=function(options,callback){var self=this,name=options.name,value=options.value;return name?isNaN(value)?doCallback(callback,[new UsergridInvalidArgumentError("'value' for increment, decrement must be a number"),null,self],self):(self._data.counters[name]=parseInt(value)||1,self.save(callback)):doCallback(callback,[new UsergridInvalidArgumentError("'name' for increment, decrement must be a number"),null,self],self)},Usergrid.Counter.prototype.decrement=function(options,callback){var self=this,name=options.name,value=options.value;self.increment({name:name,value:-(parseInt(value)||1)},callback)},Usergrid.Counter.prototype.reset=function(options,callback){var self=this,name=options.name;self.increment({name:name,value:0},callback)},Usergrid.Counter.prototype.getData=function(options,callback){var start_time,end_time,start=options.start||0,end=options.end||Date.now(),resolution=(options.resolution||"all").toLowerCase(),counters=options.counters||Object.keys(this._data.counters),res=(resolution||"all").toLowerCase();-1===COUNTER_RESOLUTIONS.indexOf(res)&&(res="all"),start_time=getSafeTime(start),end_time=getSafeTime(end);var self=this,params=Object.keys(counters).map(function(counter){return["counter",encodeURIComponent(counters[counter])].join("=")});params.push("resolution="+res),params.push("start_time="+String(start_time)),params.push("end_time="+String(end_time));var endpoint="counters?"+params.join("&");this._client.request({endpoint:endpoint},function(err,data){return data.counters&&data.counters.length&&data.counters.forEach(function(counter){self._data.counters[counter.name]=counter.value||counter.values}),doCallback(callback,[err,data,self],self)})},Usergrid.Folder=function(options,callback){var self=this;console.log("FOLDER OPTIONS",options),self._client=options.client,self._data=options.data||{},self._data.type="folders";var missingData=["name","owner","path"].some(function(required){return!(required in self._data)});return missingData?doCallback(callback,[new UsergridInvalidArgumentError("Invalid asset data: 'name', 'owner', and 'path' are required properties."),null,self],self):void self.save(function(err,response){err?doCallback(callback,[new UsergridError(response),response,self],self):(response&&response.entities&&response.entities.length&&self.set(response.entities[0]),doCallback(callback,[null,response,self],self))})},Usergrid.Folder.prototype=new Usergrid.Entity,Usergrid.Folder.prototype.fetch=function(callback){var self=this;Usergrid.Entity.prototype.fetch.call(self,function(err,data){console.log("self",self.get()),console.log("data",data),err?doCallback(callback,[null,data,self],self):self.getAssets(function(err,response){err?doCallback(callback,[new UsergridError(response),resonse,self],self):doCallback(callback,[null,self],self)})})},Usergrid.Folder.prototype.addAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset,asset instanceof Usergrid.Entity||(asset=new Usergrid.Asset(asset));break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}asset&&asset instanceof Usergrid.Entity&&asset.fetch(function(err,data){if(err)doCallback(callback,[new UsergridError(data),data,self],self);else{var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/"),options={method:"POST",endpoint:endpoint};self._client.request(options,callback)}})}else doCallback(callback,[new UsergridInvalidArgumentError("No asset specified"),null,self],self)},Usergrid.Folder.prototype.removeAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset;break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}if(asset&&null!==asset){var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/");self._client.request({method:"DELETE",endpoint:endpoint},function(err,response){err?doCallback(callback,[new UsergridError(response),response,self],self):doCallback(callback,[null,response,self],self)})}}else doCallback(callback,[new UsergridInvalidArgumentError("No asset specified"),null,self],self)},Usergrid.Folder.prototype.getAssets=function(callback){return this.getConnections("assets",callback)},XMLHttpRequest.prototype.sendAsBinary||(XMLHttpRequest.prototype.sendAsBinary=function(sData){for(var nBytes=sData.length,ui8Data=new Uint8Array(nBytes),nIdx=0;nBytes>nIdx;nIdx++)ui8Data[nIdx]=255&sData.charCodeAt(nIdx);this.send(ui8Data)}),Usergrid.Asset=function(options,callback){var self=this;self._client=options.client,self._data=options.data||{},self._data.type="assets";var missingData=["name","owner","path"].some(function(required){return!(required in self._data)});missingData?doCallback(callback,[new UsergridError("Invalid asset data: 'name', 'owner', and 'path' are required properties."),null,self],self):self.save(function(err,data){err?doCallback(callback,[new UsergridError(data),data,self],self):(data&&data.entities&&data.entities.length&&self.set(data.entities[0]),doCallback(callback,[null,data,self],self))})},Usergrid.Asset.prototype=new Usergrid.Entity,Usergrid.Asset.prototype.addToFolder=function(options,callback){var self=this;if("folder"in options&&isUUID(options.folder)){Usergrid.Folder({uuid:options.folder},function(err,folder){if(err)doCallback(callback,[UsergridError.fromResponse(folder),folder,self],self);else{var endpoint=["folders",folder.get("uuid"),"assets",self.get("uuid")].join("/"),options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,response){err?doCallback(callback,[UsergridError.fromResponse(folder),response,self],self):doCallback(callback,[null,folder,self],self)})}})}else doCallback(callback,[new UsergridError("folder not specified"),null,self],self)},Usergrid.Entity.prototype.attachAsset=function(file,callback){if(!(window.File&&window.FileReader&&window.FileList&&window.Blob))return void doCallback(callback,[new UsergridError("The File APIs are not fully supported by your browser."),null,this],this);var self=this,args=arguments,type=this._data.type,attempts=self.get("attempts");if(isNaN(attempts)&&(attempts=3),"assets"!=type&&"asset"!=type)var endpoint=[this._client.clientAppURL,type,self.get("uuid")].join("/");else{self.set("content-type",file.type),self.set("size",file.size);var endpoint=[this._client.clientAppURL,"assets",self.get("uuid"),"data"].join("/")}var xhr=new XMLHttpRequest;xhr.open("POST",endpoint,!0),xhr.onerror=function(err){doCallback(callback,[new UsergridError("The File APIs are not fully supported by your browser.")],xhr,self)},xhr.onload=function(ev){xhr.status>=500&&attempts>0?(self.set("attempts",--attempts),setTimeout(function(){self.attachAsset.apply(self,args)},100)):xhr.status>=300?(self.set("attempts"),doCallback(callback,[new UsergridError(JSON.parse(xhr.responseText)),xhr,self],self)):(self.set("attempts"),self.fetch(),doCallback(callback,[null,xhr,self],self))};var fr=new FileReader;fr.onload=function(){var binary=fr.result;("assets"===type||"asset"===type)&&(xhr.overrideMimeType("application/octet-stream"),xhr.setRequestHeader("Content-Type","application/octet-stream")),xhr.sendAsBinary(binary)},fr.readAsBinaryString(file)},Usergrid.Asset.prototype.upload=function(data,callback){this.attachAsset(data,function(err,response){err?doCallback(callback,[new UsergridError(err),response,self],self):doCallback(callback,[null,response,self],self)})},Usergrid.Entity.prototype.downloadAsset=function(callback){var endpoint,self=this,type=this._data.type,xhr=new XMLHttpRequest;endpoint="assets"!=type&&"asset"!=type?[this._client.clientAppURL,type,self.get("uuid")].join("/"):[this._client.clientAppURL,"assets",self.get("uuid"),"data"].join("/"),xhr.open("GET",endpoint,!0),xhr.responseType="blob",xhr.onload=function(ev){var blob=xhr.response;"assets"!=type&&"asset"!=type?doCallback(callback,[null,blob,xhr],self):doCallback(callback,[null,xhr,self],self)},xhr.onerror=function(err){callback(!0,err),doCallback(callback,[new UsergridError(err),xhr,self],self)},"assets"!=type&&"asset"!=type?xhr.setRequestHeader("Accept",self._data["file-metadata"]["content-type"]):xhr.overrideMimeType(self.get("content-type")), +xhr.send()},Usergrid.Asset.prototype.download=function(callback){this.downloadAsset(function(err,response){err?doCallback(callback,[new UsergridError(err),response,self],self):doCallback(callback,[null,response,self],self)})},function(global){function UsergridError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridHTTPResponseError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidHTTPMethodError(message,name,timestamp,duration,exception){this.message=message,this.name=name||"invalid_http_method",this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidURIError(message,name,timestamp,duration,exception){this.message=message,this.name=name||"invalid_uri",this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidArgumentError(message,name,timestamp,duration,exception){this.message=message,this.name=name||"invalid_argument",this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridKeystoreDatabaseUpgradeNeededError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}var short,name="UsergridError",_name=global[name],_short=short&&void 0!==short?global[short]:void 0;return UsergridError.prototype=new Error,UsergridError.prototype.constructor=UsergridError,UsergridError.fromResponse=function(response){return response&&"undefined"!=typeof response?new UsergridError(response.error_description,response.error,response.timestamp,response.duration,response.exception):new UsergridError},UsergridError.createSubClass=function(name){return name in global&&global[name]?global[name]:(global[name]=function(){},global[name].name=name,global[name].prototype=new UsergridError,global[name])},UsergridHTTPResponseError.prototype=new UsergridError,UsergridInvalidHTTPMethodError.prototype=new UsergridError,UsergridInvalidURIError.prototype=new UsergridError,UsergridInvalidArgumentError.prototype=new UsergridError,UsergridKeystoreDatabaseUpgradeNeededError.prototype=new UsergridError,global.UsergridHTTPResponseError=UsergridHTTPResponseError,global.UsergridInvalidHTTPMethodError=UsergridInvalidHTTPMethodError,global.UsergridInvalidURIError=UsergridInvalidURIError,global.UsergridInvalidArgumentError=UsergridInvalidArgumentError,global.UsergridKeystoreDatabaseUpgradeNeededError=UsergridKeystoreDatabaseUpgradeNeededError,global[name]=UsergridError,void 0!==short&&(global[short]=UsergridError),global[name].noConflict=function(){return _name&&(global[name]=_name),void 0!==short&&(global[short]=_short),UsergridError},global[name]}(this);var UsergridAuth=function(token,expiry){var self=this;self.token=token,self.expiry=expiry||0;var usingToken=token?!0:!1;return Object.defineProperty(self,"hasToken",{get:function(){return self.token?!0:!1},configurable:!0}),Object.defineProperty(self,"isExpired",{get:function(){return usingToken?!1:Date.now()>=self.expiry},configurable:!0}),Object.defineProperty(self,"isValid",{get:function(){return!self.isExpired&&self.hasToken},configurable:!0}),Object.defineProperty(self,"tokenTtl",{configurable:!0,writable:!0}),_.assign(self,{destroy:function(){self.token=void 0,self.expiry=0,self.tokenTtl=void 0}}),self},UsergridAppAuth=function(){var self=this,args=flattenArgs(arguments);return _.isPlainObject(args[0])?(self.clientId=args[0].clientId,self.clientSecret=args[0].clientSecret,self.tokenTtl=args[0].tokenTtl):(self.clientId=args[0],self.clientSecret=args[1],self.tokenTtl=args[2]),UsergridAuth.call(self),_.assign(self,UsergridAuth),self};inherits(UsergridAppAuth,UsergridAuth);var UsergridUserAuth=function(){var self=this,args=flattenArgs(arguments);return _.isPlainObject(args[0])?(self.username=args[0].username,self.email=args[0].email,self.tokenTtl=args[0].tokenTtl):(self.username=args[0],self.email=args[1],self.tokenTtl=args[2]),UsergridAuth.call(self),_.assign(self,UsergridAuth),self};inherits(UsergridUserAuth,UsergridAuth); \ No newline at end of file From 0a2a34859727e0038afd69279600def3663bf0f3 Mon Sep 17 00:00:00 2001 From: Robert Walsh Date: Tue, 27 Sep 2016 16:17:37 -0500 Subject: [PATCH 07/36] Updates --- Gruntfile.js | 22 +- lib/Usergrid.js | 35 +- lib/modules/Auth.js | 8 +- lib/modules/Client.js | 8 +- lib/modules/Query.js | 12 +- lib/modules/Response.js | 107 + lib/modules/UsergridEntity.js | 196 + lib/modules/UsergridUser.js | 150 + lib/modules/request.js | 63 + lib/modules/util/Ajax.js | 4 +- lib/modules/util/Helpers.js | 269 +- lib/modules/util/Promise.js | 26 +- package.json | 5 +- tests/mocha/index.html | 21 +- tests/mocha/test.js | 1819 ++++---- tests/mocha/test_query.js | 122 + tests/resources/js/blanket_mocha.min.js | 1 - tests/resources/js/json2.js | 486 --- tests/resources/js/mocha.js | 5341 ----------------------- tests/resources/js/should.js | 4062 ----------------- usergrid.js | 833 +++- usergrid.min.js | 16 +- 22 files changed, 2519 insertions(+), 11087 deletions(-) create mode 100644 lib/modules/Response.js create mode 100644 lib/modules/UsergridEntity.js create mode 100644 lib/modules/UsergridUser.js create mode 100644 lib/modules/request.js create mode 100644 tests/mocha/test_query.js delete mode 100644 tests/resources/js/blanket_mocha.min.js delete mode 100755 tests/resources/js/json2.js delete mode 100644 tests/resources/js/mocha.js delete mode 100644 tests/resources/js/should.js diff --git a/Gruntfile.js b/Gruntfile.js index 4d7e26f..d57a750 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -10,14 +10,17 @@ module.exports = function(grunt) { "lib/modules/Query.js", "lib/Usergrid.js", "lib/modules/Client.js", - "lib/modules/Entity.js", - "lib/modules/Collection.js", + "lib/modules/request.js", + "lib/modules/Entity.js", + "lib/modules/Auth.js", + "lib/modules/UsergridEntity.js", + "lib/modules/Collection.js", "lib/modules/Group.js", "lib/modules/Counter.js", "lib/modules/Folder.js", - "lib/modules/Asset.js", - "lib/modules/Error.js", - "lib/modules/Auth.js" + "lib/modules/Response.js", + "lib/modules/Asset.js", + "lib/modules/Error.js" ]; var tests = ["tests/mocha/index.html", "tests/mocha/test_*.html"]; // Project configuration. @@ -114,21 +117,22 @@ module.exports = function(grunt) { "files": [files, 'Gruntfile.js'], "tasks": ["default"] }, - "blanket_mocha": { + "mocha": { //"all": tests, - urls: [ 'http://localhost:8000/tests/mocha/index.html' ], "options": { + urls: [ 'http://localhost:8000/tests/mocha/index.html' ], "dest": "report/coverage.html", "reporter": "Spec", "threshold": 70 } } }); + grunt.loadNpmTasks("grunt-mocha"); grunt.loadNpmTasks("grunt-contrib-clean"); grunt.loadNpmTasks("grunt-contrib-uglify"); grunt.loadNpmTasks("grunt-contrib-watch"); grunt.loadNpmTasks("grunt-contrib-connect"); - grunt.loadNpmTasks("grunt-blanket-mocha"); + grunt.loadNpmTasks("should"); grunt.registerTask("default", [ "clean", "uglify" @@ -139,6 +143,6 @@ module.exports = function(grunt) { ]); grunt.registerTask("test", [ "connect:test", - "blanket_mocha" + "mocha" ]); }; diff --git a/lib/Usergrid.js b/lib/Usergrid.js index 8871a03..6e6b05a 100644 --- a/lib/Usergrid.js +++ b/lib/Usergrid.js @@ -201,6 +201,20 @@ function doCallback(callback, params, context) { return true; }; + Usergrid.validateAndRetrieveClient = function(args) { + var client = undefined; + if (args instanceof Usergrid.Client) { client = args } + else if (args[0] instanceof Usergrid.Client) { client = args[0] } + else if (Usergrid.isInitialized) { client = Usergrid.getInstance() } + else { throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument") } + return client + }; + + Usergrid.calculateExpiry = function(expires_in) { + return Date.now() + ((expires_in ? expires_in - 5 : 0) * 1000) + }; + + Usergrid.Request = function(method, endpoint, query_params, data, callback) { var p = new Promise(); /* @@ -227,21 +241,26 @@ function doCallback(callback, params, context) { this.logger.error(endpoint, this.endpoint, /^https:\/\//.test(endpoint)); throw new UsergridInvalidURIError("The provided endpoint is not valid: " + this.endpoint); } + /* a callback to make the request */ var request = function() { - return Ajax.request(this.method, this.endpoint, this.data) + return new UsergridRequest({method:this.method,uri:this.endpoint,body:this.data}) + // return Ajax.request(this.method, this.endpoint, this.data) }.bind(this); + /* a callback to process the response */ - var response = function(err, request) { - return new Usergrid.Response(err, request) + var response = function(request) { + return new UsergridResponse(request) }.bind(this); + /* a callback to clean up and return data to the client */ - var oncomplete = function(err, response) { - p.done(err, response); - this.logger.info("REQUEST", err, response); - doCallback(callback, [err, response]); - this.logger.timeEnd("process request " + method + " " + endpoint); + var oncomplete = function(response) { + p.done(response); + // this.logger.info("REQUEST", response); + doCallback(callback, [response]); + // this.logger.timeEnd("process request " + method + " " + endpoint); }.bind(this); + /* and a promise to chain them all together */ Promise.chain([request, response]).then(oncomplete); diff --git a/lib/modules/Auth.js b/lib/modules/Auth.js index 7e755da..1af3028 100644 --- a/lib/modules/Auth.js +++ b/lib/modules/Auth.js @@ -61,7 +61,7 @@ var UsergridAuth = function(token, expiry) { var UsergridAppAuth = function() { var self = this - var args = flattenArgs(arguments) + var args = UsergridHelpers.flattenArgs(arguments) if (_.isPlainObject(args[0])) { self.clientId = args[0].clientId self.clientSecret = args[0].clientSecret @@ -75,11 +75,11 @@ var UsergridAppAuth = function() { _.assign(self, UsergridAuth) return self } -inherits(UsergridAppAuth,UsergridAuth) +UsergridHelpers.inherits(UsergridAppAuth,UsergridAuth) var UsergridUserAuth = function() { var self = this - var args = flattenArgs(arguments) + var args = UsergridHelpers.flattenArgs(arguments) if (_.isPlainObject(args[0])) { self.username = args[0].username self.email = args[0].email @@ -93,4 +93,4 @@ var UsergridUserAuth = function() { _.assign(self, UsergridAuth) return self } -inherits(UsergridUserAuth,UsergridAuth) +UsergridHelpers.inherits(UsergridUserAuth,UsergridAuth) \ No newline at end of file diff --git a/lib/modules/Client.js b/lib/modules/Client.js index 211742a..9d18ba8 100644 --- a/lib/modules/Client.js +++ b/lib/modules/Client.js @@ -124,15 +124,11 @@ var defaultOptions = { qs = propCopy(qs, default_qs); } var self=this; - var req = new Usergrid.Request(method, uri, qs, body, function(err, response) { + var req = new Usergrid.Request(method, uri, qs, body, function(response) { /*if (AUTH_ERRORS.indexOf(response.error) !== -1) { return logoutCallback(); }*/ - if(err){ - doCallback(callback, [err, response, self], self); - }else{ - doCallback(callback, [null, response, self], self); - } + doCallback(callback, [response, self], self); //p.done(err, response); }); }; diff --git a/lib/modules/Query.js b/lib/modules/Query.js index 26012c6..1cbb81a 100644 --- a/lib/modules/Query.js +++ b/lib/modules/Query.js @@ -42,32 +42,32 @@ var UsergridQuery = function(type) { return self }, eq: function(key, value) { - query = self.andJoin(key + ' = ' + useQuotesIfRequired(value)) + query = self.andJoin(key + ' = ' + UsergridHelpers.useQuotesIfRequired(value)) return self }, equal: this.eq, gt: function(key, value) { - query = self.andJoin(key + ' > ' + useQuotesIfRequired(value)) + query = self.andJoin(key + ' > ' + UsergridHelpers.useQuotesIfRequired(value)) return self }, greaterThan: this.gt, gte: function(key, value) { - query = self.andJoin(key + ' >= ' + useQuotesIfRequired(value)) + query = self.andJoin(key + ' >= ' + UsergridHelpers.useQuotesIfRequired(value)) return self }, greaterThanOrEqual: this.gte, lt: function(key, value) { - query = self.andJoin(key + ' < ' + useQuotesIfRequired(value)) + query = self.andJoin(key + ' < ' + UsergridHelpers.useQuotesIfRequired(value)) return self }, lessThan: this.lt, lte: function(key, value) { - query = self.andJoin(key + ' <= ' + useQuotesIfRequired(value)) + query = self.andJoin(key + ' <= ' + UsergridHelpers.useQuotesIfRequired(value)) return self }, lessThanOrEqual: this.lte, contains: function(key, value) { - query = self.andJoin(key + ' contains ' + useQuotesIfRequired(value)) + query = self.andJoin(key + ' contains ' + UsergridHelpers.useQuotesIfRequired(value)) return self }, locationWithin: function(distanceInMeters, lat, lng) { diff --git a/lib/modules/Response.js b/lib/modules/Response.js new file mode 100644 index 0000000..6e786b1 --- /dev/null +++ b/lib/modules/Response.js @@ -0,0 +1,107 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +'use strict' + +var UsergridResponseError = function(responseErrorObject) { + var self = this + if (_.has(responseErrorObject,'error') === false) { + return + } + self.name = responseErrorObject.error + self.description = responseErrorObject.error_description || responseErrorObject.description + self.exception = responseErrorObject.exception + return self +} + +var UsergridResponse = function(request) { + var p = new Promise(); + var self = this + self.ok = false + + if (!request) { + return + } else { + self.statusCode = parseInt(request.status) + var responseJSON; + try { + var responseText = request.responseText + responseJSON = JSON.parse(responseText); + } catch (e) { + responseJSON = {} + } + + if (self.statusCode < 400) { + self.ok = true + if (_.has(responseJSON, 'entities')) { + var entities = responseJSON.entities.map(function (en) { + var entity = new UsergridEntity(en) + if (entity.isUser) { + entity = new UsergridUser(entity) + } + return entity + }) + + _.assign(self, { + metadata: _.cloneDeep(responseJSON), + entities: entities + }) + delete self.metadata.entities + + self.first = _.first(entities) || undefined + self.entity = self.first + self.last = _.last(entities) || undefined + + if (_.get(self, 'metadata.path') === '/users') { + self.user = self.first + self.users = self.entities + } + + Object.defineProperty(self, 'hasNextPage', { + get: function () { + return _.has(self, 'metadata.cursor') + } + }) + + UsergridHelpers.setReadOnly(self.metadata) + } + } else { + _.assign(self, { + error: new UsergridResponseError(responseJSON) + }) + } + } + if (this.success) { + p.done(this); + } else { + p.done(this); + } + return p; +} + +UsergridResponse.prototype = { + loadNextPage: function() { + var self = this + var args = UsergridHelpers.flattenArgs(arguments) + var callback = UsergridHelpers.callback(args) + if (!self.metadata.cursor) { + callback() + } + var client = Usergrid.validateAndRetrieveClient(args) + var type = _.last(_.get(self,'metadata.path').split('/')) + var limit = _.first(_.get(this,'metadata.params.limit')) + var query = new UsergridQuery(type).cursor(this.metadata.cursor).limit(limit) + return client.GET(query, callback) + } +} \ No newline at end of file diff --git a/lib/modules/UsergridEntity.js b/lib/modules/UsergridEntity.js new file mode 100644 index 0000000..6853522 --- /dev/null +++ b/lib/modules/UsergridEntity.js @@ -0,0 +1,196 @@ +function updateEntityFromRemote(usergridResponse) { + UsergridHelpers.setWritable(this, ['uuid', 'name', 'type', 'created']) + _.assign(this, usergridResponse.entity) + UsergridHelpers.setReadOnly(this, ['uuid', 'name', 'type', 'created']) +} + +var UsergridEntity = function() { + var self = this + var args = UsergridHelpers.flattenArgs(arguments) + + if (args.length === 0) { + throw new Error('A UsergridEntity object cannot be initialized without passing one or more arguments') + } + + if (_.isPlainObject(args[0])) { + _.assign(self, args[0]) + } else { + self.type = _.isString(args[0]) ? args[0] : undefined + self.name = _.isString(args[1]) ? args[1] : undefined + } + + if (!_.isString(self.type)) { + throw new Error('"type" (or "collection") parameter is required when initializing a UsergridEntity object') + } + + Object.defineProperty(self, 'tempAuth', { + enumerable: false, + configurable: true, + writable: true + }) + + Object.defineProperty(self, 'isUser', { + get: function() { + return (self.type.toLowerCase() === 'user') + } + }) + + Object.defineProperty(self, 'hasAsset', { + get: function() { + return _.has(self, 'file-metadata') + } + }) + + self.asset = undefined + + UsergridHelpers.setReadOnly(self, ['uuid', 'name', 'type', 'created']) + + return self +} + +UsergridEntity.prototype = { + putProperty: function(key, value) { + this[key] = value + }, + putProperties: function(obj) { + _.assign(this, obj) + }, + removeProperty: function(key) { + this.removeProperties([key]) + }, + removeProperties: function(keys) { + var self = this + keys.forEach(function(key) { + delete self[key] + }) + }, + insert: function(key, value, idx) { + if (!_.isArray(this[key])) { + this[key] = this[key] ? [this[key]] : [] + } + this[key].splice.apply(this[key], [idx, 0].concat(value)) + }, + append: function(key, value) { + this.insert(key, value, Number.MAX_SAFE_INTEGER) + }, + prepend: function(key, value) { + this.insert(key, value, 0) + }, + pop: function(key) { + if (_.isArray(this[key])) { + this[key].pop() + } + }, + shift: function(key) { + if (_.isArray(this[key])) { + this[key].shift() + } + }, + reload: function() { + var args = helpers.args(arguments) + var client = helpers.client.validate(args) + var callback = UsergridHelpers.callback(args) + + client.tempAuth = this.tempAuth + this.tempAuth = undefined + client.GET(this, function(error, usergridResponse) { + updateEntityFromRemote.call(this, usergridResponse) + callback(error, usergridResponse, this) + }.bind(this)) + }, + save: function() { + var args = UsergridHelpers.flattenArgs(arguments) + var client = Usergrid.validateAndRetrieveClient(args) + var callback = UsergridHelpers.callback(args) + + client.tempAuth = this.tempAuth + this.tempAuth = undefined + client.PUT(this, function(error, usergridResponse) { + updateEntityFromRemote.call(this, usergridResponse) + callback(error, usergridResponse, this) + }.bind(this)) + }, + remove: function() { + var args = UsergridHelpers.flattenArgs(arguments) + var client = Usergrid.validateAndRetrieveClient(args) + var callback = UsergridHelpers.callback(args) + + client.tempAuth = this.tempAuth + this.tempAuth = undefined + client.DELETE(this, function(error, usergridResponse) { + callback(error, usergridResponse, this) + }.bind(this)) + }, + attachAsset: function(asset) { + this.asset = asset + }, + uploadAsset: function() { + var args = UsergridHelpers.flattenArgs(arguments) + var client = Usergrid.validateAndRetrieveClient(args) + var callback = UsergridHelpers.callback(args) + client.POST(this, this.asset, function(error, usergridResponse) { + updateEntityFromRemote.call(this, usergridResponse) + callback(error, usergridResponse, this) + }.bind(this)) + }, + downloadAsset: function() { + var args = UsergridHelpers.flattenArgs(arguments) + var client = Usergrid.validateAndRetrieveClient(args) + var callback = UsergridHelpers.callback(args) + var self = this + + if (_.has(self,'asset.contentType')) { + var options = { + client: client, + entity: self, + type: this.type, + method: 'GET', + encoding: null, + headers: { + "Accept": self.asset.contentType || _.first(args.filter(_.isString)) + } + } + options.uri = helpers.build.uri(client, options) // FIXME!!!! + return new UsergridRequest(options, function(error, usergridResponse) { + if (usergridResponse.ok) { + self.attachAsset(new UsergridAsset(new Buffer(usergridResponse.body))) + } + callback(error, usergridResponse, self) + }) + } else { + callback({ + name: "asset_not_found", + description: "The specified entity does not have a valid asset attached" + }) + } + }, + connect: function() { + var args = UsergridHelpers.flattenArgs(arguments) + var client = Usergrid.validateAndRetrieveClient(args) + client.tempAuth = this.tempAuth + this.tempAuth = undefined + args[0] = this + return client.connect.apply(client, args) + }, + disconnect: function() { + var args = UsergridHelpers.flattenArgs(arguments) + var client = Usergrid.validateAndRetrieveClient(args) + client.tempAuth = this.tempAuth + this.tempAuth = undefined + args[0] = this + return client.disconnect.apply(client, args) + }, + getConnections: function() { + var args = UsergridHelpers.flattenArgs(arguments) + var client = Usergrid.validateAndRetrieveClient(args) + client.tempAuth = this.tempAuth + this.tempAuth = undefined + args.shift() + args.splice(1, 0, this) + return client.getConnections.apply(client, args) + }, + usingAuth: function(auth) { + this.tempAuth = helpers.client.configureTempAuth(auth) + return this + } +} \ No newline at end of file diff --git a/lib/modules/UsergridUser.js b/lib/modules/UsergridUser.js new file mode 100644 index 0000000..2ae9487 --- /dev/null +++ b/lib/modules/UsergridUser.js @@ -0,0 +1,150 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +'use strict' + +var UsergridUser = function(obj) { + + if (! _.has(obj,'email') && !_.has(obj,'username')) { + // This is not a user entity + throw new Error('"email" or "username" property is required when initializing a UsergridUser object') + } + + var self = this + self.type = "user" + + _.assign(self, obj, UsergridEntity) + UsergridEntity.call(self, self) + + UsergridHelpers.setWritable(self, 'name') + return self +} + +var CheckAvailable = function() { + var self = this + var args = UsergridHelpers.flattenArgs(arguments) + var client = Usergrid.validateAndRetrieveClient(args) + if (args[0] instanceof UsergridClient) { + args.shift() + } + var callback = UsergridHelpers.callback(args) + var checkQuery + + if (args[0].username && args[0].email) { + checkQuery = new UsergridQuery('users').eq('username', args[0].username).or.eq('email', args[0].email) + } else if (args[0].username) { + checkQuery = new UsergridQuery('users').eq('username', args[0].username) + } else if (args[0].email) { + checkQuery = new UsergridQuery('users').eq('email', args[0].email) + } else { + throw new Error("'username' or 'email' property is required when checking for available users") + } + + client.GET(checkQuery, function(error, usergridResponse) { + callback(error, usergridResponse, (usergridResponse.entities.length > 0)) + }.bind(self)) +} + +UsergridUser.prototype = { + uniqueId: function() { + var self = this + return _.first([self.uuid, self.username, self.email].filter(_.isString)) + }, + create: function() { + var self = this + var args = UsergridHelpers.flattenArgs(arguments) + var client = UsergridHelpers.flattenArgs(args) + var callback = UsergridHelpers.callback(args) + client.POST(self, function(error, usergridResponse) { + delete self.password + _.assign(self, usergridResponse.user) + callback(error, usergridResponse, usergridResponse.user) + }.bind(self)) + }, + login: function() { + var self = this + var args = UsergridHelpers.flattenArgs(arguments) + var callback = UsergridHelpers.callback(args) + return new UsergridRequest({ + client: UsergridHelpers.validate(args), + path: 'token', + method: 'POST', + body: UsergridHelpers.userLoginBody(self) + }, function(error, usergridResponse, body) { + delete self.password + if (usergridResponse.ok) { + self.auth = new UsergridUserAuth(body.user) + self.auth.token = body.access_token + self.auth.expiry = Usergrid.calculateExpiry(body.expires_in) + self.auth.tokenTtl = body.expires_in + } + callback(error, usergridResponse, body.access_token) + }) + }, + logout: function() { + var self = this + var args = UsergridHelpers.flattenArgs(arguments) + var callback = UsergridHelpers.callback(args) + if (!self.auth || !self.auth.isValid) { + return callback({ + name: 'no_valid_token', + description: 'this user does not have a valid token' + }) + } + + var revokeAll = _.first(args.filter(_.isBoolean)) || false + + return new UsergridRequest({ + client: Usergrid.validateAndRetrieveClient(args), + path: ['users', self.uniqueId(),('revoketoken' + ((revokeAll) ? "s" : "")) ].join('/'), + method: 'PUT', + qs: (!revokeAll) ? { + token: self.auth.token + } : undefined + }, function(error, usergridResponse, body) { + self.auth.destroy() + callback(error, usergridResponse, usergridResponse.ok) + }) + }, + logoutAllSessions: function() { + var args = UsergridHelpers.flattenArgs(arguments) + args = _.concat([Usergrid.validateAndRetrieveClient(args), true], args) + return this.logout.apply(this, args) + }, + resetPassword: function() { + var self = this + var args = UsergridHelpers.flattenArgs(arguments) + var callback = UsergridHelpers.callback(args) + var client = Usergrid.validateAndRetrieveClient(args) + if (args[0] instanceof UsergridClient) { + args.shift() + } + var body = { + oldpassword: _.isPlainObject(args[0]) ? args[0].oldPassword : _.isString(args[0]) ? args[0] : undefined, + newpassword: _.isPlainObject(args[0]) ? args[0].newPassword : _.isString(args[1]) ? args[1] : undefined + } + if (!body.oldpassword || !body.newpassword) { + throw new Error('"oldPassword" and "newPassword" properties are required when resetting a user password') + } + return new UsergridRequest({ + client: client, + path: ['users',self.uniqueId(),'password'].join('/'), + method: 'PUT', + body: body + }, function(error, usergridResponse, body) { + callback(error, usergridResponse, usergridResponse.ok) + }) + } +} +UsergridHelpers.inherits(UsergridUser, UsergridEntity) \ No newline at end of file diff --git a/lib/modules/request.js b/lib/modules/request.js new file mode 100644 index 0000000..b0ea7f0 --- /dev/null +++ b/lib/modules/request.js @@ -0,0 +1,63 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +'use strict' + +var UsergridRequest = function(options) { + var self = this; + var client = Usergrid.validateAndRetrieveClient(Usergrid.getInstance()); + + if (!_.isString(options.type) && !_.isString(options.path) && !_.isString(options.uri)) { + throw new Error('one of "type" (collection name), "path", or "uri" parameters are required when initializing a UsergridRequest') + } + + if (!_.includes(['GET', 'PUT', 'POST', 'DELETE'], options.method)) { + throw new Error('"method" parameter is required when initializing a UsergridRequest') + } + + self.method = options.method + self.uri = options.uri || UsergridHelpers.uri(client, options); + self.headers = UsergridHelpers.headers(client, options) + self.body = options.body || undefined + + self.encoding = options.encoding || null // FIXME: deal with this + self.qs = UsergridHelpers.qs(options) // FIXME: deal with this + + if( _.isPlainObject(self.body) ) { + self.body = JSON.stringify(self.body) + } + + var promise = new Promise(); + + var request = new XMLHttpRequest(); + request.open(self.method,self.uri) + request.open = function(m, u) { + for (var header in self.headers) { + if( self.headers.hasOwnProperty(header) ) { + request.setRequestHeader(header, self.headers[header]) + } + } + if (self.body !== undefined) { + request.setRequestHeader("Content-Type", "application/json"); + request.setRequestHeader("Accept", "application/json"); + } + }; + request.onreadystatechange = function() { + if( this.readyState === XMLHttpRequest.DONE ) { + promise.done(request); + } + }; + request.send(UsergridHelpers.encode(self.body)) + return promise +} \ No newline at end of file diff --git a/lib/modules/util/Ajax.js b/lib/modules/util/Ajax.js index 4b8a381..0f1b2e4 100644 --- a/lib/modules/util/Ajax.js +++ b/lib/modules/util/Ajax.js @@ -53,12 +53,12 @@ if(this.readyState === 4){ self.logger.timeEnd(m + ' ' + u); clearTimeout(timeout); - p.done(null, this); + p.done(this); } }; xhr.onerror=function(response){ clearTimeout(timeout); - p.done(response, null); + p.done(response); }; xhr.oncomplete=function(response){ clearTimeout(timeout); diff --git a/lib/modules/util/Helpers.js b/lib/modules/util/Helpers.js index f4a6180..4dba691 100644 --- a/lib/modules/util/Helpers.js +++ b/lib/modules/util/Helpers.js @@ -1,41 +1,234 @@ -function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); -} - -function flattenArgs(args) { - return _.flattenDeep(Array.prototype.slice.call(args)) -} - -function validateAndRetrieveClient(args) { - var client = undefined; - if (args instanceof UsergridClient) { client = args } - else if (args[0] instanceof UsergridClient) { client = args[0] } - else if (Usergrid.isInitialized) { client = Usergrid.getInstance() } - else { throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument") } - return client -} - -function configureTempAuth(auth) { - if (_.isString(auth) && auth !== UsergridAuthMode.NONE) { - return new UsergridAuth(auth) - } else if (!auth || auth === UsergridAuthMode.NONE) { - return undefined - } else if (auth instanceof UsergridAuth) { - return auth - } else { - return undefined +(function(global) { + var name = 'UsergridHelpers', + overwrittenName = global[name]; + + function UsergridHelpers() { } + + UsergridHelpers.inherits = function(ctor, superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + + UsergridHelpers.flattenArgs = function(args) { + return _.flattenDeep(Array.prototype.slice.call(args)) + }; + + UsergridHelpers.callback = function() { + var args = _.flattenDeep(Array.prototype.slice.call(arguments)).reverse() + var emptyFunc = function() {} + return _.first(_.flattenDeep([args, _.get(args,'0.callback'), emptyFunc]).filter(_.isFunction)) + }; + + UsergridHelpers.configureTempAuth = function(auth) { + if (_.isString(auth) && auth !== UsergridAuthMode.NONE) { + return new UsergridAuth(auth) + } else if (!auth || auth === UsergridAuthMode.NONE) { + return undefined + } else if (auth instanceof UsergridAuth) { + return auth + } else { + return undefined + } + }; + + UsergridHelpers.userLoginBody = function(options) { + var body = { + grant_type: 'password', + password: options.password + } + if (options.tokenTtl) { + body.ttl = options.tokenTtl + } + body[(options.username) ? "username" : "email"] = (options.username) ? options.username : options.email + return body + }; + + UsergridHelpers.appLoginBody = function(options) { + var body = { + grant_type: 'client_credentials', + client_id: options.clientId, + client_secret: options.clientSecret + } + if (options.tokenTtl) { + body.ttl = options.tokenTtl + } + return body + }; + + UsergridHelpers.useQuotesIfRequired = function(value) { + return (_.isFinite(value) || isUUID(value) || _.isBoolean(value) || _.isObject(value) && !_.isFunction(value) || _.isArray(value)) ? value : ("'" + value + "'") + }; + + UsergridHelpers.setReadOnly = function(obj, key) { + if (_.isArray(key)) { + return key.forEach(function(k) { + UsergridHelpers.setReadOnly(obj, k) + }) + } else if (_.isPlainObject(obj[key])) { + return Object.freeze(obj[key]) + } else if (_.isPlainObject(obj) && key === undefined) { + return Object.freeze(obj) + } else if (_.has(obj,key)) { + return Object.defineProperty(obj, key, { + writable: false + }) + } else { + return obj + } + }; + + UsergridHelpers.setWritable = function(obj, key) { + if (_.isArray(key)) { + return key.forEach(function(k) { + UsergridHelpers.setWritable(obj, k) + }) + // Note that once Object.freeze is called on an object, it cannot be unfrozen, so we need to clone it + } else if (_.isPlainObject(obj[key])) { + return _.clone(obj[key]) + } else if (_.isPlainObject(obj) && key === undefined) { + return _.clone(obj) + } else if (_.has(obj,key)) { + return Object.defineProperty(obj, key, { + writable: true + }) + } else { + return obj + } + } + + UsergridHelpers.normalize = function(str, options) { + + // make sure protocol is followed by two slashes + str = str.replace(/:\//g, '://'); + + // remove consecutive slashes + str = str.replace(/([^:\s])\/+/g, '$1/'); + + // remove trailing slash before parameters or hash + str = str.replace(/\/(\?|&|#[^!])/g, '$1'); + + // replace ? in parameters with & + str = str.replace(/(\?.+)\?/g, '$1&'); + + return str; } -} -function useQuotesIfRequired(value) { - return (_.isFinite(value) || isUUID(value) || _.isBoolean(value) || _.isObject(value) && !_.isFunction(value) || _.isArray(value)) ? value : ("'" + value + "'") -} + UsergridHelpers.urljoin = function() { + var input = arguments; + var options = {}; + + if (typeof arguments[0] === 'object') { + // new syntax with array and options + input = arguments[0]; + options = arguments[1] || {}; + } + + var joined = [].slice.call(input, 0).join('/'); + return UsergridHelpers.normalize(joined, options); + }; + + UsergridHelpers.uri = function(client, options) { + return UsergridHelpers.urljoin( + client.baseUrl, + client.orgId, + client.appId, + options.path || options.type, + options.method !== "POST" ? _.first([ + options.uuidOrName, + options.uuid, + options.name, + _.get(options,'entity.uuid'), + _.get(options,'entity.name'), + "" + ].filter(_.isString)) : "" + ) + } + + UsergridHelpers.headers = function(client, options) { + var headers = { + 'User-Agent':'usergrid-js/v' + Usergrid.USERGRID_SDK_VERSION + } + _.assign(headers, options.headers) + + var token + if (_.get(client,'tempAuth.isValid')) { + // if ad-hoc authentication was set in the client, get the token and destroy the auth + token = client.tempAuth.token + client.tempAuth = undefined + } else if (_.get(client,'currentUser.auth.isValid')) { + // defaults to using the current user's token + token = client.currentUser.auth.token + } else if (_.get(client,'authFallback') === UsergridAuthMode.APP && _.get(client,'appAuth.isValid')) { + // if auth-fallback is set to APP request will make a call using the application token + token = client.appAuth.token + } + + if (token) { + _.assign(headers, { + authorization: 'Bearer ' + token + }) + } + return headers + } + + UsergridHelpers.qs = function(options) { + return (options.query instanceof UsergridQuery) ? { + ql: options.query._ql || undefined, + limit: options.query._limit, + cursor: options.query._cursor + } : options.qs + } + + UsergridHelpers.formData = function(options) { + if (_.get(options,'asset.data')) { + var formData = {} + formData.file = { + value: options.asset.data, + options: { + filename: _.get(options,'asset.filename') || '', // UsergridAsset.DEFAULT_FILE_NAME, //FIXME!!!! + contentType: _.get(options,'asset.contentType') || 'application/octet-stream' + } + } + if (_.has(options,'asset.name')) { + formData.name = options.asset.name + } + return formData + } else { + return undefined + } + } + + UsergridHelpers.encode = function(data) { + var result = ""; + if (typeof data === "string") { + result = data; + } else { + var e = encodeURIComponent; + for (var i in data) { + if (data.hasOwnProperty(i)) { + result += '&' + e(i) + '=' + e(data[i]); + } + } + } + return result; + } + + global[name] = UsergridHelpers; + global[name].noConflict = function() { + if (overwrittenName) { + global[name] = overwrittenName; + } + return UsergridHelpers; + }; + return global[name]; +}(this)); + + diff --git a/lib/modules/util/Promise.js b/lib/modules/util/Promise.js index 76d0d04..3bfc471 100644 --- a/lib/modules/util/Promise.js +++ b/lib/modules/util/Promise.js @@ -25,7 +25,6 @@ function Promise() { this.complete = false; - this.error = null; this.result = null; this.callbacks = []; } @@ -34,17 +33,16 @@ return callback.apply(context, arguments); }; if (this.complete) { - f(this.error, this.result); + f(this.result); } else { this.callbacks.push(f); } }; - Promise.prototype.done = function(error, result) { + Promise.prototype.done = function(result) { this.complete = true; - this.error = error; this.result = result; if(this.callbacks){ - for (var i = 0; i < this.callbacks.length; i++) this.callbacks[i](error, result); + for (var i = 0; i < this.callbacks.length; i++) this.callbacks[i](result); this.callbacks.length = 0; } }; @@ -52,16 +50,14 @@ var p = new Promise(), total = promises.length, completed = 0, - errors = [], results = []; function notifier(i) { - return function(error, result) { + return function(result) { completed += 1; - errors[i] = error; results[i] = result; if (completed === total) { - p.done(errors, results); + p.done(results); } }; } @@ -70,20 +66,20 @@ } return p; }; - Promise.chain = function(promises, error, result) { + Promise.chain = function(promises, result) { var p = new Promise(); if (promises===null||promises.length === 0) { - p.done(error, result); + p.done(result); } else { - promises[0](error, result).then(function(res, err) { + promises[0](result).then(function(res) { promises.splice(0, 1); //self.logger.info(promises.length) if(promises){ - Promise.chain(promises, res, err).then(function(r, e) { - p.done(r, e); + Promise.chain(promises, res).then(function(r) { + p.done(r); }); }else{ - p.done(res, err); + p.done(res); } }); } diff --git a/package.json b/package.json index 72e2046..8d7f2e1 100644 --- a/package.json +++ b/package.json @@ -13,10 +13,11 @@ "license": "Apache 2.0", "devDependencies": { "grunt": "~0.4.2", + "grunt-mocha": "~1.0.2", "grunt-contrib-clean": "~0.5.0", "grunt-contrib-watch": "~0.5.3", "grunt-contrib-uglify": "~0.2.7", - "grunt-blanket-mocha": "~0.3.3", - "grunt-contrib-connect": "~0.6.0" + "grunt-contrib-connect": "~0.6.0", + "should": "~11.1.0" } } diff --git a/tests/mocha/index.html b/tests/mocha/index.html index 9f3c5b1..c521fa5 100644 --- a/tests/mocha/index.html +++ b/tests/mocha/index.html @@ -21,19 +21,18 @@ Mocha Tests - + + - - - - + - + - - -
diff --git a/tests/mocha/test.js b/tests/mocha/test.js index cb7a20b..e45f7cb 100644 --- a/tests/mocha/test.js +++ b/tests/mocha/test.js @@ -62,26 +62,26 @@ describe('Ajax', function() { it('should POST to a URI ' + dogURI, function(done){ // appAuth.destroy() - Ajax.post(dogURI, dogData).then(function(err, data){ - assert(!err, err); + Ajax.post(dogURI, dogData).then(function(data){ + assert(data, data); done(); }) }) it('should GET a URI',function(done){ - Ajax.get(dogURI+'/'+dogName).then(function(err, data){ - assert(!err, err); + Ajax.get(dogURI+'/'+dogName).then(function(data){ + assert(data, data); done(); }) }) it('should PUT to a URI',function(done){ - Ajax.put(dogURI+'/'+dogName, {"favorite":true}).then(function(err, data){ - assert(!err, err); + Ajax.put(dogURI+'/'+dogName, {"favorite":true}).then(function(data){ + assert(data, data); done(); }) }) it('should DELETE a URI',function(done){ - Ajax.delete(dogURI+'/'+dogName, dogData).then(function(err, data){ - assert(!err, err); + Ajax.delete(dogURI+'/'+dogName, dogData).then(function(data){ + assert(data, data); done(); }) }) @@ -221,54 +221,53 @@ describe('Usergrid', function(){ var dogData=JSON.stringify({type:"dog",name:dogName}); var dogURI=client.clientAppURL + '/dogs' it('should POST to a URI',function(done){ - var req=new Usergrid.Request("POST", dogURI, {}, dogData, function(err, response){ - assert(!err, err); - assert(response instanceof Usergrid.Response, "Response is not and instance of Usergrid.Response"); + var req=new Usergrid.Request("POST", dogURI, {}, dogData, function(response){ + assert(!response.error, response.error); + assert(response instanceof UsergridResponse, "Response is not and instance of UsergridResponse"); done(); }) }) it('should GET a URI',function(done){ - var req=new Usergrid.Request("GET", dogURI+'/'+dogName, {}, null, function(err, response){ - assert(!err, err); - assert(response instanceof Usergrid.Response, "Response is not and instance of Usergrid.Response"); + var req=new Usergrid.Request("GET", dogURI+'/'+dogName, {}, null, function(response){ + assert(!response.error, response.error); + assert(response instanceof UsergridResponse, "Response is not and instance of UsergridResponse"); done(); }) }) it('should GET an array of entity data from the Usergrid.Response object',function(done){ - var req=new Usergrid.Request("GET", dogURI, {}, null, function(err, response){ - assert(!err, err); - assert(response instanceof Usergrid.Response, "Response is not and instance of Usergrid.Response"); - var entities=response.getEntities(); - assert(entities && entities.length, "Nothing was returned") + var req=new Usergrid.Request("GET", dogURI, {}, null, function(response){ + // assert(!err, err); + assert(!response.error, response.error); + assert(response.entities && response.entities.length, "Nothing was returned") done(); }) }) it('should GET entity data from the Usergrid.Response object',function(done){ - var req=new Usergrid.Request("GET", dogURI+'/'+dogName, {}, null, function(err, response){ - var entity=response.getEntity(); - assert(!err, err); - assert(response instanceof Usergrid.Response, "Response is not and instance of Usergrid.Response"); + var req=new Usergrid.Request("GET", dogURI+'/'+dogName, {}, null, function(response){ + var entity=response.entity; + assert(!response.error, response.error); + assert(response instanceof UsergridResponse, "Response is not and instance of UsergridResponse"); assert(entity, "Nothing was returned") done(); }) }) it('should PUT to a URI',function(done){ - var req=new Usergrid.Request("PUT", dogURI+'/'+dogName, {}, {favorite:true}, function(err, response){ - assert(!err, err); - assert(response instanceof Usergrid.Response, "Response is not and instance of Usergrid.Response"); + var req=new Usergrid.Request("PUT", dogURI+'/'+dogName, {}, {favorite:true}, function(response){ + assert(!response.error, response.error); + assert(response instanceof UsergridResponse, "Response is not and instance of UsergridResponse"); done(); }) }) it('should DELETE a URI',function(done){ - var req=new Usergrid.Request("DELETE", dogURI+'/'+dogName, {}, null, function(err, response){ - assert(!err, err); - assert(response instanceof Usergrid.Response, "Response is not and instance of Usergrid.Response"); + var req=new Usergrid.Request("DELETE", dogURI+'/'+dogName, {}, null, function(response){ + assert(!response.error, response.error); + assert(response instanceof UsergridResponse, "Response is not and instance of UsergridResponse"); done(); }) }) it('should NOT allow an invalid method',function(done){ try{ - var req=new Usergrid.Request("INVALID", dogURI+'/'+dogName, {}, null, function(err, response){ + var req=new Usergrid.Request("INVALID", dogURI+'/'+dogName, {}, null, function(response){ assert(true, "Should have thrown an UsergridInvalidHTTPMethodError"); done(); }) @@ -279,7 +278,7 @@ describe('Usergrid', function(){ }) it('should NOT allow an invalid URI',function(done){ try{ - var req=new Usergrid.Request("GET", "://apigee.com", {}, null, function(err, response){ + var req=new Usergrid.Request("GET", "://apigee.com", {}, null, function(response){ assert(true, "Should have thrown an UsergridInvalidURIError"); done(); }) @@ -289,887 +288,887 @@ describe('Usergrid', function(){ } }) it('should return a UsergridError object on an invalid URI',function(done){ - var req=new Usergrid.Request("GET", dogURI+'/'+dogName+'zzzzz', {}, null, function(err, response){ - assert(err, "Should have returned an error"); - assert(response instanceof Usergrid.Response, "Response is not and instance of Usergrid.Response"); - assert(err instanceof UsergridError, "Error is not and instance of UsergridError"); + var req=new Usergrid.Request("GET", dogURI+'/'+dogName+'zzzzz', {}, null, function(response){ + assert(response.error, "Should have returned an error"); + assert(response instanceof UsergridResponse, "Response is not and instance of UsergridResponse"); + assert(response.error instanceof UsergridResponseError, "Error is not and instance of UsergridResponseError"); done(); }) }) }); - describe('Usergrid Client', function() { - var client = getClient(); - describe('Usergrid CRUD request', function() { - before(function(done) { - this.timeout(10000); - //Make sure our dog doesn't already exist - client.request({ - method: 'DELETE', - endpoint: 'users/fred' - }, function(err, data) { - done(); - }); - }); - var options = { - method: 'GET', - endpoint: 'users' - }; - it('should persist default query parameters', function(done) { - //create new client with default params - var client=new Usergrid.Client({ - orgId: 'rwalsh', - appId: 'sandbox', - logging: false, //optional - turn on logging, off by default - buildCurl: true, //optional - turn on curl commands, off by default - qs:{ - test1:'test1', - test2:'test2' - } - }); - var default_qs=client.getObject('default_qs'); - assert(default_qs.test1==='test1', "the default query parameters were not persisted"); - assert(default_qs.test2==='test2', "the default query parameters were not persisted"); - client.request({ - method: 'GET', - endpoint: 'users' - }, function(err, data) { - assert(data.params.test2[0]==='test2', "the default query parameters were not sent to the backend"); - assert(data.params.test1[0]==='test1', "the default query parameters were not sent to the backend"); - done(); - }); - }); - it('should CREATE a new user', function(done) { - client.request({ - method: 'POST', - endpoint: 'users', - body: { - username: 'fred', - password: 'secret' - } - }, function(err, data) { - usergridTestHarness(err, data, done, [ - function(err, data) { - assert(!err) - } - ]); - }); - }); - it('should RETRIEVE an existing user', function(done) { - client.request({ - method: 'GET', - endpoint: 'users/fred', - body: {} - }, function(err, data) { - usergridTestHarness(err, data, done, [ - - function(err, data) { - assert(true) - } - ]); - }); - }); - it('should UPDATE an existing user', function(done) { - client.request({ - method: 'PUT', - endpoint: 'users/fred', - body: { - newkey: 'newvalue' - } - }, function(err, data) { - usergridTestHarness(err, data, done, [ - - function(err, data) { - assert(true) - } - ]); - }); - }); - it('should DELETE the user from the database', function(done) { - client.request({ - method: 'DELETE', - endpoint: 'users/fred' - }, function(err, data) { - usergridTestHarness(err, data, done, [ - - function(err, data) { - assert(true) - } - ]); - }); - }); - }); - describe('Usergrid REST', function() { - it('should return a list of users', function(done) { - client.request({ - method: 'GET', - endpoint: 'users' - }, function(err, data) { - usergridTestHarness(err, data, done, [ - function(err, data) { - assert(data.entities.length>=0, "Request should return at least one user"); - } - ]); - }); - }); - it('should return no entities when an endpoint does not exist', function(done) { - client.request({ - method: 'GET', - endpoint: 'nonexistantendpoint' - }, function(err, data) { - usergridTestHarness(err, data, done, [ - - function(err, data) { - assert(data.entities.length===0, "Request should return no entities"); - } - ]); - }); - }); - }); - describe('Usergrid convenience methods', function(){ - before(function(){ client.logout();}); - it('createEntity',function(done){ - client.createEntity({type:'dog',name:'createEntityTestDog'}, function(err, response, dog){ - assert(!err, "createEntity returned an error") - assert(dog, "createEntity did not return a dog") - assert(dog.get("name")==='createEntityTestDog', "The dog's name is not 'createEntityTestDog'") - done(); - }) - }) - it('createEntity - existing entity',function(done){ - client.createEntity({type:'dog',name:'createEntityTestDog'}, function(err, response, dog){ - try{ - assert(err, "createEntity should return an error") - }catch(e){ - assert(true, "trying to create an entity that already exists throws an error"); - }finally{ - done(); - } - }); - }) - it('buildAssetURL',function(done){ - var assetURL=client.clientAppURL + '/assets/00000000-0000-0000-000000000000/data'; - assert(assetURL===client.buildAssetURL('00000000-0000-0000-000000000000'), "buildAssetURL doesn't work") - done(); - }) - var dogEntity; - it('getEntity',function(done){ - client.getEntity({type:'dog',name:'createEntityTestDog'}, function(err, response, dog){ - assert(!err, "createEntity returned an error") - assert(dog, "createEntity returned a dog") - assert(dog.get("uuid")!==null, "The dog's UUID was not returned") - dogEntity=dog; - done(); - }) - }) - it('restoreEntity',function(done){ - var serializedDog=dogEntity.serialize(); - var dog=client.restoreEntity(serializedDog); - assert(dog, "restoreEntity did not return a dog") - assert(dog.get("uuid")===dogEntity.get("uuid"), "The dog's UUID was not the same as the serialized dog") - assert(dog.get("type")===dogEntity.get("type"), "The dog's type was not the same as the serialized dog") - assert(dog.get("name")===dogEntity.get("name"), "The dog's name was not the same as the serialized dog") - - done(); - }) - var dogCollection; - it('createCollection',function(done){ - client.createCollection({type:'dogs' + Math.floor(Math.random()*10000)},function(err, response, dogs){ - assert(!err, "createCollection returned an error"); - assert(dogs, "createCollection did not return a dogs collection"); - dogCollection=dogs; - done(); - }) - }) - it('restoreCollection',function(done){ - var serializedDogs=dogCollection.serialize(); - var dogs=client.restoreCollection(serializedDogs); - console.warn('restoreCollection',dogs, dogCollection); - assert(dogs._type===dogCollection._type, "The dog collection type was not the same as the serialized dog collection") - assert(dogs._qs==dogCollection._qs, "The query strings do not match") - assert(dogs._list.length===dogCollection._list.length, "The collections have a different number of entities") - done(); - }) - var activityUser; - before(function(done){ - activityUser=new Usergrid.Entity({client:client,data:{"type":"user",'username':"testActivityUser"}}); - console.warn(activityUser); - activityUser.fetch(function(err, data){ - console.warn(err, data, activityUser); - if(err){ - activityUser.save(function(err, data){ - activityUser.set(data); - done(); - }); - }else{ - activityUser.set(data); - done(); - } - }) - }) - it('createUserActivity',function(done){ - var options = { - "actor" : { - "displayName" :"Test Activity User", - "uuid" : activityUser.get("uuid"), - "username" : "testActivityUser", - "email" : "usergrid@apigee.com", - "image" : { - "height" : 80, - "url" : "http://placekitten.com/80/80", - "width" : 80 - } - }, - "verb" : "post", - "content" : "test post for createUserActivity", - "lat" : 48.856614, - "lon" : 2.352222 - }; - client.createUserActivity("testActivityUser", options, function(err, activity){ - assert(!err, "createUserActivity returned an error"); - assert(activity, "createUserActivity returned no activity object") - done(); - }) - }) - it('createUserActivityWithEntity',function(done){ - client.createUserActivityWithEntity(activityUser, "Another test activity with createUserActivityWithEntity", function(err, activity){ - assert(!err, "createUserActivityWithEntity returned an error "+err); - assert(activity, "createUserActivityWithEntity returned no activity object") - done(); - }) - }) - it('getFeedForUser',function(done){ - client.getFeedForUser('testActivityUser', function(err, data, items){ - assert(!err, "getFeedForUser returned an error"); - assert(data, "getFeedForUser returned no data object") - assert(items, "getFeedForUser returned no items array") - done(); - }) - }) - var testProperty="____test_item"+Math.floor(Math.random()*10000), - testPropertyValue="test"+Math.floor(Math.random()*10000), - testPropertyObjectValue={test:testPropertyValue}; - it('set',function(done){ - client.set(testProperty, testPropertyValue); - done(); - }) - it('get',function(done){ - var retrievedValue=client.get(testProperty); - assert(retrievedValue===testPropertyValue, "Get is not working properly"); - done(); - }) - it('setObject',function(done){ - client.set(testProperty, testPropertyObjectValue); - done(); - }) - it('getObject',function(done){ - var retrievedValue=client.get(testProperty); - assert(retrievedValue==testPropertyObjectValue, "getObject is not working properly"); - done(); - }) - /*it('setToken',function(done){ - client.setToken("dummytoken"); - done(); - }) - it('getToken',function(done){ - assert(client.getToken()==="dummytoken"); - done(); - })*/ - it('remove property',function(done){ - client.set(testProperty); - assert(client.get(testProperty)===null); - done(); - }) - var newUser; - it('signup',function(done){ - client.signup("newUsergridUser", "Us3rgr1d15Aw3s0m3!", "usergrid@apigee.com", "Another Satisfied Developer", function(err, user){ - assert(!err, "signup returned an error"); - assert(user, "signup returned no user object") - newUser=user; - done(); - }) - }) - it('login',function(done){ - client.login("newUsergridUser", "Us3rgr1d15Aw3s0m3!", function(err, data, user){ - assert(!err, "login returned an error"); - assert(user, "login returned no user object") - done(); - }) - }) - /*it('reAuthenticateLite',function(done){ - client.reAuthenticateLite(function(err){ - assert(!err, "reAuthenticateLite returned an error"); - done(); - }) - })*/ - /*it('reAuthenticate',function(done){ - client.reAuthenticate("usergrid@apigee.com", function(err, data, user, organizations, applications){ - assert(!err, "reAuthenticate returned an error"); - done(); - }) - })*/ - /*it('loginFacebook',function(done){ - assert(true, "Not sure how feasible it is to test this with Mocha") - done(); - })*/ - it('isLoggedIn',function(done){ - assert(client.isLoggedIn()===true, "isLoggedIn is not detecting that we have logged in.") - done(); - }) - it('getLoggedInUser',function(done){ - setTimeout(function(){ - client.getLoggedInUser(function(err, data, user){ - assert(!err, "getLoggedInUser returned an error"); - assert(user, "getLoggedInUser returned no user object") - done(); - }) - },1000); - }) - before(function(done){ - //please enjoy this musical interlude. - setTimeout(function(){done()},1000); - }) - it('logout',function(done){ - client.logout(); - assert(null===client.getToken(), "we logged out, but the token still remains.") - done(); - }) - it('getLoggedInUser',function(done){ - client.getLoggedInUser(function(err, data, user){ - assert(err, "getLoggedInUser should return an error after logout"); - assert(user, "getLoggedInUser should not return data after logout") - done(); - }) - }) - it('isLoggedIn',function(done){ - assert(client.isLoggedIn()===false, "isLoggedIn still returns true after logout.") - done(); - }) - after(function (done) { - client.request({ - method: 'DELETE', - endpoint: 'users/newUsergridUser' - }, function (err, data) { - done(); - }); - - }) - it('buildCurlCall',function(done){ - done(); - }) - it('getDisplayImage',function(done){ - done(); - }) - after(function(done){ - dogEntity.destroy(); - //dogCollection.destroy(); - done(); - }) - }); - }); - describe('Usergrid Entity', function() { - var client = getClient(); - var dog; - before(function(done) { - //Make sure our dog doesn't already exist - client.request({ - method: 'DELETE', - endpoint: 'dogs/Rocky' - }, function(err, data) { - assert(true); - done(); - }); - }); - it('should CREATE a new dog', function(done) { - var options = { - type: 'dogs', - name: 'Rocky' - } - dog=new Usergrid.Entity({client:client,data:options}); - dog.save(function(err, entity) { - assert(!err, "dog not created"); - done(); - }); - }); - it('should RETRIEVE the dog', function(done) { - if (!dog) { - assert(false, "dog not created"); - done(); - return; - } - //once the dog is created, you can set single properties: - dog.fetch(function(err) { - assert(!err, "dog not fetched"); - done(); - }); - }); - it('should UPDATE the dog', function(done) { - if (!dog) { - assert(false, "dog not created"); - done(); - return; - } - //once the dog is created, you can set single properties: - dog.set('breed', 'Dinosaur'); - - //the set function can also take a JSON object: - var data = { - master: 'Fred', - state: 'hungry' - } - //set is additive, so previously set properties are not overwritten - dog.set(data); - //finally, call save on the object to save it back to the database - dog.save(function(err) { - assert(!err, "dog not saved"); - done(); - }); - }); - it('should DELETE the dog', function(done) { - if (!dog) { - assert(false, "dog not created"); - done(); - return; - } - //once the dog is created, you can set single properties: - dog.destroy(function(err) { - assert(!err, "dog not removed"); - done(); - }); - }); - }); - describe('Usergrid Collections', function() { - var client = getClient(); - var dog, dogs = {}; - - before(function(done) { - //Make sure our dog doesn't already exist - var options = { - type: 'dogs', - qs: { - limit: 50 - } //limit statement set to 50 - } - - client.createCollection(options, function(err, response, dogs) { - if (!err) { - assert(!err, "could not retrieve list of dogs: " + dogs.error_description); - //we got 50 dogs, now display the Entities: - //do doggy cleanup - //if (dogs.hasNextEntity()) { - while (dogs.hasNextEntity()) { - //get a reference to the dog - var dog = dogs.getNextEntity(); - console.warn(dog); - //notice('removing dog ' + dogname + ' from database'); - if(dog === null) continue; - dog.destroy(function(err, data) { - assert(!err, dog.get('name') + " not removed: " + data.error_description); - if (!dogs.hasNextEntity()) { - done(); - } - }); - } - //} else { - done(); - //} - } - }); - }); - it('should CREATE a new dogs collection', function(done) { - var options = { - client:client, - type: 'dogs', - qs: { - ql: 'order by index' - } - } - dogs=new Usergrid.Collection(options); - assert(dogs!==undefined&&dogs!==null, "could not create dogs collection"); - done(); - }); - it('should CREATE dogs in the collection', function(done) { - this.timeout(10000); - var totalDogs = 30; - Array.apply(0, Array(totalDogs)).forEach(function(x, y) { - var dogNum = y + 1; - var options = { - type: 'dogs', - name: 'dog' + dogNum, - index: y - } - dogs.addEntity(options, function(err, dog) { - assert(!err, "dog not created"); - if (dogNum === totalDogs) { - done(); - } - }); - }) - }); - it('should RETRIEVE dogs from the collection', function(done) { - while (dogs.hasNextEntity()) { - //get a reference to the dog - dog = dogs.getNextEntity(); - } - if (done) done(); - }); - it('should RETRIEVE the next page of dogs from the collection', function(done) { - if (dogs.hasNextPage()) { - dogs.getNextPage(function(err) { - loop(done); - }); - } else { - done(); - } - }); - it('should RETRIEVE the previous page of dogs from the collection', function(done) { - if (dogs.hasPreviousPage()) { - dogs.getPreviousPage(function(err) { - loop(done); - }); - } else { - done(); - } - }); - it('should RETRIEVE an entity by UUID.', function(done) { - var uuid=dogs.getFirstEntity().get("uuid") - dogs.getEntityByUUID(uuid,function(err, data){ - assert(!err, "getEntityByUUID returned an error."); - assert(uuid==data.get("uuid"), "We didn't get the dog we asked for."); - done(); - }) - }); - it('should RETRIEVE the first entity from the collection', function() { - assert(dogs.getFirstEntity(), "Could not retrieve the first dog"); - }); - it('should RETRIEVE the last entity from the collection', function() { - assert(dogs.getLastEntity(), "Could not retrieve the last dog"); - }); - it('should reset the paging', function() { - dogs.resetPaging(); - assert(!dogs.hasPreviousPage(), "Could not resetPaging"); - }); - it('should reset the entity pointer', function() { - dogs.resetEntityPointer(); - assert(!dogs.hasPrevEntity(), "Could not reset the pointer"); - assert(dogs.hasNextEntity(), "Dog has no more entities"); - assert(dogs.getNextEntity(), "Could not retrieve the next dog"); - }); - it('should RETRIEVE the next entity from the collection', function() { - assert(dogs.hasNextEntity(), "Dog has no more entities"); - assert(dogs.getNextEntity(), "Could not retrieve the next dog"); - }); - it('should RETRIEVE the previous entity from the collection', function() { - assert(dogs.getNextEntity(), "Could not retrieve the next dog"); - assert(dogs.hasPrevEntity(), "Dogs has no previous entities"); - assert(dogs.getPrevEntity(), "Could not retrieve the previous dog"); - }); - it('should DELETE the entities from the collection', function(done) { - this.timeout(20000); - function remove(){ - if(dogs.hasNextEntity()){ - dogs.destroyEntity(dogs.getNextEntity(),function(err, data){ - assert(!err, "Could not destroy dog."); - remove(); - }) - }else if(dogs.hasNextPage()){ - dogs.getNextPage(); - remove(); - }else{ - done(); - } - } - remove(); - }); - }); - describe('Usergrid Counters', function() { - var client = getClient(); - var counter; - var MINUTE = 1000 * 60; - var HOUR = MINUTE * 60; - var time = Date.now() - HOUR; - - it('should CREATE a counter', function(done) { - counter = new Usergrid.Counter({ - client: client, - data: { - category: 'mocha_test', - timestamp: time, - name: "test", - counters: { - test: 0, - test_counter: 0 - } - } - }); - assert(counter, "Counter not created"); - done(); - }); - it('should save a counter', function(done) { - counter.save(function(err, data) { - assert(!err, data.error_description); - done(); - }); - }); - it('should reset a counter', function(done) { - time += MINUTE * 10 - counter.set("timestamp", time); - counter.reset({ - name: 'test' - }, function(err, data) { - assert(!err, data.error_description); - done(); - }); - }); - it("should increment 'test' counter", function(done) { - time += MINUTE * 10 - counter.set("timestamp", time); - counter.increment({ - name: 'test', - value: 1 - }, function(err, data) { - assert(!err, data.error_description); - done(); - }); - }); - it("should increment 'test_counter' counter by 4", function(done) { - time += MINUTE * 10 - counter.set("timestamp", time); - counter.increment({ - name: 'test_counter', - value: 4 - }, function(err, data) { - assert(!err, data.error_description); - done(); - }); - }); - it("should decrement 'test' counter", function(done) { - time += MINUTE * 10 - counter.set("timestamp", time); - counter.decrement({ - name: 'test', - value: 1 - }, function(err, data) { - assert(!err, data.error_description); - done(); - }); - }); - it('should fetch the counter', function(done) { - counter.fetch(function(err, data) { - assert(!err, data.error_description); - done(); - }); - }); - it('should fetch counter data', function(done) { - counter.getData({ - resolution: 'all', - counters: ['test', 'test_counter'] - }, function(err, data) { - assert(!err, data.error_description); - done(); - }); - }); - }); - describe('Usergrid Folders and Assets', function() { - var client = getClient(); - var folder, - asset, - user, - image_type, - image_url = 'http://placekitten.com/160/90', - // image_url="https://api.usergrid.com/yourorgname/sandbox/assets/a4025e7a-8ab1-11e3-b56c-5d3c6e4ca93f/data", - test_image, - filesystem, - file_url, - filename = "kitten.jpg", - foldername = "kittens", - folderpath = '/test/' + Math.round(10000 * Math.random()), - filepath = [folderpath, foldername, filename].join('/'); - before(function(done) { - var req = new XMLHttpRequest(); - req.open('GET', image_url, true); - req.responseType = 'blob'; - req.onload = function() { - test_image = req.response; - image_type = req.getResponseHeader('Content-Type'); - done(); - } - req.onerror = function(err) { - console.error(err); - done(); - }; - req.send(null); - }); - before(function(done) { - this.timeout(10000); - client.request({ - method: 'GET', - endpoint: 'Assets' - }, function(err, data) { - var assets = []; - if(data && data.entities && data.entities.length){ - assets.concat(data.entities.filter(function(asset) { - return asset.name === filename - })); - } - if (assets.length) { - assets.forEach(function(asset) { - client.request({ - method: 'DELETE', - endpoint: 'assets/' + asset.uuid - }); - }); - done(); - } else { - done(); - } - }); - }); - before(function(done) { - this.timeout(10000); - client.request({ - method: 'GET', - endpoint: 'folders' - }, function(err, data) { - var folders = []; - if(data && data.entities && data.entities.length){ - folders.concat(data.entities.filter(function(folder) { - return folder.name === foldername - })); - } - if (folders.length) { - folders.forEach(function(folder) { - client.request({ - method: 'DELETE', - endpoint: 'folders/' + folder.uuid - }); - }); - done(); - } else { - done(); - } - }); - }); - before(function(done) { - this.timeout(10000); - user = new Usergrid.Entity({ - client: client, - data: { - type: 'users', - username: 'assetuser' - } - }); - user.fetch(function(err, data) { - if (err) { - user.save(function() { - done(); - }) - } else { - done(); - } - }) - }); - it('should CREATE a folder', function(done) { - folder = new Usergrid.Folder({ - client: client, - data: { - name: foldername, - owner: user.get("uuid"), - path: folderpath - } - }, function(err, response, folder) { - assert(!err, err); - done(); - }); - }); - it('should CREATE an asset', function(done) { - asset = new Usergrid.Asset({ - client: client, - data: { - name: filename, - owner: user.get("uuid"), - path: filepath - } - }, function(err, response, asset) { - if(err){ - assert(false, err); - } - done(); - }); - }); - it('should RETRIEVE an asset', function(done) { - asset.fetch(function(err, response, entity){ - if(err){ - assert(false, err); - }else{ - asset=entity; - } - done(); - }) - }); - it('should upload asset data', function(done) { - this.timeout(5000); - asset.upload(test_image, function(err, response, asset) { - if(err){ - assert(false, err.error_description); - } - done(); - }); - }); - it('should retrieve asset data', function(done) { - this.timeout(5000); - asset.download(function(err, response, asset1) { - if(err){ - assert(false, err.error_description); - } - assert(err == undefined); - assert(asset.get('content-type') == test_image.type, "MIME types don't match"); - assert(asset.get('size') == test_image.size, "sizes don't match"); - done(); - }); - }); - it('should add the asset to a folder', function(done) { - folder.addAsset({ - asset: asset - }, function(err, data) { - if(err){ - assert(false, err.error_description); - } - done(); - }) - }); - it('should list the assets from a folder', function(done) { - folder.getAssets(function(err, assets) { - if(err){ - assert(false, err.error_description); - } - done(); - }) - }); - it('should remove the asset from a folder', function(done) { - folder.removeAsset({ - asset: asset - }, function(err, data) { - if(err){ - assert(false, err.error_description); - } - done(); - }) - }); - after(function(done) { - asset.destroy(function(err, data) { - if(err){ - assert(false, err.error_description); - } - done(); - }) - }); - after(function(done) { - folder.destroy(function(err, data) { - if(err){ - assert(false, err.error_description); - } - done(); - }) - }); - }); + // describe('Usergrid Client', function() { + // var client = getClient(); + // describe('Usergrid CRUD request', function() { + // before(function(done) { + // this.timeout(10000); + // //Make sure our dog doesn't already exist + // client.request({ + // method: 'DELETE', + // endpoint: 'users/fred' + // }, function(err, data) { + // done(); + // }); + // }); + // var options = { + // method: 'GET', + // endpoint: 'users' + // }; + // it('should persist default query parameters', function(done) { + // //create new client with default params + // var client=new Usergrid.Client({ + // orgId: 'rwalsh', + // appId: 'sandbox', + // logging: false, //optional - turn on logging, off by default + // buildCurl: true, //optional - turn on curl commands, off by default + // qs:{ + // test1:'test1', + // test2:'test2' + // } + // }); + // var default_qs=client.getObject('default_qs'); + // assert(default_qs.test1==='test1', "the default query parameters were not persisted"); + // assert(default_qs.test2==='test2', "the default query parameters were not persisted"); + // client.request({ + // method: 'GET', + // endpoint: 'users' + // }, function(err, data) { + // assert(data.params.test2[0]==='test2', "the default query parameters were not sent to the backend"); + // assert(data.params.test1[0]==='test1', "the default query parameters were not sent to the backend"); + // done(); + // }); + // }); + // it('should CREATE a new user', function(done) { + // client.request({ + // method: 'POST', + // endpoint: 'users', + // body: { + // username: 'fred', + // password: 'secret' + // } + // }, function(err, data) { + // usergridTestHarness(err, data, done, [ + // function(err, data) { + // assert(!err) + // } + // ]); + // }); + // }); + // it('should RETRIEVE an existing user', function(done) { + // client.request({ + // method: 'GET', + // endpoint: 'users/fred', + // body: {} + // }, function(err, data) { + // usergridTestHarness(err, data, done, [ + // + // function(err, data) { + // assert(true) + // } + // ]); + // }); + // }); + // it('should UPDATE an existing user', function(done) { + // client.request({ + // method: 'PUT', + // endpoint: 'users/fred', + // body: { + // newkey: 'newvalue' + // } + // }, function(err, data) { + // usergridTestHarness(err, data, done, [ + // + // function(err, data) { + // assert(true) + // } + // ]); + // }); + // }); + // it('should DELETE the user from the database', function(done) { + // client.request({ + // method: 'DELETE', + // endpoint: 'users/fred' + // }, function(err, data) { + // usergridTestHarness(err, data, done, [ + // + // function(err, data) { + // assert(true) + // } + // ]); + // }); + // }); + // }); + // describe('Usergrid REST', function() { + // it('should return a list of users', function(done) { + // client.request({ + // method: 'GET', + // endpoint: 'users' + // }, function(err, data) { + // usergridTestHarness(err, data, done, [ + // function(err, data) { + // assert(data.entities.length>=0, "Request should return at least one user"); + // } + // ]); + // }); + // }); + // it('should return no entities when an endpoint does not exist', function(done) { + // client.request({ + // method: 'GET', + // endpoint: 'nonexistantendpoint' + // }, function(err, data) { + // usergridTestHarness(err, data, done, [ + // + // function(err, data) { + // assert(data.entities.length===0, "Request should return no entities"); + // } + // ]); + // }); + // }); + // }); + // describe('Usergrid convenience methods', function(){ + // before(function(){ client.logout();}); + // it('createEntity',function(done){ + // client.createEntity({type:'dog',name:'createEntityTestDog'}, function(err, response, dog){ + // assert(!err, "createEntity returned an error") + // assert(dog, "createEntity did not return a dog") + // assert(dog.get("name")==='createEntityTestDog', "The dog's name is not 'createEntityTestDog'") + // done(); + // }) + // }) + // it('createEntity - existing entity',function(done){ + // client.createEntity({type:'dog',name:'createEntityTestDog'}, function(err, response, dog){ + // try{ + // assert(err, "createEntity should return an error") + // }catch(e){ + // assert(true, "trying to create an entity that already exists throws an error"); + // }finally{ + // done(); + // } + // }); + // }) + // it('buildAssetURL',function(done){ + // var assetURL=client.clientAppURL + '/assets/00000000-0000-0000-000000000000/data'; + // assert(assetURL===client.buildAssetURL('00000000-0000-0000-000000000000'), "buildAssetURL doesn't work") + // done(); + // }) + // var dogEntity; + // it('getEntity',function(done){ + // client.getEntity({type:'dog',name:'createEntityTestDog'}, function(err, response, dog){ + // assert(!err, "createEntity returned an error") + // assert(dog, "createEntity returned a dog") + // assert(dog.get("uuid")!==null, "The dog's UUID was not returned") + // dogEntity=dog; + // done(); + // }) + // }) + // it('restoreEntity',function(done){ + // var serializedDog=dogEntity.serialize(); + // var dog=client.restoreEntity(serializedDog); + // assert(dog, "restoreEntity did not return a dog") + // assert(dog.get("uuid")===dogEntity.get("uuid"), "The dog's UUID was not the same as the serialized dog") + // assert(dog.get("type")===dogEntity.get("type"), "The dog's type was not the same as the serialized dog") + // assert(dog.get("name")===dogEntity.get("name"), "The dog's name was not the same as the serialized dog") + // + // done(); + // }) + // var dogCollection; + // it('createCollection',function(done){ + // client.createCollection({type:'dogs' + Math.floor(Math.random()*10000)},function(err, response, dogs){ + // assert(!err, "createCollection returned an error"); + // assert(dogs, "createCollection did not return a dogs collection"); + // dogCollection=dogs; + // done(); + // }) + // }) + // it('restoreCollection',function(done){ + // var serializedDogs=dogCollection.serialize(); + // var dogs=client.restoreCollection(serializedDogs); + // console.warn('restoreCollection',dogs, dogCollection); + // assert(dogs._type===dogCollection._type, "The dog collection type was not the same as the serialized dog collection") + // assert(dogs._qs==dogCollection._qs, "The query strings do not match") + // assert(dogs._list.length===dogCollection._list.length, "The collections have a different number of entities") + // done(); + // }) + // var activityUser; + // before(function(done){ + // activityUser=new Usergrid.Entity({client:client,data:{"type":"user",'username':"testActivityUser"}}); + // console.warn(activityUser); + // activityUser.fetch(function(err, data){ + // console.warn(err, data, activityUser); + // if(err){ + // activityUser.save(function(err, data){ + // activityUser.set(data); + // done(); + // }); + // }else{ + // activityUser.set(data); + // done(); + // } + // }) + // }) + // it('createUserActivity',function(done){ + // var options = { + // "actor" : { + // "displayName" :"Test Activity User", + // "uuid" : activityUser.get("uuid"), + // "username" : "testActivityUser", + // "email" : "usergrid@apigee.com", + // "image" : { + // "height" : 80, + // "url" : "http://placekitten.com/80/80", + // "width" : 80 + // } + // }, + // "verb" : "post", + // "content" : "test post for createUserActivity", + // "lat" : 48.856614, + // "lon" : 2.352222 + // }; + // client.createUserActivity("testActivityUser", options, function(err, activity){ + // assert(!err, "createUserActivity returned an error"); + // assert(activity, "createUserActivity returned no activity object") + // done(); + // }) + // }) + // it('createUserActivityWithEntity',function(done){ + // client.createUserActivityWithEntity(activityUser, "Another test activity with createUserActivityWithEntity", function(err, activity){ + // assert(!err, "createUserActivityWithEntity returned an error "+err); + // assert(activity, "createUserActivityWithEntity returned no activity object") + // done(); + // }) + // }) + // it('getFeedForUser',function(done){ + // client.getFeedForUser('testActivityUser', function(err, data, items){ + // assert(!err, "getFeedForUser returned an error"); + // assert(data, "getFeedForUser returned no data object") + // assert(items, "getFeedForUser returned no items array") + // done(); + // }) + // }) + // var testProperty="____test_item"+Math.floor(Math.random()*10000), + // testPropertyValue="test"+Math.floor(Math.random()*10000), + // testPropertyObjectValue={test:testPropertyValue}; + // it('set',function(done){ + // client.set(testProperty, testPropertyValue); + // done(); + // }) + // it('get',function(done){ + // var retrievedValue=client.get(testProperty); + // assert(retrievedValue===testPropertyValue, "Get is not working properly"); + // done(); + // }) + // it('setObject',function(done){ + // client.set(testProperty, testPropertyObjectValue); + // done(); + // }) + // it('getObject',function(done){ + // var retrievedValue=client.get(testProperty); + // assert(retrievedValue==testPropertyObjectValue, "getObject is not working properly"); + // done(); + // }) + // /*it('setToken',function(done){ + // client.setToken("dummytoken"); + // done(); + // }) + // it('getToken',function(done){ + // assert(client.getToken()==="dummytoken"); + // done(); + // })*/ + // it('remove property',function(done){ + // client.set(testProperty); + // assert(client.get(testProperty)===null); + // done(); + // }) + // var newUser; + // it('signup',function(done){ + // client.signup("newUsergridUser", "Us3rgr1d15Aw3s0m3!", "usergrid@apigee.com", "Another Satisfied Developer", function(err, user){ + // assert(!err, "signup returned an error"); + // assert(user, "signup returned no user object") + // newUser=user; + // done(); + // }) + // }) + // it('login',function(done){ + // client.login("newUsergridUser", "Us3rgr1d15Aw3s0m3!", function(err, data, user){ + // assert(!err, "login returned an error"); + // assert(user, "login returned no user object") + // done(); + // }) + // }) + // /*it('reAuthenticateLite',function(done){ + // client.reAuthenticateLite(function(err){ + // assert(!err, "reAuthenticateLite returned an error"); + // done(); + // }) + // })*/ + // /*it('reAuthenticate',function(done){ + // client.reAuthenticate("usergrid@apigee.com", function(err, data, user, organizations, applications){ + // assert(!err, "reAuthenticate returned an error"); + // done(); + // }) + // })*/ + // /*it('loginFacebook',function(done){ + // assert(true, "Not sure how feasible it is to test this with Mocha") + // done(); + // })*/ + // it('isLoggedIn',function(done){ + // assert(client.isLoggedIn()===true, "isLoggedIn is not detecting that we have logged in.") + // done(); + // }) + // it('getLoggedInUser',function(done){ + // setTimeout(function(){ + // client.getLoggedInUser(function(err, data, user){ + // assert(!err, "getLoggedInUser returned an error"); + // assert(user, "getLoggedInUser returned no user object") + // done(); + // }) + // },1000); + // }) + // before(function(done){ + // //please enjoy this musical interlude. + // setTimeout(function(){done()},1000); + // }) + // it('logout',function(done){ + // client.logout(); + // assert(null===client.getToken(), "we logged out, but the token still remains.") + // done(); + // }) + // it('getLoggedInUser',function(done){ + // client.getLoggedInUser(function(err, data, user){ + // assert(err, "getLoggedInUser should return an error after logout"); + // assert(user, "getLoggedInUser should not return data after logout") + // done(); + // }) + // }) + // it('isLoggedIn',function(done){ + // assert(client.isLoggedIn()===false, "isLoggedIn still returns true after logout.") + // done(); + // }) + // after(function (done) { + // client.request({ + // method: 'DELETE', + // endpoint: 'users/newUsergridUser' + // }, function (err, data) { + // done(); + // }); + // + // }) + // it('buildCurlCall',function(done){ + // done(); + // }) + // it('getDisplayImage',function(done){ + // done(); + // }) + // after(function(done){ + // dogEntity.destroy(); + // //dogCollection.destroy(); + // done(); + // }) + // }); + // }); + // describe('Usergrid Entity', function() { + // var client = getClient(); + // var dog; + // before(function(done) { + // //Make sure our dog doesn't already exist + // client.request({ + // method: 'DELETE', + // endpoint: 'dogs/Rocky' + // }, function(err, data) { + // assert(true); + // done(); + // }); + // }); + // it('should CREATE a new dog', function(done) { + // var options = { + // type: 'dogs', + // name: 'Rocky' + // } + // dog=new Usergrid.Entity({client:client,data:options}); + // dog.save(function(err, entity) { + // assert(!err, "dog not created"); + // done(); + // }); + // }); + // it('should RETRIEVE the dog', function(done) { + // if (!dog) { + // assert(false, "dog not created"); + // done(); + // return; + // } + // //once the dog is created, you can set single properties: + // dog.fetch(function(err) { + // assert(!err, "dog not fetched"); + // done(); + // }); + // }); + // it('should UPDATE the dog', function(done) { + // if (!dog) { + // assert(false, "dog not created"); + // done(); + // return; + // } + // //once the dog is created, you can set single properties: + // dog.set('breed', 'Dinosaur'); + // + // //the set function can also take a JSON object: + // var data = { + // master: 'Fred', + // state: 'hungry' + // } + // //set is additive, so previously set properties are not overwritten + // dog.set(data); + // //finally, call save on the object to save it back to the database + // dog.save(function(err) { + // assert(!err, "dog not saved"); + // done(); + // }); + // }); + // it('should DELETE the dog', function(done) { + // if (!dog) { + // assert(false, "dog not created"); + // done(); + // return; + // } + // //once the dog is created, you can set single properties: + // dog.destroy(function(err) { + // assert(!err, "dog not removed"); + // done(); + // }); + // }); + // }); + // describe('Usergrid Collections', function() { + // var client = getClient(); + // var dog, dogs = {}; + // + // before(function(done) { + // //Make sure our dog doesn't already exist + // var options = { + // type: 'dogs', + // qs: { + // limit: 50 + // } //limit statement set to 50 + // } + // + // client.createCollection(options, function(err, response, dogs) { + // if (!err) { + // assert(!err, "could not retrieve list of dogs: " + dogs.error_description); + // //we got 50 dogs, now display the Entities: + // //do doggy cleanup + // //if (dogs.hasNextEntity()) { + // while (dogs.hasNextEntity()) { + // //get a reference to the dog + // var dog = dogs.getNextEntity(); + // console.warn(dog); + // //notice('removing dog ' + dogname + ' from database'); + // if(dog === null) continue; + // dog.destroy(function(err, data) { + // assert(!err, dog.get('name') + " not removed: " + data.error_description); + // if (!dogs.hasNextEntity()) { + // done(); + // } + // }); + // } + // //} else { + // done(); + // //} + // } + // }); + // }); + // it('should CREATE a new dogs collection', function(done) { + // var options = { + // client:client, + // type: 'dogs', + // qs: { + // ql: 'order by index' + // } + // } + // dogs=new Usergrid.Collection(options); + // assert(dogs!==undefined&&dogs!==null, "could not create dogs collection"); + // done(); + // }); + // it('should CREATE dogs in the collection', function(done) { + // this.timeout(10000); + // var totalDogs = 30; + // Array.apply(0, Array(totalDogs)).forEach(function(x, y) { + // var dogNum = y + 1; + // var options = { + // type: 'dogs', + // name: 'dog' + dogNum, + // index: y + // } + // dogs.addEntity(options, function(err, dog) { + // assert(!err, "dog not created"); + // if (dogNum === totalDogs) { + // done(); + // } + // }); + // }) + // }); + // it('should RETRIEVE dogs from the collection', function(done) { + // while (dogs.hasNextEntity()) { + // //get a reference to the dog + // dog = dogs.getNextEntity(); + // } + // if (done) done(); + // }); + // it('should RETRIEVE the next page of dogs from the collection', function(done) { + // if (dogs.hasNextPage()) { + // dogs.getNextPage(function(err) { + // loop(done); + // }); + // } else { + // done(); + // } + // }); + // it('should RETRIEVE the previous page of dogs from the collection', function(done) { + // if (dogs.hasPreviousPage()) { + // dogs.getPreviousPage(function(err) { + // loop(done); + // }); + // } else { + // done(); + // } + // }); + // it('should RETRIEVE an entity by UUID.', function(done) { + // var uuid=dogs.getFirstEntity().get("uuid") + // dogs.getEntityByUUID(uuid,function(err, data){ + // assert(!err, "getEntityByUUID returned an error."); + // assert(uuid==data.get("uuid"), "We didn't get the dog we asked for."); + // done(); + // }) + // }); + // it('should RETRIEVE the first entity from the collection', function() { + // assert(dogs.getFirstEntity(), "Could not retrieve the first dog"); + // }); + // it('should RETRIEVE the last entity from the collection', function() { + // assert(dogs.getLastEntity(), "Could not retrieve the last dog"); + // }); + // it('should reset the paging', function() { + // dogs.resetPaging(); + // assert(!dogs.hasPreviousPage(), "Could not resetPaging"); + // }); + // it('should reset the entity pointer', function() { + // dogs.resetEntityPointer(); + // assert(!dogs.hasPrevEntity(), "Could not reset the pointer"); + // assert(dogs.hasNextEntity(), "Dog has no more entities"); + // assert(dogs.getNextEntity(), "Could not retrieve the next dog"); + // }); + // it('should RETRIEVE the next entity from the collection', function() { + // assert(dogs.hasNextEntity(), "Dog has no more entities"); + // assert(dogs.getNextEntity(), "Could not retrieve the next dog"); + // }); + // it('should RETRIEVE the previous entity from the collection', function() { + // assert(dogs.getNextEntity(), "Could not retrieve the next dog"); + // assert(dogs.hasPrevEntity(), "Dogs has no previous entities"); + // assert(dogs.getPrevEntity(), "Could not retrieve the previous dog"); + // }); + // it('should DELETE the entities from the collection', function(done) { + // this.timeout(20000); + // function remove(){ + // if(dogs.hasNextEntity()){ + // dogs.destroyEntity(dogs.getNextEntity(),function(err, data){ + // assert(!err, "Could not destroy dog."); + // remove(); + // }) + // }else if(dogs.hasNextPage()){ + // dogs.getNextPage(); + // remove(); + // }else{ + // done(); + // } + // } + // remove(); + // }); + // }); + // describe('Usergrid Counters', function() { + // var client = getClient(); + // var counter; + // var MINUTE = 1000 * 60; + // var HOUR = MINUTE * 60; + // var time = Date.now() - HOUR; + // + // it('should CREATE a counter', function(done) { + // counter = new Usergrid.Counter({ + // client: client, + // data: { + // category: 'mocha_test', + // timestamp: time, + // name: "test", + // counters: { + // test: 0, + // test_counter: 0 + // } + // } + // }); + // assert(counter, "Counter not created"); + // done(); + // }); + // it('should save a counter', function(done) { + // counter.save(function(err, data) { + // assert(!err, data.error_description); + // done(); + // }); + // }); + // it('should reset a counter', function(done) { + // time += MINUTE * 10 + // counter.set("timestamp", time); + // counter.reset({ + // name: 'test' + // }, function(err, data) { + // assert(!err, data.error_description); + // done(); + // }); + // }); + // it("should increment 'test' counter", function(done) { + // time += MINUTE * 10 + // counter.set("timestamp", time); + // counter.increment({ + // name: 'test', + // value: 1 + // }, function(err, data) { + // assert(!err, data.error_description); + // done(); + // }); + // }); + // it("should increment 'test_counter' counter by 4", function(done) { + // time += MINUTE * 10 + // counter.set("timestamp", time); + // counter.increment({ + // name: 'test_counter', + // value: 4 + // }, function(err, data) { + // assert(!err, data.error_description); + // done(); + // }); + // }); + // it("should decrement 'test' counter", function(done) { + // time += MINUTE * 10 + // counter.set("timestamp", time); + // counter.decrement({ + // name: 'test', + // value: 1 + // }, function(err, data) { + // assert(!err, data.error_description); + // done(); + // }); + // }); + // it('should fetch the counter', function(done) { + // counter.fetch(function(err, data) { + // assert(!err, data.error_description); + // done(); + // }); + // }); + // it('should fetch counter data', function(done) { + // counter.getData({ + // resolution: 'all', + // counters: ['test', 'test_counter'] + // }, function(err, data) { + // assert(!err, data.error_description); + // done(); + // }); + // }); + // }); + // describe('Usergrid Folders and Assets', function() { + // var client = getClient(); + // var folder, + // asset, + // user, + // image_type, + // image_url = 'http://placekitten.com/160/90', + // // image_url="https://api.usergrid.com/yourorgname/sandbox/assets/a4025e7a-8ab1-11e3-b56c-5d3c6e4ca93f/data", + // test_image, + // filesystem, + // file_url, + // filename = "kitten.jpg", + // foldername = "kittens", + // folderpath = '/test/' + Math.round(10000 * Math.random()), + // filepath = [folderpath, foldername, filename].join('/'); + // before(function(done) { + // var req = new XMLHttpRequest(); + // req.open('GET', image_url, true); + // req.responseType = 'blob'; + // req.onload = function() { + // test_image = req.response; + // image_type = req.getResponseHeader('Content-Type'); + // done(); + // } + // req.onerror = function(err) { + // console.error(err); + // done(); + // }; + // req.send(null); + // }); + // before(function(done) { + // this.timeout(10000); + // client.request({ + // method: 'GET', + // endpoint: 'Assets' + // }, function(err, data) { + // var assets = []; + // if(data && data.entities && data.entities.length){ + // assets.concat(data.entities.filter(function(asset) { + // return asset.name === filename + // })); + // } + // if (assets.length) { + // assets.forEach(function(asset) { + // client.request({ + // method: 'DELETE', + // endpoint: 'assets/' + asset.uuid + // }); + // }); + // done(); + // } else { + // done(); + // } + // }); + // }); + // before(function(done) { + // this.timeout(10000); + // client.request({ + // method: 'GET', + // endpoint: 'folders' + // }, function(err, data) { + // var folders = []; + // if(data && data.entities && data.entities.length){ + // folders.concat(data.entities.filter(function(folder) { + // return folder.name === foldername + // })); + // } + // if (folders.length) { + // folders.forEach(function(folder) { + // client.request({ + // method: 'DELETE', + // endpoint: 'folders/' + folder.uuid + // }); + // }); + // done(); + // } else { + // done(); + // } + // }); + // }); + // before(function(done) { + // this.timeout(10000); + // user = new Usergrid.Entity({ + // client: client, + // data: { + // type: 'users', + // username: 'assetuser' + // } + // }); + // user.fetch(function(err, data) { + // if (err) { + // user.save(function() { + // done(); + // }) + // } else { + // done(); + // } + // }) + // }); + // it('should CREATE a folder', function(done) { + // folder = new Usergrid.Folder({ + // client: client, + // data: { + // name: foldername, + // owner: user.get("uuid"), + // path: folderpath + // } + // }, function(err, response, folder) { + // assert(!err, err); + // done(); + // }); + // }); + // it('should CREATE an asset', function(done) { + // asset = new Usergrid.Asset({ + // client: client, + // data: { + // name: filename, + // owner: user.get("uuid"), + // path: filepath + // } + // }, function(err, response, asset) { + // if(err){ + // assert(false, err); + // } + // done(); + // }); + // }); + // it('should RETRIEVE an asset', function(done) { + // asset.fetch(function(err, response, entity){ + // if(err){ + // assert(false, err); + // }else{ + // asset=entity; + // } + // done(); + // }) + // }); + // it('should upload asset data', function(done) { + // this.timeout(5000); + // asset.upload(test_image, function(err, response, asset) { + // if(err){ + // assert(false, err.error_description); + // } + // done(); + // }); + // }); + // it('should retrieve asset data', function(done) { + // this.timeout(5000); + // asset.download(function(err, response, asset1) { + // if(err){ + // assert(false, err.error_description); + // } + // assert(err == undefined); + // assert(asset.get('content-type') == test_image.type, "MIME types don't match"); + // assert(asset.get('size') == test_image.size, "sizes don't match"); + // done(); + // }); + // }); + // it('should add the asset to a folder', function(done) { + // folder.addAsset({ + // asset: asset + // }, function(err, data) { + // if(err){ + // assert(false, err.error_description); + // } + // done(); + // }) + // }); + // it('should list the assets from a folder', function(done) { + // folder.getAssets(function(err, assets) { + // if(err){ + // assert(false, err.error_description); + // } + // done(); + // }) + // }); + // it('should remove the asset from a folder', function(done) { + // folder.removeAsset({ + // asset: asset + // }, function(err, data) { + // if(err){ + // assert(false, err.error_description); + // } + // done(); + // }) + // }); + // after(function(done) { + // asset.destroy(function(err, data) { + // if(err){ + // assert(false, err.error_description); + // } + // done(); + // }) + // }); + // after(function(done) { + // folder.destroy(function(err, data) { + // if(err){ + // assert(false, err.error_description); + // } + // done(); + // }) + // }); + // }); }); diff --git a/tests/mocha/test_query.js b/tests/mocha/test_query.js new file mode 100644 index 0000000..d56fce1 --- /dev/null +++ b/tests/mocha/test_query.js @@ -0,0 +1,122 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +describe('UsergridQuery', function() { + + describe('_type', function() { + it('_type should equal "cats" when passing "type" as a parameter to UsergridQuery', function() { + var query = new UsergridQuery('cats') + query.should.have.property('_type').equal('cats') + }) + + it('_type should equal "cats" when calling .type() builder method', function() { + var query = new UsergridQuery().type('cats') + query.should.have.property('_type').equal('cats') + }) + + it('_type should equal "cats" when calling .collection() builder method', function() { + var query = new UsergridQuery().collection('cats') + query.should.have.property('_type').equal('cats') + }) + }) + + describe('_limit', function() { + it('_limit should equal 2 when setting .limit(2)', function() { + var query = new UsergridQuery('cats').limit(2) + query.should.have.property('_limit').equal(2) + }) + + it('_limit should equal 10 when setting .limit(10)', function() { + var query = new UsergridQuery('cats').limit(10) + query.should.have.property('_limit').equal(10) + }) + }) + + describe('_ql', function() { + it('should be an empty string if query or sort are empty or underfined', function() { + var query = new UsergridQuery('cats') + query.should.have.property('_ql').equal("") + }) + + it('should support complex builder pattern syntax (chained constructor methods)', function() { + var query = new UsergridQuery('cats') + .gt('weight', 2.4) + .contains('color', 'bl*') + .not + .eq('color', 'blue') + .or + .eq('color', 'orange') + query.should.have.property('_ql').equal("select * where weight > 2.4 and color contains 'bl*' and not color = 'blue' or color = 'orange'") + }) + + it('and operator should be implied when joining multiple conditions', function() { + var query1 = new UsergridQuery('cats') + .gt('weight', 2.4) + .contains('color', 'bl*') + query1.should.have.property('_ql').equal("select * where weight > 2.4 and color contains 'bl*'") + var query2 = new UsergridQuery('cats') + .gt('weight', 2.4) + .and + .contains('color', 'bl*') + query2.should.have.property('_ql').equal("select * where weight > 2.4 and color contains 'bl*'") + }) + + it('not operator should precede conditional statement', function() { + var query = new UsergridQuery('cats') + .not + .eq('color', 'white') + query.should.have.property('_ql').equal("select * where not color = 'white'") + }) + + it('fromString should set _ql directly, bypassing builder pattern methods', function() { + var q = "where color = 'black' or color = 'orange'" + var query = new UsergridQuery('cats') + .fromString(q) + query.should.have.property('_ql').equal(q) + }) + + it('string values should be contained in single quotes', function() { + var query = new UsergridQuery('cats') + .eq('color', 'black') + query.should.have.property('_ql').equal("select * where color = 'black'") + }) + + it('boolean values should not be contained in single quotes', function() { + var query = new UsergridQuery('cats') + .eq('longHair', true) + query.should.have.property('_ql').equal("select * where longHair = true") + }) + + it('float values should not be contained in single quotes', function() { + var query = new UsergridQuery('cats') + .lt('weight', 18) + query.should.have.property('_ql').equal("select * where weight < 18") + }) + + it('integer values should not be contained in single quotes', function() { + var query = new UsergridQuery('cats') + .gte('weight', 2) + query.should.have.property('_ql').equal("select * where weight >= 2") + }) + + it('uuid values should not be contained in single quotes', function() { + var query = new UsergridQuery('cats') + .eq('uuid', 'a61e29ba-944f-11e5-8690-fbb14f62c803') + query.should.have.property('_ql').equal("select * where uuid = a61e29ba-944f-11e5-8690-fbb14f62c803") + }) + }) +}); \ No newline at end of file diff --git a/tests/resources/js/blanket_mocha.min.js b/tests/resources/js/blanket_mocha.min.js deleted file mode 100644 index db01cab..0000000 --- a/tests/resources/js/blanket_mocha.min.js +++ /dev/null @@ -1 +0,0 @@ -(function(e){(function(t,n){"use strict";typeof e=="function"&&e.amd?e(["exports"],n):typeof exports!="undefined"?n(exports):n(t.esprima={})})(this,function(e){"use strict";function m(e,t){if(!e)throw new Error("ASSERT: "+t)}function g(e,t){return u.slice(e,t)}function y(e){return"0123456789".indexOf(e)>=0}function b(e){return"0123456789abcdefABCDEF".indexOf(e)>=0}function w(e){return"01234567".indexOf(e)>=0}function E(e){return e===" "||e===" "||e==="\f"||e==="\u00a0"||e.charCodeAt(0)>=5760&&"\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\ufeff".indexOf(e)>=0}function S(e){return e==="\n"||e==="\r"||e==="\u2028"||e==="\u2029"}function x(e){return e==="$"||e==="_"||e==="\\"||e>="a"&&e<="z"||e>="A"&&e<="Z"||e.charCodeAt(0)>=128&&o.NonAsciiIdentifierStart.test(e)}function T(e){return e==="$"||e==="_"||e==="\\"||e>="a"&&e<="z"||e>="A"&&e<="Z"||e>="0"&&e<="9"||e.charCodeAt(0)>=128&&o.NonAsciiIdentifierPart.test(e)}function N(e){switch(e){case"class":case"enum":case"export":case"extends":case"import":case"super":return!0}return!1}function C(e){switch(e){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"yield":case"let":return!0}return!1}function k(e){return e==="eval"||e==="arguments"}function L(e){var t=!1;switch(e.length){case 2:t=e==="if"||e==="in"||e==="do";break;case 3:t=e==="var"||e==="for"||e==="new"||e==="try";break;case 4:t=e==="this"||e==="else"||e==="case"||e==="void"||e==="with";break;case 5:t=e==="while"||e==="break"||e==="catch"||e==="throw";break;case 6:t=e==="return"||e==="typeof"||e==="delete"||e==="switch";break;case 7:t=e==="default"||e==="finally";break;case 8:t=e==="function"||e==="continue"||e==="debugger";break;case 10:t=e==="instanceof"}if(t)return!0;switch(e){case"const":return!0;case"yield":case"let":return!0}return a&&C(e)?!0:N(e)}function A(){var e,t,n;t=!1,n=!1;while(f=h&&R({},s.UnexpectedToken,"ILLEGAL")):(e=u[f++],f>=h&&R({},s.UnexpectedToken,"ILLEGAL"),e==="*"&&(e=u[f],e==="/"&&(++f,t=!1)));else if(e==="/"){e=u[f+1];if(e==="/")f+=2,n=!0;else{if(e!=="*")break;f+=2,t=!0,f>=h&&R({},s.UnexpectedToken,"ILLEGAL")}}else if(E(e))++f;else{if(!S(e))break;++f,e==="\r"&&u[f]==="\n"&&++f,++l,c=f}}}function O(e){var t,n,r,i=0;n=e==="u"?4:2;for(t=0;t"&&r===">"&&i===">"&&s==="=")return f+=4,{type:t.Punctuator,value:">>>=",lineNumber:l,lineStart:c,range:[e,f]};if(n==="="&&r==="="&&i==="=")return f+=3,{type:t.Punctuator,value:"===",lineNumber:l,lineStart:c,range:[e,f]};if(n==="!"&&r==="="&&i==="=")return f+=3,{type:t.Punctuator,value:"!==",lineNumber:l,lineStart:c,range:[e,f]};if(n===">"&&r===">"&&i===">")return f+=3,{type:t.Punctuator,value:">>>",lineNumber:l,lineStart:c,range:[e,f]};if(n==="<"&&r==="<"&&i==="=")return f+=3,{type:t.Punctuator,value:"<<=",lineNumber:l,lineStart:c,range:[e,f]};if(n===">"&&r===">"&&i==="=")return f+=3,{type:t.Punctuator,value:">>=",lineNumber:l,lineStart:c,range:[e,f]};if(r==="="&&"<>=!+-*%&|^/".indexOf(n)>=0)return f+=2,{type:t.Punctuator,value:n+r,lineNumber:l,lineStart:c,range:[e,f]};if(n===r&&"+-<>&|".indexOf(n)>=0&&"+-<>&|".indexOf(r)>=0)return f+=2,{type:t.Punctuator,value:n+r,lineNumber:l,lineStart:c,range:[e,f]};if("[]<>+-*%&|^!~?:=/".indexOf(n)>=0)return{type:t.Punctuator,value:u[f++],lineNumber:l,lineStart:c,range:[e,f]}}function D(){var e,n,r;r=u[f],m(y(r)||r===".","Numeric literal must start with a decimal digit or a decimal point"),n=f,e="";if(r!=="."){e=u[f++],r=u[f];if(e==="0"){if(r==="x"||r==="X"){e+=u[f++];while(f=h&&(r=""),R({},s.UnexpectedToken,"ILLEGAL")}return f=0&&f=h)return{type:t.EOF,lineNumber:l,lineStart:c,range:[f,f]};n=_();if(typeof n!="undefined")return n;e=u[f];if(e==="'"||e==='"')return P();if(e==="."||y(e))return D();n=M();if(typeof n!="undefined")return n;R({},s.UnexpectedToken,"ILLEGAL")}function F(){var e;return p?(f=p.range[1],l=p.lineNumber,c=p.lineStart,e=p,p=null,e):(p=null,j())}function I(){var e,t,n;return p!==null?p:(e=f,t=l,n=c,p=j(),f=e,l=t,c=n,p)}function q(){var e,t,n,r;return e=f,t=l,n=c,A(),r=l!==t,f=e,l=t,c=n,r}function R(e,t){var n,r=Array.prototype.slice.call(arguments,2),i=t.replace(/%(\d)/g,function(e,t){return r[t]||""});throw typeof e.lineNumber=="number"?(n=new Error("Line "+e.lineNumber+": "+i),n.index=e.range[0],n.lineNumber=e.lineNumber,n.column=e.range[0]-c+1):(n=new Error("Line "+l+": "+i),n.index=f,n.lineNumber=l,n.column=f-c+1),n}function U(){try{R.apply(null,arguments)}catch(e){if(!v.errors)throw e;v.errors.push(e)}}function z(e){e.type===t.EOF&&R(e,s.UnexpectedEOS),e.type===t.NumericLiteral&&R(e,s.UnexpectedNumber),e.type===t.StringLiteral&&R(e,s.UnexpectedString),e.type===t.Identifier&&R(e,s.UnexpectedIdentifier);if(e.type===t.Keyword){if(N(e.value))R(e,s.UnexpectedReserved);else if(a&&C(e.value)){U(e,s.StrictReservedWord);return}R(e,s.UnexpectedToken,e.value)}R(e,s.UnexpectedToken,e.value)}function W(e){var n=F();(n.type!==t.Punctuator||n.value!==e)&&z(n)}function X(e){var n=F();(n.type!==t.Keyword||n.value!==e)&&z(n)}function V(e){var n=I();return n.type===t.Punctuator&&n.value===e}function $(e){var n=I();return n.type===t.Keyword&&n.value===e}function J(){var e=I(),n=e.value;return e.type!==t.Punctuator?!1:n==="="||n==="*="||n==="/="||n==="%="||n==="+="||n==="-="||n==="<<="||n===">>="||n===">>>="||n==="&="||n==="^="||n==="|="}function K(){var e,n;if(u[f]===";"){F();return}n=l,A();if(l!==n)return;if(V(";")){F();return}e=I(),e.type!==t.EOF&&!V("}")&&z(e)}function Q(e){return e.type===r.Identifier||e.type===r.MemberExpression}function G(){var e=[];W("[");while(!V("]"))V(",")?(F(),e.push(null)):(e.push(Tt()),V("]")||W(","));return W("]"),{type:r.ArrayExpression,elements:e}}function Y(e,t){var n,i;return n=a,i=Gt(),t&&a&&k(e[0].name)&&U(t,s.StrictParamName),a=n,{type:r.FunctionExpression,id:null,params:e,defaults:[],body:i,rest:null,generator:!1,expression:!1}}function Z(){var e=F();return e.type===t.StringLiteral||e.type===t.NumericLiteral?(a&&e.octal&&U(e,s.StrictOctalLiteral),ln(e)):{type:r.Identifier,name:e.value}}function et(){var e,n,i,o;e=I();if(e.type===t.Identifier)return i=Z(),e.value==="get"&&!V(":")?(n=Z(),W("("),W(")"),{type:r.Property,key:n,value:Y([]),kind:"get"}):e.value==="set"&&!V(":")?(n=Z(),W("("),e=I(),e.type!==t.Identifier?(W(")"),U(e,s.UnexpectedToken,e.value),{type:r.Property,key:n,value:Y([]),kind:"set"}):(o=[Lt()],W(")"),{type:r.Property,key:n,value:Y(o,e),kind:"set"})):(W(":"),{type:r.Property,key:i,value:Tt(),kind:"init"});if(e.type!==t.EOF&&e.type!==t.Punctuator)return n=Z(),W(":"),{type:r.Property,key:n,value:Tt(),kind:"init"};z(e)}function tt(){var e=[],t,n,o,u={},f=String;W("{");while(!V("}"))t=et(),t.key.type===r.Identifier?n=t.key.name:n=f(t.key.value),o=t.kind==="init"?i.Data:t.kind==="get"?i.Get:i.Set,Object.prototype.hasOwnProperty.call(u,n)?(u[n]===i.Data?a&&o===i.Data?U({},s.StrictDuplicateProperty):o!==i.Data&&U({},s.AccessorDataProperty):o===i.Data?U({},s.AccessorDataProperty):u[n]&o&&U({},s.AccessorGetSet),u[n]|=o):u[n]=o,e.push(t),V("}")||W(",");return W("}"),{type:r.ObjectExpression,properties:e}}function nt(){var e;return W("("),e=Nt(),W(")"),e}function rt(){var e=I(),n=e.type;if(n===t.Identifier)return{type:r.Identifier,name:F().value};if(n===t.StringLiteral||n===t.NumericLiteral)return a&&e.octal&&U(e,s.StrictOctalLiteral),ln(F());if(n===t.Keyword){if($("this"))return F(),{type:r.ThisExpression};if($("function"))return Zt()}return n===t.BooleanLiteral?(F(),e.value=e.value==="true",ln(e)):n===t.NullLiteral?(F(),e.value=null,ln(e)):V("[")?G():V("{")?tt():V("(")?nt():V("/")||V("/=")?ln(H()):z(F())}function it(){var e=[];W("(");if(!V(")"))while(f>")||V(">>>"))e={type:r.BinaryExpression,operator:F().value,left:e,right:dt()};return e}function mt(){var e,t;t=d.allowIn,d.allowIn=!0,e=vt();while(V("<")||V(">")||V("<=")||V(">=")||t&&$("in")||$("instanceof"))e={type:r.BinaryExpression,operator:F().value,left:e,right:vt()};return d.allowIn=t,e}function gt(){var e=mt();while(V("==")||V("!=")||V("===")||V("!=="))e={type:r.BinaryExpression,operator:F().value,left:e,right:mt()};return e}function yt(){var e=gt();while(V("&"))F(),e={type:r.BinaryExpression,operator:"&",left:e,right:gt()};return e}function bt(){var e=yt();while(V("^"))F(),e={type:r.BinaryExpression,operator:"^",left:e,right:yt()};return e}function wt(){var e=bt();while(V("|"))F(),e={type:r.BinaryExpression,operator:"|",left:e,right:bt()};return e}function Et(){var e=wt();while(V("&&"))F(),e={type:r.LogicalExpression,operator:"&&",left:e,right:wt()};return e}function St(){var e=Et();while(V("||"))F(),e={type:r.LogicalExpression,operator:"||",left:e,right:Et()};return e}function xt(){var e,t,n;return e=St(),V("?")&&(F(),t=d.allowIn,d.allowIn=!0,n=Tt(),d.allowIn=t,W(":"),e={type:r.ConditionalExpression,test:e,consequent:n,alternate:Tt()}),e}function Tt(){var e,t;return e=I(),t=xt(),J()&&(Q(t)||U({},s.InvalidLHSInAssignment),a&&t.type===r.Identifier&&k(t.name)&&U(e,s.StrictLHSAssignment),t={type:r.AssignmentExpression,operator:F().value,left:t,right:Tt()}),t}function Nt(){var e=Tt();if(V(",")){e={type:r.SequenceExpression,expressions:[e]};while(f0&&v.comments[v.comments.length-1].range[1]>n)return;v.comments.push({type:e,value:t,range:[n,r],loc:i})}function sn(){var e,t,n,r,i,o;e="",i=!1,o=!1;while(f=h?(o=!1,e+=t,n.end={line:l,column:h-c},rn("Line",e,r,h,n)):e+=t;else if(i)S(t)?(t==="\r"&&u[f+1]==="\n"?(++f,e+="\r\n"):e+=t,++l,++f,c=f,f>=h&&R({},s.UnexpectedToken,"ILLEGAL")):(t=u[f++],f>=h&&R({},s.UnexpectedToken,"ILLEGAL"),e+=t,t==="*"&&(t=u[f],t==="/"&&(e=e.substr(0,e.length-1),i=!1,++f,n.end={line:l,column:f-c},rn("Block",e,r,f,n),e="")));else if(t==="/"){t=u[f+1];if(t==="/")n={start:{line:l,column:f-c}},r=f,f+=2,o=!0,f>=h&&(n.end={line:l,column:f-c},o=!1,rn("Line",e,r,f,n));else{if(t!=="*")break;r=f,f+=2,i=!0,n={start:{line:l,column:f-c-2}},f>=h&&R({},s.UnexpectedToken,"ILLEGAL")}}else if(E(t))++f;else{if(!S(t))break;++f,t==="\r"&&u[f]==="\n"&&++f,++l,c=f}}}function on(){var e,t,n,r=[];for(e=0;e0&&(r=v.tokens[v.tokens.length-1],r.range[0]===e&&r.type==="Punctuator"&&(r.value==="/"||r.value==="/=")&&v.tokens.pop()),v.tokens.push({type:"RegularExpression",value:n.literal,range:[e,f],loc:t}),n}function fn(){var e,t,n,r=[];for(e=0;e0?1:0,c=0,h=u.length,p=null,d={allowIn:!0,labelSet:{},inFunctionBody:!1,inIteration:!1,inSwitch:!1},v={},typeof t!="undefined"&&(v.range=typeof t.range=="boolean"&&t.range,v.loc=typeof t.loc=="boolean"&&t.loc,v.raw=typeof t.raw=="boolean"&&t.raw,typeof t.tokens=="boolean"&&t.tokens&&(v.tokens=[]),typeof t.comment=="boolean"&&t.comment&&(v.comments=[]),typeof t.tolerant=="boolean"&&t.tolerant&&(v.errors=[])),h>0&&typeof u[0]=="undefined"&&(e instanceof String&&(u=e.valueOf()),typeof u[0]=="undefined"&&(u=wn(e))),yn();try{n=nn(),typeof v.comments!="undefined"&&(on(),n.comments=v.comments),typeof v.tokens!="undefined"&&(fn(),n.tokens=v.tokens),typeof v.errors!="undefined"&&(n.errors=v.errors);if(v.range||v.loc)n.body=mn(n.body)}catch(i){throw i}finally{bn(),v={}}return n}var t,n,r,i,s,o,u,a,f,l,c,h,p,d,v;t={BooleanLiteral:1,EOF:2,Identifier:3,Keyword:4,NullLiteral:5,NumericLiteral:6,Punctuator:7,StringLiteral:8},n={},n[t.BooleanLiteral]="Boolean",n[t.EOF]="",n[t.Identifier]="Identifier",n[t.Keyword]="Keyword",n[t.NullLiteral]="Null",n[t.NumericLiteral]="Numeric",n[t.Punctuator]="Punctuator",n[t.StringLiteral]="String",r={AssignmentExpression:"AssignmentExpression",ArrayExpression:"ArrayExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DoWhileStatement:"DoWhileStatement",DebuggerStatement:"DebuggerStatement",EmptyStatement:"EmptyStatement",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",Identifier:"Identifier",IfStatement:"IfStatement",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",Program:"Program",Property:"Property",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement"},i={Data:1,Get:2,Set:4},s={UnexpectedToken:"Unexpected token %0",UnexpectedNumber:"Unexpected number",UnexpectedString:"Unexpected string",UnexpectedIdentifier:"Unexpected identifier",UnexpectedReserved:"Unexpected reserved word",UnexpectedEOS:"Unexpected end of input",NewlineAfterThrow:"Illegal newline after throw",InvalidRegExp:"Invalid regular expression",UnterminatedRegExp:"Invalid regular expression: missing /",InvalidLHSInAssignment:"Invalid left-hand side in assignment",InvalidLHSInForIn:"Invalid left-hand side in for-in",MultipleDefaultsInSwitch:"More than one default clause in switch statement",NoCatchOrFinally:"Missing catch or finally after try",UnknownLabel:"Undefined label '%0'",Redeclaration:"%0 '%1' has already been declared",IllegalContinue:"Illegal continue statement",IllegalBreak:"Illegal break statement",IllegalReturn:"Illegal return statement",StrictModeWith:"Strict mode code may not include a with statement",StrictCatchVariable:"Catch variable may not be eval or arguments in strict mode",StrictVarName:"Variable name may not be eval or arguments in strict mode",StrictParamName:"Parameter name eval or arguments is not allowed in strict mode",StrictParamDupe:"Strict mode function may not have duplicate parameter names",StrictFunctionName:"Function name may not be eval or arguments in strict mode",StrictOctalLiteral:"Octal literals are not allowed in strict mode.",StrictDelete:"Delete of an unqualified identifier in strict mode.",StrictDuplicateProperty:"Duplicate data property in object literal not allowed in strict mode",AccessorDataProperty:"Object literal may not have data and accessor property with the same name",AccessorGetSet:"Object literal may not have multiple get/set accessors with the same name",StrictLHSAssignment:"Assignment to eval or arguments is not allowed in strict mode",StrictLHSPostfix:"Postfix increment/decrement may not have eval or arguments operand in strict mode",StrictLHSPrefix:"Prefix increment/decrement may not have eval or arguments operand in strict mode",StrictReservedWord:"Use of future reserved word in strict mode"},o={NonAsciiIdentifierStart:new RegExp("[\u00aa\u00b5\u00ba\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]"),NonAsciiIdentifierPart:new RegExp("[\u00aa\u00b5\u00ba\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]")},typeof "esprima"[0]=="undefined"&&(g=function(t,n){return u.slice(t,n).join("")}),e.version="1.0.4",e.parse=En,e.Syntax=function(){var e,t={};typeof Object.create=="function"&&(t=Object.create(null));for(e in r)r.hasOwnProperty(e)&&(t[e]=r[e]);return typeof Object.freeze=="function"&&Object.freeze(t),t}()})})(null),function(e,t){function o(e,t,n){function o(t){n[e.range[0]]=t;for(var r=e.range[0]+1;rparseInt(t,10)}).forEach(function(t){i+=s+"['"+e+"']["+t+"]=0;\n"}),n&&_blanket._branchingArraySetup.sort(function(e,t){return e.line>t.line}).sort(function(e,t){return e.column>t.column}).forEach(function(t){t.file===e&&(i+="if (typeof "+s+"['"+e+"'].branchData["+t.line+"] === 'undefined'){\n",i+=s+"['"+e+"'].branchData["+t.line+"]=[];\n",i+="}",i+=s+"['"+e+"'].branchData["+t.line+"]["+t.column+"] = [];\n",i+=s+"['"+e+"'].branchData["+t.line+"]["+t.column+"].consequent = "+JSON.stringify(t.consequent)+";\n",i+=s+"['"+e+"'].branchData["+t.line+"]["+t.column+"].alternate = "+JSON.stringify(t.alternate)+";\n")}),i+="}",i},_blockifyIf:function(e){if(t.indexOf(e.type)>-1){var n=e.consequent||e.body,r=e.alternate;r&&r.type!=="BlockStatement"&&r.update("{\n"+r.source()+"}\n"),n&&n.type!=="BlockStatement"&&n.update("{\n"+n.source()+"}\n")}},_trackBranch:function(e,t){var n=e.loc.start.line,r=e.loc.start.column;_blanket._branchingArraySetup.push({line:n,column:r,file:t,consequent:e.consequent.loc,alternate:e.alternate.loc});var i="_$branchFcn('"+t+"',"+n+","+r+","+e.test.source()+")?"+e.consequent.source()+":"+e.alternate.source();e.update(i)},_addTracking:function(t){var n=_blanket.getCovVar();return function(r){_blanket._blockifyIf(r);if(e.indexOf(r.type)>-1&&r.parent.type!=="LabeledStatement"){_blanket._checkDefs(r,t);if(r.type==="VariableDeclaration"&&(r.parent.type==="ForStatement"||r.parent.type==="ForInStatement"))return;if(!r.loc||!r.loc.start)throw new Error("The instrumenter encountered a node with no location: "+Object.keys(r));r.update(n+"['"+t+"']["+r.loc.start.line+"]++;\n"+r.source()),_blanket._trackingArraySetup.push(r.loc.start.line)}else _blanket.options("branchTracking")&&r.type==="ConditionalExpression"&&_blanket._trackBranch(r,t)}},_checkDefs:function(e,t){if(inBrowser){e.type==="VariableDeclaration"&&e.declarations&&e.declarations.forEach(function(n){if(n.id.name==="window")throw new Error("Instrumentation error, you cannot redefine the 'window' variable in "+t+":"+e.loc.start.line)}),e.type==="FunctionDeclaration"&&e.params&&e.params.forEach(function(n){if(n.name==="window")throw new Error("Instrumentation error, you cannot redefine the 'window' variable in "+t+":"+e.loc.start.line)});if(e.type==="ExpressionStatement"&&e.expression&&e.expression.left&&e.expression.left.object&&e.expression.left.property&&e.expression.left.object.name+"."+e.expression.left.property.name===_blanket.getCovVar())throw new Error("Instrumentation error, you cannot redefine the coverage variable in "+t+":"+e.loc.start.line)}else if(e.type==="ExpressionStatement"&&e.expression&&e.expression.left&&!e.expression.left.object&&!e.expression.left.property&&e.expression.left.name===_blanket.getCovVar())throw new Error("Instrumentation error, you cannot redefine the coverage variable in "+t+":"+e.loc.start.line)},setupCoverage:function(){i.instrumentation="blanket",i.stats={suites:0,tests:0,passes:0,pending:0,failures:0,start:new Date}},_checkIfSetup:function(){if(!i.stats)throw new Error("You must call blanket.setupCoverage() first.")},onTestStart:function(){_blanket.options("debug")&&console.log("BLANKET-Test event started"),this._checkIfSetup(),i.stats.tests++,i.stats.pending++},onTestDone:function(e,t){this._checkIfSetup(),t===e?i.stats.passes++:i.stats.failures++,i.stats.pending--},onModuleStart:function(){this._checkIfSetup(),i.stats.suites++},onTestsDone:function(){_blanket.options("debug")&&console.log("BLANKET-Test event done"),this._checkIfSetup(),i.stats.end=new Date,inBrowser?this.report(i):(_blanket.options("branchTracking")||delete (inBrowser?window:global)[_blanket.getCovVar()].branchFcn,this.options("reporter").call(this,i))}},_blanket}(),function(e){var t=e.options;e.extend({outstandingRequireFiles:[],options:function(n,r){var i={};if(typeof n!="string")t(n),i=n;else{if(typeof r=="undefined")return t(n);t(n,r),i[n]=r}i.adapter&&e._loadFile(i.adapter),i.loader&&e._loadFile(i.loader)},requiringFile:function(t,n){typeof t=="undefined"?e.outstandingRequireFiles=[]:typeof n=="undefined"?e.outstandingRequireFiles.push(t):e.outstandingRequireFiles.splice(e.outstandingRequireFiles.indexOf(t),1)},requireFilesLoaded:function(){return e.outstandingRequireFiles.length===0},showManualLoader:function(){if(document.getElementById("blanketLoaderDialog"))return;var e="
";e+=" 
",e+="
",e+="
",e+="Error: Blanket.js encountered a cross origin request error while instrumenting the source files. ",e+="

This is likely caused by the source files being referenced locally (using the file:// protocol). ",e+="

Some solutions include starting Chrome with special flags, running a server locally, or using a browser without these CORS restrictions (Safari).",e+="
",typeof FileReader!="undefined"&&(e+="
Or, try the experimental loader. When prompted, simply click on the directory containing all the source files you want covered.",e+="Start Loader",e+=""),e+="
Close",e+="
",e+="
";var t=".blanketDialogWrapper {";t+="display:block;",t+="position:fixed;",t+="z-index:40001; }",t+=".blanketDialogOverlay {",t+="position:fixed;",t+="width:100%;",t+="height:100%;",t+="background-color:black;",t+="opacity:.5; ",t+="-ms-filter:'progid:DXImageTransform.Microsoft.Alpha(Opacity=50)'; ",t+="filter:alpha(opacity=50); ",t+="z-index:40001; }",t+=".blanketDialogVerticalOffset { ",t+="position:fixed;",t+="top:30%;",t+="width:100%;",t+="z-index:40002; }",t+=".blanketDialogBox { ",t+="width:405px; ",t+="position:relative;",t+="margin:0 auto;",t+="background-color:white;",t+="padding:10px;",t+="border:1px solid black; }";var n=document.createElement("style");n.innerHTML=t,document.head.appendChild(n);var r=document.createElement("div");r.id="blanketLoaderDialog",r.className="blanketDialogWrapper",r.innerHTML=e,document.body.insertBefore(r,document.body.firstChild)},manualFileLoader:function(e){function o(e){var t=new FileReader;t.onload=s,t.readAsText(e)}var t=Array.prototype.slice;e=t.call(e).filter(function(e){return e.type!==""});var n=e.length-1,r=0,i={};sessionStorage.blanketSessionLoader&&(i=JSON.parse(sessionStorage.blanketSessionLoader));var s=function(t){var s=t.currentTarget.result,u=e[r],a=u.webkitRelativePath&&u.webkitRelativePath!==""?u.webkitRelativePath:u.name;i[a]=s,r++,r===n?(sessionStorage.setItem("blanketSessionLoader",JSON.stringify(i)),document.location.reload()):o(e[r])};o(e[r])},_loadFile:function(t){if(typeof t!="undefined"){var n=new XMLHttpRequest;n.open("GET",t,!1),n.send(),e._addScript(n.responseText)}},_addScript:function(e){var t=document.createElement("script");t.type="text/javascript",t.text=e,(document.body||document.getElementsByTagName("head")[0]).appendChild(t)},hasAdapter:function(t){return e.options("adapter")!==null},report:function(t){document.getElementById("blanketLoaderDialog")||(e.blanketSession=null),t.files=window._$blanket;var n=blanket.options("commonJS")?blanket._commonjs.require:window.require;if(!t.files||!Object.keys(t.files).length){e.options("debug")&&console.log("BLANKET-Reporting No files were instrumented.");return}typeof t.files.branchFcn!="undefined"&&delete t.files.branchFcn;if(typeof e.options("reporter")=="string")e._loadFile(e.options("reporter")),e.customReporter(t,e.options("reporter_options"));else if(typeof e.options("reporter")=="function")e.options("reporter")(t,e.options("reporter_options"));else{if(typeof e.defaultReporter!="function")throw new Error("no reporter defined.");e.defaultReporter(t,e.options("reporter_options"))}},_bindStartTestRunner:function(e,t){e?e(t):window.addEventListener("load",t,!1)},_loadSourceFiles:function(t){function r(e){var t=Object.create(Object.getPrototypeOf(e)),n=Object.getOwnPropertyNames(e);return n.forEach(function(n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r)}),t}var n=blanket.options("commonJS")?blanket._commonjs.require:window.require;e.options("debug")&&console.log("BLANKET-Collecting page scripts");var i=e.utils.collectPageScripts();if(i.length===0)t();else{sessionStorage.blanketSessionLoader&&(e.blanketSession=JSON.parse(sessionStorage.blanketSessionLoader)),i.forEach(function(t,n){e.utils.cache[t]={loaded:!1}});var s=-1;e.utils.loadAll(function(e){return e?typeof i[s+1]!="undefined":(s++,s>=i.length?null:i[s])},t)}},beforeStartTestRunner:function(t){t=t||{},t.checkRequirejs=typeof t.checkRequirejs=="undefined"?!0:t.checkRequirejs,t.callback=t.callback||function(){},t.coverage=typeof t.coverage=="undefined"?!0:t.coverage,t.coverage?e._bindStartTestRunner(t.bindEvent,function(){e._loadSourceFiles(function(){var n=function(){return t.condition?t.condition():e.requireFilesLoaded()},r=function(){if(n()){e.options("debug")&&console.log("BLANKET-All files loaded, init start test runner callback.");var i=e.options("testReadyCallback");i?typeof i=="function"?i(t.callback):typeof i=="string"&&(e._addScript(i),t.callback()):t.callback()}else setTimeout(r,13)};r()})}):t.callback()},utils:{qualifyURL:function(e){var t=document.createElement("a");return t.href=e,t.href}}})}(blanket),blanket.defaultReporter=function(e){function l(e){var t=document.getElementById(e);t.style.display==="block"?t.style.display="none":t.style.display="block"}function d(e){return e.replace(/\&/g,"&").replace(//g,">").replace(/\"/g,""").replace(/\'/g,"'")}function v(e,t){var n=t?0:1;return typeof e=="undefined"||typeof e===null||typeof e[n]=="undefined"?!1:e[n].length>0}function g(e,t,n,r,i){var s="",o="";if(m.length>0){s+="";if(m[0][0].end.line===i){s+=d(t.slice(0,m[0][0].end.column))+"",t=t.slice(m[0][0].end.column),m.shift();if(m.length>0){s+="";if(m[0][0].end.line===i){s+=d(t.slice(0,m[0][0].end.column))+"",t=t.slice(m[0][0].end.column),m.shift();if(!n)return{src:s+d(t),cols:n}}else{if(!n)return{src:s+d(t)+"",cols:n};o=""}}else if(!n)return{src:s+d(t),cols:n}}else{if(!n)return{src:s+d(t)+"",cols:n};o=""}}var u=n[e],a=u.consequent;if(a.start.line>i)m.unshift([u.alternate,u]),m.unshift([a,u]),t=d(t);else{var f="";s+=d(t.slice(0,a.start.column-r))+f;if(n.length>e+1&&n[e+1].consequent.start.line===i&&n[e+1].consequent.start.column-r";var c=u.alternate;if(c.start.line>i)s+=d(t.slice(a.end.column-r)),m.unshift([c,u]);else{s+=d(t.slice(a.end.column-r,c.start.column-r)),f="",s+=f;if(n.length>e+1&&n[e+1].consequent.start.line===i&&n[e+1].consequent.start.column-r",s+=d(t.slice(c.end.column-r)),t=s}}return{src:t+o,cols:n}}var t="#blanket-main {margin:2px;background:#EEE;color:#333;clear:both;font-family:'Helvetica Neue Light', 'HelveticaNeue-Light', 'Helvetica Neue', Calibri, Helvetica, Arial, sans-serif; font-size:17px;} #blanket-main a {color:#333;text-decoration:none;} #blanket-main a:hover {text-decoration:underline;} .blanket {margin:0;padding:5px;clear:both;border-bottom: 1px solid #FFFFFF;} .bl-error {color:red;}.bl-success {color:#5E7D00;} .bl-file{width:auto;} .bl-cl{float:left;} .blanket div.rs {margin-left:50px; width:150px; float:right} .bl-nb {padding-right:10px;} #blanket-main a.bl-logo {color: #EB1764;cursor: pointer;font-weight: bold;text-decoration: none} .bl-source{ overflow-x:scroll; background-color: #FFFFFF; border: 1px solid #CBCBCB; color: #363636; margin: 25px 20px; width: 80%;} .bl-source div{white-space: pre;font-family: monospace;} .bl-source > div > span:first-child{background-color: #EAEAEA;color: #949494;display: inline-block;padding: 0 10px;text-align: center;width: 30px;} .bl-source .miss{background-color:#e6c3c7} .bl-source span.branchWarning{color:#000;background-color:yellow;} .bl-source span.branchOkay{color:#000;background-color:transparent;}",n=60,r=document.head,i=0,s=document.body,o,u=Object.keys(e.files).some(function(t){return typeof e.files[t].branchData!="undefined"}),a="
results
Coverage (%)
Covered/Total Smts.
"+(u?"
Covered/Total Branches
":"")+"
",f="
{{fileNumber}}.{{file}}
{{percentage}} %
{{numberCovered}}/{{totalSmts}}
"+(u?"
{{passedBranches}}/{{totalBranches}}
":"")+"
";grandTotalTemplate="
{{rowTitle}}
{{percentage}} %
{{numberCovered}}/{{totalSmts}}
"+(u?"
{{passedBranches}}/{{totalBranches}}
":"")+"
";var c=document.createElement("script");c.type="text/javascript",c.text=l.toString().replace("function "+l.name,"function blanket_toggleSource"),s.appendChild(c);var h=function(e,t){return Math.round(e/t*100*100)/100},p=function(e,t,n){var r=document.createElement(e);r.innerHTML=n,t.appendChild(r)},m=[],y=function(e){return typeof e!="undefined"},b=e.files,w={totalSmts:0,numberOfFilesCovered:0,passedBranches:0,totalBranches:0,moduleTotalStatements:{},moduleTotalCoveredStatements:{},moduleTotalBranches:{},moduleTotalCoveredBranches:{}},E=_blanket.options("modulePattern"),S=E?new RegExp(E):null;for(var x in b){i++;var T=b[x],N=0,C=0,k=[],L,A=[];for(L=0;L0||typeof T.branchData!="undefined")if(typeof T.branchData[L+1]!="undefined"){var M=T.branchData[L+1].filter(y),_=0;O=g(_,O,M,0,L+1).src}else m.length?O=g(0,O,null,0,L+1).src:O=d(O);else O=d(O);var D="";T[L+1]?(C+=1,N+=1,D="hit"):T[L+1]===0&&(N++,D="miss"),k[L+1]="
"+(L+1)+""+O+"
"}w.totalSmts+=N,w.numberOfFilesCovered+=C;var P=0,H=0;if(typeof T.branchData!="undefined")for(var B=0;B0&&typeof T.branchData[B][j][1]!="undefined"&&T.branchData[B][j][1].length>0&&H++);w.passedBranches+=H,w.totalBranches+=P;if(S){var F=x.match(S)[1];w.moduleTotalStatements.hasOwnProperty(F)||(w.moduleTotalStatements[F]=0,w.moduleTotalCoveredStatements[F]=0),w.moduleTotalStatements[F]+=N,w.moduleTotalCoveredStatements[F]+=C,w.moduleTotalBranches.hasOwnProperty(F)||(w.moduleTotalBranches[F]=0,w.moduleTotalCoveredBranches[F]=0),w.moduleTotalBranches[F]+=P,w.moduleTotalCoveredBranches[F]+=H}var I=h(C,N),q=f.replace("{{file}}",x).replace("{{percentage}}",I).replace("{{numberCovered}}",C).replace(/\{\{fileNumber\}\}/g,i).replace("{{totalSmts}}",N).replace("{{totalBranches}}",P).replace("{{passedBranches}}",H).replace("{{source}}",k.join(" "));I",p("style",r,t),document.getElementById("blanket-main")?document.getElementById("blanket-main").innerHTML=a.slice(23,-6):p("div",s,a)},function(){var e={},t=Array.prototype.slice,n=t.call(document.scripts);t.call(n[n.length-1].attributes).forEach(function(t){t.nodeName==="data-cover-only"&&(e.filter=t.nodeValue),t.nodeName==="data-cover-never"&&(e.antifilter=t.nodeValue),t.nodeName==="data-cover-reporter"&&(e.reporter=t.nodeValue),t.nodeName==="data-cover-adapter"&&(e.adapter=t.nodeValue),t.nodeName==="data-cover-loader"&&(e.loader=t.nodeValue),t.nodeName==="data-cover-timeout"&&(e.timeout=t.nodeValue),t.nodeName==="data-cover-modulepattern"&&(e.modulePattern=t.nodeValue);if(t.nodeName==="data-cover-reporter-options")try{e.reporter_options=JSON.parse(t.nodeValue)}catch(n){if(blanket.options("debug"))throw new Error("Invalid reporter options. Must be a valid stringified JSON object.")}t.nodeName==="data-cover-testReadyCallback"&&(e.testReadyCallback=t.nodeValue),t.nodeName==="data-cover-customVariable"&&(e.customVariable=t.nodeValue);if(t.nodeName==="data-cover-flags"){var r=" "+t.nodeValue+" ";r.indexOf(" ignoreError ")>-1&&(e.ignoreScriptError=!0),r.indexOf(" autoStart ")>-1&&(e.autoStart=!0),r.indexOf(" ignoreCors ")>-1&&(e.ignoreCors=!0),r.indexOf(" branchTracking ")>-1&&(e.branchTracking=!0),r.indexOf(" sourceURL ")>-1&&(e.sourceURL=!0),r.indexOf(" debug ")>-1&&(e.debug=!0),r.indexOf(" engineOnly ")>-1&&(e.engineOnly=!0),r.indexOf(" commonJS ")>-1&&(e.commonJS=!0),r.indexOf(" instrumentCache ")>-1&&(e.instrumentCache=!0)}}),blanket.options(e),typeof requirejs!="undefined"&&blanket.options("existingRequireJS",!0),blanket.options("commonJS")&&(blanket._commonjs={})}(),function(e){e.extend({utils:{normalizeBackslashes:function(e){return e.replace(/\\/g,"/")},matchPatternAttribute:function(t,n){if(typeof n=="string"){if(n.indexOf("[")===0){var r=n.slice(1,n.length-1).split(",");return r.some(function(n){return e.utils.matchPatternAttribute(t,e.utils.normalizeBackslashes(n.slice(1,-1)))})}if(n.indexOf("//")===0){var i=n.slice(2,n.lastIndexOf("/")),s=n.slice(n.lastIndexOf("/")+1),o=new RegExp(i,s);return o.test(t)}return n.indexOf("#")===0?window[n.slice(1)].call(window,t):t.indexOf(e.utils.normalizeBackslashes(n))>-1}if(n instanceof Array)return n.some(function(n){return e.utils.matchPatternAttribute(t,n)});if(n instanceof RegExp)return n.test(t);if(typeof n=="function")return n.call(window,t)},blanketEval:function(t){e._addScript(t)},collectPageScripts:function(){var t=Array.prototype.slice,n=t.call(document.scripts),r=[],i=[],s=e.options("filter");if(s!=null){var o=e.options("antifilter");r=t.call(document.scripts).filter(function(n){return t.call(n.attributes).filter(function(t){return t.nodeName==="src"&&e.utils.matchPatternAttribute(t.nodeValue,s)&&(typeof o=="undefined"||!e.utils.matchPatternAttribute(t.nodeValue,o))}).length===1})}else r=t.call(document.querySelectorAll("script[data-cover]"));return i=r.map(function(n){return e.utils.qualifyURL(t.call(n.attributes).filter(function(e){return e.nodeName==="src"})[0].nodeValue)}),s||e.options("filter","['"+i.join("','")+"']"),i},loadAll:function(t,n,r){var i=t(),s=e.utils.scriptIsLoaded(i,e.utils.ifOrdered,t,n);if(!e.utils.cache[i]||!e.utils.cache[i].loaded){var o=function(){e.options("debug")&&console.log("BLANKET-Mark script:"+i+", as loaded and move to next script."),s()},u=function(t){e.options("debug")&&console.log("BLANKET-File loading finished"),typeof t!="undefined"&&(e.options("debug")&&console.log("BLANKET-Add file to DOM."),e._addScript(t)),o()};e.utils.attachScript({url:i},function(t){e.utils.processFile(t,i,u,u)})}else s()},attachScript:function(t,n){var r=e.options("timeout")||3e3;setTimeout(function(){if(!e.utils.cache[t.url].loaded)throw new Error("error loading source script")},r),e.utils.getFile(t.url,n,function(){throw new Error("error loading source script")})},ifOrdered:function(t,n){var r=t(!0);r?e.utils.loadAll(t,n):n(new Error("Error in loading chain."))},scriptIsLoaded:function(t,n,r,i){return e.options("debug")&&console.log("BLANKET-Returning function"),function(){e.options("debug")&&console.log("BLANKET-Marking file as loaded: "+t),e.utils.cache[t].loaded=!0,e.utils.allLoaded()?(e.options("debug")&&console.log("BLANKET-All files loaded"),i()):n&&(e.options("debug")&&console.log("BLANKET-Load next file."),n(r,i))}},cache:{},allLoaded:function(){var t=Object.keys(e.utils.cache);for(var n=0;n-1){n(e.blanketSession[a]),s=!0;return}}}if(!s){var f=e.utils.createXhr();f.open("GET",t,!0),i&&i(f,t),f.onreadystatechange=function(e){var i,s;f.readyState===4&&(i=f.status,i>399&&i<600?(s=new Error(t+" HTTP status: "+i),s.xhr=f,r(s)):n(f.responseText))};try{f.send(null)}catch(l){if(!l.code||l.code!==101&&l.code!==1012||e.options("ignoreCors")!==!1)throw l;e.showManualLoader()}}}}}),function(){var t=blanket.options("commonJS")?blanket._commonjs.require:window.require,n=blanket.options("commonJS")?blanket._commonjs.requirejs:window.requirejs;!e.options("engineOnly")&&e.options("existingRequireJS")&&(e.utils.oldloader=n.load,n.load=function(t,n,r){e.requiringFile(r),e.utils.getFile(r,function(i){e.utils.processFile(i,r,function(){t.completeLoad(n)},function(){e.utils.oldloader(t,n,r)})},function(t){throw e.requiringFile(),t})}),e.utils.cacheXhrConstructor()}()}(blanket),function(){if(!mocha)throw new Exception("mocha library does not exist in global namespace!");var e=mocha._reporter,t=function(t){t.on("start",function(){blanket.setupCoverage()}),t.on("end",function(){blanket.onTestsDone()}),t.on("suite",function(){blanket.onModuleStart()}),t.on("test",function(){blanket.onTestStart()}),t.on("test end",function(e){blanket.onTestDone(e.parent.tests.length,e.state==="passed")}),e.apply(this,arguments)};mocha.reporter(t);var n=mocha.run,r=null;mocha.run=function(e){r=e,console.log("waiting for blanket...")},blanket.beforeStartTestRunner({callback:function(){blanket.options("existingRequireJS")||n(r),mocha.run=n}})}(); diff --git a/tests/resources/js/json2.js b/tests/resources/js/json2.js deleted file mode 100755 index c7745df..0000000 --- a/tests/resources/js/json2.js +++ /dev/null @@ -1,486 +0,0 @@ -/* - json2.js - 2012-10-08 - - Public Domain. - - NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. - - See http://www.JSON.org/js.html - - - This code should be minified before deployment. - See http://javascript.crockford.com/jsmin.html - - USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO - NOT CONTROL. - - - This file creates a global JSON object containing two methods: stringify - and parse. - - JSON.stringify(value, replacer, space) - value any JavaScript value, usually an object or array. - - replacer an optional parameter that determines how object - values are stringified for objects. It can be a - function or an array of strings. - - space an optional parameter that specifies the indentation - of nested structures. If it is omitted, the text will - be packed without extra whitespace. If it is a number, - it will specify the number of spaces to indent at each - level. If it is a string (such as '\t' or ' '), - it contains the characters used to indent at each level. - - This method produces a JSON text from a JavaScript value. - - When an object value is found, if the object contains a toJSON - method, its toJSON method will be called and the result will be - stringified. A toJSON method does not serialize: it returns the - value represented by the name/value pair that should be serialized, - or undefined if nothing should be serialized. The toJSON method - will be passed the key associated with the value, and this will be - bound to the value - - For example, this would serialize Dates as ISO strings. - - Date.prototype.toJSON = function (key) { - function f(n) { - // Format integers to have at least two digits. - return n < 10 ? '0' + n : n; - } - - return this.getUTCFullYear() + '-' + - f(this.getUTCMonth() + 1) + '-' + - f(this.getUTCDate()) + 'T' + - f(this.getUTCHours()) + ':' + - f(this.getUTCMinutes()) + ':' + - f(this.getUTCSeconds()) + 'Z'; - }; - - You can provide an optional replacer method. It will be passed the - key and value of each member, with this bound to the containing - object. The value that is returned from your method will be - serialized. If your method returns undefined, then the member will - be excluded from the serialization. - - If the replacer parameter is an array of strings, then it will be - used to select the members to be serialized. It filters the results - such that only members with keys listed in the replacer array are - stringified. - - Values that do not have JSON representations, such as undefined or - functions, will not be serialized. Such values in objects will be - dropped; in arrays they will be replaced with null. You can use - a replacer function to replace those with JSON values. - JSON.stringify(undefined) returns undefined. - - The optional space parameter produces a stringification of the - value that is filled with line breaks and indentation to make it - easier to read. - - If the space parameter is a non-empty string, then that string will - be used for indentation. If the space parameter is a number, then - the indentation will be that many spaces. - - Example: - - text = JSON.stringify(['e', {pluribus: 'unum'}]); - // text is '["e",{"pluribus":"unum"}]' - - - text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); - // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' - - text = JSON.stringify([new Date()], function (key, value) { - return this[key] instanceof Date ? - 'Date(' + this[key] + ')' : value; - }); - // text is '["Date(---current time---)"]' - - - JSON.parse(text, reviver) - This method parses a JSON text to produce an object or array. - It can throw a SyntaxError exception. - - The optional reviver parameter is a function that can filter and - transform the results. It receives each of the keys and values, - and its return value is used instead of the original value. - If it returns what it received, then the structure is not modified. - If it returns undefined then the member is deleted. - - Example: - - // Parse the text. Values that look like ISO date strings will - // be converted to Date objects. - - myData = JSON.parse(text, function (key, value) { - var a; - if (typeof value === 'string') { - a = -/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); - if (a) { - return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], - +a[5], +a[6])); - } - } - return value; - }); - - myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { - var d; - if (typeof value === 'string' && - value.slice(0, 5) === 'Date(' && - value.slice(-1) === ')') { - d = new Date(value.slice(5, -1)); - if (d) { - return d; - } - } - return value; - }); - - - This is a reference implementation. You are free to copy, modify, or - redistribute. -*/ - -/*jslint evil: true, regexp: true */ - -/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, - call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, - getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, - lastIndex, length, parse, prototype, push, replace, slice, stringify, - test, toJSON, toString, valueOf -*/ - - -// Create a JSON object only if one does not already exist. We create the -// methods in a closure to avoid creating global variables. - -if (typeof JSON !== 'object') { - JSON = {}; -} - -(function () { - 'use strict'; - - function f(n) { - // Format integers to have at least two digits. - return n < 10 ? '0' + n : n; - } - - if (typeof Date.prototype.toJSON !== 'function') { - - Date.prototype.toJSON = function (key) { - - return isFinite(this.valueOf()) - ? this.getUTCFullYear() + '-' + - f(this.getUTCMonth() + 1) + '-' + - f(this.getUTCDate()) + 'T' + - f(this.getUTCHours()) + ':' + - f(this.getUTCMinutes()) + ':' + - f(this.getUTCSeconds()) + 'Z' - : null; - }; - - String.prototype.toJSON = - Number.prototype.toJSON = - Boolean.prototype.toJSON = function (key) { - return this.valueOf(); - }; - } - - var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - gap, - indent, - meta = { // table of character substitutions - '\b': '\\b', - '\t': '\\t', - '\n': '\\n', - '\f': '\\f', - '\r': '\\r', - '"' : '\\"', - '\\': '\\\\' - }, - rep; - - - function quote(string) { - -// If the string contains no control characters, no quote characters, and no -// backslash characters, then we can safely slap some quotes around it. -// Otherwise we must also replace the offending characters with safe escape -// sequences. - - escapable.lastIndex = 0; - return escapable.test(string) ? '"' + string.replace(escapable, function (a) { - var c = meta[a]; - return typeof c === 'string' - ? c - : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }) + '"' : '"' + string + '"'; - } - - - function str(key, holder) { - -// Produce a string from holder[key]. - - var i, // The loop counter. - k, // The member key. - v, // The member value. - length, - mind = gap, - partial, - value = holder[key]; - -// If the value has a toJSON method, call it to obtain a replacement value. - - if (value && typeof value === 'object' && - typeof value.toJSON === 'function') { - value = value.toJSON(key); - } - -// If we were called with a replacer function, then call the replacer to -// obtain a replacement value. - - if (typeof rep === 'function') { - value = rep.call(holder, key, value); - } - -// What happens next depends on the value's type. - - switch (typeof value) { - case 'string': - return quote(value); - - case 'number': - -// JSON numbers must be finite. Encode non-finite numbers as null. - - return isFinite(value) ? String(value) : 'null'; - - case 'boolean': - case 'null': - -// If the value is a boolean or null, convert it to a string. Note: -// typeof null does not produce 'null'. The case is included here in -// the remote chance that this gets fixed someday. - - return String(value); - -// If the type is 'object', we might be dealing with an object or an array or -// null. - - case 'object': - -// Due to a specification blunder in ECMAScript, typeof null is 'object', -// so watch out for that case. - - if (!value) { - return 'null'; - } - -// Make an array to hold the partial results of stringifying this object value. - - gap += indent; - partial = []; - -// Is the value an array? - - if (Object.prototype.toString.apply(value) === '[object Array]') { - -// The value is an array. Stringify every element. Use null as a placeholder -// for non-JSON values. - - length = value.length; - for (i = 0; i < length; i += 1) { - partial[i] = str(i, value) || 'null'; - } - -// Join all of the elements together, separated with commas, and wrap them in -// brackets. - - v = partial.length === 0 - ? '[]' - : gap - ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' - : '[' + partial.join(',') + ']'; - gap = mind; - return v; - } - -// If the replacer is an array, use it to select the members to be stringified. - - if (rep && typeof rep === 'object') { - length = rep.length; - for (i = 0; i < length; i += 1) { - if (typeof rep[i] === 'string') { - k = rep[i]; - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } else { - -// Otherwise, iterate through all of the keys in the object. - - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } - -// Join all of the member texts together, separated with commas, -// and wrap them in braces. - - v = partial.length === 0 - ? '{}' - : gap - ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' - : '{' + partial.join(',') + '}'; - gap = mind; - return v; - } - } - -// If the JSON object does not yet have a stringify method, give it one. - - if (typeof JSON.stringify !== 'function') { - JSON.stringify = function (value, replacer, space) { - -// The stringify method takes a value and an optional replacer, and an optional -// space parameter, and returns a JSON text. The replacer can be a function -// that can replace values, or an array of strings that will select the keys. -// A default replacer method can be provided. Use of the space parameter can -// produce text that is more easily readable. - - var i; - gap = ''; - indent = ''; - -// If the space parameter is a number, make an indent string containing that -// many spaces. - - if (typeof space === 'number') { - for (i = 0; i < space; i += 1) { - indent += ' '; - } - -// If the space parameter is a string, it will be used as the indent string. - - } else if (typeof space === 'string') { - indent = space; - } - -// If there is a replacer, it must be a function or an array. -// Otherwise, throw an error. - - rep = replacer; - if (replacer && typeof replacer !== 'function' && - (typeof replacer !== 'object' || - typeof replacer.length !== 'number')) { - throw new Error('JSON.stringify'); - } - -// Make a fake root object containing our value under the key of ''. -// Return the result of stringifying the value. - - return str('', {'': value}); - }; - } - - -// If the JSON object does not yet have a parse method, give it one. - - if (typeof JSON.parse !== 'function') { - JSON.parse = function (text, reviver) { - -// The parse method takes a text and an optional reviver function, and returns -// a JavaScript value if the text is a valid JSON text. - - var j; - - function walk(holder, key) { - -// The walk method is used to recursively walk the resulting structure so -// that modifications can be made. - - var k, v, value = holder[key]; - if (value && typeof value === 'object') { - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = walk(value, k); - if (v !== undefined) { - value[k] = v; - } else { - delete value[k]; - } - } - } - } - return reviver.call(holder, key, value); - } - - -// Parsing happens in four stages. In the first stage, we replace certain -// Unicode characters with escape sequences. JavaScript handles many characters -// incorrectly, either silently deleting them, or treating them as line endings. - - text = String(text); - cx.lastIndex = 0; - if (cx.test(text)) { - text = text.replace(cx, function (a) { - return '\\u' + - ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }); - } - -// In the second stage, we run the text against regular expressions that look -// for non-JSON patterns. We are especially concerned with '()' and 'new' -// because they can cause invocation, and '=' because it can cause mutation. -// But just to be safe, we want to reject all unexpected forms. - -// We split the second stage into 4 regexp operations in order to work around -// crippling inefficiencies in IE's and Safari's regexp engines. First we -// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we -// replace all simple value tokens with ']' characters. Third, we delete all -// open brackets that follow a colon or comma or that begin the text. Finally, -// we look to see that the remaining characters are only whitespace or ']' or -// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. - - if (/^[\],:{}\s]*$/ - .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') - .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') - .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { - -// In the third stage we use the eval function to compile the text into a -// JavaScript structure. The '{' operator is subject to a syntactic ambiguity -// in JavaScript: it can begin a block or an object literal. We wrap the text -// in parens to eliminate the ambiguity. - - j = eval('(' + text + ')'); - -// In the optional fourth stage, we recursively walk the new structure, passing -// each name/value pair to a reviver function for possible transformation. - - return typeof reviver === 'function' - ? walk({'': j}, '') - : j; - } - -// If the text is not JSON parseable, then a SyntaxError is thrown. - - throw new SyntaxError('JSON.parse'); - }; - } -}()); diff --git a/tests/resources/js/mocha.js b/tests/resources/js/mocha.js deleted file mode 100644 index 00dcda1..0000000 --- a/tests/resources/js/mocha.js +++ /dev/null @@ -1,5341 +0,0 @@ -;(function(){ - - -// CommonJS require() - -function require(p){ - var path = require.resolve(p) - , mod = require.modules[path]; - if (!mod) throw new Error('failed to require "' + p + '"'); - if (!mod.exports) { - mod.exports = {}; - mod.call(mod.exports, mod, mod.exports, require.relative(path)); - } - return mod.exports; - } - -require.modules = {}; - -require.resolve = function (path){ - var orig = path - , reg = path + '.js' - , index = path + '/index.js'; - return require.modules[reg] && reg - || require.modules[index] && index - || orig; - }; - -require.register = function (path, fn){ - require.modules[path] = fn; - }; - -require.relative = function (parent) { - return function(p){ - if ('.' != p.charAt(0)) return require(p); - - var path = parent.split('/') - , segs = p.split('/'); - path.pop(); - - for (var i = 0; i < segs.length; i++) { - var seg = segs[i]; - if ('..' == seg) path.pop(); - else if ('.' != seg) path.push(seg); - } - - return require(path.join('/')); - }; - }; - - -require.register("browser/debug.js", function(module, exports, require){ - -module.exports = function(type){ - return function(){ - - } -}; -}); // module: browser/debug.js - -require.register("browser/diff.js", function(module, exports, require){ -/* See license.txt for terms of usage */ - -/* - * Text diff implementation. - * - * This library supports the following APIS: - * JsDiff.diffChars: Character by character diff - * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace - * JsDiff.diffLines: Line based diff - * - * JsDiff.diffCss: Diff targeted at CSS content - * - * These methods are based on the implementation proposed in - * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). - * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927 - */ -var JsDiff = (function() { - function clonePath(path) { - return { newPos: path.newPos, components: path.components.slice(0) }; - } - function removeEmpty(array) { - var ret = []; - for (var i = 0; i < array.length; i++) { - if (array[i]) { - ret.push(array[i]); - } - } - return ret; - } - function escapeHTML(s) { - var n = s; - n = n.replace(/&/g, "&"); - n = n.replace(//g, ">"); - n = n.replace(/"/g, """); - - return n; - } - - - var fbDiff = function(ignoreWhitespace) { - this.ignoreWhitespace = ignoreWhitespace; - }; - fbDiff.prototype = { - diff: function(oldString, newString) { - // Handle the identity case (this is due to unrolling editLength == 0 - if (newString == oldString) { - return [{ value: newString }]; - } - if (!newString) { - return [{ value: oldString, removed: true }]; - } - if (!oldString) { - return [{ value: newString, added: true }]; - } - - newString = this.tokenize(newString); - oldString = this.tokenize(oldString); - - var newLen = newString.length, oldLen = oldString.length; - var maxEditLength = newLen + oldLen; - var bestPath = [{ newPos: -1, components: [] }]; - - // Seed editLength = 0 - var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); - if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) { - return bestPath[0].components; - } - - for (var editLength = 1; editLength <= maxEditLength; editLength++) { - for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) { - var basePath; - var addPath = bestPath[diagonalPath-1], - removePath = bestPath[diagonalPath+1]; - oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; - if (addPath) { - // No one else is going to attempt to use this value, clear it - bestPath[diagonalPath-1] = undefined; - } - - var canAdd = addPath && addPath.newPos+1 < newLen; - var canRemove = removePath && 0 <= oldPos && oldPos < oldLen; - if (!canAdd && !canRemove) { - bestPath[diagonalPath] = undefined; - continue; - } - - // Select the diagonal that we want to branch from. We select the prior - // path whose position in the new string is the farthest from the origin - // and does not pass the bounds of the diff graph - if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) { - basePath = clonePath(removePath); - this.pushComponent(basePath.components, oldString[oldPos], undefined, true); - } else { - basePath = clonePath(addPath); - basePath.newPos++; - this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined); - } - - var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath); - - if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) { - return basePath.components; - } else { - bestPath[diagonalPath] = basePath; - } - } - } - }, - - pushComponent: function(components, value, added, removed) { - var last = components[components.length-1]; - if (last && last.added === added && last.removed === removed) { - // We need to clone here as the component clone operation is just - // as shallow array clone - components[components.length-1] = - {value: this.join(last.value, value), added: added, removed: removed }; - } else { - components.push({value: value, added: added, removed: removed }); - } - }, - extractCommon: function(basePath, newString, oldString, diagonalPath) { - var newLen = newString.length, - oldLen = oldString.length, - newPos = basePath.newPos, - oldPos = newPos - diagonalPath; - while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) { - newPos++; - oldPos++; - - this.pushComponent(basePath.components, newString[newPos], undefined, undefined); - } - basePath.newPos = newPos; - return oldPos; - }, - - equals: function(left, right) { - var reWhitespace = /\S/; - if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) { - return true; - } else { - return left == right; - } - }, - join: function(left, right) { - return left + right; - }, - tokenize: function(value) { - return value; - } - }; - - var CharDiff = new fbDiff(); - - var WordDiff = new fbDiff(true); - WordDiff.tokenize = function(value) { - return removeEmpty(value.split(/(\s+|\b)/)); - }; - - var CssDiff = new fbDiff(true); - CssDiff.tokenize = function(value) { - return removeEmpty(value.split(/([{}:;,]|\s+)/)); - }; - - var LineDiff = new fbDiff(); - LineDiff.tokenize = function(value) { - return value.split(/^/m); - }; - - return { - diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); }, - diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); }, - diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); }, - - diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); }, - - createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) { - var ret = []; - - ret.push("Index: " + fileName); - ret.push("==================================================================="); - ret.push("--- " + fileName + (typeof oldHeader === "undefined" ? "" : "\t" + oldHeader)); - ret.push("+++ " + fileName + (typeof newHeader === "undefined" ? "" : "\t" + newHeader)); - - var diff = LineDiff.diff(oldStr, newStr); - if (!diff[diff.length-1].value) { - diff.pop(); // Remove trailing newline add - } - diff.push({value: "", lines: []}); // Append an empty value to make cleanup easier - - function contextLines(lines) { - return lines.map(function(entry) { return ' ' + entry; }); - } - function eofNL(curRange, i, current) { - var last = diff[diff.length-2], - isLast = i === diff.length-2, - isLastOfType = i === diff.length-3 && (current.added === !last.added || current.removed === !last.removed); - - // Figure out if this is the last line for the given file and missing NL - if (!/\n$/.test(current.value) && (isLast || isLastOfType)) { - curRange.push('\\ No newline at end of file'); - } - } - - var oldRangeStart = 0, newRangeStart = 0, curRange = [], - oldLine = 1, newLine = 1; - for (var i = 0; i < diff.length; i++) { - var current = diff[i], - lines = current.lines || current.value.replace(/\n$/, "").split("\n"); - current.lines = lines; - - if (current.added || current.removed) { - if (!oldRangeStart) { - var prev = diff[i-1]; - oldRangeStart = oldLine; - newRangeStart = newLine; - - if (prev) { - curRange = contextLines(prev.lines.slice(-4)); - oldRangeStart -= curRange.length; - newRangeStart -= curRange.length; - } - } - curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?"+":"-") + entry; })); - eofNL(curRange, i, current); - - if (current.added) { - newLine += lines.length; - } else { - oldLine += lines.length; - } - } else { - if (oldRangeStart) { - // Close out any changes that have been output (or join overlapping) - if (lines.length <= 8 && i < diff.length-2) { - // Overlapping - curRange.push.apply(curRange, contextLines(lines)); - } else { - // end the range and output - var contextSize = Math.min(lines.length, 4); - ret.push( - "@@ -" + oldRangeStart + "," + (oldLine-oldRangeStart+contextSize) - + " +" + newRangeStart + "," + (newLine-newRangeStart+contextSize) - + " @@"); - ret.push.apply(ret, curRange); - ret.push.apply(ret, contextLines(lines.slice(0, contextSize))); - if (lines.length <= 4) { - eofNL(ret, i, current); - } - - oldRangeStart = 0; newRangeStart = 0; curRange = []; - } - } - oldLine += lines.length; - newLine += lines.length; - } - } - - return ret.join('\n') + '\n'; - }, - - convertChangesToXML: function(changes){ - var ret = []; - for ( var i = 0; i < changes.length; i++) { - var change = changes[i]; - if (change.added) { - ret.push(""); - } else if (change.removed) { - ret.push(""); - } - - ret.push(escapeHTML(change.value)); - - if (change.added) { - ret.push(""); - } else if (change.removed) { - ret.push(""); - } - } - return ret.join(""); - } - }; -})(); - -if (typeof module !== "undefined") { - module.exports = JsDiff; -} - -}); // module: browser/diff.js - -require.register("browser/events.js", function(module, exports, require){ - -/** - * Module exports. - */ - -exports.EventEmitter = EventEmitter; - -/** - * Check if `obj` is an array. - */ - -function isArray(obj) { - return '[object Array]' == {}.toString.call(obj); -} - -/** - * Event emitter constructor. - * - * @api public - */ - -function EventEmitter(){}; - -/** - * Adds a listener. - * - * @api public - */ - -EventEmitter.prototype.on = function (name, fn) { - if (!this.$events) { - this.$events = {}; - } - - if (!this.$events[name]) { - this.$events[name] = fn; - } else if (isArray(this.$events[name])) { - this.$events[name].push(fn); - } else { - this.$events[name] = [this.$events[name], fn]; - } - - return this; -}; - -EventEmitter.prototype.addListener = EventEmitter.prototype.on; - -/** - * Adds a volatile listener. - * - * @api public - */ - -EventEmitter.prototype.once = function (name, fn) { - var self = this; - - function on () { - self.removeListener(name, on); - fn.apply(this, arguments); - }; - - on.listener = fn; - this.on(name, on); - - return this; -}; - -/** - * Removes a listener. - * - * @api public - */ - -EventEmitter.prototype.removeListener = function (name, fn) { - if (this.$events && this.$events[name]) { - var list = this.$events[name]; - - if (isArray(list)) { - var pos = -1; - - for (var i = 0, l = list.length; i < l; i++) { - if (list[i] === fn || (list[i].listener && list[i].listener === fn)) { - pos = i; - break; - } - } - - if (pos < 0) { - return this; - } - - list.splice(pos, 1); - - if (!list.length) { - delete this.$events[name]; - } - } else if (list === fn || (list.listener && list.listener === fn)) { - delete this.$events[name]; - } - } - - return this; -}; - -/** - * Removes all listeners for an event. - * - * @api public - */ - -EventEmitter.prototype.removeAllListeners = function (name) { - if (name === undefined) { - this.$events = {}; - return this; - } - - if (this.$events && this.$events[name]) { - this.$events[name] = null; - } - - return this; -}; - -/** - * Gets all listeners for a certain event. - * - * @api public - */ - -EventEmitter.prototype.listeners = function (name) { - if (!this.$events) { - this.$events = {}; - } - - if (!this.$events[name]) { - this.$events[name] = []; - } - - if (!isArray(this.$events[name])) { - this.$events[name] = [this.$events[name]]; - } - - return this.$events[name]; -}; - -/** - * Emits an event. - * - * @api public - */ - -EventEmitter.prototype.emit = function (name) { - if (!this.$events) { - return false; - } - - var handler = this.$events[name]; - - if (!handler) { - return false; - } - - var args = [].slice.call(arguments, 1); - - if ('function' == typeof handler) { - handler.apply(this, args); - } else if (isArray(handler)) { - var listeners = handler.slice(); - - for (var i = 0, l = listeners.length; i < l; i++) { - listeners[i].apply(this, args); - } - } else { - return false; - } - - return true; -}; -}); // module: browser/events.js - -require.register("browser/fs.js", function(module, exports, require){ - -}); // module: browser/fs.js - -require.register("browser/path.js", function(module, exports, require){ - -}); // module: browser/path.js - -require.register("browser/progress.js", function(module, exports, require){ - -/** - * Expose `Progress`. - */ - -module.exports = Progress; - -/** - * Initialize a new `Progress` indicator. - */ - -function Progress() { - this.percent = 0; - this.size(0); - this.fontSize(11); - this.font('helvetica, arial, sans-serif'); -} - -/** - * Set progress size to `n`. - * - * @param {Number} n - * @return {Progress} for chaining - * @api public - */ - -Progress.prototype.size = function(n){ - this._size = n; - return this; -}; - -/** - * Set text to `str`. - * - * @param {String} str - * @return {Progress} for chaining - * @api public - */ - -Progress.prototype.text = function(str){ - this._text = str; - return this; -}; - -/** - * Set font size to `n`. - * - * @param {Number} n - * @return {Progress} for chaining - * @api public - */ - -Progress.prototype.fontSize = function(n){ - this._fontSize = n; - return this; -}; - -/** - * Set font `family`. - * - * @param {String} family - * @return {Progress} for chaining - */ - -Progress.prototype.font = function(family){ - this._font = family; - return this; -}; - -/** - * Update percentage to `n`. - * - * @param {Number} n - * @return {Progress} for chaining - */ - -Progress.prototype.update = function(n){ - this.percent = n; - return this; -}; - -/** - * Draw on `ctx`. - * - * @param {CanvasRenderingContext2d} ctx - * @return {Progress} for chaining - */ - -Progress.prototype.draw = function(ctx){ - var percent = Math.min(this.percent, 100) - , size = this._size - , half = size / 2 - , x = half - , y = half - , rad = half - 1 - , fontSize = this._fontSize; - - ctx.font = fontSize + 'px ' + this._font; - - var angle = Math.PI * 2 * (percent / 100); - ctx.clearRect(0, 0, size, size); - - // outer circle - ctx.strokeStyle = '#9f9f9f'; - ctx.beginPath(); - ctx.arc(x, y, rad, 0, angle, false); - ctx.stroke(); - - // inner circle - ctx.strokeStyle = '#eee'; - ctx.beginPath(); - ctx.arc(x, y, rad - 1, 0, angle, true); - ctx.stroke(); - - // text - var text = this._text || (percent | 0) + '%' - , w = ctx.measureText(text).width; - - ctx.fillText( - text - , x - w / 2 + 1 - , y + fontSize / 2 - 1); - - return this; -}; - -}); // module: browser/progress.js - -require.register("browser/tty.js", function(module, exports, require){ - -exports.isatty = function(){ - return true; -}; - -exports.getWindowSize = function(){ - return [window.innerHeight, window.innerWidth]; -}; -}); // module: browser/tty.js - -require.register("context.js", function(module, exports, require){ - -/** - * Expose `Context`. - */ - -module.exports = Context; - -/** - * Initialize a new `Context`. - * - * @api private - */ - -function Context(){} - -/** - * Set or get the context `Runnable` to `runnable`. - * - * @param {Runnable} runnable - * @return {Context} - * @api private - */ - -Context.prototype.runnable = function(runnable){ - if (0 == arguments.length) return this._runnable; - this.test = this._runnable = runnable; - return this; -}; - -/** - * Set test timeout `ms`. - * - * @param {Number} ms - * @return {Context} self - * @api private - */ - -Context.prototype.timeout = function(ms){ - this.runnable().timeout(ms); - return this; -}; - -/** - * Set test slowness threshold `ms`. - * - * @param {Number} ms - * @return {Context} self - * @api private - */ - -Context.prototype.slow = function(ms){ - this.runnable().slow(ms); - return this; -}; - -/** - * Inspect the context void of `._runnable`. - * - * @return {String} - * @api private - */ - -Context.prototype.inspect = function(){ - return JSON.stringify(this, function(key, val){ - if ('_runnable' == key) return; - if ('test' == key) return; - return val; - }, 2); -}; - -}); // module: context.js - -require.register("hook.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Runnable = require('./runnable'); - -/** - * Expose `Hook`. - */ - -module.exports = Hook; - -/** - * Initialize a new `Hook` with the given `title` and callback `fn`. - * - * @param {String} title - * @param {Function} fn - * @api private - */ - -function Hook(title, fn) { - Runnable.call(this, title, fn); - this.type = 'hook'; -} - -/** - * Inherit from `Runnable.prototype`. - */ - -function F(){}; -F.prototype = Runnable.prototype; -Hook.prototype = new F; -Hook.prototype.constructor = Hook; - - -/** - * Get or set the test `err`. - * - * @param {Error} err - * @return {Error} - * @api public - */ - -Hook.prototype.error = function(err){ - if (0 == arguments.length) { - var err = this._error; - this._error = null; - return err; - } - - this._error = err; -}; - - -}); // module: hook.js - -require.register("interfaces/bdd.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test'); - -/** - * BDD-style interface: - * - * describe('Array', function(){ - * describe('#indexOf()', function(){ - * it('should return -1 when not present', function(){ - * - * }); - * - * it('should return the index when present', function(){ - * - * }); - * }); - * }); - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('pre-require', function(context, file, mocha){ - - /** - * Execute before running tests. - */ - - context.before = function(fn){ - suites[0].beforeAll(fn); - }; - - /** - * Execute after running tests. - */ - - context.after = function(fn){ - suites[0].afterAll(fn); - }; - - /** - * Execute before each test case. - */ - - context.beforeEach = function(fn){ - suites[0].beforeEach(fn); - }; - - /** - * Execute after each test case. - */ - - context.afterEach = function(fn){ - suites[0].afterEach(fn); - }; - - /** - * Describe a "suite" with the given `title` - * and callback `fn` containing nested suites - * and/or tests. - */ - - context.describe = context.context = function(title, fn){ - var suite = Suite.create(suites[0], title); - suites.unshift(suite); - fn.call(suite); - suites.shift(); - return suite; - }; - - /** - * Pending describe. - */ - - context.xdescribe = - context.xcontext = - context.describe.skip = function(title, fn){ - var suite = Suite.create(suites[0], title); - suite.pending = true; - suites.unshift(suite); - fn.call(suite); - suites.shift(); - }; - - /** - * Exclusive suite. - */ - - context.describe.only = function(title, fn){ - var suite = context.describe(title, fn); - mocha.grep(suite.fullTitle()); - }; - - /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. - */ - - context.it = context.specify = function(title, fn){ - var suite = suites[0]; - if (suite.pending) var fn = null; - var test = new Test(title, fn); - suite.addTest(test); - return test; - }; - - /** - * Exclusive test-case. - */ - - context.it.only = function(title, fn){ - var test = context.it(title, fn); - mocha.grep(test.fullTitle()); - }; - - /** - * Pending test case. - */ - - context.xit = - context.xspecify = - context.it.skip = function(title){ - context.it(title); - }; - }); -}; - -}); // module: interfaces/bdd.js - -require.register("interfaces/exports.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test'); - -/** - * TDD-style interface: - * - * exports.Array = { - * '#indexOf()': { - * 'should return -1 when the value is not present': function(){ - * - * }, - * - * 'should return the correct index when the value is present': function(){ - * - * } - * } - * }; - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('require', visit); - - function visit(obj) { - var suite; - for (var key in obj) { - if ('function' == typeof obj[key]) { - var fn = obj[key]; - switch (key) { - case 'before': - suites[0].beforeAll(fn); - break; - case 'after': - suites[0].afterAll(fn); - break; - case 'beforeEach': - suites[0].beforeEach(fn); - break; - case 'afterEach': - suites[0].afterEach(fn); - break; - default: - suites[0].addTest(new Test(key, fn)); - } - } else { - var suite = Suite.create(suites[0], key); - suites.unshift(suite); - visit(obj[key]); - suites.shift(); - } - } - } -}; -}); // module: interfaces/exports.js - -require.register("interfaces/index.js", function(module, exports, require){ - -exports.bdd = require('./bdd'); -exports.tdd = require('./tdd'); -exports.qunit = require('./qunit'); -exports.exports = require('./exports'); - -}); // module: interfaces/index.js - -require.register("interfaces/qunit.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test'); - -/** - * QUnit-style interface: - * - * suite('Array'); - * - * test('#length', function(){ - * var arr = [1,2,3]; - * ok(arr.length == 3); - * }); - * - * test('#indexOf()', function(){ - * var arr = [1,2,3]; - * ok(arr.indexOf(1) == 0); - * ok(arr.indexOf(2) == 1); - * ok(arr.indexOf(3) == 2); - * }); - * - * suite('String'); - * - * test('#length', function(){ - * ok('foo'.length == 3); - * }); - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('pre-require', function(context){ - - /** - * Execute before running tests. - */ - - context.before = function(fn){ - suites[0].beforeAll(fn); - }; - - /** - * Execute after running tests. - */ - - context.after = function(fn){ - suites[0].afterAll(fn); - }; - - /** - * Execute before each test case. - */ - - context.beforeEach = function(fn){ - suites[0].beforeEach(fn); - }; - - /** - * Execute after each test case. - */ - - context.afterEach = function(fn){ - suites[0].afterEach(fn); - }; - - /** - * Describe a "suite" with the given `title`. - */ - - context.suite = function(title){ - if (suites.length > 1) suites.shift(); - var suite = Suite.create(suites[0], title); - suites.unshift(suite); - }; - - /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. - */ - - context.test = function(title, fn){ - suites[0].addTest(new Test(title, fn)); - }; - }); -}; - -}); // module: interfaces/qunit.js - -require.register("interfaces/tdd.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test'); - -/** - * TDD-style interface: - * - * suite('Array', function(){ - * suite('#indexOf()', function(){ - * suiteSetup(function(){ - * - * }); - * - * test('should return -1 when not present', function(){ - * - * }); - * - * test('should return the index when present', function(){ - * - * }); - * - * suiteTeardown(function(){ - * - * }); - * }); - * }); - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('pre-require', function(context, file, mocha){ - - /** - * Execute before each test case. - */ - - context.setup = function(fn){ - suites[0].beforeEach(fn); - }; - - /** - * Execute after each test case. - */ - - context.teardown = function(fn){ - suites[0].afterEach(fn); - }; - - /** - * Execute before the suite. - */ - - context.suiteSetup = function(fn){ - suites[0].beforeAll(fn); - }; - - /** - * Execute after the suite. - */ - - context.suiteTeardown = function(fn){ - suites[0].afterAll(fn); - }; - - /** - * Describe a "suite" with the given `title` - * and callback `fn` containing nested suites - * and/or tests. - */ - - context.suite = function(title, fn){ - var suite = Suite.create(suites[0], title); - suites.unshift(suite); - fn.call(suite); - suites.shift(); - return suite; - }; - - /** - * Exclusive test-case. - */ - - context.suite.only = function(title, fn){ - var suite = context.suite(title, fn); - mocha.grep(suite.fullTitle()); - }; - - /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. - */ - - context.test = function(title, fn){ - var test = new Test(title, fn); - suites[0].addTest(test); - return test; - }; - - /** - * Exclusive test-case. - */ - - context.test.only = function(title, fn){ - var test = context.test(title, fn); - mocha.grep(test.fullTitle()); - }; - - /** - * Pending test case. - */ - - context.test.skip = function(title){ - context.test(title); - }; - }); -}; - -}); // module: interfaces/tdd.js - -require.register("mocha.js", function(module, exports, require){ -/*! - * mocha - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var path = require('browser/path') - , utils = require('./utils'); - -/** - * Expose `Mocha`. - */ - -exports = module.exports = Mocha; - -/** - * Expose internals. - */ - -exports.utils = utils; -exports.interfaces = require('./interfaces'); -exports.reporters = require('./reporters'); -exports.Runnable = require('./runnable'); -exports.Context = require('./context'); -exports.Runner = require('./runner'); -exports.Suite = require('./suite'); -exports.Hook = require('./hook'); -exports.Test = require('./test'); - -/** - * Return image `name` path. - * - * @param {String} name - * @return {String} - * @api private - */ - -function image(name) { - return __dirname + '/../images/' + name + '.png'; -} - -/** - * Setup mocha with `options`. - * - * Options: - * - * - `ui` name "bdd", "tdd", "exports" etc - * - `reporter` reporter instance, defaults to `mocha.reporters.Dot` - * - `globals` array of accepted globals - * - `timeout` timeout in milliseconds - * - `bail` bail on the first test failure - * - `slow` milliseconds to wait before considering a test slow - * - `ignoreLeaks` ignore global leaks - * - `grep` string or regexp to filter tests with - * - * @param {Object} options - * @api public - */ - -function Mocha(options) { - options = options || {}; - this.files = []; - this.options = options; - this.grep(options.grep); - this.suite = new exports.Suite('', new exports.Context); - this.ui(options.ui); - this.bail(options.bail); - this.reporter(options.reporter); - if (options.timeout) this.timeout(options.timeout); - if (options.slow) this.slow(options.slow); -} - -/** - * Enable or disable bailing on the first failure. - * - * @param {Boolean} [bail] - * @api public - */ - -Mocha.prototype.bail = function(bail){ - if (0 == arguments.length) bail = true; - this.suite.bail(bail); - return this; -}; - -/** - * Add test `file`. - * - * @param {String} file - * @api public - */ - -Mocha.prototype.addFile = function(file){ - this.files.push(file); - return this; -}; - -/** - * Set reporter to `reporter`, defaults to "dot". - * - * @param {String|Function} reporter name or constructor - * @api public - */ - -Mocha.prototype.reporter = function(reporter){ - if ('function' == typeof reporter) { - this._reporter = reporter; - } else { - reporter = reporter || 'dot'; - try { - this._reporter = require('./reporters/' + reporter); - } catch (err) { - this._reporter = require(reporter); - } - if (!this._reporter) throw new Error('invalid reporter "' + reporter + '"'); - } - return this; -}; - -/** - * Set test UI `name`, defaults to "bdd". - * - * @param {String} bdd - * @api public - */ - -Mocha.prototype.ui = function(name){ - name = name || 'bdd'; - this._ui = exports.interfaces[name]; - if (!this._ui) throw new Error('invalid interface "' + name + '"'); - this._ui = this._ui(this.suite); - return this; -}; - -/** - * Load registered files. - * - * @api private - */ - -Mocha.prototype.loadFiles = function(fn){ - var self = this; - var suite = this.suite; - var pending = this.files.length; - this.files.forEach(function(file){ - file = path.resolve(file); - suite.emit('pre-require', global, file, self); - suite.emit('require', require(file), file, self); - suite.emit('post-require', global, file, self); - --pending || (fn && fn()); - }); -}; - -/** - * Enable growl support. - * - * @api private - */ - -Mocha.prototype._growl = function(runner, reporter) { - var notify = require('growl'); - - runner.on('end', function(){ - var stats = reporter.stats; - if (stats.failures) { - var msg = stats.failures + ' of ' + runner.total + ' tests failed'; - notify(msg, { name: 'mocha', title: 'Failed', image: image('error') }); - } else { - notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', { - name: 'mocha' - , title: 'Passed' - , image: image('ok') - }); - } - }); -}; - -/** - * Add regexp to grep, if `re` is a string it is escaped. - * - * @param {RegExp|String} re - * @return {Mocha} - * @api public - */ - -Mocha.prototype.grep = function(re){ - this.options.grep = 'string' == typeof re - ? new RegExp(utils.escapeRegexp(re)) - : re; - return this; -}; - -/** - * Invert `.grep()` matches. - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.invert = function(){ - this.options.invert = true; - return this; -}; - -/** - * Ignore global leaks. - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.ignoreLeaks = function(){ - this.options.ignoreLeaks = true; - return this; -}; - -/** - * Enable global leak checking. - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.checkLeaks = function(){ - this.options.ignoreLeaks = false; - return this; -}; - -/** - * Enable growl support. - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.growl = function(){ - this.options.growl = true; - return this; -}; - -/** - * Ignore `globals` array or string. - * - * @param {Array|String} globals - * @return {Mocha} - * @api public - */ - -Mocha.prototype.globals = function(globals){ - this.options.globals = (this.options.globals || []).concat(globals); - return this; -}; - -/** - * Set the timeout in milliseconds. - * - * @param {Number} timeout - * @return {Mocha} - * @api public - */ - -Mocha.prototype.timeout = function(timeout){ - this.suite.timeout(timeout); - return this; -}; - -/** - * Set slowness threshold in milliseconds. - * - * @param {Number} slow - * @return {Mocha} - * @api public - */ - -Mocha.prototype.slow = function(slow){ - this.suite.slow(slow); - return this; -}; - -/** - * Makes all tests async (accepting a callback) - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.asyncOnly = function(){ - this.options.asyncOnly = true; - return this; -}; - -/** - * Run tests and invoke `fn()` when complete. - * - * @param {Function} fn - * @return {Runner} - * @api public - */ - -Mocha.prototype.run = function(fn){ - if (this.files.length) this.loadFiles(); - var suite = this.suite; - var options = this.options; - var runner = new exports.Runner(suite); - var reporter = new this._reporter(runner); - runner.ignoreLeaks = options.ignoreLeaks; - runner.asyncOnly = options.asyncOnly; - if (options.grep) runner.grep(options.grep, options.invert); - if (options.globals) runner.globals(options.globals); - if (options.growl) this._growl(runner, reporter); - return runner.run(fn); -}; - -}); // module: blanket_mocha.js - -require.register("ms.js", function(module, exports, require){ - -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; - -/** - * Parse or format the given `val`. - * - * @param {String|Number} val - * @return {String|Number} - * @api public - */ - -module.exports = function(val){ - if ('string' == typeof val) return parse(val); - return format(val); -} - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - var m = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str); - if (!m) return; - var n = parseFloat(m[1]); - var type = (m[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'y': - return n * 31557600000; - case 'days': - case 'day': - case 'd': - return n * 86400000; - case 'hours': - case 'hour': - case 'h': - return n * 3600000; - case 'minutes': - case 'minute': - case 'm': - return n * 60000; - case 'seconds': - case 'second': - case 's': - return n * 1000; - case 'ms': - return n; - } -} - -/** - * Format the given `ms`. - * - * @param {Number} ms - * @return {String} - * @api public - */ - -function format(ms) { - if (ms == d) return Math.round(ms / d) + ' day'; - if (ms > d) return Math.round(ms / d) + ' days'; - if (ms == h) return Math.round(ms / h) + ' hour'; - if (ms > h) return Math.round(ms / h) + ' hours'; - if (ms == m) return Math.round(ms / m) + ' minute'; - if (ms > m) return Math.round(ms / m) + ' minutes'; - if (ms == s) return Math.round(ms / s) + ' second'; - if (ms > s) return Math.round(ms / s) + ' seconds'; - return ms + ' ms'; -} -}); // module: ms.js - -require.register("reporters/base.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var tty = require('browser/tty') - , diff = require('browser/diff') - , ms = require('../ms'); - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; - -/** - * Check if both stdio streams are associated with a tty. - */ - -var isatty = tty.isatty(1) && tty.isatty(2); - -/** - * Expose `Base`. - */ - -exports = module.exports = Base; - -/** - * Enable coloring by default. - */ - -exports.useColors = isatty; - -/** - * Default color map. - */ - -exports.colors = { - 'pass': 90 - , 'fail': 31 - , 'bright pass': 92 - , 'bright fail': 91 - , 'bright yellow': 93 - , 'pending': 36 - , 'suite': 0 - , 'error title': 0 - , 'error message': 31 - , 'error stack': 90 - , 'checkmark': 32 - , 'fast': 90 - , 'medium': 33 - , 'slow': 31 - , 'green': 32 - , 'light': 90 - , 'diff gutter': 90 - , 'diff added': 42 - , 'diff removed': 41 -}; - -/** - * Default symbol map. - */ - -exports.symbols = { - ok: '✓', - err: '✖', - dot: '․' -}; - -// With node.js on Windows: use symbols available in terminal default fonts -if ('win32' == process.platform) { - exports.symbols.ok = '\u221A'; - exports.symbols.err = '\u00D7'; - exports.symbols.dot = '.'; -} - -/** - * Color `str` with the given `type`, - * allowing colors to be disabled, - * as well as user-defined color - * schemes. - * - * @param {String} type - * @param {String} str - * @return {String} - * @api private - */ - -var color = exports.color = function(type, str) { - if (!exports.useColors) return str; - return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m'; -}; - -/** - * Expose term window size, with some - * defaults for when stderr is not a tty. - */ - -exports.window = { - width: isatty - ? process.stdout.getWindowSize - ? process.stdout.getWindowSize(1)[0] - : tty.getWindowSize()[1] - : 75 -}; - -/** - * Expose some basic cursor interactions - * that are common among reporters. - */ - -exports.cursor = { - hide: function(){ - process.stdout.write('\u001b[?25l'); - }, - - show: function(){ - process.stdout.write('\u001b[?25h'); - }, - - deleteLine: function(){ - process.stdout.write('\u001b[2K'); - }, - - beginningOfLine: function(){ - process.stdout.write('\u001b[0G'); - }, - - CR: function(){ - exports.cursor.deleteLine(); - exports.cursor.beginningOfLine(); - } -}; - -/** - * Outut the given `failures` as a list. - * - * @param {Array} failures - * @api public - */ - -exports.list = function(failures){ - console.error(); - failures.forEach(function(test, i){ - // format - var fmt = color('error title', ' %s) %s:\n') - + color('error message', ' %s') - + color('error stack', '\n%s\n'); - - // msg - var err = test.err - , message = err.message || '' - , stack = err.stack || message - , index = stack.indexOf(message) + message.length - , msg = stack.slice(0, index) - , actual = err.actual - , expected = err.expected - , escape = true; - - // explicitly show diff - if (err.showDiff) { - escape = false; - err.actual = actual = JSON.stringify(actual, null, 2); - err.expected = expected = JSON.stringify(expected, null, 2); - } - - // actual / expected diff - if ('string' == typeof actual && 'string' == typeof expected) { - var len = Math.max(actual.length, expected.length); - - if (len < 20) msg = errorDiff(err, 'Chars', escape); - else msg = errorDiff(err, 'Words', escape); - - // linenos - var lines = msg.split('\n'); - if (lines.length > 4) { - var width = String(lines.length).length; - msg = lines.map(function(str, i){ - return pad(++i, width) + ' |' + ' ' + str; - }).join('\n'); - } - - // legend - msg = '\n' - + color('diff removed', 'actual') - + ' ' - + color('diff added', 'expected') - + '\n\n' - + msg - + '\n'; - - // indent - msg = msg.replace(/^/gm, ' '); - - fmt = color('error title', ' %s) %s:\n%s') - + color('error stack', '\n%s\n'); - } - - // indent stack trace without msg - stack = stack.slice(index ? index + 1 : index) - .replace(/^/gm, ' '); - - console.error(fmt, (i + 1), test.fullTitle(), msg, stack); - }); -}; - -/** - * Initialize a new `Base` reporter. - * - * All other reporters generally - * inherit from this reporter, providing - * stats such as test duration, number - * of tests passed / failed etc. - * - * @param {Runner} runner - * @api public - */ - -function Base(runner) { - var self = this - , stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 } - , failures = this.failures = []; - - if (!runner) return; - this.runner = runner; - - runner.stats = stats; - - runner.on('start', function(){ - stats.start = new Date; - }); - - runner.on('suite', function(suite){ - stats.suites = stats.suites || 0; - suite.root || stats.suites++; - }); - - runner.on('test end', function(test){ - stats.tests = stats.tests || 0; - stats.tests++; - }); - - runner.on('pass', function(test){ - stats.passes = stats.passes || 0; - - var medium = test.slow() / 2; - test.speed = test.duration > test.slow() - ? 'slow' - : test.duration > medium - ? 'medium' - : 'fast'; - - stats.passes++; - }); - - runner.on('fail', function(test, err){ - stats.failures = stats.failures || 0; - stats.failures++; - test.err = err; - failures.push(test); - }); - - runner.on('end', function(){ - stats.end = new Date; - stats.duration = new Date - stats.start; - }); - - runner.on('pending', function(){ - stats.pending++; - }); -} - -/** - * Output common epilogue used by many of - * the bundled reporters. - * - * @api public - */ - -Base.prototype.epilogue = function(){ - var stats = this.stats - , fmt - , tests; - - console.log(); - - function pluralize(n) { - return 1 == n ? 'test' : 'tests'; - } - - // failure - if (stats.failures) { - fmt = color('bright fail', ' ' + exports.symbols.err) - + color('fail', ' %d of %d %s failed') - + color('light', ':') - - console.error(fmt, - stats.failures, - this.runner.total, - pluralize(this.runner.total)); - - Base.list(this.failures); - console.error(); - return; - } - - // pass - fmt = color('bright pass', ' ') - + color('green', ' %d %s complete') - + color('light', ' (%s)'); - - console.log(fmt, - stats.tests || 0, - pluralize(stats.tests), - ms(stats.duration)); - - // pending - if (stats.pending) { - fmt = color('pending', ' ') - + color('pending', ' %d %s pending'); - - console.log(fmt, stats.pending, pluralize(stats.pending)); - } - - console.log(); -}; - -/** - * Pad the given `str` to `len`. - * - * @param {String} str - * @param {String} len - * @return {String} - * @api private - */ - -function pad(str, len) { - str = String(str); - return Array(len - str.length + 1).join(' ') + str; -} - -/** - * Return a character diff for `err`. - * - * @param {Error} err - * @return {String} - * @api private - */ - -function errorDiff(err, type, escape) { - return diff['diff' + type](err.actual, err.expected).map(function(str){ - if (escape) { - str.value = str.value - .replace(/\t/g, '') - .replace(/\r/g, '') - .replace(/\n/g, '\n'); - } - if (str.added) return colorLines('diff added', str.value); - if (str.removed) return colorLines('diff removed', str.value); - return str.value; - }).join(''); -} - -/** - * Color lines for `str`, using the color `name`. - * - * @param {String} name - * @param {String} str - * @return {String} - * @api private - */ - -function colorLines(name, str) { - return str.split('\n').map(function(str){ - return color(name, str); - }).join('\n'); -} - -}); // module: reporters/base.js - -require.register("reporters/doc.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils'); - -/** - * Expose `Doc`. - */ - -exports = module.exports = Doc; - -/** - * Initialize a new `Doc` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Doc(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , total = runner.total - , indents = 2; - - function indent() { - return Array(indents).join(' '); - } - - runner.on('suite', function(suite){ - if (suite.root) return; - ++indents; - console.log('%s
', indent()); - ++indents; - console.log('%s

%s

', indent(), utils.escape(suite.title)); - console.log('%s
', indent()); - }); - - runner.on('suite end', function(suite){ - if (suite.root) return; - console.log('%s
', indent()); - --indents; - console.log('%s
', indent()); - --indents; - }); - - runner.on('pass', function(test){ - console.log('%s
%s
', indent(), utils.escape(test.title)); - var code = utils.escape(utils.clean(test.fn.toString())); - console.log('%s
%s
', indent(), code); - }); -} - -}); // module: reporters/doc.js - -require.register("reporters/dot.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , color = Base.color; - -/** - * Expose `Dot`. - */ - -exports = module.exports = Dot; - -/** - * Initialize a new `Dot` matrix test reporter. - * - * @param {Runner} runner - * @api public - */ - -function Dot(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , n = 0; - - runner.on('start', function(){ - process.stdout.write('\n '); - }); - - runner.on('pending', function(test){ - process.stdout.write(color('pending', Base.symbols.dot)); - }); - - runner.on('pass', function(test){ - if (++n % width == 0) process.stdout.write('\n '); - if ('slow' == test.speed) { - process.stdout.write(color('bright yellow', Base.symbols.dot)); - } else { - process.stdout.write(color(test.speed, Base.symbols.dot)); - } - }); - - runner.on('fail', function(test, err){ - if (++n % width == 0) process.stdout.write('\n '); - process.stdout.write(color('fail', Base.symbols.dot)); - }); - - runner.on('end', function(){ - console.log(); - self.epilogue(); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Dot.prototype = new F; -Dot.prototype.constructor = Dot; - -}); // module: reporters/dot.js - -require.register("reporters/html-cov.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var JSONCov = require('./json-cov') - , fs = require('browser/fs'); - -/** - * Expose `HTMLCov`. - */ - -exports = module.exports = HTMLCov; - -/** - * Initialize a new `JsCoverage` reporter. - * - * @param {Runner} runner - * @api public - */ - -function HTMLCov(runner) { - var jade = require('jade') - , file = __dirname + '/templates/coverage.jade' - , str = fs.readFileSync(file, 'utf8') - , fn = jade.compile(str, { filename: file }) - , self = this; - - JSONCov.call(this, runner, false); - - runner.on('end', function(){ - process.stdout.write(fn({ - cov: self.cov - , coverageClass: coverageClass - })); - }); -} - -/** - * Return coverage class for `n`. - * - * @return {String} - * @api private - */ - -function coverageClass(n) { - if (n >= 75) return 'high'; - if (n >= 50) return 'medium'; - if (n >= 25) return 'low'; - return 'terrible'; -} -}); // module: reporters/html-cov.js - -require.register("reporters/html.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils') - , Progress = require('../browser/progress') - , escape = utils.escape; - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; - -/** - * Expose `Doc`. - */ - -exports = module.exports = HTML; - -/** - * Stats template. - */ - -var statsTemplate = ''; - -/** - * Initialize a new `Doc` reporter. - * - * @param {Runner} runner - * @api public - */ - -function HTML(runner, root) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , total = runner.total - , stat = fragment(statsTemplate) - , items = stat.getElementsByTagName('li') - , passes = items[1].getElementsByTagName('em')[0] - , passesLink = items[1].getElementsByTagName('a')[0] - , failures = items[2].getElementsByTagName('em')[0] - , failuresLink = items[2].getElementsByTagName('a')[0] - , duration = items[3].getElementsByTagName('em')[0] - , canvas = stat.getElementsByTagName('canvas')[0] - , report = fragment('
    ') - , stack = [report] - , progress - , ctx - - root = root || document.getElementById('mocha'); - - if (canvas.getContext) { - var ratio = window.devicePixelRatio || 1; - canvas.style.width = canvas.width; - canvas.style.height = canvas.height; - canvas.width *= ratio; - canvas.height *= ratio; - ctx = canvas.getContext('2d'); - ctx.scale(ratio, ratio); - progress = new Progress; - } - - if (!root) return error('#mocha div missing, add it to your document'); - - // pass toggle - on(passesLink, 'click', function(){ - unhide(); - var name = /pass/.test(report.className) ? '' : ' pass'; - report.className = report.className.replace(/fail|pass/g, '') + name; - if (report.className.trim()) hideSuitesWithout('test pass'); - }); - - // failure toggle - on(failuresLink, 'click', function(){ - unhide(); - var name = /fail/.test(report.className) ? '' : ' fail'; - report.className = report.className.replace(/fail|pass/g, '') + name; - if (report.className.trim()) hideSuitesWithout('test fail'); - }); - - root.appendChild(stat); - root.appendChild(report); - - if (progress) progress.size(40); - - runner.on('suite', function(suite){ - if (suite.root) return; - - // suite - var url = '?grep=' + encodeURIComponent(suite.fullTitle()); - var el = fragment('
  • %s

  • ', url, escape(suite.title)); - - // container - stack[0].appendChild(el); - stack.unshift(document.createElement('ul')); - el.appendChild(stack[0]); - }); - - runner.on('suite end', function(suite){ - if (suite.root) return; - stack.shift(); - }); - - runner.on('fail', function(test, err){ - if ('hook' == test.type) runner.emit('test end', test); - }); - - runner.on('test end', function(test){ - window.scrollTo(0, document.body.scrollHeight); - - // TODO: add to stats - var percent = stats.tests / this.total * 100 | 0; - if (progress) progress.update(percent).draw(ctx); - - // update stats - var ms = new Date - stats.start; - text(passes, stats.passes); - text(failures, stats.failures); - text(duration, (ms / 1000).toFixed(2)); - - // test - if ('passed' == test.state) { - var el = fragment('
  • %e%ems

  • ', test.speed, test.title, test.duration, encodeURIComponent(test.fullTitle())); - } else if (test.pending) { - var el = fragment('
  • %e

  • ', test.title); - } else { - var el = fragment('
  • %e

  • ', test.title, encodeURIComponent(test.fullTitle())); - var str = test.err.stack || test.err.toString(); - - // FF / Opera do not add the message - if (!~str.indexOf(test.err.message)) { - str = test.err.message + '\n' + str; - } - - // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we - // check for the result of the stringifying. - if ('[object Error]' == str) str = test.err.message; - - // Safari doesn't give you a stack. Let's at least provide a source line. - if (!test.err.stack && test.err.sourceURL && test.err.line !== undefined) { - str += "\n(" + test.err.sourceURL + ":" + test.err.line + ")"; - } - - el.appendChild(fragment('
    %e
    ', str)); - } - - // toggle code - // TODO: defer - if (!test.pending) { - var h2 = el.getElementsByTagName('h2')[0]; - - on(h2, 'click', function(){ - pre.style.display = 'none' == pre.style.display - ? 'block' - : 'none'; - }); - - var pre = fragment('
    %e
    ', utils.clean(test.fn.toString())); - el.appendChild(pre); - pre.style.display = 'none'; - } - - // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack. - if (stack[0]) stack[0].appendChild(el); - }); -} - -/** - * Display error `msg`. - */ - -function error(msg) { - document.body.appendChild(fragment('
    %s
    ', msg)); -} - -/** - * Return a DOM fragment from `html`. - */ - -function fragment(html) { - var args = arguments - , div = document.createElement('div') - , i = 1; - - div.innerHTML = html.replace(/%([se])/g, function(_, type){ - switch (type) { - case 's': return String(args[i++]); - case 'e': return escape(args[i++]); - } - }); - - return div.firstChild; -} - -/** - * Check for suites that do not have elements - * with `classname`, and hide them. - */ - -function hideSuitesWithout(classname) { - var suites = document.getElementsByClassName('suite'); - for (var i = 0; i < suites.length; i++) { - var els = suites[i].getElementsByClassName(classname); - if (0 == els.length) suites[i].className += ' hidden'; - } -} - -/** - * Unhide .hidden suites. - */ - -function unhide() { - var els = document.getElementsByClassName('suite hidden'); - for (var i = 0; i < els.length; ++i) { - els[i].className = els[i].className.replace('suite hidden', 'suite'); - } -} - -/** - * Set `el` text to `str`. - */ - -function text(el, str) { - if (el.textContent) { - el.textContent = str; - } else { - el.innerText = str; - } -} - -/** - * Listen on `event` with callback `fn`. - */ - -function on(el, event, fn) { - if (el.addEventListener) { - el.addEventListener(event, fn, false); - } else { - el.attachEvent('on' + event, fn); - } -} - -}); // module: reporters/html.js - -require.register("reporters/index.js", function(module, exports, require){ - -exports.Base = require('./base'); -exports.Dot = require('./dot'); -exports.Doc = require('./doc'); -exports.TAP = require('./tap'); -exports.JSON = require('./json'); -exports.HTML = require('./html'); -exports.List = require('./list'); -exports.Min = require('./min'); -exports.Spec = require('./spec'); -exports.Nyan = require('./nyan'); -exports.XUnit = require('./xunit'); -exports.Markdown = require('./markdown'); -exports.Progress = require('./progress'); -exports.Landing = require('./landing'); -exports.JSONCov = require('./json-cov'); -exports.HTMLCov = require('./html-cov'); -exports.JSONStream = require('./json-stream'); -exports.Teamcity = require('./teamcity'); - -}); // module: reporters/index.js - -require.register("reporters/json-cov.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base'); - -/** - * Expose `JSONCov`. - */ - -exports = module.exports = JSONCov; - -/** - * Initialize a new `JsCoverage` reporter. - * - * @param {Runner} runner - * @param {Boolean} output - * @api public - */ - -function JSONCov(runner, output) { - var self = this - , output = 1 == arguments.length ? true : output; - - Base.call(this, runner); - - var tests = [] - , failures = [] - , passes = []; - - runner.on('test end', function(test){ - tests.push(test); - }); - - runner.on('pass', function(test){ - passes.push(test); - }); - - runner.on('fail', function(test){ - failures.push(test); - }); - - runner.on('end', function(){ - var cov = global._$jscoverage || {}; - var result = self.cov = map(cov); - result.stats = self.stats; - result.tests = tests.map(clean); - result.failures = failures.map(clean); - result.passes = passes.map(clean); - if (!output) return; - process.stdout.write(JSON.stringify(result, null, 2 )); - }); -} - -/** - * Map jscoverage data to a JSON structure - * suitable for reporting. - * - * @param {Object} cov - * @return {Object} - * @api private - */ - -function map(cov) { - var ret = { - instrumentation: 'node-jscoverage' - , sloc: 0 - , hits: 0 - , misses: 0 - , coverage: 0 - , files: [] - }; - - for (var filename in cov) { - var data = coverage(filename, cov[filename]); - ret.files.push(data); - ret.hits += data.hits; - ret.misses += data.misses; - ret.sloc += data.sloc; - } - - ret.files.sort(function(a, b) { - return a.filename.localeCompare(b.filename); - }); - - if (ret.sloc > 0) { - ret.coverage = (ret.hits / ret.sloc) * 100; - } - - return ret; -}; - -/** - * Map jscoverage data for a single source file - * to a JSON structure suitable for reporting. - * - * @param {String} filename name of the source file - * @param {Object} data jscoverage coverage data - * @return {Object} - * @api private - */ - -function coverage(filename, data) { - var ret = { - filename: filename, - coverage: 0, - hits: 0, - misses: 0, - sloc: 0, - source: {} - }; - - data.source.forEach(function(line, num){ - num++; - - if (data[num] === 0) { - ret.misses++; - ret.sloc++; - } else if (data[num] !== undefined) { - ret.hits++; - ret.sloc++; - } - - ret.source[num] = { - source: line - , coverage: data[num] === undefined - ? '' - : data[num] - }; - }); - - ret.coverage = ret.hits / ret.sloc * 100; - - return ret; -} - -/** - * Return a plain-object representation of `test` - * free of cyclic properties etc. - * - * @param {Object} test - * @return {Object} - * @api private - */ - -function clean(test) { - return { - title: test.title - , fullTitle: test.fullTitle() - , duration: test.duration - } -} - -}); // module: reporters/json-cov.js - -require.register("reporters/json-stream.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , color = Base.color; - -/** - * Expose `List`. - */ - -exports = module.exports = List; - -/** - * Initialize a new `List` test reporter. - * - * @param {Runner} runner - * @api public - */ - -function List(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , total = runner.total; - - runner.on('start', function(){ - console.log(JSON.stringify(['start', { total: total }])); - }); - - runner.on('pass', function(test){ - console.log(JSON.stringify(['pass', clean(test)])); - }); - - runner.on('fail', function(test, err){ - console.log(JSON.stringify(['fail', clean(test)])); - }); - - runner.on('end', function(){ - process.stdout.write(JSON.stringify(['end', self.stats])); - }); -} - -/** - * Return a plain-object representation of `test` - * free of cyclic properties etc. - * - * @param {Object} test - * @return {Object} - * @api private - */ - -function clean(test) { - return { - title: test.title - , fullTitle: test.fullTitle() - , duration: test.duration - } -} -}); // module: reporters/json-stream.js - -require.register("reporters/json.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `JSON`. - */ - -exports = module.exports = JSONReporter; - -/** - * Initialize a new `JSON` reporter. - * - * @param {Runner} runner - * @api public - */ - -function JSONReporter(runner) { - var self = this; - Base.call(this, runner); - - var tests = [] - , failures = [] - , passes = []; - - runner.on('test end', function(test){ - tests.push(test); - }); - - runner.on('pass', function(test){ - passes.push(test); - }); - - runner.on('fail', function(test){ - failures.push(test); - }); - - runner.on('end', function(){ - var obj = { - stats: self.stats - , tests: tests.map(clean) - , failures: failures.map(clean) - , passes: passes.map(clean) - }; - - process.stdout.write(JSON.stringify(obj, null, 2)); - }); -} - -/** - * Return a plain-object representation of `test` - * free of cyclic properties etc. - * - * @param {Object} test - * @return {Object} - * @api private - */ - -function clean(test) { - return { - title: test.title - , fullTitle: test.fullTitle() - , duration: test.duration - } -} -}); // module: reporters/json.js - -require.register("reporters/landing.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `Landing`. - */ - -exports = module.exports = Landing; - -/** - * Airplane color. - */ - -Base.colors.plane = 0; - -/** - * Airplane crash color. - */ - -Base.colors['plane crash'] = 31; - -/** - * Runway color. - */ - -Base.colors.runway = 90; - -/** - * Initialize a new `Landing` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Landing(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , total = runner.total - , stream = process.stdout - , plane = color('plane', '✈') - , crashed = -1 - , n = 0; - - function runway() { - var buf = Array(width).join('-'); - return ' ' + color('runway', buf); - } - - runner.on('start', function(){ - stream.write('\n '); - cursor.hide(); - }); - - runner.on('test end', function(test){ - // check if the plane crashed - var col = -1 == crashed - ? width * ++n / total | 0 - : crashed; - - // show the crash - if ('failed' == test.state) { - plane = color('plane crash', '✈'); - crashed = col; - } - - // render landing strip - stream.write('\u001b[4F\n\n'); - stream.write(runway()); - stream.write('\n '); - stream.write(color('runway', Array(col).join('⋅'))); - stream.write(plane) - stream.write(color('runway', Array(width - col).join('⋅') + '\n')); - stream.write(runway()); - stream.write('\u001b[0m'); - }); - - runner.on('end', function(){ - cursor.show(); - console.log(); - self.epilogue(); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Landing.prototype = new F; -Landing.prototype.constructor = Landing; - -}); // module: reporters/landing.js - -require.register("reporters/list.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `List`. - */ - -exports = module.exports = List; - -/** - * Initialize a new `List` test reporter. - * - * @param {Runner} runner - * @api public - */ - -function List(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , n = 0; - - runner.on('start', function(){ - console.log(); - }); - - runner.on('test', function(test){ - process.stdout.write(color('pass', ' ' + test.fullTitle() + ': ')); - }); - - runner.on('pending', function(test){ - var fmt = color('checkmark', ' -') - + color('pending', ' %s'); - console.log(fmt, test.fullTitle()); - }); - - runner.on('pass', function(test){ - var fmt = color('checkmark', ' '+Base.symbols.dot) - + color('pass', ' %s: ') - + color(test.speed, '%dms'); - cursor.CR(); - console.log(fmt, test.fullTitle(), test.duration); - }); - - runner.on('fail', function(test, err){ - cursor.CR(); - console.log(color('fail', ' %d) %s'), ++n, test.fullTitle()); - }); - - runner.on('end', self.epilogue.bind(self)); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -List.prototype = new F; -List.prototype.constructor = List; - - -}); // module: reporters/list.js - -require.register("reporters/markdown.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils'); - -/** - * Expose `Markdown`. - */ - -exports = module.exports = Markdown; - -/** - * Initialize a new `Markdown` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Markdown(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , level = 0 - , buf = ''; - - function title(str) { - return Array(level).join('#') + ' ' + str; - } - - function indent() { - return Array(level).join(' '); - } - - function mapTOC(suite, obj) { - var ret = obj; - obj = obj[suite.title] = obj[suite.title] || { suite: suite }; - suite.suites.forEach(function(suite){ - mapTOC(suite, obj); - }); - return ret; - } - - function stringifyTOC(obj, level) { - ++level; - var buf = ''; - var link; - for (var key in obj) { - if ('suite' == key) continue; - if (key) link = ' - [' + key + '](#' + utils.slug(obj[key].suite.fullTitle()) + ')\n'; - if (key) buf += Array(level).join(' ') + link; - buf += stringifyTOC(obj[key], level); - } - --level; - return buf; - } - - function generateTOC(suite) { - var obj = mapTOC(suite, {}); - return stringifyTOC(obj, 0); - } - - generateTOC(runner.suite); - - runner.on('suite', function(suite){ - ++level; - var slug = utils.slug(suite.fullTitle()); - buf += '' + '\n'; - buf += title(suite.title) + '\n'; - }); - - runner.on('suite end', function(suite){ - --level; - }); - - runner.on('pass', function(test){ - var code = utils.clean(test.fn.toString()); - buf += test.title + '.\n'; - buf += '\n```js\n'; - buf += code + '\n'; - buf += '```\n\n'; - }); - - runner.on('end', function(){ - process.stdout.write('# TOC\n'); - process.stdout.write(generateTOC(runner.suite)); - process.stdout.write(buf); - }); -} -}); // module: reporters/markdown.js - -require.register("reporters/min.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base'); - -/** - * Expose `Min`. - */ - -exports = module.exports = Min; - -/** - * Initialize a new `Min` minimal test reporter (best used with --watch). - * - * @param {Runner} runner - * @api public - */ - -function Min(runner) { - Base.call(this, runner); - - runner.on('start', function(){ - // clear screen - process.stdout.write('\u001b[2J'); - // set cursor position - process.stdout.write('\u001b[1;3H'); - }); - - runner.on('end', this.epilogue.bind(this)); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Min.prototype = new F; -Min.prototype.constructor = Min; - -}); // module: reporters/min.js - -require.register("reporters/nyan.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , color = Base.color; - -/** - * Expose `Dot`. - */ - -exports = module.exports = NyanCat; - -/** - * Initialize a new `Dot` matrix test reporter. - * - * @param {Runner} runner - * @api public - */ - -function NyanCat(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , rainbowColors = this.rainbowColors = self.generateColors() - , colorIndex = this.colorIndex = 0 - , numerOfLines = this.numberOfLines = 4 - , trajectories = this.trajectories = [[], [], [], []] - , nyanCatWidth = this.nyanCatWidth = 11 - , trajectoryWidthMax = this.trajectoryWidthMax = (width - nyanCatWidth) - , scoreboardWidth = this.scoreboardWidth = 5 - , tick = this.tick = 0 - , n = 0; - - runner.on('start', function(){ - Base.cursor.hide(); - self.draw('start'); - }); - - runner.on('pending', function(test){ - self.draw('pending'); - }); - - runner.on('pass', function(test){ - self.draw('pass'); - }); - - runner.on('fail', function(test, err){ - self.draw('fail'); - }); - - runner.on('end', function(){ - Base.cursor.show(); - for (var i = 0; i < self.numberOfLines; i++) write('\n'); - self.epilogue(); - }); -} - -/** - * Draw the nyan cat with runner `status`. - * - * @param {String} status - * @api private - */ - -NyanCat.prototype.draw = function(status){ - this.appendRainbow(); - this.drawScoreboard(); - this.drawRainbow(); - this.drawNyanCat(status); - this.tick = !this.tick; -}; - -/** - * Draw the "scoreboard" showing the number - * of passes, failures and pending tests. - * - * @api private - */ - -NyanCat.prototype.drawScoreboard = function(){ - var stats = this.stats; - var colors = Base.colors; - - function draw(color, n) { - write(' '); - write('\u001b[' + color + 'm' + n + '\u001b[0m'); - write('\n'); - } - - draw(colors.green, stats.passes); - draw(colors.fail, stats.failures); - draw(colors.pending, stats.pending); - write('\n'); - - this.cursorUp(this.numberOfLines); -}; - -/** - * Append the rainbow. - * - * @api private - */ - -NyanCat.prototype.appendRainbow = function(){ - var segment = this.tick ? '_' : '-'; - var rainbowified = this.rainbowify(segment); - - for (var index = 0; index < this.numberOfLines; index++) { - var trajectory = this.trajectories[index]; - if (trajectory.length >= this.trajectoryWidthMax) trajectory.shift(); - trajectory.push(rainbowified); - } -}; - -/** - * Draw the rainbow. - * - * @api private - */ - -NyanCat.prototype.drawRainbow = function(){ - var self = this; - - this.trajectories.forEach(function(line, index) { - write('\u001b[' + self.scoreboardWidth + 'C'); - write(line.join('')); - write('\n'); - }); - - this.cursorUp(this.numberOfLines); -}; - -/** - * Draw the nyan cat with `status`. - * - * @param {String} status - * @api private - */ - -NyanCat.prototype.drawNyanCat = function(status) { - var self = this; - var startWidth = this.scoreboardWidth + this.trajectories[0].length; - - [0, 1, 2, 3].forEach(function(index) { - write('\u001b[' + startWidth + 'C'); - - switch (index) { - case 0: - write('_,------,'); - write('\n'); - break; - case 1: - var padding = self.tick ? ' ' : ' '; - write('_|' + padding + '/\\_/\\ '); - write('\n'); - break; - case 2: - var padding = self.tick ? '_' : '__'; - var tail = self.tick ? '~' : '^'; - var face; - switch (status) { - case 'pass': - face = '( ^ .^)'; - break; - case 'fail': - face = '( o .o)'; - break; - default: - face = '( - .-)'; - } - write(tail + '|' + padding + face + ' '); - write('\n'); - break; - case 3: - var padding = self.tick ? ' ' : ' '; - write(padding + '"" "" '); - write('\n'); - break; - } - }); - - this.cursorUp(this.numberOfLines); -}; - -/** - * Move cursor up `n`. - * - * @param {Number} n - * @api private - */ - -NyanCat.prototype.cursorUp = function(n) { - write('\u001b[' + n + 'A'); -}; - -/** - * Move cursor down `n`. - * - * @param {Number} n - * @api private - */ - -NyanCat.prototype.cursorDown = function(n) { - write('\u001b[' + n + 'B'); -}; - -/** - * Generate rainbow colors. - * - * @return {Array} - * @api private - */ - -NyanCat.prototype.generateColors = function(){ - var colors = []; - - for (var i = 0; i < (6 * 7); i++) { - var pi3 = Math.floor(Math.PI / 3); - var n = (i * (1.0 / 6)); - var r = Math.floor(3 * Math.sin(n) + 3); - var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3); - var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3); - colors.push(36 * r + 6 * g + b + 16); - } - - return colors; -}; - -/** - * Apply rainbow to the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -NyanCat.prototype.rainbowify = function(str){ - var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length]; - this.colorIndex += 1; - return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m'; -}; - -/** - * Stdout helper. - */ - -function write(string) { - process.stdout.write(string); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -NyanCat.prototype = new F; -NyanCat.prototype.constructor = NyanCat; - - -}); // module: reporters/nyan.js - -require.register("reporters/progress.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `Progress`. - */ - -exports = module.exports = Progress; - -/** - * General progress bar color. - */ - -Base.colors.progress = 90; - -/** - * Initialize a new `Progress` bar test reporter. - * - * @param {Runner} runner - * @param {Object} options - * @api public - */ - -function Progress(runner, options) { - Base.call(this, runner); - - var self = this - , options = options || {} - , stats = this.stats - , width = Base.window.width * .50 | 0 - , total = runner.total - , complete = 0 - , max = Math.max; - - // default chars - options.open = options.open || '['; - options.complete = options.complete || '▬'; - options.incomplete = options.incomplete || Base.symbols.dot; - options.close = options.close || ']'; - options.verbose = false; - - // tests started - runner.on('start', function(){ - console.log(); - cursor.hide(); - }); - - // tests complete - runner.on('test end', function(){ - complete++; - var incomplete = total - complete - , percent = complete / total - , n = width * percent | 0 - , i = width - n; - - cursor.CR(); - process.stdout.write('\u001b[J'); - process.stdout.write(color('progress', ' ' + options.open)); - process.stdout.write(Array(n).join(options.complete)); - process.stdout.write(Array(i).join(options.incomplete)); - process.stdout.write(color('progress', options.close)); - if (options.verbose) { - process.stdout.write(color('progress', ' ' + complete + ' of ' + total)); - } - }); - - // tests are complete, output some stats - // and the failures if any - runner.on('end', function(){ - cursor.show(); - console.log(); - self.epilogue(); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Progress.prototype = new F; -Progress.prototype.constructor = Progress; - - -}); // module: reporters/progress.js - -require.register("reporters/spec.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `Spec`. - */ - -exports = module.exports = Spec; - -/** - * Initialize a new `Spec` test reporter. - * - * @param {Runner} runner - * @api public - */ - -function Spec(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , indents = 0 - , n = 0; - - function indent() { - return Array(indents).join(' ') - } - - runner.on('start', function(){ - console.log(); - }); - - runner.on('suite', function(suite){ - ++indents; - console.log(color('suite', '%s%s'), indent(), suite.title); - }); - - runner.on('suite end', function(suite){ - --indents; - if (1 == indents) console.log(); - }); - - runner.on('test', function(test){ - process.stdout.write(indent() + color('pass', ' ◦ ' + test.title + ': ')); - }); - - runner.on('pending', function(test){ - var fmt = indent() + color('pending', ' - %s'); - console.log(fmt, test.title); - }); - - runner.on('pass', function(test){ - if ('fast' == test.speed) { - var fmt = indent() - + color('checkmark', ' ' + Base.symbols.ok) - + color('pass', ' %s '); - cursor.CR(); - console.log(fmt, test.title); - } else { - var fmt = indent() - + color('checkmark', ' ' + Base.symbols.ok) - + color('pass', ' %s ') - + color(test.speed, '(%dms)'); - cursor.CR(); - console.log(fmt, test.title, test.duration); - } - }); - - runner.on('fail', function(test, err){ - cursor.CR(); - console.log(indent() + color('fail', ' %d) %s'), ++n, test.title); - }); - - runner.on('end', self.epilogue.bind(self)); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Spec.prototype = new F; -Spec.prototype.constructor = Spec; - - -}); // module: reporters/spec.js - -require.register("reporters/tap.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `TAP`. - */ - -exports = module.exports = TAP; - -/** - * Initialize a new `TAP` reporter. - * - * @param {Runner} runner - * @api public - */ - -function TAP(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , n = 1 - , passes = 0 - , failures = 0; - - runner.on('start', function(){ - var total = runner.grepTotal(runner.suite); - console.log('%d..%d', 1, total); - }); - - runner.on('test end', function(){ - ++n; - }); - - runner.on('pending', function(test){ - console.log('ok %d %s # SKIP -', n, title(test)); - }); - - runner.on('pass', function(test){ - passes++; - console.log('ok %d %s', n, title(test)); - }); - - runner.on('fail', function(test, err){ - failures++; - console.log('not ok %d %s', n, title(test)); - if (err.stack) console.log(err.stack.replace(/^/gm, ' ')); - }); - - runner.on('end', function(){ - console.log('# tests ' + (passes + failures)); - console.log('# pass ' + passes); - console.log('# fail ' + failures); - }); -} - -/** - * Return a TAP-safe title of `test` - * - * @param {Object} test - * @return {String} - * @api private - */ - -function title(test) { - return test.fullTitle().replace(/#/g, ''); -} - -}); // module: reporters/tap.js - -require.register("reporters/teamcity.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base'); - -/** - * Expose `Teamcity`. - */ - -exports = module.exports = Teamcity; - -/** - * Initialize a new `Teamcity` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Teamcity(runner) { - Base.call(this, runner); - var stats = this.stats; - - runner.on('start', function() { - console.log("##teamcity[testSuiteStarted name='mocha.suite']"); - }); - - runner.on('test', function(test) { - console.log("##teamcity[testStarted name='" + escape(test.fullTitle()) + "']"); - }); - - runner.on('fail', function(test, err) { - console.log("##teamcity[testFailed name='" + escape(test.fullTitle()) + "' message='" + escape(err.message) + "']"); - }); - - runner.on('pending', function(test) { - console.log("##teamcity[testIgnored name='" + escape(test.fullTitle()) + "' message='pending']"); - }); - - runner.on('test end', function(test) { - console.log("##teamcity[testFinished name='" + escape(test.fullTitle()) + "' duration='" + test.duration + "']"); - }); - - runner.on('end', function() { - console.log("##teamcity[testSuiteFinished name='mocha.suite' duration='" + stats.duration + "']"); - }); -} - -/** - * Escape the given `str`. - */ - -function escape(str) { - return str - .replace(/\|/g, "||") - .replace(/\n/g, "|n") - .replace(/\r/g, "|r") - .replace(/\[/g, "|[") - .replace(/\]/g, "|]") - .replace(/\u0085/g, "|x") - .replace(/\u2028/g, "|l") - .replace(/\u2029/g, "|p") - .replace(/'/g, "|'"); -} - -}); // module: reporters/teamcity.js - -require.register("reporters/xunit.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils') - , escape = utils.escape; - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; - -/** - * Expose `XUnit`. - */ - -exports = module.exports = XUnit; - -/** - * Initialize a new `XUnit` reporter. - * - * @param {Runner} runner - * @api public - */ - -function XUnit(runner) { - Base.call(this, runner); - var stats = this.stats - , tests = [] - , self = this; - - runner.on('pass', function(test){ - tests.push(test); - }); - - runner.on('fail', function(test){ - tests.push(test); - }); - - runner.on('end', function(){ - console.log(tag('testsuite', { - name: 'Mocha Tests' - , tests: stats.tests - , failures: stats.failures - , errors: stats.failures - , skip: stats.tests - stats.failures - stats.passes - , timestamp: (new Date).toUTCString() - , time: stats.duration / 1000 - }, false)); - - tests.forEach(test); - console.log(''); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -XUnit.prototype = new F; -XUnit.prototype.constructor = XUnit; - - -/** - * Output tag for the given `test.` - */ - -function test(test) { - var attrs = { - classname: test.parent.fullTitle() - , name: test.title - , time: test.duration / 1000 - }; - - if ('failed' == test.state) { - var err = test.err; - attrs.message = escape(err.message); - console.log(tag('testcase', attrs, false, tag('failure', attrs, false, cdata(err.stack)))); - } else if (test.pending) { - console.log(tag('testcase', attrs, false, tag('skipped', {}, true))); - } else { - console.log(tag('testcase', attrs, true) ); - } -} - -/** - * HTML tag helper. - */ - -function tag(name, attrs, close, content) { - var end = close ? '/>' : '>' - , pairs = [] - , tag; - - for (var key in attrs) { - pairs.push(key + '="' + escape(attrs[key]) + '"'); - } - - tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end; - if (content) tag += content + ''; -} - -}); // module: reporters/xunit.js - -require.register("runnable.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var EventEmitter = require('browser/events').EventEmitter - , debug = require('browser/debug')('mocha:runnable') - , milliseconds = require('./ms'); - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; - -/** - * Object#toString(). - */ - -var toString = Object.prototype.toString; - -/** - * Expose `Runnable`. - */ - -module.exports = Runnable; - -/** - * Initialize a new `Runnable` with the given `title` and callback `fn`. - * - * @param {String} title - * @param {Function} fn - * @api private - */ - -function Runnable(title, fn) { - this.title = title; - this.fn = fn; - this.async = fn && fn.length; - this.sync = ! this.async; - this._timeout = 2000; - this._slow = 75; - this.timedOut = false; -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -function F(){}; -F.prototype = EventEmitter.prototype; -Runnable.prototype = new F; -Runnable.prototype.constructor = Runnable; - - -/** - * Set & get timeout `ms`. - * - * @param {Number|String} ms - * @return {Runnable|Number} ms or self - * @api private - */ - -Runnable.prototype.timeout = function(ms){ - if (0 == arguments.length) return this._timeout; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('timeout %d', ms); - this._timeout = ms; - if (this.timer) this.resetTimeout(); - return this; -}; - -/** - * Set & get slow `ms`. - * - * @param {Number|String} ms - * @return {Runnable|Number} ms or self - * @api private - */ - -Runnable.prototype.slow = function(ms){ - if (0 === arguments.length) return this._slow; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('timeout %d', ms); - this._slow = ms; - return this; -}; - -/** - * Return the full title generated by recursively - * concatenating the parent's full title. - * - * @return {String} - * @api public - */ - -Runnable.prototype.fullTitle = function(){ - return this.parent.fullTitle() + ' ' + this.title; -}; - -/** - * Clear the timeout. - * - * @api private - */ - -Runnable.prototype.clearTimeout = function(){ - clearTimeout(this.timer); -}; - -/** - * Inspect the runnable void of private properties. - * - * @return {String} - * @api private - */ - -Runnable.prototype.inspect = function(){ - return JSON.stringify(this, function(key, val){ - if ('_' == key[0]) return; - if ('parent' == key) return '#'; - if ('ctx' == key) return '#'; - return val; - }, 2); -}; - -/** - * Reset the timeout. - * - * @api private - */ - -Runnable.prototype.resetTimeout = function(){ - var self = this - , ms = this.timeout(); - - this.clearTimeout(); - if (ms) { - this.timer = setTimeout(function(){ - self.callback(new Error('timeout of ' + ms + 'ms exceeded')); - self.timedOut = true; - }, ms); - } -}; - -/** - * Run the test and invoke `fn(err)`. - * - * @param {Function} fn - * @api private - */ - -Runnable.prototype.run = function(fn){ - var self = this - , ms = this.timeout() - , start = new Date - , ctx = this.ctx - , finished - , emitted; - - if (ctx) ctx.runnable(this); - - // timeout - if (this.async) { - if (ms) { - this.timer = setTimeout(function(){ - done(new Error('timeout of ' + ms + 'ms exceeded')); - self.timedOut = true; - }, ms); - } - } - - // called multiple times - function multiple(err) { - if (emitted) return; - emitted = true; - self.emit('error', err || new Error('done() called multiple times')); - } - - // finished - function done(err) { - if (self.timedOut) return; - if (finished) return multiple(err); - self.clearTimeout(); - self.duration = new Date - start; - finished = true; - fn(err); - } - - // for .resetTimeout() - this.callback = done; - - // async - if (this.async) { - try { - this.fn.call(ctx, function(err){ - if (err instanceof Error || toString.call(err) === "[object Error]") return done(err); - if (null != err) return done(new Error('done() invoked with non-Error: ' + err)); - done(); - }); - } catch (err) { - done(err); - } - return; - } - - if (this.asyncOnly) { - return done(new Error('--async-only option in use without declaring `done()`')); - } - - // sync - try { - if (!this.pending) this.fn.call(ctx); - this.duration = new Date - start; - fn(); - } catch (err) { - fn(err); - } -}; - -}); // module: runnable.js - -require.register("runner.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var EventEmitter = require('browser/events').EventEmitter - , debug = require('browser/debug')('mocha:runner') - , Test = require('./test') - , utils = require('./utils') - , filter = utils.filter - , keys = utils.keys - , noop = function(){} - , immediately = global.setImmediate || process.nextTick; - -/** - * Non-enumerable globals. - */ - -var globals = [ - 'setTimeout', - 'clearTimeout', - 'setInterval', - 'clearInterval', - 'XMLHttpRequest', - 'Date' -]; - -/** - * Expose `Runner`. - */ - -module.exports = Runner; - -/** - * Initialize a `Runner` for the given `suite`. - * - * Events: - * - * - `start` execution started - * - `end` execution complete - * - `suite` (suite) test suite execution started - * - `suite end` (suite) all tests (and sub-suites) have finished - * - `test` (test) test execution started - * - `test end` (test) test completed - * - `hook` (hook) hook execution started - * - `hook end` (hook) hook complete - * - `pass` (test) test passed - * - `fail` (test, err) test failed - * - * @api public - */ - -function Runner(suite) { - var self = this; - this._globals = []; - this.suite = suite; - this.total = suite.total(); - this.failures = 0; - this.on('test end', function(test){ self.checkGlobals(test); }); - this.on('hook end', function(hook){ self.checkGlobals(hook); }); - this.grep(/.*/); - this.globals(this.globalProps().concat(['errno'])); -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -function F(){}; -F.prototype = EventEmitter.prototype; -Runner.prototype = new F; -Runner.prototype.constructor = Runner; - - -/** - * Run tests with full titles matching `re`. Updates runner.total - * with number of tests matched. - * - * @param {RegExp} re - * @param {Boolean} invert - * @return {Runner} for chaining - * @api public - */ - -Runner.prototype.grep = function(re, invert){ - debug('grep %s', re); - this._grep = re; - this._invert = invert; - this.total = this.grepTotal(this.suite); - return this; -}; - -/** - * Returns the number of tests matching the grep search for the - * given suite. - * - * @param {Suite} suite - * @return {Number} - * @api public - */ - -Runner.prototype.grepTotal = function(suite) { - var self = this; - var total = 0; - - suite.eachTest(function(test){ - var match = self._grep.test(test.fullTitle()); - if (self._invert) match = !match; - if (match) total++; - }); - - return total; -}; - -/** - * Return a list of global properties. - * - * @return {Array} - * @api private - */ - -Runner.prototype.globalProps = function() { - var props = utils.keys(global); - - // non-enumerables - for (var i = 0; i < globals.length; ++i) { - if (~utils.indexOf(props, globals[i])) continue; - props.push(globals[i]); - } - - return props; -}; - -/** - * Allow the given `arr` of globals. - * - * @param {Array} arr - * @return {Runner} for chaining - * @api public - */ - -Runner.prototype.globals = function(arr){ - if (0 == arguments.length) return this._globals; - debug('globals %j', arr); - utils.forEach(arr, function(arr){ - this._globals.push(arr); - }, this); - return this; -}; - -/** - * Check for global variable leaks. - * - * @api private - */ - -Runner.prototype.checkGlobals = function(test){ - if (this.ignoreLeaks) return; - var ok = this._globals; - var globals = this.globalProps(); - var isNode = process.kill; - var leaks; - - // check length - 2 ('errno' and 'location' globals) - if (isNode && 1 == ok.length - globals.length) return - else if (2 == ok.length - globals.length) return; - - leaks = filterLeaks(ok, globals); - this._globals = this._globals.concat(leaks); - - if (leaks.length > 1) { - this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + '')); - } else if (leaks.length) { - this.fail(test, new Error('global leak detected: ' + leaks[0])); - } -}; - -/** - * Fail the given `test`. - * - * @param {Test} test - * @param {Error} err - * @api private - */ - -Runner.prototype.fail = function(test, err){ - ++this.failures; - test.state = 'failed'; - - if ('string' == typeof err) { - err = new Error('the string "' + err + '" was thrown, throw an Error :)'); - } - - this.emit('fail', test, err); -}; - -/** - * Fail the given `hook` with `err`. - * - * Hook failures (currently) hard-end due - * to that fact that a failing hook will - * surely cause subsequent tests to fail, - * causing jumbled reporting. - * - * @param {Hook} hook - * @param {Error} err - * @api private - */ - -Runner.prototype.failHook = function(hook, err){ - this.fail(hook, err); - this.emit('end'); -}; - -/** - * Run hook `name` callbacks and then invoke `fn()`. - * - * @param {String} name - * @param {Function} function - * @api private - */ - -Runner.prototype.hook = function(name, fn){ - var suite = this.suite - , hooks = suite['_' + name] - , self = this - , timer; - - function next(i) { - var hook = hooks[i]; - if (!hook) return fn(); - self.currentRunnable = hook; - - self.emit('hook', hook); - - hook.on('error', function(err){ - self.failHook(hook, err); - }); - - hook.run(function(err){ - hook.removeAllListeners('error'); - var testError = hook.error(); - if (testError) self.fail(self.test, testError); - if (err) return self.failHook(hook, err); - self.emit('hook end', hook); - next(++i); - }); - } - - immediately(function(){ - next(0); - }); -}; - -/** - * Run hook `name` for the given array of `suites` - * in order, and callback `fn(err)`. - * - * @param {String} name - * @param {Array} suites - * @param {Function} fn - * @api private - */ - -Runner.prototype.hooks = function(name, suites, fn){ - var self = this - , orig = this.suite; - - function next(suite) { - self.suite = suite; - - if (!suite) { - self.suite = orig; - return fn(); - } - - self.hook(name, function(err){ - if (err) { - self.suite = orig; - return fn(err); - } - - next(suites.pop()); - }); - } - - next(suites.pop()); -}; - -/** - * Run hooks from the top level down. - * - * @param {String} name - * @param {Function} fn - * @api private - */ - -Runner.prototype.hookUp = function(name, fn){ - var suites = [this.suite].concat(this.parents()).reverse(); - this.hooks(name, suites, fn); -}; - -/** - * Run hooks from the bottom up. - * - * @param {String} name - * @param {Function} fn - * @api private - */ - -Runner.prototype.hookDown = function(name, fn){ - var suites = [this.suite].concat(this.parents()); - this.hooks(name, suites, fn); -}; - -/** - * Return an array of parent Suites from - * closest to furthest. - * - * @return {Array} - * @api private - */ - -Runner.prototype.parents = function(){ - var suite = this.suite - , suites = []; - while (suite = suite.parent) suites.push(suite); - return suites; -}; - -/** - * Run the current test and callback `fn(err)`. - * - * @param {Function} fn - * @api private - */ - -Runner.prototype.runTest = function(fn){ - var test = this.test - , self = this; - - if (this.asyncOnly) test.asyncOnly = true; - - try { - test.on('error', function(err){ - self.fail(test, err); - }); - test.run(fn); - } catch (err) { - fn(err); - } -}; - -/** - * Run tests in the given `suite` and invoke - * the callback `fn()` when complete. - * - * @param {Suite} suite - * @param {Function} fn - * @api private - */ - -Runner.prototype.runTests = function(suite, fn){ - var self = this - , tests = suite.tests.slice() - , test; - - function next(err) { - // if we bail after first err - if (self.failures && suite._bail) return fn(); - - // next test - test = tests.shift(); - - // all done - if (!test) return fn(); - - // grep - var match = self._grep.test(test.fullTitle()); - if (self._invert) match = !match; - if (!match) return next(); - - // pending - if (test.pending) { - self.emit('pending', test); - self.emit('test end', test); - return next(); - } - - // execute test and hook(s) - self.emit('test', self.test = test); - self.hookDown('beforeEach', function(){ - self.currentRunnable = self.test; - self.runTest(function(err){ - test = self.test; - - if (err) { - self.fail(test, err); - self.emit('test end', test); - return self.hookUp('afterEach', next); - } - - test.state = 'passed'; - self.emit('pass', test); - self.emit('test end', test); - self.hookUp('afterEach', next); - }); - }); - } - - this.next = next; - next(); -}; - -/** - * Run the given `suite` and invoke the - * callback `fn()` when complete. - * - * @param {Suite} suite - * @param {Function} fn - * @api private - */ - -Runner.prototype.runSuite = function(suite, fn){ - var total = this.grepTotal(suite) - , self = this - , i = 0; - - debug('run suite %s', suite.fullTitle()); - - if (!total) return fn(); - - this.emit('suite', this.suite = suite); - - function next() { - var curr = suite.suites[i++]; - if (!curr) return done(); - self.runSuite(curr, next); - } - - function done() { - self.suite = suite; - self.hook('afterAll', function(){ - self.emit('suite end', suite); - fn(); - }); - } - - this.hook('beforeAll', function(){ - self.runTests(suite, next); - }); -}; - -/** - * Handle uncaught exceptions. - * - * @param {Error} err - * @api private - */ - -Runner.prototype.uncaught = function(err){ - debug('uncaught exception %s', err.message); - var runnable = this.currentRunnable; - if (!runnable || 'failed' == runnable.state) return; - runnable.clearTimeout(); - err.uncaught = true; - this.fail(runnable, err); - - // recover from test - if ('test' == runnable.type) { - this.emit('test end', runnable); - this.hookUp('afterEach', this.next); - return; - } - - // bail on hooks - this.emit('end'); -}; - -/** - * Run the root suite and invoke `fn(failures)` - * on completion. - * - * @param {Function} fn - * @return {Runner} for chaining - * @api public - */ - -Runner.prototype.run = function(fn){ - var self = this - , fn = fn || function(){}; - - function uncaught(err){ - self.uncaught(err); - } - - debug('start'); - - // callback - this.on('end', function(){ - debug('end'); - process.removeListener('uncaughtException', uncaught); - fn(self.failures); - }); - - // run suites - this.emit('start'); - this.runSuite(this.suite, function(){ - debug('finished running'); - self.emit('end'); - }); - - // uncaught exception - process.on('uncaughtException', uncaught); - - return this; -}; - -/** - * Filter leaks with the given globals flagged as `ok`. - * - * @param {Array} ok - * @param {Array} globals - * @return {Array} - * @api private - */ - -function filterLeaks(ok, globals) { - return filter(globals, function(key){ - var matched = filter(ok, function(ok){ - if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]); - // Opera and IE expose global variables for HTML element IDs (issue #243) - if (/^mocha-/.test(key)) return true; - return key == ok; - }); - return matched.length == 0 && (!global.navigator || 'onerror' !== key); - }); -} - -}); // module: runner.js - -require.register("suite.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var EventEmitter = require('browser/events').EventEmitter - , debug = require('browser/debug')('mocha:suite') - , milliseconds = require('./ms') - , utils = require('./utils') - , Hook = require('./hook'); - -/** - * Expose `Suite`. - */ - -exports = module.exports = Suite; - -/** - * Create a new `Suite` with the given `title` - * and parent `Suite`. When a suite with the - * same title is already present, that suite - * is returned to provide nicer reporter - * and more flexible meta-testing. - * - * @param {Suite} parent - * @param {String} title - * @return {Suite} - * @api public - */ - -exports.create = function(parent, title){ - var suite = new Suite(title, parent.ctx); - suite.parent = parent; - if (parent.pending) suite.pending = true; - title = suite.fullTitle(); - parent.addSuite(suite); - return suite; -}; - -/** - * Initialize a new `Suite` with the given - * `title` and `ctx`. - * - * @param {String} title - * @param {Context} ctx - * @api private - */ - -function Suite(title, ctx) { - this.title = title; - this.ctx = ctx; - this.suites = []; - this.tests = []; - this.pending = false; - this._beforeEach = []; - this._beforeAll = []; - this._afterEach = []; - this._afterAll = []; - this.root = !title; - this._timeout = 2000; - this._slow = 75; - this._bail = false; -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -function F(){}; -F.prototype = EventEmitter.prototype; -Suite.prototype = new F; -Suite.prototype.constructor = Suite; - - -/** - * Return a clone of this `Suite`. - * - * @return {Suite} - * @api private - */ - -Suite.prototype.clone = function(){ - var suite = new Suite(this.title); - debug('clone'); - suite.ctx = this.ctx; - suite.timeout(this.timeout()); - suite.slow(this.slow()); - suite.bail(this.bail()); - return suite; -}; - -/** - * Set timeout `ms` or short-hand such as "2s". - * - * @param {Number|String} ms - * @return {Suite|Number} for chaining - * @api private - */ - -Suite.prototype.timeout = function(ms){ - if (0 == arguments.length) return this._timeout; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('timeout %d', ms); - this._timeout = parseInt(ms, 10); - return this; -}; - -/** - * Set slow `ms` or short-hand such as "2s". - * - * @param {Number|String} ms - * @return {Suite|Number} for chaining - * @api private - */ - -Suite.prototype.slow = function(ms){ - if (0 === arguments.length) return this._slow; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('slow %d', ms); - this._slow = ms; - return this; -}; - -/** - * Sets whether to bail after first error. - * - * @parma {Boolean} bail - * @return {Suite|Number} for chaining - * @api private - */ - -Suite.prototype.bail = function(bail){ - if (0 == arguments.length) return this._bail; - debug('bail %s', bail); - this._bail = bail; - return this; -}; - -/** - * Run `fn(test[, done])` before running tests. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.beforeAll = function(fn){ - if (this.pending) return this; - var hook = new Hook('"before all" hook', fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._beforeAll.push(hook); - this.emit('beforeAll', hook); - return this; -}; - -/** - * Run `fn(test[, done])` after running tests. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.afterAll = function(fn){ - if (this.pending) return this; - var hook = new Hook('"after all" hook', fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._afterAll.push(hook); - this.emit('afterAll', hook); - return this; -}; - -/** - * Run `fn(test[, done])` before each test case. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.beforeEach = function(fn){ - if (this.pending) return this; - var hook = new Hook('"before each" hook', fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._beforeEach.push(hook); - this.emit('beforeEach', hook); - return this; -}; - -/** - * Run `fn(test[, done])` after each test case. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.afterEach = function(fn){ - if (this.pending) return this; - var hook = new Hook('"after each" hook', fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._afterEach.push(hook); - this.emit('afterEach', hook); - return this; -}; - -/** - * Add a test `suite`. - * - * @param {Suite} suite - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.addSuite = function(suite){ - suite.parent = this; - suite.timeout(this.timeout()); - suite.slow(this.slow()); - suite.bail(this.bail()); - this.suites.push(suite); - this.emit('suite', suite); - return this; -}; - -/** - * Add a `test` to this suite. - * - * @param {Test} test - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.addTest = function(test){ - test.parent = this; - test.timeout(this.timeout()); - test.slow(this.slow()); - test.ctx = this.ctx; - this.tests.push(test); - this.emit('test', test); - return this; -}; - -/** - * Return the full title generated by recursively - * concatenating the parent's full title. - * - * @return {String} - * @api public - */ - -Suite.prototype.fullTitle = function(){ - if (this.parent) { - var full = this.parent.fullTitle(); - if (full) return full + ' ' + this.title; - } - return this.title; -}; - -/** - * Return the total number of tests. - * - * @return {Number} - * @api public - */ - -Suite.prototype.total = function(){ - return utils.reduce(this.suites, function(sum, suite){ - return sum + suite.total(); - }, 0) + this.tests.length; -}; - -/** - * Iterates through each suite recursively to find - * all tests. Applies a function in the format - * `fn(test)`. - * - * @param {Function} fn - * @return {Suite} - * @api private - */ - -Suite.prototype.eachTest = function(fn){ - utils.forEach(this.tests, fn); - utils.forEach(this.suites, function(suite){ - suite.eachTest(fn); - }); - return this; -}; - -}); // module: suite.js - -require.register("test.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Runnable = require('./runnable'); - -/** - * Expose `Test`. - */ - -module.exports = Test; - -/** - * Initialize a new `Test` with the given `title` and callback `fn`. - * - * @param {String} title - * @param {Function} fn - * @api private - */ - -function Test(title, fn) { - Runnable.call(this, title, fn); - this.pending = !fn; - this.type = 'test'; -} - -/** - * Inherit from `Runnable.prototype`. - */ - -function F(){}; -F.prototype = Runnable.prototype; -Test.prototype = new F; -Test.prototype.constructor = Test; - - -}); // module: test.js - -require.register("utils.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var fs = require('browser/fs') - , path = require('browser/path') - , join = path.join - , debug = require('browser/debug')('mocha:watch'); - -/** - * Ignored directories. - */ - -var ignore = ['node_modules', '.git']; - -/** - * Escape special characters in the given string of html. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function(html){ - return String(html) - .replace(/&/g, '&') - .replace(/"/g, '"') - .replace(//g, '>'); -}; - -/** - * Array#forEach (<=IE8) - * - * @param {Array} array - * @param {Function} fn - * @param {Object} scope - * @api private - */ - -exports.forEach = function(arr, fn, scope){ - for (var i = 0, l = arr.length; i < l; i++) - fn.call(scope, arr[i], i); -}; - -/** - * Array#indexOf (<=IE8) - * - * @parma {Array} arr - * @param {Object} obj to find index of - * @param {Number} start - * @api private - */ - -exports.indexOf = function(arr, obj, start){ - for (var i = start || 0, l = arr.length; i < l; i++) { - if (arr[i] === obj) - return i; - } - return -1; -}; - -/** - * Array#reduce (<=IE8) - * - * @param {Array} array - * @param {Function} fn - * @param {Object} initial value - * @api private - */ - -exports.reduce = function(arr, fn, val){ - var rval = val; - - for (var i = 0, l = arr.length; i < l; i++) { - rval = fn(rval, arr[i], i, arr); - } - - return rval; -}; - -/** - * Array#filter (<=IE8) - * - * @param {Array} array - * @param {Function} fn - * @api private - */ - -exports.filter = function(arr, fn){ - var ret = []; - - for (var i = 0, l = arr.length; i < l; i++) { - var val = arr[i]; - if (fn(val, i, arr)) ret.push(val); - } - - return ret; -}; - -/** - * Object.keys (<=IE8) - * - * @param {Object} obj - * @return {Array} keys - * @api private - */ - -exports.keys = Object.keys || function(obj) { - var keys = [] - , has = Object.prototype.hasOwnProperty // for `window` on <=IE8 - - for (var key in obj) { - if (has.call(obj, key)) { - keys.push(key); - } - } - - return keys; -}; - -/** - * Watch the given `files` for changes - * and invoke `fn(file)` on modification. - * - * @param {Array} files - * @param {Function} fn - * @api private - */ - -exports.watch = function(files, fn){ - var options = { interval: 100 }; - files.forEach(function(file){ - debug('file %s', file); - fs.watchFile(file, options, function(curr, prev){ - if (prev.mtime < curr.mtime) fn(file); - }); - }); -}; - -/** - * Ignored files. - */ - -function ignored(path){ - return !~ignore.indexOf(path); -} - -/** - * Lookup files in the given `dir`. - * - * @return {Array} - * @api private - */ - -exports.files = function(dir, ret){ - ret = ret || []; - - fs.readdirSync(dir) - .filter(ignored) - .forEach(function(path){ - path = join(dir, path); - if (fs.statSync(path).isDirectory()) { - exports.files(path, ret); - } else if (path.match(/\.(js|coffee)$/)) { - ret.push(path); - } - }); - - return ret; -}; - -/** - * Compute a slug from the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -exports.slug = function(str){ - return str - .toLowerCase() - .replace(/ +/g, '-') - .replace(/[^-\w]/g, ''); -}; - -/** - * Strip the function definition from `str`, - * and re-indent for pre whitespace. - */ - -exports.clean = function(str) { - str = str - .replace(/^function *\(.*\) *{/, '') - .replace(/\s+\}$/, ''); - - var spaces = str.match(/^\n?( *)/)[1].length - , re = new RegExp('^ {' + spaces + '}', 'gm'); - - str = str.replace(re, ''); - - return exports.trim(str); -}; - -/** - * Escape regular expression characters in `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -exports.escapeRegexp = function(str){ - return str.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&"); -}; - -/** - * Trim the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -exports.trim = function(str){ - return str.replace(/^\s+|\s+$/g, ''); -}; - -/** - * Parse the given `qs`. - * - * @param {String} qs - * @return {Object} - * @api private - */ - -exports.parseQuery = function(qs){ - return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair){ - var i = pair.indexOf('=') - , key = pair.slice(0, i) - , val = pair.slice(++i); - - obj[key] = decodeURIComponent(val); - return obj; - }, {}); -}; - -/** - * Highlight the given string of `js`. - * - * @param {String} js - * @return {String} - * @api private - */ - -function highlight(js) { - return js - .replace(//g, '>') - .replace(/\/\/(.*)/gm, '//$1') - .replace(/('.*?')/gm, '$1') - .replace(/(\d+\.\d+)/gm, '$1') - .replace(/(\d+)/gm, '$1') - .replace(/\bnew *(\w+)/gm, 'new $1') - .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '$1') -} - -/** - * Highlight the contents of tag `name`. - * - * @param {String} name - * @api private - */ - -exports.highlightTags = function(name) { - var code = document.getElementsByTagName(name); - for (var i = 0, len = code.length; i < len; ++i) { - code[i].innerHTML = highlight(code[i].innerHTML); - } -}; - -}); // module: utils.js -/** - * Node shims. - * - * These are meant only to allow - * blanket_mocha.js to run untouched, not - * to allow running node code in - * the browser. - */ - -process = {}; -process.exit = function(status){}; -process.stdout = {}; -global = window; - -/** - * next tick implementation. - */ - -process.nextTick = (function(){ - // postMessage behaves badly on IE8 - if (window.ActiveXObject || !window.postMessage) { - return function(fn){ fn() }; - } - - // based on setZeroTimeout by David Baron - // - http://dbaron.org/log/20100309-faster-timeouts - var timeouts = [] - , name = 'mocha-zero-timeout' - - window.addEventListener('message', function(e){ - if (e.source == window && e.data == name) { - if (e.stopPropagation) e.stopPropagation(); - if (timeouts.length) timeouts.shift()(); - } - }, true); - - return function(fn){ - timeouts.push(fn); - window.postMessage(name, '*'); - } -})(); - -/** - * Remove uncaughtException listener. - */ - -process.removeListener = function(e){ - if ('uncaughtException' == e) { - window.onerror = null; - } -}; - -/** - * Implements uncaughtException listener. - */ - -process.on = function(e, fn){ - if ('uncaughtException' == e) { - window.onerror = function(err, url, line){ - fn(new Error(err + ' (' + url + ':' + line + ')')); - }; - } -}; - -// boot -;(function(){ - - /** - * Expose mocha. - */ - - var Mocha = window.Mocha = require('mocha'), - mocha = window.mocha = new Mocha({ reporter: 'html' }); - - /** - * Override ui to ensure that the ui functions are initialized. - * Normally this would happen in Mocha.prototype.loadFiles. - */ - - mocha.ui = function(ui){ - Mocha.prototype.ui.call(this, ui); - this.suite.emit('pre-require', window, null, this); - return this; - }; - - /** - * Setup mocha with the given setting options. - */ - - mocha.setup = function(opts){ - if ('string' == typeof opts) opts = { ui: opts }; - for (var opt in opts) this[opt](opts[opt]); - return this; - }; - - /** - * Run mocha, returning the Runner. - */ - - mocha.run = function(fn){ - var options = mocha.options; - mocha.globals('location'); - - var query = Mocha.utils.parseQuery(window.location.search || ''); - if (query.grep) mocha.grep(query.grep); - if (query.invert) mocha.invert(); - - return Mocha.prototype.run.call(mocha, function(){ - Mocha.utils.highlightTags('code'); - if (fn) fn(); - }); - }; -})(); -})(); \ No newline at end of file diff --git a/tests/resources/js/should.js b/tests/resources/js/should.js deleted file mode 100644 index 4422bff..0000000 --- a/tests/resources/js/should.js +++ /dev/null @@ -1,4062 +0,0 @@ -/*! - * should - test framework agnostic BDD-style assertions - * @version v11.1.0 - * @author TJ Holowaychuk , Denis Bardadym and other contributors - * @link https://github.com/shouldjs/should.js - * @license MIT - */ - -(function (root) { - 'use strict'; - - var types = { - NUMBER: 'number', - UNDEFINED: 'undefined', - STRING: 'string', - BOOLEAN: 'boolean', - OBJECT: 'object', - FUNCTION: 'function', - NULL: 'null', - ARRAY: 'array', - REGEXP: 'regexp', - DATE: 'date', - ERROR: 'error', - ARGUMENTS: 'arguments', - SYMBOL: 'symbol', - ARRAY_BUFFER: 'array-buffer', - TYPED_ARRAY: 'typed-array', - DATA_VIEW: 'data-view', - MAP: 'map', - SET: 'set', - WEAK_SET: 'weak-set', - WEAK_MAP: 'weak-map', - PROMISE: 'promise', - - // node buffer - BUFFER: 'buffer', - - // dom html element - HTML_ELEMENT: 'html-element', - HTML_ELEMENT_TEXT: 'html-element-text', - DOCUMENT: 'document', - WINDOW: 'window', - FILE: 'file', - FILE_LIST: 'file-list', - BLOB: 'blob', - - HOST: 'host', - - XHR: 'xhr', - - // simd - SIMD: 'simd' - }; - - /* - * Simple data function to store type information - * @param {string} type Usually what is returned from typeof - * @param {string} cls Sanitized @Class via Object.prototype.toString - * @param {string} sub If type and cls the same, and need to specify somehow - * @private - * @example - * - * //for null - * new Type('null'); - * - * //for Date - * new Type('object', 'date'); - * - * //for Uint8Array - * - * new Type('object', 'typed-array', 'uint8'); - */ - function Type(type, cls, sub) { - if (!type) { - throw new Error('Type class must be initialized at least with `type` information'); - } - this.type = type; - this.cls = cls; - this.sub = sub; - } - - Type.prototype = { - toString: function(sep) { - sep = sep || ';'; - var str = [this.type]; - if (this.cls) { - str.push(this.cls); - } - if (this.sub) { - str.push(this.sub); - } - return str.join(sep); - }, - - toTryTypes: function() { - var _types = []; - if (this.sub) { - _types.push(new Type(this.type, this.cls, this.sub)); - } - if (this.cls) { - _types.push(new Type(this.type, this.cls)); - } - _types.push(new Type(this.type)); - - return _types; - } - }; - - var toString = Object.prototype.toString; - - - - /** - * Function to store type checks - * @private - */ - function TypeChecker() { - this.checks = []; - } - - TypeChecker.prototype = { - add: function(func) { - this.checks.push(func); - return this; - }, - - addBeforeFirstMatch: function(obj, func) { - var match = this.getFirstMatch(obj); - if (match) { - this.checks.splice(match.index, 0, func); - } else { - this.add(func); - } - }, - - addTypeOf: function(type, res) { - return this.add(function(obj, tpeOf) { - if (tpeOf === type) { - return new Type(res); - } - }); - }, - - addClass: function(cls, res, sub) { - return this.add(function(obj, tpeOf, objCls) { - if (objCls === cls) { - return new Type(types.OBJECT, res, sub); - } - }); - }, - - getFirstMatch: function(obj) { - var typeOf = typeof obj; - var cls = toString.call(obj); - - for (var i = 0, l = this.checks.length; i < l; i++) { - var res = this.checks[i].call(this, obj, typeOf, cls); - if (typeof res !== 'undefined') { - return { result: res, func: this.checks[i], index: i }; - } - } - }, - - getType: function(obj) { - var match = this.getFirstMatch(obj); - return match && match.result; - } - }; - - var main = new TypeChecker(); - - //TODO add iterators - - main - .addTypeOf(types.NUMBER, types.NUMBER) - .addTypeOf(types.UNDEFINED, types.UNDEFINED) - .addTypeOf(types.STRING, types.STRING) - .addTypeOf(types.BOOLEAN, types.BOOLEAN) - .addTypeOf(types.FUNCTION, types.FUNCTION) - .addTypeOf(types.SYMBOL, types.SYMBOL) - .add(function(obj) { - if (obj === null) { - return new Type(types.NULL); - } - }) - .addClass('[object String]', types.STRING) - .addClass('[object Boolean]', types.BOOLEAN) - .addClass('[object Number]', types.NUMBER) - .addClass('[object Array]', types.ARRAY) - .addClass('[object RegExp]', types.REGEXP) - .addClass('[object Error]', types.ERROR) - .addClass('[object Date]', types.DATE) - .addClass('[object Arguments]', types.ARGUMENTS) - - .addClass('[object ArrayBuffer]', types.ARRAY_BUFFER) - .addClass('[object Int8Array]', types.TYPED_ARRAY, 'int8') - .addClass('[object Uint8Array]', types.TYPED_ARRAY, 'uint8') - .addClass('[object Uint8ClampedArray]', types.TYPED_ARRAY, 'uint8clamped') - .addClass('[object Int16Array]', types.TYPED_ARRAY, 'int16') - .addClass('[object Uint16Array]', types.TYPED_ARRAY, 'uint16') - .addClass('[object Int32Array]', types.TYPED_ARRAY, 'int32') - .addClass('[object Uint32Array]', types.TYPED_ARRAY, 'uint32') - .addClass('[object Float32Array]', types.TYPED_ARRAY, 'float32') - .addClass('[object Float64Array]', types.TYPED_ARRAY, 'float64') - - .addClass('[object Bool16x8]', types.SIMD, 'bool16x8') - .addClass('[object Bool32x4]', types.SIMD, 'bool32x4') - .addClass('[object Bool8x16]', types.SIMD, 'bool8x16') - .addClass('[object Float32x4]', types.SIMD, 'float32x4') - .addClass('[object Int16x8]', types.SIMD, 'int16x8') - .addClass('[object Int32x4]', types.SIMD, 'int32x4') - .addClass('[object Int8x16]', types.SIMD, 'int8x16') - .addClass('[object Uint16x8]', types.SIMD, 'uint16x8') - .addClass('[object Uint32x4]', types.SIMD, 'uint32x4') - .addClass('[object Uint8x16]', types.SIMD, 'uint8x16') - - .addClass('[object DataView]', types.DATA_VIEW) - .addClass('[object Map]', types.MAP) - .addClass('[object WeakMap]', types.WEAK_MAP) - .addClass('[object Set]', types.SET) - .addClass('[object WeakSet]', types.WEAK_SET) - .addClass('[object Promise]', types.PROMISE) - .addClass('[object Blob]', types.BLOB) - .addClass('[object File]', types.FILE) - .addClass('[object FileList]', types.FILE_LIST) - .addClass('[object XMLHttpRequest]', types.XHR) - .add(function(obj) { - if ((typeof Promise === types.FUNCTION && obj instanceof Promise) || - (typeof obj.then === types.FUNCTION)) { - return new Type(types.OBJECT, types.PROMISE); - } - }) - .add(function(obj) { - if (typeof Buffer !== 'undefined' && obj instanceof Buffer) {// eslint-disable-line no-undef - return new Type(types.OBJECT, types.BUFFER); - } - }) - .add(function(obj) { - if (typeof Node !== 'undefined' && obj instanceof Node) { - return new Type(types.OBJECT, types.HTML_ELEMENT, obj.nodeName); - } - }) - .add(function(obj) { - // probably at the begginging should be enough these checks - if (obj.Boolean === Boolean && obj.Number === Number && obj.String === String && obj.Date === Date) { - return new Type(types.OBJECT, types.HOST); - } - }) - .add(function() { - return new Type(types.OBJECT); - }); - - /** - * Get type information of anything - * - * @param {any} obj Anything that could require type information - * @return {Type} type info - * @private - */ - function getGlobalType(obj) { - return main.getType(obj); - } - - getGlobalType.checker = main; - getGlobalType.TypeChecker = TypeChecker; - getGlobalType.Type = Type; - - Object.keys(types).forEach(function(typeName) { - getGlobalType[typeName] = types[typeName]; - }); - - function format$1(msg) { - var args = arguments; - for (var i = 1, l = args.length; i < l; i++) { - msg = msg.replace(/%s/, args[i]); - } - return msg; - } - - var hasOwnProperty = Object.prototype.hasOwnProperty; - - function EqualityFail(a, b, reason, path) { - this.a = a; - this.b = b; - this.reason = reason; - this.path = path; - } - - function typeToString(tp) { - return tp.type + (tp.cls ? '(' + tp.cls + (tp.sub ? ' ' + tp.sub : '') + ')' : ''); - } - - var PLUS_0_AND_MINUS_0 = '+0 is not equal to -0'; - var DIFFERENT_TYPES = 'A has type %s and B has type %s'; - var EQUALITY = 'A is not equal to B'; - var EQUALITY_PROTOTYPE = 'A and B have different prototypes'; - var WRAPPED_VALUE = 'A wrapped value is not equal to B wrapped value'; - var FUNCTION_SOURCES = 'function A is not equal to B by source code value (via .toString call)'; - var MISSING_KEY = '%s has no key %s'; - var SET_MAP_MISSING_KEY = 'Set/Map missing key %s'; - - - var DEFAULT_OPTIONS = { - checkProtoEql: true, - checkSubType: true, - plusZeroAndMinusZeroEqual: true, - collectAllFails: false - }; - - function setBooleanDefault(property, obj, opts, defaults) { - obj[property] = typeof opts[property] !== 'boolean' ? defaults[property] : opts[property]; - } - - var METHOD_PREFIX = '_check_'; - - function EQ(opts, a, b, path) { - opts = opts || {}; - - setBooleanDefault('checkProtoEql', this, opts, DEFAULT_OPTIONS); - setBooleanDefault('plusZeroAndMinusZeroEqual', this, opts, DEFAULT_OPTIONS); - setBooleanDefault('checkSubType', this, opts, DEFAULT_OPTIONS); - setBooleanDefault('collectAllFails', this, opts, DEFAULT_OPTIONS); - - this.a = a; - this.b = b; - - this._meet = opts._meet || []; - - this.fails = opts.fails || []; - - this.path = path || []; - } - - function ShortcutError(fail) { - this.name = 'ShortcutError'; - this.message = 'fail fast'; - this.fail = fail; - } - - ShortcutError.prototype = Object.create(Error.prototype); - - EQ.checkStrictEquality = function(a, b) { - this.collectFail(a !== b, EQUALITY); - }; - - EQ.add = function add(type, cls, sub, f) { - var args = Array.prototype.slice.call(arguments); - f = args.pop(); - EQ.prototype[METHOD_PREFIX + args.join('_')] = f; - }; - - EQ.prototype = { - check: function() { - try { - this.check0(); - } catch (e) { - if (e instanceof ShortcutError) { - return [e.fail]; - } - throw e; - } - return this.fails; - }, - - check0: function() { - var a = this.a; - var b = this.b; - - // equal a and b exit early - if (a === b) { - // check for +0 !== -0; - return this.collectFail(a === 0 && (1 / a !== 1 / b) && !this.plusZeroAndMinusZeroEqual, PLUS_0_AND_MINUS_0); - } - - var typeA = getGlobalType(a); - var typeB = getGlobalType(b); - - // if objects has different types they are not equal - if (typeA.type !== typeB.type || typeA.cls !== typeB.cls || typeA.sub !== typeB.sub) { - return this.collectFail(true, format$1(DIFFERENT_TYPES, typeToString(typeA), typeToString(typeB))); - } - - // as types the same checks type specific things - var name1 = typeA.type, name2 = typeA.type; - if (typeA.cls) { - name1 += '_' + typeA.cls; - name2 += '_' + typeA.cls; - } - if (typeA.sub) { - name2 += '_' + typeA.sub; - } - - var f = this[METHOD_PREFIX + name2] || this[METHOD_PREFIX + name1] || this[METHOD_PREFIX + typeA.type] || this.defaultCheck; - - f.call(this, this.a, this.b); - }, - - collectFail: function(comparison, reason, showReason) { - if (comparison) { - var res = new EqualityFail(this.a, this.b, reason, this.path); - res.showReason = !!showReason; - - this.fails.push(res); - - if (!this.collectAllFails) { - throw new ShortcutError(res); - } - } - }, - - checkPlainObjectsEquality: function(a, b) { - // compare deep objects and arrays - // stacks contain references only - // - var meet = this._meet; - var m = this._meet.length; - while (m--) { - var st = meet[m]; - if (st[0] === a && st[1] === b) { - return; - } - } - - // add `a` and `b` to the stack of traversed objects - meet.push([a, b]); - - // TODO maybe something else like getOwnPropertyNames - var key; - for (key in b) { - if (hasOwnProperty.call(b, key)) { - if (hasOwnProperty.call(a, key)) { - this.checkPropertyEquality(key); - } else { - this.collectFail(true, format$1(MISSING_KEY, 'A', key)); - } - } - } - - // ensure both objects have the same number of properties - for (key in a) { - if (hasOwnProperty.call(a, key)) { - this.collectFail(!hasOwnProperty.call(b, key), format$1(MISSING_KEY, 'B', key)); - } - } - - meet.pop(); - - if (this.checkProtoEql) { - //TODO should i check prototypes for === or use eq? - this.collectFail(Object.getPrototypeOf(a) !== Object.getPrototypeOf(b), EQUALITY_PROTOTYPE, true); - } - - }, - - checkPropertyEquality: function(propertyName) { - var _eq = new EQ(this, this.a[propertyName], this.b[propertyName], this.path.concat([propertyName])); - _eq.check0(); - }, - - defaultCheck: EQ.checkStrictEquality - }; - - - EQ.add(getGlobalType.NUMBER, function(a, b) { - this.collectFail((a !== a && b === b) || (b !== b && a === a) || (a !== b && a === a && b === b), EQUALITY); - }); - - [getGlobalType.SYMBOL, getGlobalType.BOOLEAN, getGlobalType.STRING].forEach(function(tp) { - EQ.add(tp, EQ.checkStrictEquality); - }); - - EQ.add(getGlobalType.FUNCTION, function(a, b) { - // functions are compared by their source code - this.collectFail(a.toString() !== b.toString(), FUNCTION_SOURCES); - // check user properties - this.checkPlainObjectsEquality(a, b); - }); - - EQ.add(getGlobalType.OBJECT, getGlobalType.REGEXP, function(a, b) { - // check regexp flags - var flags = ['source', 'global', 'multiline', 'lastIndex', 'ignoreCase', 'sticky', 'unicode']; - while (flags.length) { - this.checkPropertyEquality(flags.shift()); - } - // check user properties - this.checkPlainObjectsEquality(a, b); - }); - - EQ.add(getGlobalType.OBJECT, getGlobalType.DATE, function(a, b) { - //check by timestamp only (using .valueOf) - this.collectFail(+a !== +b, EQUALITY); - // check user properties - this.checkPlainObjectsEquality(a, b); - }); - - [getGlobalType.NUMBER, getGlobalType.BOOLEAN, getGlobalType.STRING].forEach(function(tp) { - EQ.add(getGlobalType.OBJECT, tp, function(a, b) { - //primitive type wrappers - this.collectFail(a.valueOf() !== b.valueOf(), WRAPPED_VALUE); - // check user properties - this.checkPlainObjectsEquality(a, b); - }); - }); - - EQ.add(getGlobalType.OBJECT, function(a, b) { - this.checkPlainObjectsEquality(a, b); - }); - - [getGlobalType.ARRAY, getGlobalType.ARGUMENTS, getGlobalType.TYPED_ARRAY].forEach(function(tp) { - EQ.add(getGlobalType.OBJECT, tp, function(a, b) { - this.checkPropertyEquality('length'); - - this.checkPlainObjectsEquality(a, b); - }); - }); - - EQ.add(getGlobalType.OBJECT, getGlobalType.ARRAY_BUFFER, function(a, b) { - this.checkPropertyEquality('byteLength'); - - this.checkPlainObjectsEquality(a, b); - }); - - EQ.add(getGlobalType.OBJECT, getGlobalType.ERROR, function(a, b) { - this.checkPropertyEquality('name'); - this.checkPropertyEquality('message'); - - this.checkPlainObjectsEquality(a, b); - }); - - EQ.add(getGlobalType.OBJECT, getGlobalType.BUFFER, function(a) { - this.checkPropertyEquality('length'); - - var l = a.length; - while (l--) { - this.checkPropertyEquality(l); - } - - //we do not check for user properties because - //node Buffer have some strange hidden properties - }); - - [getGlobalType.MAP, getGlobalType.SET, getGlobalType.WEAK_MAP, getGlobalType.WEAK_SET].forEach(function(tp) { - EQ.add(getGlobalType.OBJECT, tp, function(a, b) { - this._meet.push([a, b]); - - var iteratorA = a.entries(); - for (var nextA = iteratorA.next(); !nextA.done; nextA = iteratorA.next()) { - - var iteratorB = b.entries(); - var keyFound = false; - for (var nextB = iteratorB.next(); !nextB.done; nextB = iteratorB.next()) { - // try to check keys first - var r = eq(nextA.value[0], nextB.value[0], { collectAllFails: false, _meet: this._meet }); - - if (r.length === 0) { - keyFound = true; - - // check values also - eq(nextA.value[1], nextB.value[1], this); - } - } - - if (!keyFound) { - // no such key at all - this.collectFail(true, format$1(SET_MAP_MISSING_KEY, nextA.value[0])); - } - } - - this._meet.pop(); - - this.checkPlainObjectsEquality(a, b); - }); - }); - - - function eq(a, b, opts) { - return new EQ(opts, a, b).check(); - } - - eq.EQ = EQ; - - var _hasOwnProperty = Object.prototype.hasOwnProperty; - var _propertyIsEnumerable = Object.prototype.propertyIsEnumerable; - - function hasOwnProperty$1(obj, key) { - return _hasOwnProperty.call(obj, key); - } - - function propertyIsEnumerable(obj, key) { - return _propertyIsEnumerable.call(obj, key); - } - - function merge(a, b) { - if (a && b) { - for (var key in b) { - a[key] = b[key]; - } - } - return a; - } - - function isIterator(obj) { - if (!obj) { - return false; - } - - if (obj.__shouldIterator__) { - return true; - } - - return typeof obj.next === 'function' && - typeof Symbol === 'function' && - typeof Symbol.iterator === 'symbol' && - typeof obj[Symbol.iterator] === 'function' && - obj[Symbol.iterator]() === obj; - } - - //TODO find better way - function isGeneratorFunction(f) { - return typeof f === 'function' && /^function\s*\*\s*/.test(f.toString()); - } - - // TODO in future add generators instead of forEach and iterator implementation - - - function ObjectIterator(obj) { - this._obj = obj; - } - - ObjectIterator.prototype = { - __shouldIterator__: true, // special marker - - next: function() { - if (this._done) { - throw new Error('Iterator already reached the end'); - } - - if (!this._keys) { - this._keys = Object.keys(this._obj); - this._index = 0; - } - - var key = this._keys[this._index]; - this._done = this._index === this._keys.length; - this._index += 1; - - return { - value: this._done ? void 0: [key, this._obj[key]], - done: this._done - }; - } - }; - - if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') { - ObjectIterator.prototype[Symbol.iterator] = function() { - return this; - }; - } - - - function TypeAdaptorStorage() { - this._typeAdaptors = []; - this._iterableTypes = {}; - } - - TypeAdaptorStorage.prototype = { - add: function(type, cls, sub, adaptor) { - return this.addType(new getGlobalType.Type(type, cls, sub), adaptor); - }, - - addType: function(type, adaptor) { - this._typeAdaptors[type.toString()] = adaptor; - }, - - getAdaptor: function(tp, funcName) { - var tries = tp.toTryTypes(); - while (tries.length) { - var toTry = tries.shift(); - var ad = this._typeAdaptors[toTry]; - if (ad && ad[funcName]) { - return ad[funcName]; - } - } - }, - - requireAdaptor: function(tp, funcName) { - var a = this.getAdaptor(tp, funcName); - if (!a) { - throw new Error('There is no type adaptor `' + funcName + '` for ' + tp.toString()); - } - return a; - }, - - addIterableType: function(tp) { - this._iterableTypes[tp.toString()] = true; - }, - - isIterableType: function(tp) { - return !!this._iterableTypes[tp.toString()]; - } - }; - - var defaultTypeAdaptorStorage = new TypeAdaptorStorage(); - - // default for objects - defaultTypeAdaptorStorage.addType(new getGlobalType.Type(getGlobalType.OBJECT), { - forEach: function(obj, f, context) { - for (var prop in obj) { - if (hasOwnProperty$1(obj, prop) && propertyIsEnumerable(obj, prop)) { - if (f.call(context, obj[prop], prop, obj) === false) { - return; - } - } - } - }, - - has: function(obj, prop) { - return hasOwnProperty$1(obj, prop); - }, - - get: function(obj, prop) { - return obj[prop]; - }, - - iterator: function(obj) { - return new ObjectIterator(obj); - } - }); - - var mapAdaptor = { - has: function(obj, key) { - return obj.has(key); - }, - - get: function(obj, key) { - return obj.get(key); - }, - - forEach: function(obj, f, context) { - var iter = obj.entries(); - forEach(iter, function(value) { - return f.call(context, value[1], value[0], obj); - }); - }, - - size: function(obj) { - return obj.size; - }, - - isEmpty: function(obj) { - return obj.size === 0; - }, - - iterator: function(obj) { - return obj.entries(); - } - }; - - var setAdaptor = merge({}, mapAdaptor); - setAdaptor.get = function(obj, key) { - if (obj.has(key)) { - return key; - } - }; - - defaultTypeAdaptorStorage.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.MAP), mapAdaptor); - defaultTypeAdaptorStorage.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.SET), setAdaptor); - defaultTypeAdaptorStorage.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.WEAK_SET), setAdaptor); - defaultTypeAdaptorStorage.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.WEAK_MAP), mapAdaptor); - - defaultTypeAdaptorStorage.addType(new getGlobalType.Type(getGlobalType.STRING), { - isEmpty: function(obj) { - return obj === ''; - }, - - size: function(obj) { - return obj.length; - } - }); - - defaultTypeAdaptorStorage.addIterableType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.ARRAY)); - defaultTypeAdaptorStorage.addIterableType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.ARGUMENTS)); - - function forEach(obj, f, context) { - if (isGeneratorFunction(obj)) { - return forEach(obj(), f, context); - } else if (isIterator(obj)) { - var value = obj.next(); - while (!value.done) { - if (f.call(context, value.value, 'value', obj) === false) { - return; - } - value = obj.next(); - } - } else { - var type = getGlobalType(obj); - var func = defaultTypeAdaptorStorage.requireAdaptor(type, 'forEach'); - func(obj, f, context); - } - } - - - function size(obj) { - var type = getGlobalType(obj); - var func = defaultTypeAdaptorStorage.getAdaptor(type, 'size'); - if (func) { - return func(obj); - } else { - var len = 0; - forEach(obj, function() { - len += 1; - }); - return len; - } - } - - function isEmpty(obj) { - var type = getGlobalType(obj); - var func = defaultTypeAdaptorStorage.getAdaptor(type, 'isEmpty'); - if (func) { - return func(obj); - } else { - var res = true; - forEach(obj, function() { - res = false; - return false; - }); - return res; - } - } - - // return boolean if obj has such 'key' - function has(obj, key) { - var type = getGlobalType(obj); - var func = defaultTypeAdaptorStorage.requireAdaptor(type, 'has'); - return func(obj, key); - } - - // return value for given key - function get(obj, key) { - var type = getGlobalType(obj); - var func = defaultTypeAdaptorStorage.requireAdaptor(type, 'get'); - return func(obj, key); - } - - function some(obj, f, context) { - var res = false; - forEach(obj, function(value, key) { - if (f.call(context, value, key, obj)) { - res = true; - return false; - } - }, context); - return res; - } - - function isIterable(obj) { - return defaultTypeAdaptorStorage.isIterableType(getGlobalType(obj)); - } - - function iterator(obj) { - return defaultTypeAdaptorStorage.requireAdaptor(getGlobalType(obj), 'iterator')(obj); - } - - function looksLikeANumber(n) { - return !!n.match(/\d+/); - } - - function keyCompare(a, b) { - var aNum = looksLikeANumber(a); - var bNum = looksLikeANumber(b); - if (aNum && bNum) { - return 1*a - 1*b; - } else if (aNum && !bNum) { - return -1; - } else if (!aNum && bNum) { - return 1; - } else { - return a.localeCompare(b); - } - } - - function genKeysFunc(f) { - return function(value) { - var k = f(value); - k.sort(keyCompare); - return k; - }; - } - - function Formatter(opts) { - opts = opts || {}; - - this.seen = []; - - var keysFunc; - if (typeof opts.keysFunc === 'function') { - keysFunc = opts.keysFunc; - } else if (opts.keys === false) { - keysFunc = Object.getOwnPropertyNames; - } else { - keysFunc = Object.keys; - } - - this.getKeys = genKeysFunc(keysFunc); - - this.maxLineLength = typeof opts.maxLineLength === 'number' ? opts.maxLineLength : 60; - this.propSep = opts.propSep || ','; - - this.isUTCdate = !!opts.isUTCdate; - } - - - - Formatter.prototype = { - constructor: Formatter, - - format: function(value) { - var tp = getGlobalType(value); - - if (tp.type === getGlobalType.OBJECT && this.alreadySeen(value)) { - return '[Circular]'; - } - - var tries = tp.toTryTypes(); - var f = this.defaultFormat; - while (tries.length) { - var toTry = tries.shift(); - var name = Formatter.formatterFunctionName(toTry); - if (this[name]) { - f = this[name]; - break; - } - } - return f.call(this, value).trim(); - }, - - defaultFormat: function(obj) { - return String(obj); - }, - - alreadySeen: function(value) { - return this.seen.indexOf(value) >= 0; - } - - }; - - Formatter.addType = function addType(tp, f) { - Formatter.prototype[Formatter.formatterFunctionName(tp)] = f; - }; - - Formatter.formatterFunctionName = function formatterFunctionName(tp) { - return '_format_' + tp.toString('_'); - }; - - var EOL = '\n'; - - function indent$1(v, indentation) { - return v - .split(EOL) - .map(function(vv) { - return indentation + vv; - }) - .join(EOL); - } - - function pad(str, value, filler) { - str = String(str); - var isRight = false; - - if (value < 0) { - isRight = true; - value = -value; - } - - if (str.length < value) { - var padding = new Array(value - str.length + 1).join(filler); - return isRight ? str + padding : padding + str; - } else { - return str; - } - } - - function pad0(str, value) { - return pad(str, value, '0'); - } - - var functionNameRE = /^\s*function\s*(\S*)\s*\(/; - - function functionName$1(f) { - if (f.name) { - return f.name; - } - var matches = f.toString().match(functionNameRE); - if (matches === null) { - // `functionNameRE` doesn't match arrow functions. - return ''; - } - var name = matches[1]; - return name; - } - - function constructorName(obj) { - while (obj) { - var descriptor = Object.getOwnPropertyDescriptor(obj, 'constructor'); - if (descriptor !== undefined && typeof descriptor.value === 'function') { - var name = functionName$1(descriptor.value); - if (name !== '') { - return name; - } - } - - obj = Object.getPrototypeOf(obj); - } - } - - var INDENT = ' '; - - function addSpaces(str) { - return indent$1(str, INDENT); - } - - function typeAdaptorForEachFormat(obj, opts) { - opts = opts || {}; - var filterKey = opts.filterKey || function() { return true; }; - - var formatKey = opts.formatKey || this.format; - var formatValue = opts.formatValue || this.format; - - var keyValueSep = typeof opts.keyValueSep !== 'undefined' ? opts.keyValueSep : ': '; - - this.seen.push(obj); - - var formatLength = 0; - var pairs = []; - - forEach(obj, function(value, key) { - if (!filterKey(key)) { - return; - } - - var formattedKey = formatKey.call(this, key); - var formattedValue = formatValue.call(this, value, key); - - var pair = formattedKey ? (formattedKey + keyValueSep + formattedValue) : formattedValue; - - formatLength += pair.length; - pairs.push(pair); - }, this); - - this.seen.pop(); - - (opts.additionalKeys || []).forEach(function(keyValue) { - var pair = keyValue[0] + keyValueSep + this.format(keyValue[1]); - formatLength += pair.length; - pairs.push(pair); - }, this); - - var prefix = opts.prefix || constructorName(obj) || ''; - if (prefix.length > 0) { - prefix += ' '; - } - - var lbracket, rbracket; - if (Array.isArray(opts.brackets)) { - lbracket = opts.brackets[0]; - rbracket = opts.brackets[1]; - } else { - lbracket = '{'; - rbracket = '}'; - } - - var rootValue = opts.value || ''; - - if (pairs.length === 0) { - return rootValue || (prefix + lbracket + rbracket); - } - - if (formatLength <= this.maxLineLength) { - return prefix + lbracket + ' ' + (rootValue ? rootValue + ' ' : '') + pairs.join(this.propSep + ' ') + ' ' + rbracket; - } else { - return prefix + lbracket + '\n' + (rootValue ? ' ' + rootValue + '\n' : '') + pairs.map(addSpaces).join(this.propSep + '\n') + '\n' + rbracket; - } - } - - function formatPlainObjectKey(key) { - return typeof key === 'string' && key.match(/^[a-zA-Z_$][a-zA-Z_$0-9]*$/) ? key : this.format(key); - } - - function getPropertyDescriptor(obj, key) { - var desc; - try { - desc = Object.getOwnPropertyDescriptor(obj, key) || { value: obj[key] }; - } catch (e) { - desc = { value: e }; - } - return desc; - } - - function formatPlainObjectValue(obj, key) { - var desc = getPropertyDescriptor(obj, key); - if (desc.get && desc.set) { - return '[Getter/Setter]'; - } - if (desc.get) { - return '[Getter]'; - } - if (desc.set) { - return '[Setter]'; - } - - return this.format(desc.value); - } - - function formatPlainObject(obj, opts) { - opts = opts || {}; - opts.keyValueSep = ': '; - opts.formatKey = opts.formatKey || formatPlainObjectKey; - opts.formatValue = opts.formatValue || function(value, key) { - return formatPlainObjectValue.call(this, obj, key); - }; - return typeAdaptorForEachFormat.call(this, obj, opts); - } - - function formatWrapper1(value) { - return formatPlainObject.call(this, value, { - additionalKeys: [['[[PrimitiveValue]]', value.valueOf()]] - }); - } - - - function formatWrapper2(value) { - var realValue = value.valueOf(); - - return formatPlainObject.call(this, value, { - filterKey: function(key) { - //skip useless indexed properties - return !(key.match(/\d+/) && parseInt(key, 10) < realValue.length); - }, - additionalKeys: [['[[PrimitiveValue]]', realValue]] - }); - } - - function formatRegExp(value) { - return formatPlainObject.call(this, value, { - value: String(value) - }); - } - - function formatFunction(value) { - var obj = {}; - Object.keys(value).forEach(function(key) { - obj[key] = value[key]; - }); - return formatPlainObject.call(this, obj, { - prefix: 'Function', - additionalKeys: [['name', functionName$1(value)]] - }); - } - - function formatArray(value) { - return formatPlainObject.call(this, value, { - formatKey: function(key) { - if (!key.match(/\d+/)) { - return formatPlainObjectKey.call(this, key); - } - }, - brackets: ['[', ']'] - }); - } - - function formatArguments(value) { - return formatPlainObject.call(this, value, { - formatKey: function(key) { - if (!key.match(/\d+/)) { - return formatPlainObjectKey.call(this, key); - } - }, - brackets: ['[', ']'], - prefix: 'Arguments' - }); - } - - function _formatDate(value, isUTC) { - var prefix = isUTC ? 'UTC' : ''; - - var date = value['get' + prefix + 'FullYear']() + - '-' + - pad0(value['get' + prefix + 'Month']() + 1, 2) + - '-' + - pad0(value['get' + prefix + 'Date'](), 2); - - var time = pad0(value['get' + prefix + 'Hours'](), 2) + - ':' + - pad0(value['get' + prefix + 'Minutes'](), 2) + - ':' + - pad0(value['get' + prefix + 'Seconds'](), 2) + - '.' + - pad0(value['get' + prefix + 'Milliseconds'](), 3); - - var to = value.getTimezoneOffset(); - var absTo = Math.abs(to); - var hours = Math.floor(absTo / 60); - var minutes = absTo - hours * 60; - var tzFormat = (to < 0 ? '+' : '-') + pad0(hours, 2) + pad0(minutes, 2); - - return date + ' ' + time + (isUTC ? '' : ' ' + tzFormat); - } - - function formatDate(value) { - return formatPlainObject.call(this, value, { value: _formatDate(value, this.isUTCdate) }); - } - - function formatError(value) { - return formatPlainObject.call(this, value, { - prefix: value.name, - additionalKeys: [['message', value.message]] - }); - } - - function generateFormatForNumberArray(lengthProp, name, padding) { - return function(value) { - var max = this.byteArrayMaxLength || 50; - var length = value[lengthProp]; - var formattedValues = []; - var len = 0; - for (var i = 0; i < max && i < length; i++) { - var b = value[i] || 0; - var v = pad0(b.toString(16), padding); - len += v.length; - formattedValues.push(v); - } - var prefix = value.constructor.name || name || ''; - if (prefix) { - prefix += ' '; - } - - if (formattedValues.length === 0) { - return prefix + '[]'; - } - - if (len <= this.maxLineLength) { - return prefix + '[ ' + formattedValues.join(this.propSep + ' ') + ' ' + ']'; - } else { - return prefix + '[\n' + formattedValues.map(addSpaces).join(this.propSep + '\n') + '\n' + ']'; - } - }; - } - - function formatMap(obj) { - return typeAdaptorForEachFormat.call(this, obj, { - keyValueSep: ' => ' - }); - } - - function formatSet(obj) { - return typeAdaptorForEachFormat.call(this, obj, { - keyValueSep: '', - formatKey: function() { return ''; } - }); - } - - function genSimdVectorFormat(constructorName, length) { - return function(value) { - var Constructor = value.constructor; - var extractLane = Constructor.extractLane; - - var len = 0; - var props = []; - - for (var i = 0; i < length; i ++) { - var key = this.format(extractLane(value, i)); - len += key.length; - props.push(key); - } - - if (len <= this.maxLineLength) { - return constructorName + ' [ ' + props.join(this.propSep + ' ') + ' ]'; - } else { - return constructorName + ' [\n' + props.map(addSpaces).join(this.propSep + '\n') + '\n' + ']'; - } - }; - } - - function defaultFormat(value, opts) { - return new Formatter(opts).format(value); - } - - defaultFormat.Formatter = Formatter; - defaultFormat.addSpaces = addSpaces; - defaultFormat.pad0 = pad0; - defaultFormat.functionName = functionName$1; - defaultFormat.constructorName = constructorName; - defaultFormat.formatPlainObjectKey = formatPlainObjectKey; - defaultFormat.typeAdaptorForEachFormat = typeAdaptorForEachFormat; - // adding primitive types - Formatter.addType(new getGlobalType.Type(getGlobalType.UNDEFINED), function() { - return 'undefined'; - }); - Formatter.addType(new getGlobalType.Type(getGlobalType.NULL), function() { - return 'null'; - }); - Formatter.addType(new getGlobalType.Type(getGlobalType.BOOLEAN), function(value) { - return value ? 'true': 'false'; - }); - Formatter.addType(new getGlobalType.Type(getGlobalType.SYMBOL), function(value) { - return value.toString(); - }); - Formatter.addType(new getGlobalType.Type(getGlobalType.NUMBER), function(value) { - if (value === 0 && 1 / value < 0) { - return '-0'; - } - return String(value); - }); - - Formatter.addType(new getGlobalType.Type(getGlobalType.STRING), function(value) { - return '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - }); - - Formatter.addType(new getGlobalType.Type(getGlobalType.FUNCTION), formatFunction); - - // plain object - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT), formatPlainObject); - - // type wrappers - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.NUMBER), formatWrapper1); - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.BOOLEAN), formatWrapper1); - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.STRING), formatWrapper2); - - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.REGEXP), formatRegExp); - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.ARRAY), formatArray); - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.ARGUMENTS), formatArguments); - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.DATE), formatDate); - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.ERROR), formatError); - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.SET), formatSet); - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.MAP), formatMap); - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.WEAK_MAP), formatMap); - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.WEAK_SET), formatSet); - - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.BUFFER), generateFormatForNumberArray('length', 'Buffer', 2)); - - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.ARRAY_BUFFER), generateFormatForNumberArray('byteLength', 'ArrayBuffer', 2)); - - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.TYPED_ARRAY, 'int8'), generateFormatForNumberArray('length', 'Int8Array', 2)); - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.TYPED_ARRAY, 'uint8'), generateFormatForNumberArray('length', 'Uint8Array', 2)); - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.TYPED_ARRAY, 'uint8clamped'), generateFormatForNumberArray('length', 'Uint8ClampedArray', 2)); - - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.TYPED_ARRAY, 'int16'), generateFormatForNumberArray('length', 'Int16Array', 4)); - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.TYPED_ARRAY, 'uint16'), generateFormatForNumberArray('length', 'Uint16Array', 4)); - - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.TYPED_ARRAY, 'int32'), generateFormatForNumberArray('length', 'Int32Array', 8)); - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.TYPED_ARRAY, 'uint32'), generateFormatForNumberArray('length', 'Uint32Array', 8)); - - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.SIMD, 'bool16x8'), genSimdVectorFormat('Bool16x8', 8)); - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.SIMD, 'bool32x4'), genSimdVectorFormat('Bool32x4', 4)); - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.SIMD, 'bool8x16'), genSimdVectorFormat('Bool8x16', 16)); - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.SIMD, 'float32x4'), genSimdVectorFormat('Float32x4', 4)); - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.SIMD, 'int16x8'), genSimdVectorFormat('Int16x8', 8)); - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.SIMD, 'int32x4'), genSimdVectorFormat('Int32x4', 4)); - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.SIMD, 'int8x16'), genSimdVectorFormat('Int8x16', 16)); - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.SIMD, 'uint16x8'), genSimdVectorFormat('Uint16x8', 8)); - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.SIMD, 'uint32x4'), genSimdVectorFormat('Uint32x4', 4)); - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.SIMD, 'uint8x16'), genSimdVectorFormat('Uint8x16', 16)); - - - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.PROMISE), function() { - return '[Promise]';//TODO it could be nice to inspect its state and value - }); - - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.XHR), function() { - return '[XMLHttpRequest]';//TODO it could be nice to inspect its state - }); - - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.HTML_ELEMENT), function(value) { - return value.outerHTML; - }); - - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.HTML_ELEMENT, '#text'), function(value) { - return value.nodeValue; - }); - - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.HTML_ELEMENT, '#document'), function(value) { - return value.documentElement.outerHTML; - }); - - Formatter.addType(new getGlobalType.Type(getGlobalType.OBJECT, getGlobalType.HOST), function() { - return '[Host]'; - }); - - function isWrapperType(obj) { - return obj instanceof Number || - obj instanceof String || - obj instanceof Boolean; - } - - function convertPropertyName(name) { - return (typeof name === 'symbol') ? name : String(name); - } - - var functionName = defaultFormat.functionName; - - var config = { - typeAdaptors: defaultTypeAdaptorStorage, - - getFormatter: function(opts) { - return new defaultFormat.Formatter(opts || config); - } - }; - - function format(value, opts) { - return config.getFormatter(opts).format(value); - } - - function formatProp(value) { - var formatter = config.getFormatter(); - return defaultFormat.formatPlainObjectKey.call(formatter, value); - } - - /** - * should AssertionError - * @param {Object} options - * @constructor - * @memberOf should - * @static - */ - function AssertionError(options) { - merge(this, options); - - if (!options.message) { - Object.defineProperty(this, 'message', { - get: function() { - if (!this._message) { - this._message = this.generateMessage(); - this.generatedMessage = true; - } - return this._message; - }, - configurable: true, - enumerable: false - } - ); - } - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.stackStartFunction); - } else { - // non v8 browsers so we can have a stacktrace - var err = new Error(); - if (err.stack) { - var out = err.stack; - - if (this.stackStartFunction) { - // try to strip useless frames - var fn_name = functionName(this.stackStartFunction); - var idx = out.indexOf('\n' + fn_name); - if (idx >= 0) { - // once we have located the function frame - // we need to strip out everything before it (and its line) - var next_line = out.indexOf('\n', idx + 1); - out = out.substring(next_line + 1); - } - } - - this.stack = out; - } - } - } - - - var indent = ' '; - function prependIndent(line) { - return indent + line; - } - - function indentLines(text) { - return text.split('\n').map(prependIndent).join('\n'); - } - - - // assert.AssertionError instanceof Error - AssertionError.prototype = Object.create(Error.prototype, { - name: { - value: 'AssertionError' - }, - - generateMessage: { - value: function() { - if (!this.operator && this.previous) { - return this.previous.message; - } - var actual = format(this.actual); - var expected = 'expected' in this ? ' ' + format(this.expected) : ''; - var details = 'details' in this && this.details ? ' (' + this.details + ')' : ''; - - var previous = this.previous ? '\n' + indentLines(this.previous.message) : ''; - - return 'expected ' + actual + (this.negate ? ' not ' : ' ') + this.operator + expected + details + previous; - } - } - }); - - /** - * should Assertion - * @param {*} obj Given object for assertion - * @constructor - * @memberOf should - * @static - */ - function Assertion(obj) { - this.obj = obj; - - this.anyOne = false; - this.negate = false; - - this.params = {actual: obj}; - } - - Assertion.prototype = { - constructor: Assertion, - - /** - * Base method for assertions. - * - * Before calling this method need to fill Assertion#params object. This method usually called from other assertion methods. - * `Assertion#params` can contain such properties: - * * `operator` - required string containing description of this assertion - * * `obj` - optional replacement for this.obj, it usefull if you prepare more clear object then given - * * `message` - if this property filled with string any others will be ignored and this one used as assertion message - * * `expected` - any object used when you need to assert relation between given object and expected. Like given == expected (== is a relation) - * * `details` - additional string with details to generated message - * - * @memberOf Assertion - * @category assertion - * @param {*} expr Any expression that will be used as a condition for asserting. - * @example - * - * var a = new should.Assertion(42); - * - * a.params = { - * operator: 'to be magic number', - * } - * - * a.assert(false); - * //throws AssertionError: expected 42 to be magic number - */ - assert: function(expr) { - if (expr) { - return this; - } - - var params = this.params; - - if ('obj' in params && !('actual' in params)) { - params.actual = params.obj; - } else if (!('obj' in params) && !('actual' in params)) { - params.actual = this.obj; - } - - params.stackStartFunction = params.stackStartFunction || this.assert; - params.negate = this.negate; - - params.assertion = this; - - throw new AssertionError(params); - }, - - /** - * Shortcut for `Assertion#assert(false)`. - * - * @memberOf Assertion - * @category assertion - * @example - * - * var a = new should.Assertion(42); - * - * a.params = { - * operator: 'to be magic number', - * } - * - * a.fail(); - * //throws AssertionError: expected 42 to be magic number - */ - fail: function() { - return this.assert(false); - } - }; - - - - /** - * Assertion used to delegate calls of Assertion methods inside of Promise. - * It has almost all methods of Assertion.prototype - * - * @param {Promise} obj - */ - function PromisedAssertion(/* obj */) { - Assertion.apply(this, arguments); - } - - /** - * Make PromisedAssertion to look like promise. Delegate resolve and reject to given promise. - * - * @private - * @returns {Promise} - */ - PromisedAssertion.prototype.then = function(resolve, reject) { - return this.obj.then(resolve, reject); - }; - - /** - * Way to extend Assertion function. It uses some logic - * to define only positive assertions and itself rule with negative assertion. - * - * All actions happen in subcontext and this method take care about negation. - * Potentially we can add some more modifiers that does not depends from state of assertion. - * - * @memberOf Assertion - * @static - * @param {String} name Name of assertion. It will be used for defining method or getter on Assertion.prototype - * @param {Function} func Function that will be called on executing assertion - * @example - * - * Assertion.add('asset', function() { - * this.params = { operator: 'to be asset' } - * - * this.obj.should.have.property('id').which.is.a.Number() - * this.obj.should.have.property('path') - * }) - */ - Assertion.add = function(name, func) { - Object.defineProperty(Assertion.prototype, name, { - enumerable: true, - configurable: true, - value: function() { - var context = new Assertion(this.obj, this, name); - context.anyOne = this.anyOne; - - try { - func.apply(context, arguments); - } catch (e) { - // check for fail - if (e instanceof AssertionError) { - // negative fail - if (this.negate) { - this.obj = context.obj; - this.negate = false; - return this; - } - - if (context !== e.assertion) { - context.params.previous = e; - } - - // positive fail - context.negate = false; - context.fail(); - } - // throw if it is another exception - throw e; - } - - // negative pass - if (this.negate) { - context.negate = true; // because .fail will set negate - context.params.details = 'false negative fail'; - context.fail(); - } - - // positive pass - if (!this.params.operator) { - this.params = context.params; // shortcut - } - this.obj = context.obj; - this.negate = false; - return this; - } - }); - - Object.defineProperty(PromisedAssertion.prototype, name, { - enumerable: true, - configurable: true, - value: function() { - var args = arguments; - this.obj = this.obj.then(function(a) { - return a[name].apply(a, args); - }); - - return this; - } - }); - }; - - /** - * Add chaining getter to Assertion like .a, .which etc - * - * @memberOf Assertion - * @static - * @param {string} name name of getter - * @param {function} [onCall] optional function to call - */ - Assertion.addChain = function(name, onCall) { - onCall = onCall || function() {}; - Object.defineProperty(Assertion.prototype, name, { - get: function() { - onCall.call(this); - return this; - }, - enumerable: true - }); - - Object.defineProperty(PromisedAssertion.prototype, name, { - enumerable: true, - configurable: true, - get: function() { - this.obj = this.obj.then(function(a) { - return a[name]; - }); - - return this; - } - }); - }; - - /** - * Create alias for some `Assertion` property - * - * @memberOf Assertion - * @static - * @param {String} from Name of to map - * @param {String} to Name of alias - * @example - * - * Assertion.alias('true', 'True') - */ - Assertion.alias = function(from, to) { - var desc = Object.getOwnPropertyDescriptor(Assertion.prototype, from); - if (!desc) { - throw new Error('Alias ' + from + ' -> ' + to + ' could not be created as ' + from + ' not defined'); - } - Object.defineProperty(Assertion.prototype, to, desc); - - var desc2 = Object.getOwnPropertyDescriptor(PromisedAssertion.prototype, from); - if (desc2) { - Object.defineProperty(PromisedAssertion.prototype, to, desc2); - } - }; - /** - * Negation modifier. Current assertion chain become negated. Each call invert negation on current assertion. - * - * @name not - * @property - * @memberOf Assertion - * @category assertion - */ - Assertion.addChain('not', function() { - this.negate = !this.negate; - }); - - /** - * Any modifier - it affect on execution of sequenced assertion to do not `check all`, but `check any of`. - * - * @name any - * @property - * @memberOf Assertion - * @category assertion - */ - Assertion.addChain('any', function() { - this.anyOne = true; - }); - - var pSlice = Array.prototype.slice; - - // 1. The assert module provides functions that throw - // AssertionError's when particular conditions are not met. The - // assert module must conform to the following interface. - - var assert = ok; - // 3. All of the following functions must throw an AssertionError - // when a corresponding condition is not met, with a message that - // may be undefined if not provided. All assertion methods provide - // both the actual and expected values to the assertion error for - // display purposes. - /** - * Node.js standard [`assert.fail`](http://nodejs.org/api/assert.html#assert_assert_fail_actual_expected_message_operator). - * @static - * @memberOf should - * @category assertion assert - * @param {*} actual Actual object - * @param {*} expected Expected object - * @param {string} message Message for assertion - * @param {string} operator Operator text - */ - function fail(actual, expected, message, operator, stackStartFunction) { - var a = new Assertion(actual); - a.params = { - operator: operator, - expected: expected, - message: message, - stackStartFunction: stackStartFunction || fail - }; - - a.fail(); - } - - // EXTENSION! allows for well behaved errors defined elsewhere. - assert.fail = fail; - - // 4. Pure assertion tests whether a value is truthy, as determined - // by !!guard. - // assert.ok(guard, message_opt); - // This statement is equivalent to assert.equal(true, !!guard, - // message_opt);. To test strictly for the value true, use - // assert.strictEqual(true, guard, message_opt);. - /** - * Node.js standard [`assert.ok`](http://nodejs.org/api/assert.html#assert_assert_value_message_assert_ok_value_message). - * @static - * @memberOf should - * @category assertion assert - * @param {*} value - * @param {string} [message] - */ - function ok(value, message) { - if (!value) { - fail(value, true, message, '==', assert.ok); - } - } - assert.ok = ok; - - // 5. The equality assertion tests shallow, coercive equality with - // ==. - // assert.equal(actual, expected, message_opt); - - /** - * Node.js standard [`assert.equal`](http://nodejs.org/api/assert.html#assert_assert_equal_actual_expected_message). - * @static - * @memberOf should - * @category assertion assert - * @param {*} actual - * @param {*} expected - * @param {string} [message] - */ - assert.equal = function equal(actual, expected, message) { - if (actual != expected) { - fail(actual, expected, message, '==', assert.equal); - } - }; - - // 6. The non-equality assertion tests for whether two objects are not equal - // with != assert.notEqual(actual, expected, message_opt); - /** - * Node.js standard [`assert.notEqual`](http://nodejs.org/api/assert.html#assert_assert_notequal_actual_expected_message). - * @static - * @memberOf should - * @category assertion assert - * @param {*} actual - * @param {*} expected - * @param {string} [message] - */ - assert.notEqual = function notEqual(actual, expected, message) { - if (actual == expected) { - fail(actual, expected, message, '!=', assert.notEqual); - } - }; - - // 7. The equivalence assertion tests a deep equality relation. - // assert.deepEqual(actual, expected, message_opt); - /** - * Node.js standard [`assert.deepEqual`](http://nodejs.org/api/assert.html#assert_assert_deepequal_actual_expected_message). - * But uses should.js .eql implementation instead of Node.js own deepEqual. - * - * @static - * @memberOf should - * @category assertion assert - * @param {*} actual - * @param {*} expected - * @param {string} [message] - */ - assert.deepEqual = function deepEqual(actual, expected, message) { - if (eq(actual, expected).length !== 0) { - fail(actual, expected, message, 'deepEqual', assert.deepEqual); - } - }; - - - // 8. The non-equivalence assertion tests for any deep inequality. - // assert.notDeepEqual(actual, expected, message_opt); - /** - * Node.js standard [`assert.notDeepEqual`](http://nodejs.org/api/assert.html#assert_assert_notdeepequal_actual_expected_message). - * But uses should.js .eql implementation instead of Node.js own deepEqual. - * - * @static - * @memberOf should - * @category assertion assert - * @param {*} actual - * @param {*} expected - * @param {string} [message] - */ - assert.notDeepEqual = function notDeepEqual(actual, expected, message) { - if (eq(actual, expected).result) { - fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); - } - }; - - // 9. The strict equality assertion tests strict equality, as determined by ===. - // assert.strictEqual(actual, expected, message_opt); - /** - * Node.js standard [`assert.strictEqual`](http://nodejs.org/api/assert.html#assert_assert_strictequal_actual_expected_message). - * @static - * @memberOf should - * @category assertion assert - * @param {*} actual - * @param {*} expected - * @param {string} [message] - */ - assert.strictEqual = function strictEqual(actual, expected, message) { - if (actual !== expected) { - fail(actual, expected, message, '===', assert.strictEqual); - } - }; - - // 10. The strict non-equality assertion tests for strict inequality, as - // determined by !==. assert.notStrictEqual(actual, expected, message_opt); - /** - * Node.js standard [`assert.notStrictEqual`](http://nodejs.org/api/assert.html#assert_assert_notstrictequal_actual_expected_message). - * @static - * @memberOf should - * @category assertion assert - * @param {*} actual - * @param {*} expected - * @param {string} [message] - */ - assert.notStrictEqual = function notStrictEqual(actual, expected, message) { - if (actual === expected) { - fail(actual, expected, message, '!==', assert.notStrictEqual); - } - }; - - function expectedException(actual, expected) { - if (!actual || !expected) { - return false; - } - - if (Object.prototype.toString.call(expected) == '[object RegExp]') { - return expected.test(actual); - } else if (actual instanceof expected) { - return true; - } else if (expected.call({}, actual) === true) { - return true; - } - - return false; - } - - function _throws(shouldThrow, block, expected, message) { - var actual; - - if (typeof expected == 'string') { - message = expected; - expected = null; - } - - try { - block(); - } catch (e) { - actual = e; - } - - message = (expected && expected.name ? ' (' + expected.name + ')' : '.') + - (message ? ' ' + message : '.'); - - if (shouldThrow && !actual) { - fail(actual, expected, 'Missing expected exception' + message); - } - - if (!shouldThrow && expectedException(actual, expected)) { - fail(actual, expected, 'Got unwanted exception' + message); - } - - if ((shouldThrow && actual && expected && !expectedException(actual, expected)) || (!shouldThrow && actual)) { - throw actual; - } - } - - // 11. Expected to throw an error: - // assert.throws(block, Error_opt, message_opt); - /** - * Node.js standard [`assert.throws`](http://nodejs.org/api/assert.html#assert_assert_throws_block_error_message). - * @static - * @memberOf should - * @category assertion assert - * @param {Function} block - * @param {Function} [error] - * @param {String} [message] - */ - assert.throws = function(/*block, error, message*/) { - _throws.apply(this, [true].concat(pSlice.call(arguments))); - }; - - // EXTENSION! This is annoying to write outside this module. - /** - * Node.js standard [`assert.doesNotThrow`](http://nodejs.org/api/assert.html#assert_assert_doesnotthrow_block_message). - * @static - * @memberOf should - * @category assertion assert - * @param {Function} block - * @param {String} [message] - */ - assert.doesNotThrow = function(/*block, message*/) { - _throws.apply(this, [false].concat(pSlice.call(arguments))); - }; - - /** - * Node.js standard [`assert.ifError`](http://nodejs.org/api/assert.html#assert_assert_iferror_value). - * @static - * @memberOf should - * @category assertion assert - * @param {Error} err - */ - assert.ifError = function(err) { - if (err) { - throw err; - } - }; - - function assertExtensions(should) { - var i = should.format; - - /* - * Expose assert to should - * - * This allows you to do things like below - * without require()ing the assert module. - * - * should.equal(foo.bar, undefined); - * - */ - merge(should, assert); - - /** - * Assert _obj_ exists, with optional message. - * - * @static - * @memberOf should - * @category assertion assert - * @alias should.exists - * @param {*} obj - * @param {String} [msg] - * @example - * - * should.exist(1); - * should.exist(new Date()); - */ - should.exist = should.exists = function(obj, msg) { - if (null == obj) { - throw new AssertionError({ - message: msg || ('expected ' + i(obj) + ' to exist'), stackStartFunction: should.exist - }); - } - }; - - should.not = {}; - /** - * Asserts _obj_ does not exist, with optional message. - * - * @name not.exist - * @static - * @memberOf should - * @category assertion assert - * @alias should.not.exists - * @param {*} obj - * @param {String} [msg] - * @example - * - * should.not.exist(null); - * should.not.exist(void 0); - */ - should.not.exist = should.not.exists = function(obj, msg) { - if (null != obj) { - throw new AssertionError({ - message: msg || ('expected ' + i(obj) + ' to not exist'), stackStartFunction: should.not.exist - }); - } - }; - } - - /* - * should.js - assertion library - * Copyright(c) 2010-2013 TJ Holowaychuk - * Copyright(c) 2013-2016 Denis Bardadym - * MIT Licensed - */ - - function chainAssertions(should, Assertion) { - /** - * Simple chaining. It actually do nothing. - * - * @memberOf Assertion - * @name be - * @property {should.Assertion} be - * @alias Assertion#an - * @alias Assertion#of - * @alias Assertion#a - * @alias Assertion#and - * @alias Assertion#have - * @alias Assertion#has - * @alias Assertion#with - * @alias Assertion#is - * @alias Assertion#which - * @alias Assertion#the - * @alias Assertion#it - * @category assertion chaining - */ - ['an', 'of', 'a', 'and', 'be', 'has', 'have', 'with', 'is', 'which', 'the', 'it'].forEach(function(name) { - Assertion.addChain(name); - }); - } - - /* - * should.js - assertion library - * Copyright(c) 2010-2013 TJ Holowaychuk - * Copyright(c) 2013-2016 Denis Bardadym - * MIT Licensed - */ - - function booleanAssertions(should, Assertion) { - /** - * Assert given object is exactly `true`. - * - * @name true - * @memberOf Assertion - * @category assertion bool - * @alias Assertion#True - * @param {string} [message] Optional message - * @example - * - * (true).should.be.true(); - * false.should.not.be.true(); - * - * ({ a: 10}).should.not.be.true(); - */ - Assertion.add('true', function(message) { - this.is.exactly(true, message); - }); - - Assertion.alias('true', 'True'); - - /** - * Assert given object is exactly `false`. - * - * @name false - * @memberOf Assertion - * @category assertion bool - * @alias Assertion#False - * @param {string} [message] Optional message - * @example - * - * (true).should.not.be.false(); - * false.should.be.false(); - */ - Assertion.add('false', function(message) { - this.is.exactly(false, message); - }); - - Assertion.alias('false', 'False'); - - /** - * Assert given object is truthy according javascript type conversions. - * - * @name ok - * @memberOf Assertion - * @category assertion bool - * @example - * - * (true).should.be.ok(); - * ''.should.not.be.ok(); - * should(null).not.be.ok(); - * should(void 0).not.be.ok(); - * - * (10).should.be.ok(); - * (0).should.not.be.ok(); - */ - Assertion.add('ok', function() { - this.params = { operator: 'to be truthy' }; - - this.assert(this.obj); - }); - } - - /* - * should.js - assertion library - * Copyright(c) 2010-2013 TJ Holowaychuk - * Copyright(c) 2013-2016 Denis Bardadym - * MIT Licensed - */ - - function numberAssertions(should, Assertion) { - - /** - * Assert given object is NaN - * @name NaN - * @memberOf Assertion - * @category assertion numbers - * @example - * - * (10).should.not.be.NaN(); - * NaN.should.be.NaN(); - */ - Assertion.add('NaN', function() { - this.params = { operator: 'to be NaN' }; - - this.assert(this.obj !== this.obj); - }); - - /** - * Assert given object is not finite (positive or negative) - * - * @name Infinity - * @memberOf Assertion - * @category assertion numbers - * @example - * - * (10).should.not.be.Infinity(); - * NaN.should.not.be.Infinity(); - */ - Assertion.add('Infinity', function() { - this.params = { operator: 'to be Infinity' }; - - this.is.a.Number() - .and.not.a.NaN() - .and.assert(!isFinite(this.obj)); - }); - - /** - * Assert given number between `start` and `finish` or equal one of them. - * - * @name within - * @memberOf Assertion - * @category assertion numbers - * @param {number} start Start number - * @param {number} finish Finish number - * @param {string} [description] Optional message - * @example - * - * (10).should.be.within(0, 20); - */ - Assertion.add('within', function(start, finish, description) { - this.params = { operator: 'to be within ' + start + '..' + finish, message: description }; - - this.assert(this.obj >= start && this.obj <= finish); - }); - - /** - * Assert given number near some other `value` within `delta` - * - * @name approximately - * @memberOf Assertion - * @category assertion numbers - * @param {number} value Center number - * @param {number} delta Radius - * @param {string} [description] Optional message - * @example - * - * (9.99).should.be.approximately(10, 0.1); - */ - Assertion.add('approximately', function(value, delta, description) { - this.params = { operator: 'to be approximately ' + value + ' ±' + delta, message: description }; - - this.assert(Math.abs(this.obj - value) <= delta); - }); - - /** - * Assert given number above `n`. - * - * @name above - * @alias Assertion#greaterThan - * @memberOf Assertion - * @category assertion numbers - * @param {number} n Margin number - * @param {string} [description] Optional message - * @example - * - * (10).should.be.above(0); - */ - Assertion.add('above', function(n, description) { - this.params = { operator: 'to be above ' + n, message: description }; - - this.assert(this.obj > n); - }); - - /** - * Assert given number below `n`. - * - * @name below - * @alias Assertion#lessThan - * @memberOf Assertion - * @category assertion numbers - * @param {number} n Margin number - * @param {string} [description] Optional message - * @example - * - * (0).should.be.below(10); - */ - Assertion.add('below', function(n, description) { - this.params = { operator: 'to be below ' + n, message: description }; - - this.assert(this.obj < n); - }); - - Assertion.alias('above', 'greaterThan'); - Assertion.alias('below', 'lessThan'); - - /** - * Assert given number above `n`. - * - * @name aboveOrEqual - * @alias Assertion#greaterThanOrEqual - * @memberOf Assertion - * @category assertion numbers - * @param {number} n Margin number - * @param {string} [description] Optional message - * @example - * - * (10).should.be.aboveOrEqual(0); - * (10).should.be.aboveOrEqual(10); - */ - Assertion.add('aboveOrEqual', function(n, description) { - this.params = { operator: 'to be above or equal' + n, message: description }; - - this.assert(this.obj >= n); - }); - - /** - * Assert given number below `n`. - * - * @name belowOrEqual - * @alias Assertion#lessThanOrEqual - * @memberOf Assertion - * @category assertion numbers - * @param {number} n Margin number - * @param {string} [description] Optional message - * @example - * - * (0).should.be.belowOrEqual(10); - * (0).should.be.belowOrEqual(0); - */ - Assertion.add('belowOrEqual', function(n, description) { - this.params = { operator: 'to be below or equal' + n, message: description }; - - this.assert(this.obj <= n); - }); - - Assertion.alias('aboveOrEqual', 'greaterThanOrEqual'); - Assertion.alias('belowOrEqual', 'lessThanOrEqual'); - - } - - function typeAssertions(should, Assertion) { - /** - * Assert given object is number - * @name Number - * @memberOf Assertion - * @category assertion types - */ - Assertion.add('Number', function() { - this.params = {operator: 'to be a number'}; - - this.have.type('number'); - }); - - /** - * Assert given object is arguments - * @name arguments - * @alias Assertion#Arguments - * @memberOf Assertion - * @category assertion types - */ - Assertion.add('arguments', function() { - this.params = {operator: 'to be arguments'}; - - this.have.class('Arguments'); - }); - - Assertion.alias('arguments', 'Arguments'); - - /** - * Assert given object has some type using `typeof` - * @name type - * @memberOf Assertion - * @param {string} type Type name - * @param {string} [description] Optional message - * @category assertion types - */ - Assertion.add('type', function(type, description) { - this.params = {operator: 'to have type ' + type, message: description}; - - should(typeof this.obj).be.exactly(type); - }); - - /** - * Assert given object is instance of `constructor` - * @name instanceof - * @alias Assertion#instanceOf - * @memberOf Assertion - * @param {Function} constructor Constructor function - * @param {string} [description] Optional message - * @category assertion types - */ - Assertion.add('instanceof', function(constructor, description) { - this.params = {operator: 'to be an instance of ' + functionName(constructor), message: description}; - - this.assert(Object(this.obj) instanceof constructor); - }); - - Assertion.alias('instanceof', 'instanceOf'); - - /** - * Assert given object is function - * @name Function - * @memberOf Assertion - * @category assertion types - */ - Assertion.add('Function', function() { - this.params = {operator: 'to be a function'}; - - this.have.type('function'); - }); - - /** - * Assert given object is object - * @name Object - * @memberOf Assertion - * @category assertion types - */ - Assertion.add('Object', function() { - this.params = {operator: 'to be an object'}; - - this.is.not.null().and.have.type('object'); - }); - - /** - * Assert given object is string - * @name String - * @memberOf Assertion - * @category assertion types - */ - Assertion.add('String', function() { - this.params = {operator: 'to be a string'}; - - this.have.type('string'); - }); - - /** - * Assert given object is array - * @name Array - * @memberOf Assertion - * @category assertion types - */ - Assertion.add('Array', function() { - this.params = {operator: 'to be an array'}; - - this.have.class('Array'); - }); - - /** - * Assert given object is boolean - * @name Boolean - * @memberOf Assertion - * @category assertion types - */ - Assertion.add('Boolean', function() { - this.params = {operator: 'to be a boolean'}; - - this.have.type('boolean'); - }); - - /** - * Assert given object is error - * @name Error - * @memberOf Assertion - * @category assertion types - */ - Assertion.add('Error', function() { - this.params = {operator: 'to be an error'}; - - this.have.instanceOf(Error); - }); - - /** - * Assert given object is a date - * @name Date - * @memberOf Assertion - * @category assertion types - */ - Assertion.add('Date', function() { - this.params = {operator: 'to be a date'}; - - this.have.instanceOf(Date); - }); - - /** - * Assert given object is null - * @name null - * @alias Assertion#Null - * @memberOf Assertion - * @category assertion types - */ - Assertion.add('null', function() { - this.params = {operator: 'to be null'}; - - this.assert(this.obj === null); - }); - - Assertion.alias('null', 'Null'); - - /** - * Assert given object has some internal [[Class]], via Object.prototype.toString call - * @name class - * @alias Assertion#Class - * @memberOf Assertion - * @category assertion types - */ - Assertion.add('class', function(cls) { - this.params = {operator: 'to have [[Class]] ' + cls}; - - this.assert(Object.prototype.toString.call(this.obj) === '[object ' + cls + ']'); - }); - - Assertion.alias('class', 'Class'); - - /** - * Assert given object is undefined - * @name undefined - * @alias Assertion#Undefined - * @memberOf Assertion - * @category assertion types - */ - Assertion.add('undefined', function() { - this.params = {operator: 'to be undefined'}; - - this.assert(this.obj === void 0); - }); - - Assertion.alias('undefined', 'Undefined'); - - /** - * Assert given object supports es6 iterable protocol (just check - * that object has property Symbol.iterator, which is a function) - * @name iterable - * @memberOf Assertion - * @category assertion es6 - */ - Assertion.add('iterable', function() { - this.params = {operator: 'to be iterable'}; - - should(this.obj).have.property(Symbol.iterator).which.is.a.Function(); - }); - - /** - * Assert given object supports es6 iterator protocol (just check - * that object has property next, which is a function) - * @name iterator - * @memberOf Assertion - * @category assertion es6 - */ - Assertion.add('iterator', function() { - this.params = {operator: 'to be iterator'}; - - should(this.obj).have.property('next').which.is.a.Function(); - }); - - /** - * Assert given object is a generator object - * @name generator - * @memberOf Assertion - * @category assertion es6 - */ - Assertion.add('generator', function() { - this.params = {operator: 'to be generator'}; - - should(this.obj).be.iterable - .and.iterator - .and.it.is.equal(this.obj[Symbol.iterator]()); - }); - } - - function formatEqlResult(r, a, b) { - return ((r.path.length > 0 ? 'at ' + r.path.map(formatProp).join(' -> ') : '') + - (r.a === a ? '' : ', A has ' + format(r.a)) + - (r.b === b ? '' : ' and B has ' + format(r.b)) + - (r.showReason ? ' because ' + r.reason : '')).trim(); - } - - function equalityAssertions(should, Assertion) { - - - /** - * Deep object equality comparison. For full spec see [`should-equal tests`](https://github.com/shouldjs/equal/blob/master/test.js). - * - * @name eql - * @memberOf Assertion - * @category assertion equality - * @alias Assertion#deepEqual - * @param {*} val Expected value - * @param {string} [description] Optional message - * @example - * - * (10).should.be.eql(10); - * ('10').should.not.be.eql(10); - * (-0).should.not.be.eql(+0); - * - * NaN.should.be.eql(NaN); - * - * ({ a: 10}).should.be.eql({ a: 10 }); - * [ 'a' ].should.not.be.eql({ '0': 'a' }); - */ - Assertion.add('eql', function(val, description) { - this.params = {operator: 'to equal', expected: val, message: description}; - var obj = this.obj; - var fails = eq(this.obj, val, should.config); - this.params.details = fails.map(function(fail) { - return formatEqlResult(fail, obj, val); - }).join(', '); - - this.params.showDiff = eq(getGlobalType(obj), getGlobalType(val)).length === 0; - - this.assert(fails.length === 0); - }); - - /** - * Exact comparison using ===. - * - * @name equal - * @memberOf Assertion - * @category assertion equality - * @alias Assertion#exactly - * @param {*} val Expected value - * @param {string} [description] Optional message - * @example - * - * 10.should.be.equal(10); - * 'a'.should.be.exactly('a'); - * - * should(null).be.exactly(null); - */ - Assertion.add('equal', function(val, description) { - this.params = {operator: 'to be', expected: val, message: description}; - - this.params.showDiff = eq(getGlobalType(this.obj), getGlobalType(val)).length === 0; - - this.assert(val === this.obj); - }); - - Assertion.alias('equal', 'exactly'); - Assertion.alias('eql', 'deepEqual'); - - function addOneOf(name, message, method) { - Assertion.add(name, function(vals) { - if (arguments.length !== 1) { - vals = Array.prototype.slice.call(arguments); - } else { - should(vals).be.Array(); - } - - this.params = {operator: message, expected: vals}; - - var obj = this.obj; - var found = false; - - forEach(vals, function(val) { - try { - should(val)[method](obj); - found = true; - return false; - } catch (e) { - if (e instanceof should.AssertionError) { - return;//do nothing - } - throw e; - } - }); - - this.assert(found); - }); - } - - /** - * Exact comparison using === to be one of supplied objects. - * - * @name equalOneOf - * @memberOf Assertion - * @category assertion equality - * @param {Array|*} vals Expected values - * @example - * - * 'ab'.should.be.equalOneOf('a', 10, 'ab'); - * 'ab'.should.be.equalOneOf(['a', 10, 'ab']); - */ - addOneOf('equalOneOf', 'to be equals one of', 'equal'); - - /** - * Exact comparison using .eql to be one of supplied objects. - * - * @name oneOf - * @memberOf Assertion - * @category assertion equality - * @param {Array|*} vals Expected values - * @example - * - * ({a: 10}).should.be.oneOf('a', 10, 'ab', {a: 10}); - * ({a: 10}).should.be.oneOf(['a', 10, 'ab', {a: 10}]); - */ - addOneOf('oneOf', 'to be one of', 'eql'); - - } - - function promiseAssertions(should, Assertion) { - /** - * Assert given object is a Promise - * - * @name Promise - * @memberOf Assertion - * @category assertion promises - * @example - * - * promise.should.be.Promise() - * (new Promise(function(resolve, reject) { resolve(10); })).should.be.a.Promise() - * (10).should.not.be.a.Promise() - */ - Assertion.add('Promise', function() { - this.params = {operator: 'to be promise'}; - - var obj = this.obj; - - should(obj).have.property('then') - .which.is.a.Function(); - }); - - /** - * Assert given promise will be fulfilled. Result of assertion is still .thenable and should be handled accordingly. - * - * @name fulfilled - * @memberOf Assertion - * @returns {Promise} - * @category assertion promises - * @example - * - * // don't forget to handle async nature - * (new Promise(function(resolve, reject) { resolve(10); })).should.be.fulfilled(); - * - * // test example with mocha it is possible to return promise - * it('is async', () => { - * return new Promise(resolve => resolve(10)) - * .should.be.fulfilled(); - * }); - */ - Assertion.prototype.fulfilled = function Assertion$fulfilled() { - this.params = {operator: 'to be fulfilled'}; - - should(this.obj).be.a.Promise(); - - var that = this; - return this.obj.then(function next$onResolve(value) { - if (that.negate) { - that.fail(); - } - return value; - }, function next$onReject(err) { - if (!that.negate) { - that.params.operator += ', but it was rejected with ' + should.format(err); - that.fail(); - } - return err; - }); - }; - - /** - * Assert given promise will be rejected. Result of assertion is still .thenable and should be handled accordingly. - * - * @name rejected - * @memberOf Assertion - * @category assertion promises - * @returns {Promise} - * @example - * - * // don't forget to handle async nature - * (new Promise(function(resolve, reject) { resolve(10); })) - * .should.not.be.rejected(); - * - * // test example with mocha it is possible to return promise - * it('is async', () => { - * return new Promise((resolve, reject) => reject(new Error('boom'))) - * .should.be.rejected(); - * }); - */ - Assertion.prototype.rejected = function() { - this.params = {operator: 'to be rejected'}; - - should(this.obj).be.a.Promise(); - - var that = this; - return this.obj.then(function(value) { - if (!that.negate) { - that.params.operator += ', but it was fulfilled'; - if (arguments.length != 0) { - that.params.operator += ' with ' + should.format(value); - } - that.fail(); - } - return value; - }, function next$onError(err) { - if (that.negate) { - that.fail(); - } - return err; - }); - }; - - /** - * Assert given promise will be fulfilled with some expected value (value compared using .eql). - * Result of assertion is still .thenable and should be handled accordingly. - * - * @name fulfilledWith - * @memberOf Assertion - * @category assertion promises - * @returns {Promise} - * @example - * - * // don't forget to handle async nature - * (new Promise(function(resolve, reject) { resolve(10); })) - * .should.be.fulfilledWith(10); - * - * // test example with mocha it is possible to return promise - * it('is async', () => { - * return new Promise((resolve, reject) => resolve(10)) - * .should.be.fulfilledWith(10); - * }); - */ - Assertion.prototype.fulfilledWith = function(expectedValue) { - this.params = {operator: 'to be fulfilled with ' + should.format(expectedValue)}; - - should(this.obj).be.a.Promise(); - - var that = this; - return this.obj.then(function(value) { - if (that.negate) { - that.fail(); - } - should(value).eql(expectedValue); - return value; - }, function next$onError(err) { - if (!that.negate) { - that.params.operator += ', but it was rejected with ' + should.format(err); - that.fail(); - } - return err; - }); - }; - - /** - * Assert given promise will be rejected with some sort of error. Arguments is the same for Assertion#throw. - * Result of assertion is still .thenable and should be handled accordingly. - * - * @name rejectedWith - * @memberOf Assertion - * @category assertion promises - * @returns {Promise} - * @example - * - * function failedPromise() { - * return new Promise(function(resolve, reject) { - * reject(new Error('boom')) - * }) - * } - * failedPromise().should.be.rejectedWith(Error); - * failedPromise().should.be.rejectedWith('boom'); - * failedPromise().should.be.rejectedWith(/boom/); - * failedPromise().should.be.rejectedWith(Error, { message: 'boom' }); - * failedPromise().should.be.rejectedWith({ message: 'boom' }); - * - * // test example with mocha it is possible to return promise - * it('is async', () => { - * return failedPromise().should.be.rejectedWith({ message: 'boom' }); - * }); - */ - Assertion.prototype.rejectedWith = function(message, properties) { - this.params = {operator: 'to be rejected'}; - - should(this.obj).be.a.Promise(); - - var that = this; - return this.obj.then(function(value) { - if (!that.negate) { - that.fail(); - } - return value; - }, function next$onError(err) { - if (that.negate) { - that.fail(); - } - - var errorMatched = true; - var errorInfo = ''; - - if ('string' === typeof message) { - errorMatched = message === err.message; - } else if (message instanceof RegExp) { - errorMatched = message.test(err.message); - } else if ('function' === typeof message) { - errorMatched = err instanceof message; - } else if (message !== null && typeof message === 'object') { - try { - should(err).match(message); - } catch (e) { - if (e instanceof should.AssertionError) { - errorInfo = ': ' + e.message; - errorMatched = false; - } else { - throw e; - } - } - } - - if (!errorMatched) { - if ( typeof message === 'string' || message instanceof RegExp) { - errorInfo = ' with a message matching ' + should.format(message) + ", but got '" + err.message + "'"; - } else if ('function' === typeof message) { - errorInfo = ' of type ' + functionName(message) + ', but got ' + functionName(err.constructor); - } - } else if ('function' === typeof message && properties) { - try { - should(err).match(properties); - } catch (e) { - if (e instanceof should.AssertionError) { - errorInfo = ': ' + e.message; - errorMatched = false; - } else { - throw e; - } - } - } - - that.params.operator += errorInfo; - - that.assert(errorMatched); - - return err; - }); - }; - - /** - * Assert given object is promise and wrap it in PromisedAssertion, which has all properties of Assertion. - * That means you can chain as with usual Assertion. - * Result of assertion is still .thenable and should be handled accordingly. - * - * @name finally - * @memberOf Assertion - * @alias Assertion#eventually - * @category assertion promises - * @returns {PromisedAssertion} Like Assertion, but .then this.obj in Assertion - * @example - * - * (new Promise(function(resolve, reject) { resolve(10); })) - * .should.be.eventually.equal(10); - * - * // test example with mocha it is possible to return promise - * it('is async', () => { - * return new Promise(resolve => resolve(10)) - * .should.be.finally.equal(10); - * }); - */ - Object.defineProperty(Assertion.prototype, 'finally', { - get: function() { - should(this.obj).be.a.Promise(); - - var that = this; - - return new PromisedAssertion(this.obj.then(function(obj) { - var a = should(obj); - - a.negate = that.negate; - a.anyOne = that.anyOne; - - return a; - })); - } - }); - - Assertion.alias('finally', 'eventually'); - } - - /* - * should.js - assertion library - * Copyright(c) 2010-2013 TJ Holowaychuk - * Copyright(c) 2013-2016 Denis Bardadym - * MIT Licensed - */ - - function stringAssertions(should, Assertion) { - /** - * Assert given string starts with prefix - * @name startWith - * @memberOf Assertion - * @category assertion strings - * @param {string} str Prefix - * @param {string} [description] Optional message - * @example - * - * 'abc'.should.startWith('a'); - */ - Assertion.add('startWith', function(str, description) { - this.params = { operator: 'to start with ' + should.format(str), message: description }; - - this.assert(0 === this.obj.indexOf(str)); - }); - - /** - * Assert given string ends with prefix - * @name endWith - * @memberOf Assertion - * @category assertion strings - * @param {string} str Prefix - * @param {string} [description] Optional message - * @example - * - * 'abca'.should.endWith('a'); - */ - Assertion.add('endWith', function(str, description) { - this.params = { operator: 'to end with ' + should.format(str), message: description }; - - this.assert(this.obj.indexOf(str, this.obj.length - str.length) >= 0); - }); - } - - function containAssertions(should, Assertion) { - var i = should.format; - - /** - * Assert that given object contain something that equal to `other`. It uses `should-equal` for equality checks. - * If given object is array it search that one of elements was equal to `other`. - * If given object is string it checks if `other` is a substring - expected that `other` is a string. - * If given object is Object it checks that `other` is a subobject - expected that `other` is a object. - * - * @name containEql - * @memberOf Assertion - * @category assertion contain - * @param {*} other Nested object - * @example - * - * [1, 2, 3].should.containEql(1); - * [{ a: 1 }, 'a', 10].should.containEql({ a: 1 }); - * - * 'abc'.should.containEql('b'); - * 'ab1c'.should.containEql(1); - * - * ({ a: 10, c: { d: 10 }}).should.containEql({ a: 10 }); - * ({ a: 10, c: { d: 10 }}).should.containEql({ c: { d: 10 }}); - * ({ a: 10, c: { d: 10 }}).should.containEql({ b: 10 }); - * // throws AssertionError: expected { a: 10, c: { d: 10 } } to contain { b: 10 } - * // expected { a: 10, c: { d: 10 } } to have property b - */ - Assertion.add('containEql', function(other) { - this.params = { operator: 'to contain ' + i(other) }; - - this.is.not.null().and.not.undefined(); - - var obj = this.obj; - - if (typeof obj == 'string') { - this.assert(obj.indexOf(String(other)) >= 0); - } else if (isIterable(obj)) { - this.assert(some(obj, function(v) { - return eq(v, other).length === 0; - })); - } else { - forEach(other, function(value, key) { - should(obj).have.value(key, value); - }, this); - } - }); - - /** - * Assert that given object is contain equally structured object on the same depth level. - * If given object is an array and `other` is an array it checks that the eql elements is going in the same sequence in given array (recursive) - * If given object is an object it checks that the same keys contain deep equal values (recursive) - * On other cases it try to check with `.eql` - * - * @name containDeepOrdered - * @memberOf Assertion - * @category assertion contain - * @param {*} other Nested object - * @example - * - * [ 1, 2, 3].should.containDeepOrdered([1, 2]); - * [ 1, 2, [ 1, 2, 3 ]].should.containDeepOrdered([ 1, [ 2, 3 ]]); - * - * ({ a: 10, b: { c: 10, d: [1, 2, 3] }}).should.containDeepOrdered({a: 10}); - * ({ a: 10, b: { c: 10, d: [1, 2, 3] }}).should.containDeepOrdered({b: {c: 10}}); - * ({ a: 10, b: { c: 10, d: [1, 2, 3] }}).should.containDeepOrdered({b: {d: [1, 3]}}); - */ - Assertion.add('containDeepOrdered', function(other) { - this.params = {operator: 'to contain ' + i(other)}; - - var obj = this.obj; - if (typeof obj == 'string') {// expect other to be string - this.is.equal(String(other)); - } else if (isIterable(obj) && isIterable(other)) { - var objIterator = iterator(obj); - var otherIterator = iterator(other); - - var nextObj = objIterator.next(); - var nextOther = otherIterator.next(); - while (!nextObj.done && !nextOther.done) { - try { - should(nextObj.value[1]).containDeepOrdered(nextOther.value[1]); - nextOther = otherIterator.next(); - } catch (e) { - if (!(e instanceof should.AssertionError)) { - throw e; - } - } - nextObj = objIterator.next(); - } - - this.assert(nextOther.done); - } else if (obj != null && other != null && typeof obj == 'object' && typeof other == 'object') {//TODO compare types object contains object case - forEach(other, function(value, key) { - should(obj[key]).containDeepOrdered(value); - }); - - // if both objects is empty means we finish traversing - and we need to compare for hidden values - if (isEmpty(other)) { - this.eql(other); - } - } else { - this.eql(other); - } - }); - - /** - * The same like `Assertion#containDeepOrdered` but all checks on arrays without order. - * - * @name containDeep - * @memberOf Assertion - * @category assertion contain - * @param {*} other Nested object - * @example - * - * [ 1, 2, 3].should.containDeep([2, 1]); - * [ 1, 2, [ 1, 2, 3 ]].should.containDeep([ 1, [ 3, 1 ]]); - */ - Assertion.add('containDeep', function(other) { - this.params = {operator: 'to contain ' + i(other)}; - - var obj = this.obj; - if (typeof obj == 'string') {// expect other to be string - this.is.equal(String(other)); - } else if (isIterable(obj) && isIterable(other)) { - var usedKeys = {}; - forEach(other, function(otherItem) { - this.assert(some(obj, function(item, index) { - if (index in usedKeys) { - return false; - } - - try { - should(item).containDeep(otherItem); - usedKeys[index] = true; - return true; - } catch (e) { - if (e instanceof should.AssertionError) { - return false; - } - throw e; - } - })); - }, this); - } else if (obj != null && other != null && typeof obj == 'object' && typeof other == 'object') {// object contains object case - forEach(other, function(value, key) { - should(obj[key]).containDeep(value); - }); - - // if both objects is empty means we finish traversing - and we need to compare for hidden values - if (isEmpty(other)) { - this.eql(other); - } - } else { - this.eql(other); - } - }); - - } - - var aSlice = Array.prototype.slice; - - function propertyAssertions(should, Assertion) { - var i = should.format; - /** - * Asserts given object has some descriptor. **On success it change given object to be value of property**. - * - * @name propertyWithDescriptor - * @memberOf Assertion - * @category assertion property - * @param {string} name Name of property - * @param {Object} desc Descriptor like used in Object.defineProperty (not required to add all properties) - * @example - * - * ({ a: 10 }).should.have.propertyWithDescriptor('a', { enumerable: true }); - */ - Assertion.add('propertyWithDescriptor', function(name, desc) { - this.params = {actual: this.obj, operator: 'to have own property with descriptor ' + i(desc)}; - var obj = this.obj; - this.have.ownProperty(name); - should(Object.getOwnPropertyDescriptor(Object(obj), name)).have.properties(desc); - }); - - function processPropsArgs() { - var args = {}; - if (arguments.length > 1) { - args.names = aSlice.call(arguments); - } else { - var arg = arguments[0]; - if (typeof arg === 'string') { - args.names = [arg]; - } else if (Array.isArray(arg)) { - args.names = arg; - } else { - args.names = Object.keys(arg); - args.values = arg; - } - } - return args; - } - - - /** - * Asserts given object has enumerable property with optionally value. **On success it change given object to be value of property**. - * - * @name enumerable - * @memberOf Assertion - * @category assertion property - * @param {string} name Name of property - * @param {*} [val] Optional property value to check - * @example - * - * ({ a: 10 }).should.have.enumerable('a'); - */ - Assertion.add('enumerable', function(name, val) { - name = convertPropertyName(name); - - this.params = { - operator: "to have enumerable property " + formatProp(name) + (arguments.length > 1 ? " equal to " + i(val): "") - }; - - var desc = { enumerable: true }; - if (arguments.length > 1) { - desc.value = val; - } - this.have.propertyWithDescriptor(name, desc); - }); - - /** - * Asserts given object has enumerable properties - * - * @name enumerables - * @memberOf Assertion - * @category assertion property - * @param {Array|...string|Object} names Names of property - * @example - * - * ({ a: 10, b: 10 }).should.have.enumerables('a'); - */ - Assertion.add('enumerables', function(/*names*/) { - var args = processPropsArgs.apply(null, arguments); - - this.params = { - operator: "to have enumerables " + args.names.map(formatProp) - }; - - var obj = this.obj; - args.names.forEach(function(name) { - should(obj).have.enumerable(name); - }); - }); - - /** - * Asserts given object has property with optionally value. **On success it change given object to be value of property**. - * - * @name property - * @memberOf Assertion - * @category assertion property - * @param {string} name Name of property - * @param {*} [val] Optional property value to check - * @example - * - * ({ a: 10 }).should.have.property('a'); - */ - Assertion.add('property', function(name, val) { - name = convertPropertyName(name); - if (arguments.length > 1) { - var p = {}; - p[name] = val; - this.have.properties(p); - } else { - this.have.properties(name); - } - this.obj = this.obj[name]; - }); - - /** - * Asserts given object has properties. On this method affect .any modifier, which allow to check not all properties. - * - * @name properties - * @memberOf Assertion - * @category assertion property - * @param {Array|...string|Object} names Names of property - * @example - * - * ({ a: 10 }).should.have.properties('a'); - * ({ a: 10, b: 20 }).should.have.properties([ 'a' ]); - * ({ a: 10, b: 20 }).should.have.properties({ b: 20 }); - */ - Assertion.add('properties', function(names) { - var values = {}; - if (arguments.length > 1) { - names = aSlice.call(arguments); - } else if (!Array.isArray(names)) { - if (typeof names == 'string' || typeof names == 'symbol') { - names = [names]; - } else { - values = names; - names = Object.keys(names); - } - } - - var obj = Object(this.obj), missingProperties = []; - - //just enumerate properties and check if they all present - names.forEach(function(name) { - if (!(name in obj)) { - missingProperties.push(formatProp(name)); - } - }); - - var props = missingProperties; - if (props.length === 0) { - props = names.map(formatProp); - } else if (this.anyOne) { - props = names.filter(function(name) { - return missingProperties.indexOf(formatProp(name)) < 0; - }).map(formatProp); - } - - var operator = (props.length === 1 ? - 'to have property ' : 'to have ' + (this.anyOne ? 'any of ' : '') + 'properties ') + props.join(', '); - - this.params = {obj: this.obj, operator: operator}; - - //check that all properties presented - //or if we request one of them that at least one them presented - this.assert(missingProperties.length === 0 || (this.anyOne && missingProperties.length != names.length)); - - // check if values in object matched expected - var valueCheckNames = Object.keys(values); - if (valueCheckNames.length) { - var wrongValues = []; - props = []; - - // now check values, as there we have all properties - valueCheckNames.forEach(function(name) { - var value = values[name]; - if (eq(obj[name], value).length !== 0) { - wrongValues.push(formatProp(name) + ' of ' + i(value) + ' (got ' + i(obj[name]) + ')'); - } else { - props.push(formatProp(name) + ' of ' + i(value)); - } - }); - - if ((wrongValues.length !== 0 && !this.anyOne) || (this.anyOne && props.length === 0)) { - props = wrongValues; - } - - operator = (props.length === 1 ? - 'to have property ' : 'to have ' + (this.anyOne ? 'any of ' : '') + 'properties ') + props.join(', '); - - this.params = {obj: this.obj, operator: operator}; - - //if there is no not matched values - //or there is at least one matched - this.assert(wrongValues.length === 0 || (this.anyOne && wrongValues.length != valueCheckNames.length)); - } - }); - - /** - * Asserts given object has property `length` with given value `n` - * - * @name length - * @alias Assertion#lengthOf - * @memberOf Assertion - * @category assertion property - * @param {number} n Expected length - * @param {string} [description] Optional message - * @example - * - * [1, 2].should.have.length(2); - */ - Assertion.add('length', function(n, description) { - this.have.property('length', n, description); - }); - - Assertion.alias('length', 'lengthOf'); - - /** - * Asserts given object has own property. **On success it change given object to be value of property**. - * - * @name ownProperty - * @alias Assertion#hasOwnProperty - * @memberOf Assertion - * @category assertion property - * @param {string} name Name of property - * @param {string} [description] Optional message - * @example - * - * ({ a: 10 }).should.have.ownProperty('a'); - */ - Assertion.add('ownProperty', function(name, description) { - name = convertPropertyName(name); - this.params = { - actual: this.obj, - operator: 'to have own property ' + formatProp(name), - message: description - }; - - this.assert(hasOwnProperty$1(this.obj, name)); - - this.obj = this.obj[name]; - }); - - Assertion.alias('ownProperty', 'hasOwnProperty'); - - /** - * Asserts given object is empty. For strings, arrays and arguments it checks .length property, for objects it checks keys. - * - * @name empty - * @memberOf Assertion - * @category assertion property - * @example - * - * ''.should.be.empty(); - * [].should.be.empty(); - * ({}).should.be.empty(); - */ - Assertion.add('empty', function() { - this.params = {operator: 'to be empty'}; - this.assert(isEmpty(this.obj)); - }, true); - - /** - * Asserts given object has such keys. Compared to `properties`, `keys` does not accept Object as a argument. - * When calling via .key current object in assertion changed to value of this key - * - * @name keys - * @alias Assertion#key - * @memberOf Assertion - * @category assertion property - * @param {...*} keys Keys to check - * @example - * - * ({ a: 10 }).should.have.keys('a'); - * ({ a: 10, b: 20 }).should.have.keys('a', 'b'); - * (new Map([[1, 2]])).should.have.key(1); - */ - Assertion.add('keys', function(keys) { - keys = aSlice.call(arguments); - - var obj = Object(this.obj); - - // first check if some keys are missing - var missingKeys = keys.filter(function(key) { - return !has(obj, key); - }); - - var verb = 'to have ' + (keys.length === 1 ? 'key ' : 'keys '); - - this.params = {operator: verb + keys.join(', ')}; - - if (missingKeys.length > 0) { - this.params.operator += '\n\tmissing keys: ' + missingKeys.join(', '); - } - - this.assert(missingKeys.length === 0); - }); - - - Assertion.add('key', function(key) { - this.have.keys(key); - this.obj = get(this.obj, key); - }); - - /** - * Asserts given object has such value for given key - * - * @name value - * @memberOf Assertion - * @category assertion property - * @param {*} key Key to check - * @param {*} value Value to check - * @example - * - * ({ a: 10 }).should.have.value('a', 10); - * (new Map([[1, 2]])).should.have.value(1, 2); - */ - Assertion.add('value', function(key, value) { - this.have.key(key).which.is.eql(value); - }); - - /** - * Asserts given object has such size. - * - * @name size - * @memberOf Assertion - * @category assertion property - * @param {number} s Size to check - * @example - * - * ({ a: 10 }).should.have.size(1); - * (new Map([[1, 2]])).should.have.size(1); - */ - Assertion.add('size', function(s) { - this.params = { operator: 'to have size ' + s }; - size(this.obj).should.be.exactly(s); - }); - - /** - * Asserts given object has nested property in depth by path. **On success it change given object to be value of final property**. - * - * @name propertyByPath - * @memberOf Assertion - * @category assertion property - * @param {Array|...string} properties Properties path to search - * @example - * - * ({ a: {b: 10}}).should.have.propertyByPath('a', 'b').eql(10); - */ - Assertion.add('propertyByPath', function(properties) { - if (arguments.length > 1) { - properties = aSlice.call(arguments); - } else if (arguments.length === 1 && typeof properties == 'string') { - properties = [properties]; - } else if (arguments.length === 0) { - properties = []; - } - - var allProps = properties.map(formatProp); - - properties = properties.map(String); - - var obj = should(Object(this.obj)); - - var foundProperties = []; - - var currentProperty; - while (properties.length) { - currentProperty = properties.shift(); - this.params = {operator: 'to have property by path ' + allProps.join(', ') + ' - failed on ' + formatProp(currentProperty)}; - obj = obj.have.property(currentProperty); - foundProperties.push(currentProperty); - } - - this.params = {obj: this.obj, operator: 'to have property by path ' + allProps.join(', ')}; - - this.obj = obj.obj; - }); - } - - function errorAssertions(should, Assertion) { - var i = should.format; - - /** - * Assert given function throws error with such message. - * - * @name throw - * @memberOf Assertion - * @category assertion errors - * @alias Assertion#throwError - * @param {string|RegExp|Function|Object|GeneratorFunction|GeneratorObject} [message] Message to match or properties - * @param {Object} [properties] Optional properties that will be matched to thrown error - * @example - * - * (function(){ throw new Error('fail') }).should.throw(); - * (function(){ throw new Error('fail') }).should.throw('fail'); - * (function(){ throw new Error('fail') }).should.throw(/fail/); - * - * (function(){ throw new Error('fail') }).should.throw(Error); - * var error = new Error(); - * error.a = 10; - * (function(){ throw error; }).should.throw(Error, { a: 10 }); - * (function(){ throw error; }).should.throw({ a: 10 }); - * (function*() { - * yield throwError(); - * }).should.throw(); - */ - Assertion.add('throw', function(message, properties) { - var fn = this.obj; - var err = {}; - var errorInfo = ''; - var thrown = false; - - if (isGeneratorFunction(fn)) { - return should(fn()).throw(message, properties); - } else if (isIterator(fn)) { - return should(fn.next.bind(fn)).throw(message, properties); - } - - this.is.a.Function(); - - var errorMatched = true; - - try { - fn(); - } catch (e) { - thrown = true; - err = e; - } - - if (thrown) { - if (message) { - if ('string' == typeof message) { - errorMatched = message == err.message; - } else if (message instanceof RegExp) { - errorMatched = message.test(err.message); - } else if ('function' == typeof message) { - errorMatched = err instanceof message; - } else if (null != message) { - try { - should(err).match(message); - } catch (e) { - if (e instanceof should.AssertionError) { - errorInfo = ": " + e.message; - errorMatched = false; - } else { - throw e; - } - } - } - - if (!errorMatched) { - if ('string' == typeof message || message instanceof RegExp) { - errorInfo = " with a message matching " + i(message) + ", but got '" + err.message + "'"; - } else if ('function' == typeof message) { - errorInfo = " of type " + functionName(message) + ", but got " + functionName(err.constructor); - } - } else if ('function' == typeof message && properties) { - try { - should(err).match(properties); - } catch (e) { - if (e instanceof should.AssertionError) { - errorInfo = ": " + e.message; - errorMatched = false; - } else { - throw e; - } - } - } - } else { - errorInfo = " (got " + i(err) + ")"; - } - } - - this.params = { operator: 'to throw exception' + errorInfo }; - - this.assert(thrown); - this.assert(errorMatched); - }); - - Assertion.alias('throw', 'throwError'); - } - - function matchingAssertions(should, Assertion) { - var i = should.format; - - /** - * Asserts if given object match `other` object, using some assumptions: - * First object matched if they are equal, - * If `other` is a regexp and given object is a string check on matching with regexp - * If `other` is a regexp and given object is an array check if all elements matched regexp - * If `other` is a regexp and given object is an object check values on matching regexp - * If `other` is a function check if this function throws AssertionError on given object or return false - it will be assumed as not matched - * If `other` is an object check if the same keys matched with above rules - * All other cases failed. - * - * Usually it is right idea to add pre type assertions, like `.String()` or `.Object()` to be sure assertions will do what you are expecting. - * Object iteration happen by keys (properties with enumerable: true), thus some objects can cause small pain. Typical example is js - * Error - it by default has 2 properties `name` and `message`, but they both non-enumerable. In this case make sure you specify checking props (see examples). - * - * @name match - * @memberOf Assertion - * @category assertion matching - * @param {*} other Object to match - * @param {string} [description] Optional message - * @example - * 'foobar'.should.match(/^foo/); - * 'foobar'.should.not.match(/^bar/); - * - * ({ a: 'foo', c: 'barfoo' }).should.match(/foo$/); - * - * ['a', 'b', 'c'].should.match(/[a-z]/); - * - * (5).should.not.match(function(n) { - * return n < 0; - * }); - * (5).should.not.match(function(it) { - * it.should.be.an.Array(); - * }); - * ({ a: 10, b: 'abc', c: { d: 10 }, d: 0 }).should - * .match({ a: 10, b: /c$/, c: function(it) { - * return it.should.have.property('d', 10); - * }}); - * - * [10, 'abc', { d: 10 }, 0].should - * .match({ '0': 10, '1': /c$/, '2': function(it) { - * return it.should.have.property('d', 10); - * }}); - * - * var myString = 'abc'; - * - * myString.should.be.a.String().and.match(/abc/); - * - * myString = {}; - * - * myString.should.match(/abc/); //yes this will pass - * //better to do - * myString.should.be.an.Object().and.not.empty().and.match(/abc/);//fixed - * - * (new Error('boom')).should.match(/abc/);//passed because no keys - * (new Error('boom')).should.not.match({ message: /abc/ });//check specified property - */ - Assertion.add('match', function(other, description) { - this.params = {operator: 'to match ' + i(other), message: description}; - - if (eq(this.obj, other).length !== 0) { - if (other instanceof RegExp) { // something - regex - - if (typeof this.obj == 'string') { - - this.assert(other.exec(this.obj)); - } else if (null != this.obj && typeof this.obj == 'object') { - - var notMatchedProps = [], matchedProps = []; - forEach(this.obj, function(value, name) { - if (other.exec(value)) { - matchedProps.push(formatProp(name)); - } else { - notMatchedProps.push(formatProp(name) + ' (' + i(value) + ')'); - } - }, this); - - if (notMatchedProps.length) { - this.params.operator += '\n not matched properties: ' + notMatchedProps.join(', '); - } - if (matchedProps.length) { - this.params.operator += '\n matched properties: ' + matchedProps.join(', '); - } - - this.assert(notMatchedProps.length === 0); - } // should we try to convert to String and exec? - } else if (typeof other == 'function') { - var res; - - res = other(this.obj); - - //if we throw exception ok - it is used .should inside - if (typeof res == 'boolean') { - this.assert(res); // if it is just boolean function assert on it - } - } else if (other != null && this.obj != null && typeof other == 'object' && typeof this.obj == 'object') { // try to match properties (for Object and Array) - notMatchedProps = []; - matchedProps = []; - - forEach(other, function(value, key) { - try { - should(this.obj).have.property(key).which.match(value); - matchedProps.push(formatProp(key)); - } catch (e) { - if (e instanceof should.AssertionError) { - notMatchedProps.push(formatProp(key) + ' (' + i(this.obj[key]) + ')'); - } else { - throw e; - } - } - }, this); - - if (notMatchedProps.length) { - this.params.operator += '\n not matched properties: ' + notMatchedProps.join(', '); - } - if (matchedProps.length) { - this.params.operator += '\n matched properties: ' + matchedProps.join(', '); - } - - this.assert(notMatchedProps.length === 0); - } else { - this.assert(false); - } - } - }); - - /** - * Asserts if given object values or array elements all match `other` object, using some assumptions: - * First object matched if they are equal, - * If `other` is a regexp - matching with regexp - * If `other` is a function check if this function throws AssertionError on given object or return false - it will be assumed as not matched - * All other cases check if this `other` equal to each element - * - * @name matchEach - * @memberOf Assertion - * @category assertion matching - * @alias Assertion#matchEvery - * @param {*} other Object to match - * @param {string} [description] Optional message - * @example - * [ 'a', 'b', 'c'].should.matchEach(/\w+/); - * [ 'a', 'a', 'a'].should.matchEach('a'); - * - * [ 'a', 'a', 'a'].should.matchEach(function(value) { value.should.be.eql('a') }); - * - * { a: 'a', b: 'a', c: 'a' }.should.matchEach(function(value) { value.should.be.eql('a') }); - */ - Assertion.add('matchEach', function(other, description) { - this.params = {operator: 'to match each ' + i(other), message: description}; - - forEach(this.obj, function(value) { - should(value).match(other); - }, this); - }); - - /** - * Asserts if any of given object values or array elements match `other` object, using some assumptions: - * First object matched if they are equal, - * If `other` is a regexp - matching with regexp - * If `other` is a function check if this function throws AssertionError on given object or return false - it will be assumed as not matched - * All other cases check if this `other` equal to each element - * - * @name matchAny - * @memberOf Assertion - * @category assertion matching - * @param {*} other Object to match - * @alias Assertion#matchSome - * @param {string} [description] Optional message - * @example - * [ 'a', 'b', 'c'].should.matchAny(/\w+/); - * [ 'a', 'b', 'c'].should.matchAny('a'); - * - * [ 'a', 'b', 'c'].should.matchAny(function(value) { value.should.be.eql('a') }); - * - * { a: 'a', b: 'b', c: 'c' }.should.matchAny(function(value) { value.should.be.eql('a') }); - */ - Assertion.add('matchAny', function(other, description) { - this.params = {operator: 'to match any ' + i(other), message: description}; - - this.assert(some(this.obj, function(value) { - try { - should(value).match(other); - return true; - } catch (e) { - if (e instanceof should.AssertionError) { - // Caught an AssertionError, return false to the iterator - return false; - } - throw e; - } - })); - }); - - Assertion.alias('matchAny', 'matchSome'); - Assertion.alias('matchEach', 'matchEvery'); - } - - /** - * Our function should - * - * @param {*} obj Object to assert - * @returns {should.Assertion} Returns new Assertion for beginning assertion chain - * @example - * - * var should = require('should'); - * should('abc').be.a.String(); - */ - function should(obj) { - return (new Assertion(obj)); - } - - should.AssertionError = AssertionError; - should.Assertion = Assertion; - - // exposing modules dirty way - should.modules = { - format: defaultFormat, - type: getGlobalType, - equal: eq - }; - should.format = format; - - /** - * Object with configuration. - * It contains such properties: - * * `checkProtoEql` boolean - Affect if `.eql` will check objects prototypes - * * `plusZeroAndMinusZeroEqual` boolean - Affect if `.eql` will treat +0 and -0 as equal - * Also it can contain options for should-format. - * - * @type {Object} - * @memberOf should - * @static - * @example - * - * var a = { a: 10 }, b = Object.create(null); - * b.a = 10; - * - * a.should.be.eql(b); - * //not throws - * - * should.config.checkProtoEql = true; - * a.should.be.eql(b); - * //throws AssertionError: expected { a: 10 } to equal { a: 10 } (because A and B have different prototypes) - */ - should.config = config; - - /** - * Allow to extend given prototype with should property using given name. This getter will **unwrap** all standard wrappers like `Number`, `Boolean`, `String`. - * Using `should(obj)` is the equivalent of using `obj.should` with known issues (like nulls and method calls etc). - * - * To add new assertions, need to use Assertion.add method. - * - * @param {string} [propertyName] Name of property to add. Default is `'should'`. - * @param {Object} [proto] Prototype to extend with. Default is `Object.prototype`. - * @memberOf should - * @returns {{ name: string, descriptor: Object, proto: Object }} Descriptor enough to return all back - * @static - * @example - * - * var prev = should.extend('must', Object.prototype); - * - * 'abc'.must.startWith('a'); - * - * var should = should.noConflict(prev); - * should.not.exist(Object.prototype.must); - */ - should.extend = function(propertyName, proto) { - propertyName = propertyName || 'should'; - proto = proto || Object.prototype; - - var prevDescriptor = Object.getOwnPropertyDescriptor(proto, propertyName); - - Object.defineProperty(proto, propertyName, { - set: function() { - }, - get: function() { - return should(isWrapperType(this) ? this.valueOf() : this); - }, - configurable: true - }); - - return { name: propertyName, descriptor: prevDescriptor, proto: proto }; - }; - - /** - * Delete previous extension. If `desc` missing it will remove default extension. - * - * @param {{ name: string, descriptor: Object, proto: Object }} [desc] Returned from `should.extend` object - * @memberOf should - * @returns {Function} Returns should function - * @static - * @example - * - * var should = require('should').noConflict(); - * - * should(Object.prototype).not.have.property('should'); - * - * var prev = should.extend('must', Object.prototype); - * 'abc'.must.startWith('a'); - * should.noConflict(prev); - * - * should(Object.prototype).not.have.property('must'); - */ - should.noConflict = function(desc) { - desc = desc || should._prevShould; - - if (desc) { - delete desc.proto[desc.name]; - - if (desc.descriptor) { - Object.defineProperty(desc.proto, desc.name, desc.descriptor); - } - } - return should; - }; - - /** - * Simple utility function for a bit more easier should assertion extension - * @param {Function} f So called plugin function. It should accept 2 arguments: `should` function and `Assertion` constructor - * @memberOf should - * @returns {Function} Returns `should` function - * @static - * @example - * - * should.use(function(should, Assertion) { - * Assertion.add('asset', function() { - * this.params = { operator: 'to be asset' }; - * - * this.obj.should.have.property('id').which.is.a.Number(); - * this.obj.should.have.property('path'); - * }) - * }) - */ - should.use = function(f) { - f(should, should.Assertion); - return this; - }; - - should - .use(assertExtensions) - .use(chainAssertions) - .use(booleanAssertions) - .use(numberAssertions) - .use(equalityAssertions) - .use(typeAssertions) - .use(stringAssertions) - .use(propertyAssertions) - .use(errorAssertions) - .use(matchingAssertions) - .use(containAssertions) - .use(promiseAssertions); - - var defaultProto = Object.prototype; - var defaultProperty = 'should'; - - //Expose api via `Object#should`. - try { - var prevShould = should.extend(defaultProperty, defaultProto); - should._prevShould = prevShould; - } catch (e) { - //ignore errors - } - - - if (typeof define === 'function' && define.amd) { - define([], function() { return should }); - } else if (typeof module === 'object' && module.exports) { - module.exports = should; - } else { - var _root = root; - - _root.Should = should; - - Object.defineProperty(_root, 'should', { - enumerable: false, - configurable: true, - value: should - }); - } - -}(this)); \ No newline at end of file diff --git a/usergrid.js b/usergrid.js index 5df4f0f..1e09e53 100644 --- a/usergrid.js +++ b/usergrid.js @@ -17,7 +17,7 @@ *under the License. * * - * usergrid@0.11.0 2016-09-21 + * usergrid@0.11.0 2016-09-23 */ var UsergridAuthMode = Object.freeze({ NONE: "none", @@ -155,7 +155,6 @@ UsergridEventable.mixin = function(destObject) { var name = "Promise", overwrittenName = global[name], exports; function Promise() { this.complete = false; - this.error = null; this.result = null; this.callbacks = []; } @@ -164,29 +163,27 @@ UsergridEventable.mixin = function(destObject) { return callback.apply(context, arguments); }; if (this.complete) { - f(this.error, this.result); + f(this.result); } else { this.callbacks.push(f); } }; - Promise.prototype.done = function(error, result) { + Promise.prototype.done = function(result) { this.complete = true; - this.error = error; this.result = result; if (this.callbacks) { - for (var i = 0; i < this.callbacks.length; i++) this.callbacks[i](error, result); + for (var i = 0; i < this.callbacks.length; i++) this.callbacks[i](result); this.callbacks.length = 0; } }; Promise.join = function(promises) { - var p = new Promise(), total = promises.length, completed = 0, errors = [], results = []; + var p = new Promise(), total = promises.length, completed = 0, results = []; function notifier(i) { - return function(error, result) { + return function(result) { completed += 1; - errors[i] = error; results[i] = result; if (completed === total) { - p.done(errors, results); + p.done(results); } }; } @@ -195,19 +192,19 @@ UsergridEventable.mixin = function(destObject) { } return p; }; - Promise.chain = function(promises, error, result) { + Promise.chain = function(promises, result) { var p = new Promise(); if (promises === null || promises.length === 0) { - p.done(error, result); + p.done(result); } else { - promises[0](error, result).then(function(res, err) { + promises[0](result).then(function(res) { promises.splice(0, 1); if (promises) { - Promise.chain(promises, res, err).then(function(r, e) { - p.done(r, e); + Promise.chain(promises, res).then(function(r) { + p.done(r); }); } else { - p.done(res, err); + p.done(res); } }); } @@ -255,12 +252,12 @@ UsergridEventable.mixin = function(destObject) { if (this.readyState === 4) { self.logger.timeEnd(m + " " + u); clearTimeout(timeout); - p.done(null, this); + p.done(this); } }; xhr.onerror = function(response) { clearTimeout(timeout); - p.done(response, null); + p.done(response); }; xhr.oncomplete = function(response) { clearTimeout(timeout); @@ -15476,51 +15473,187 @@ UsergridEventable.mixin = function(destObject) { } }).call(this); -function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true +(function(global) { + var name = "UsergridHelpers", overwrittenName = global[name]; + function UsergridHelpers() {} + UsergridHelpers.inherits = function(ctor, superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + UsergridHelpers.flattenArgs = function(args) { + return _.flattenDeep(Array.prototype.slice.call(args)); + }; + UsergridHelpers.callback = function() { + var args = _.flattenDeep(Array.prototype.slice.call(arguments)).reverse(); + var emptyFunc = function() {}; + return _.first(_.flattenDeep([ args, _.get(args, "0.callback"), emptyFunc ]).filter(_.isFunction)); + }; + UsergridHelpers.configureTempAuth = function(auth) { + if (_.isString(auth) && auth !== UsergridAuthMode.NONE) { + return new UsergridAuth(auth); + } else if (!auth || auth === UsergridAuthMode.NONE) { + return undefined; + } else if (auth instanceof UsergridAuth) { + return auth; + } else { + return undefined; } - }); -} - -function flattenArgs(args) { - return _.flattenDeep(Array.prototype.slice.call(args)); -} - -function validateAndRetrieveClient(args) { - var client = undefined; - if (args instanceof UsergridClient) { - client = args; - } else if (args[0] instanceof UsergridClient) { - client = args[0]; - } else if (Usergrid.isInitialized) { - client = Usergrid.getInstance(); - } else { - throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument"); - } - return client; -} - -function configureTempAuth(auth) { - if (_.isString(auth) && auth !== UsergridAuthMode.NONE) { - return new UsergridAuth(auth); - } else if (!auth || auth === UsergridAuthMode.NONE) { - return undefined; - } else if (auth instanceof UsergridAuth) { - return auth; - } else { - return undefined; - } -} - -function useQuotesIfRequired(value) { - return _.isFinite(value) || isUUID(value) || _.isBoolean(value) || _.isObject(value) && !_.isFunction(value) || _.isArray(value) ? value : "'" + value + "'"; -} + }; + UsergridHelpers.userLoginBody = function(options) { + var body = { + grant_type: "password", + password: options.password + }; + if (options.tokenTtl) { + body.ttl = options.tokenTtl; + } + body[options.username ? "username" : "email"] = options.username ? options.username : options.email; + return body; + }; + UsergridHelpers.appLoginBody = function(options) { + var body = { + grant_type: "client_credentials", + client_id: options.clientId, + client_secret: options.clientSecret + }; + if (options.tokenTtl) { + body.ttl = options.tokenTtl; + } + return body; + }; + UsergridHelpers.useQuotesIfRequired = function(value) { + return _.isFinite(value) || isUUID(value) || _.isBoolean(value) || _.isObject(value) && !_.isFunction(value) || _.isArray(value) ? value : "'" + value + "'"; + }; + UsergridHelpers.setReadOnly = function(obj, key) { + if (_.isArray(key)) { + return key.forEach(function(k) { + UsergridHelpers.setReadOnly(obj, k); + }); + } else if (_.isPlainObject(obj[key])) { + return Object.freeze(obj[key]); + } else if (_.isPlainObject(obj) && key === undefined) { + return Object.freeze(obj); + } else if (_.has(obj, key)) { + return Object.defineProperty(obj, key, { + writable: false + }); + } else { + return obj; + } + }; + UsergridHelpers.setWritable = function(obj, key) { + if (_.isArray(key)) { + return key.forEach(function(k) { + UsergridHelpers.setWritable(obj, k); + }); + } else if (_.isPlainObject(obj[key])) { + return _.clone(obj[key]); + } else if (_.isPlainObject(obj) && key === undefined) { + return _.clone(obj); + } else if (_.has(obj, key)) { + return Object.defineProperty(obj, key, { + writable: true + }); + } else { + return obj; + } + }; + UsergridHelpers.normalize = function(str, options) { + str = str.replace(/:\//g, "://"); + str = str.replace(/([^:\s])\/+/g, "$1/"); + str = str.replace(/\/(\?|&|#[^!])/g, "$1"); + str = str.replace(/(\?.+)\?/g, "$1&"); + return str; + }; + UsergridHelpers.urljoin = function() { + var input = arguments; + var options = {}; + if (typeof arguments[0] === "object") { + input = arguments[0]; + options = arguments[1] || {}; + } + var joined = [].slice.call(input, 0).join("/"); + return UsergridHelpers.normalize(joined, options); + }; + UsergridHelpers.uri = function(client, options) { + return UsergridHelpers.urljoin(client.baseUrl, client.orgId, client.appId, options.path || options.type, options.method !== "POST" ? _.first([ options.uuidOrName, options.uuid, options.name, _.get(options, "entity.uuid"), _.get(options, "entity.name"), "" ].filter(_.isString)) : ""); + }; + UsergridHelpers.headers = function(client, options) { + var headers = { + "User-Agent": "usergrid-js/v" + Usergrid.USERGRID_SDK_VERSION + }; + _.assign(headers, options.headers); + var token; + if (_.get(client, "tempAuth.isValid")) { + token = client.tempAuth.token; + client.tempAuth = undefined; + } else if (_.get(client, "currentUser.auth.isValid")) { + token = client.currentUser.auth.token; + } else if (_.get(client, "authFallback") === UsergridAuthMode.APP && _.get(client, "appAuth.isValid")) { + token = client.appAuth.token; + } + if (token) { + _.assign(headers, { + authorization: "Bearer " + token + }); + } + return headers; + }; + UsergridHelpers.qs = function(options) { + return options.query instanceof UsergridQuery ? { + ql: options.query._ql || undefined, + limit: options.query._limit, + cursor: options.query._cursor + } : options.qs; + }; + UsergridHelpers.formData = function(options) { + if (_.get(options, "asset.data")) { + var formData = {}; + formData.file = { + value: options.asset.data, + options: { + filename: _.get(options, "asset.filename") || "", + contentType: _.get(options, "asset.contentType") || "application/octet-stream" + } + }; + if (_.has(options, "asset.name")) { + formData.name = options.asset.name; + } + return formData; + } else { + return undefined; + } + }; + UsergridHelpers.encode = function(data) { + var result = ""; + if (typeof data === "string") { + result = data; + } else { + var e = encodeURIComponent; + for (var i in data) { + if (data.hasOwnProperty(i)) { + result += "&" + e(i) + "=" + e(data[i]); + } + } + } + return result; + }; + global[name] = UsergridHelpers; + global[name].noConflict = function() { + if (overwrittenName) { + global[name] = overwrittenName; + } + return UsergridHelpers; + }; + return global[name]; +})(this); /* Licensed under the Apache License, Version 2.0 (the "License"); @@ -15558,32 +15691,32 @@ var UsergridQuery = function(type) { return self; }, eq: function(key, value) { - query = self.andJoin(key + " = " + useQuotesIfRequired(value)); + query = self.andJoin(key + " = " + UsergridHelpers.useQuotesIfRequired(value)); return self; }, equal: this.eq, gt: function(key, value) { - query = self.andJoin(key + " > " + useQuotesIfRequired(value)); + query = self.andJoin(key + " > " + UsergridHelpers.useQuotesIfRequired(value)); return self; }, greaterThan: this.gt, gte: function(key, value) { - query = self.andJoin(key + " >= " + useQuotesIfRequired(value)); + query = self.andJoin(key + " >= " + UsergridHelpers.useQuotesIfRequired(value)); return self; }, greaterThanOrEqual: this.gte, lt: function(key, value) { - query = self.andJoin(key + " < " + useQuotesIfRequired(value)); + query = self.andJoin(key + " < " + UsergridHelpers.useQuotesIfRequired(value)); return self; }, lessThan: this.lt, lte: function(key, value) { - query = self.andJoin(key + " <= " + useQuotesIfRequired(value)); + query = self.andJoin(key + " <= " + UsergridHelpers.useQuotesIfRequired(value)); return self; }, lessThanOrEqual: this.lte, contains: function(key, value) { - query = self.andJoin(key + " contains " + useQuotesIfRequired(value)); + query = self.andJoin(key + " contains " + UsergridHelpers.useQuotesIfRequired(value)); return self; }, locationWithin: function(distanceInMeters, lat, lng) { @@ -15833,6 +15966,22 @@ function doCallback(callback, params, context) { Usergrid.isValidEndpoint = function(endpoint) { return true; }; + Usergrid.validateAndRetrieveClient = function(args) { + var client = undefined; + if (args instanceof Usergrid.Client) { + client = args; + } else if (args[0] instanceof Usergrid.Client) { + client = args[0]; + } else if (Usergrid.isInitialized) { + client = Usergrid.getInstance(); + } else { + throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument"); + } + return client; + }; + Usergrid.calculateExpiry = function(expires_in) { + return Date.now() + (expires_in ? expires_in - 5 : 0) * 1e3; + }; Usergrid.Request = function(method, endpoint, query_params, data, callback) { var p = new Promise(); /* @@ -15858,18 +16007,20 @@ function doCallback(callback, params, context) { } /* a callback to make the request */ var request = function() { - return Ajax.request(this.method, this.endpoint, this.data); + return new UsergridRequest({ + method: this.method, + uri: this.endpoint, + body: this.data + }); }.bind(this); /* a callback to process the response */ - var response = function(err, request) { - return new Usergrid.Response(err, request); + var response = function(request) { + return new UsergridResponse(request); }.bind(this); /* a callback to clean up and return data to the client */ - var oncomplete = function(err, response) { - p.done(err, response); - this.logger.info("REQUEST", err, response); - doCallback(callback, [ err, response ]); - this.logger.timeEnd("process request " + method + " " + endpoint); + var oncomplete = function(response) { + p.done(response); + doCallback(callback, [ response ]); }.bind(this); /* and a promise to chain them all together */ Promise.chain([ request, response ]).then(oncomplete); @@ -16044,15 +16195,11 @@ var defaultOptions = { qs = propCopy(qs, default_qs); } var self = this; - var req = new Usergrid.Request(method, uri, qs, body, function(err, response) { + var req = new Usergrid.Request(method, uri, qs, body, function(response) { /*if (AUTH_ERRORS.indexOf(response.error) !== -1) { return logoutCallback(); }*/ - if (err) { - doCallback(callback, [ err, response, self ], self); - } else { - doCallback(callback, [ null, response, self ], self); - } + doCallback(callback, [ response, self ], self); }); }; /* @@ -16769,6 +16916,62 @@ var defaultOptions = { return global[name]; })(); +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ +"use strict"; + +var UsergridRequest = function(options) { + var self = this; + var client = Usergrid.validateAndRetrieveClient(Usergrid.getInstance()); + if (!_.isString(options.type) && !_.isString(options.path) && !_.isString(options.uri)) { + throw new Error('one of "type" (collection name), "path", or "uri" parameters are required when initializing a UsergridRequest'); + } + if (!_.includes([ "GET", "PUT", "POST", "DELETE" ], options.method)) { + throw new Error('"method" parameter is required when initializing a UsergridRequest'); + } + self.method = options.method; + self.uri = options.uri || UsergridHelpers.uri(client, options); + self.headers = UsergridHelpers.headers(client, options); + self.body = options.body || undefined; + self.encoding = options.encoding || null; + self.qs = UsergridHelpers.qs(options); + if (_.isPlainObject(self.body)) { + self.body = JSON.stringify(self.body); + } + var promise = new Promise(); + var request = new XMLHttpRequest(); + request.open(self.method, self.uri); + request.open = function(m, u) { + for (var header in self.headers) { + if (self.headers.hasOwnProperty(header)) { + request.setRequestHeader(header, self.headers[header]); + } + } + if (self.body !== undefined) { + request.setRequestHeader("Content-Type", "application/json"); + request.setRequestHeader("Accept", "application/json"); + } + }; + request.onreadystatechange = function() { + if (this.readyState === XMLHttpRequest.DONE) { + promise.done(request); + } + }; + request.send(UsergridHelpers.encode(self.body)); + return promise; +}; + var ENTITY_SYSTEM_PROPERTIES = [ "metadata", "created", "modified", "oldpassword", "newpassword", "type", "activated", "uuid" ]; /* @@ -17434,6 +17637,280 @@ Usergrid.Entity.prototype.getPermissions = function(callback) { }); }; +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ +"use strict"; + +var UsergridAuth = function(token, expiry) { + var self = this; + self.token = token; + self.expiry = expiry || 0; + var usingToken = token ? true : false; + Object.defineProperty(self, "hasToken", { + get: function() { + return self.token ? true : false; + }, + configurable: true + }); + Object.defineProperty(self, "isExpired", { + get: function() { + return usingToken ? false : Date.now() >= self.expiry; + }, + configurable: true + }); + Object.defineProperty(self, "isValid", { + get: function() { + return !self.isExpired && self.hasToken; + }, + configurable: true + }); + Object.defineProperty(self, "tokenTtl", { + configurable: true, + writable: true + }); + _.assign(self, { + destroy: function() { + self.token = undefined; + self.expiry = 0; + self.tokenTtl = undefined; + } + }); + return self; +}; + +var UsergridAppAuth = function() { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + if (_.isPlainObject(args[0])) { + self.clientId = args[0].clientId; + self.clientSecret = args[0].clientSecret; + self.tokenTtl = args[0].tokenTtl; + } else { + self.clientId = args[0]; + self.clientSecret = args[1]; + self.tokenTtl = args[2]; + } + UsergridAuth.call(self); + _.assign(self, UsergridAuth); + return self; +}; + +UsergridHelpers.inherits(UsergridAppAuth, UsergridAuth); + +var UsergridUserAuth = function() { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + if (_.isPlainObject(args[0])) { + self.username = args[0].username; + self.email = args[0].email; + self.tokenTtl = args[0].tokenTtl; + } else { + self.username = args[0]; + self.email = args[1]; + self.tokenTtl = args[2]; + } + UsergridAuth.call(self); + _.assign(self, UsergridAuth); + return self; +}; + +UsergridHelpers.inherits(UsergridUserAuth, UsergridAuth); + +function updateEntityFromRemote(usergridResponse) { + UsergridHelpers.setWritable(this, [ "uuid", "name", "type", "created" ]); + _.assign(this, usergridResponse.entity); + UsergridHelpers.setReadOnly(this, [ "uuid", "name", "type", "created" ]); +} + +var UsergridEntity = function() { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + if (args.length === 0) { + throw new Error("A UsergridEntity object cannot be initialized without passing one or more arguments"); + } + if (_.isPlainObject(args[0])) { + _.assign(self, args[0]); + } else { + self.type = _.isString(args[0]) ? args[0] : undefined; + self.name = _.isString(args[1]) ? args[1] : undefined; + } + if (!_.isString(self.type)) { + throw new Error('"type" (or "collection") parameter is required when initializing a UsergridEntity object'); + } + Object.defineProperty(self, "tempAuth", { + enumerable: false, + configurable: true, + writable: true + }); + Object.defineProperty(self, "isUser", { + get: function() { + return self.type.toLowerCase() === "user"; + } + }); + Object.defineProperty(self, "hasAsset", { + get: function() { + return _.has(self, "file-metadata"); + } + }); + self.asset = undefined; + UsergridHelpers.setReadOnly(self, [ "uuid", "name", "type", "created" ]); + return self; +}; + +UsergridEntity.prototype = { + putProperty: function(key, value) { + this[key] = value; + }, + putProperties: function(obj) { + _.assign(this, obj); + }, + removeProperty: function(key) { + this.removeProperties([ key ]); + }, + removeProperties: function(keys) { + var self = this; + keys.forEach(function(key) { + delete self[key]; + }); + }, + insert: function(key, value, idx) { + if (!_.isArray(this[key])) { + this[key] = this[key] ? [ this[key] ] : []; + } + this[key].splice.apply(this[key], [ idx, 0 ].concat(value)); + }, + append: function(key, value) { + this.insert(key, value, Number.MAX_SAFE_INTEGER); + }, + prepend: function(key, value) { + this.insert(key, value, 0); + }, + pop: function(key) { + if (_.isArray(this[key])) { + this[key].pop(); + } + }, + shift: function(key) { + if (_.isArray(this[key])) { + this[key].shift(); + } + }, + reload: function() { + var args = helpers.args(arguments); + var client = helpers.client.validate(args); + var callback = UsergridHelpers.callback(args); + client.tempAuth = this.tempAuth; + this.tempAuth = undefined; + client.GET(this, function(error, usergridResponse) { + updateEntityFromRemote.call(this, usergridResponse); + callback(error, usergridResponse, this); + }.bind(this)); + }, + save: function() { + var args = UsergridHelpers.flattenArgs(arguments); + var client = Usergrid.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + client.tempAuth = this.tempAuth; + this.tempAuth = undefined; + client.PUT(this, function(error, usergridResponse) { + updateEntityFromRemote.call(this, usergridResponse); + callback(error, usergridResponse, this); + }.bind(this)); + }, + remove: function() { + var args = UsergridHelpers.flattenArgs(arguments); + var client = Usergrid.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + client.tempAuth = this.tempAuth; + this.tempAuth = undefined; + client.DELETE(this, function(error, usergridResponse) { + callback(error, usergridResponse, this); + }.bind(this)); + }, + attachAsset: function(asset) { + this.asset = asset; + }, + uploadAsset: function() { + var args = UsergridHelpers.flattenArgs(arguments); + var client = Usergrid.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + client.POST(this, this.asset, function(error, usergridResponse) { + updateEntityFromRemote.call(this, usergridResponse); + callback(error, usergridResponse, this); + }.bind(this)); + }, + downloadAsset: function() { + var args = UsergridHelpers.flattenArgs(arguments); + var client = Usergrid.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + var self = this; + if (_.has(self, "asset.contentType")) { + var options = { + client: client, + entity: self, + type: this.type, + method: "GET", + encoding: null, + headers: { + Accept: self.asset.contentType || _.first(args.filter(_.isString)) + } + }; + options.uri = helpers.build.uri(client, options); + return new UsergridRequest(options, function(error, usergridResponse) { + if (usergridResponse.ok) { + self.attachAsset(new UsergridAsset(new Buffer(usergridResponse.body))); + } + callback(error, usergridResponse, self); + }); + } else { + callback({ + name: "asset_not_found", + description: "The specified entity does not have a valid asset attached" + }); + } + }, + connect: function() { + var args = UsergridHelpers.flattenArgs(arguments); + var client = Usergrid.validateAndRetrieveClient(args); + client.tempAuth = this.tempAuth; + this.tempAuth = undefined; + args[0] = this; + return client.connect.apply(client, args); + }, + disconnect: function() { + var args = UsergridHelpers.flattenArgs(arguments); + var client = Usergrid.validateAndRetrieveClient(args); + client.tempAuth = this.tempAuth; + this.tempAuth = undefined; + args[0] = this; + return client.disconnect.apply(client, args); + }, + getConnections: function() { + var args = UsergridHelpers.flattenArgs(arguments); + var client = Usergrid.validateAndRetrieveClient(args); + client.tempAuth = this.tempAuth; + this.tempAuth = undefined; + args.shift(); + args.splice(1, 0, this); + return client.getConnections.apply(client, args); + }, + usingAuth: function(auth) { + this.tempAuth = helpers.client.configureTempAuth(auth); + return this; + } +}; + /* * The Collection class models Usergrid Collections. It essentially * acts as a container for holding Entity objects, while providing @@ -18403,6 +18880,106 @@ Usergrid.Folder.prototype.getAssets = function(callback) { return this.getConnections("assets", callback); }; +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ +"use strict"; + +var UsergridResponseError = function(responseErrorObject) { + var self = this; + if (_.has(responseErrorObject, "error") === false) { + return; + } + self.name = responseErrorObject.error; + self.description = responseErrorObject.error_description || responseErrorObject.description; + self.exception = responseErrorObject.exception; + return self; +}; + +var UsergridResponse = function(request) { + var p = new Promise(); + var self = this; + self.ok = false; + if (!request) { + return; + } else { + self.statusCode = parseInt(request.status); + var responseJSON; + try { + var responseText = request.responseText; + responseJSON = JSON.parse(responseText); + } catch (e) { + responseJSON = {}; + } + if (self.statusCode < 400) { + self.ok = true; + if (_.has(responseJSON, "entities")) { + var entities = responseJSON.entities.map(function(en) { + var entity = new UsergridEntity(en); + if (entity.isUser) { + entity = new UsergridUser(entity); + } + return entity; + }); + _.assign(self, { + metadata: _.cloneDeep(responseJSON), + entities: entities + }); + delete self.metadata.entities; + self.first = _.first(entities) || undefined; + self.entity = self.first; + self.last = _.last(entities) || undefined; + if (_.get(self, "metadata.path") === "/users") { + self.user = self.first; + self.users = self.entities; + } + Object.defineProperty(self, "hasNextPage", { + get: function() { + return _.has(self, "metadata.cursor"); + } + }); + UsergridHelpers.setReadOnly(self.metadata); + } + } else { + _.assign(self, { + error: new UsergridResponseError(responseJSON) + }); + } + } + if (this.success) { + p.done(this); + } else { + p.done(this); + } + return p; +}; + +UsergridResponse.prototype = { + loadNextPage: function() { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var callback = UsergridHelpers.callback(args); + if (!self.metadata.cursor) { + callback(); + } + var client = Usergrid.validateAndRetrieveClient(args); + var type = _.last(_.get(self, "metadata.path").split("/")); + var limit = _.first(_.get(this, "metadata.params.limit")); + var query = new UsergridQuery(type).cursor(this.metadata.cursor).limit(limit); + return client.GET(query, callback); + } +}; + /* * XMLHttpRequest.prototype.sendAsBinary polyfill * from: https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#sendAsBinary() @@ -18737,94 +19314,4 @@ Usergrid.Asset.prototype.download = function(callback) { return UsergridError; }; return global[name]; -})(this); - -/* - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -"use strict"; - -var UsergridAuth = function(token, expiry) { - var self = this; - self.token = token; - self.expiry = expiry || 0; - var usingToken = token ? true : false; - Object.defineProperty(self, "hasToken", { - get: function() { - return self.token ? true : false; - }, - configurable: true - }); - Object.defineProperty(self, "isExpired", { - get: function() { - return usingToken ? false : Date.now() >= self.expiry; - }, - configurable: true - }); - Object.defineProperty(self, "isValid", { - get: function() { - return !self.isExpired && self.hasToken; - }, - configurable: true - }); - Object.defineProperty(self, "tokenTtl", { - configurable: true, - writable: true - }); - _.assign(self, { - destroy: function() { - self.token = undefined; - self.expiry = 0; - self.tokenTtl = undefined; - } - }); - return self; -}; - -var UsergridAppAuth = function() { - var self = this; - var args = flattenArgs(arguments); - if (_.isPlainObject(args[0])) { - self.clientId = args[0].clientId; - self.clientSecret = args[0].clientSecret; - self.tokenTtl = args[0].tokenTtl; - } else { - self.clientId = args[0]; - self.clientSecret = args[1]; - self.tokenTtl = args[2]; - } - UsergridAuth.call(self); - _.assign(self, UsergridAuth); - return self; -}; - -inherits(UsergridAppAuth, UsergridAuth); - -var UsergridUserAuth = function() { - var self = this; - var args = flattenArgs(arguments); - if (_.isPlainObject(args[0])) { - self.username = args[0].username; - self.email = args[0].email; - self.tokenTtl = args[0].tokenTtl; - } else { - self.username = args[0]; - self.email = args[1]; - self.tokenTtl = args[2]; - } - UsergridAuth.call(self); - _.assign(self, UsergridAuth); - return self; -}; - -inherits(UsergridUserAuth, UsergridAuth); \ No newline at end of file +})(this); \ No newline at end of file diff --git a/usergrid.min.js b/usergrid.min.js index 6c12b8d..f8b74c6 100644 --- a/usergrid.min.js +++ b/usergrid.min.js @@ -17,12 +17,12 @@ *under the License. * * - * usergrid@0.11.0 2016-09-21 + * usergrid@0.11.0 2016-09-23 */ -"use strict";function inherits(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})}function flattenArgs(args){return _.flattenDeep(Array.prototype.slice.call(args))}function validateAndRetrieveClient(args){var client=void 0;if(args instanceof UsergridClient)client=args;else if(args[0]instanceof UsergridClient)client=args[0];else{if(!Usergrid.isInitialized)throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument");client=Usergrid.getInstance()}return client}function configureTempAuth(auth){return _.isString(auth)&&auth!==UsergridAuthMode.NONE?new UsergridAuth(auth):auth&&auth!==UsergridAuthMode.NONE&&auth instanceof UsergridAuth?auth:void 0}function useQuotesIfRequired(value){return _.isFinite(value)||isUUID(value)||_.isBoolean(value)||_.isObject(value)&&!_.isFunction(value)||_.isArray(value)?value:"'"+value+"'"}function extend(subClass,superClass){var F=function(){};return F.prototype=superClass.prototype,subClass.prototype=new F,subClass.prototype.constructor=subClass,subClass.superclass=superClass.prototype,superClass.prototype.constructor==Object.prototype.constructor&&(superClass.prototype.constructor=superClass),subClass}function propCopy(from,to){for(var prop in from)from.hasOwnProperty(prop)&&("object"==typeof from[prop]&&"object"==typeof to[prop]?to[prop]=propCopy(from[prop],to[prop]):to[prop]=from[prop]);return to}function NOOP(){}function isValidUrl(url){if(!url)return!1;var doc,base,anchor,isValid=!1;try{doc=document.implementation.createHTMLDocument(""),base=doc.createElement("base"),base.href=base||window.lo,doc.head.appendChild(base),anchor=doc.createElement("a"),anchor.href=url,doc.body.appendChild(anchor),isValid=!(""===anchor.href)}catch(e){console.error(e)}finally{return doc.head.removeChild(base),doc.body.removeChild(anchor),base=null,anchor=null,doc=null,isValid}}function isUUID(uuid){return uuid?uuidValueRegex.test(uuid):!1}function encodeParams(params){var queryString;return params&&Object.keys(params)&&(queryString=[].slice.call(arguments).reduce(function(a,b){return a.concat(b instanceof Array?b:[b])},[]).filter(function(c){return"object"==typeof c}).reduce(function(p,c){return c instanceof Array?p.push(c):p=p.concat(Object.keys(c).map(function(key){return[key,c[key]]})),p},[]).reduce(function(p,c){return 2===c.length?p.push(c):p=p.concat(c),p},[]).reduce(function(p,c){return c[1]instanceof Array?c[1].forEach(function(v){p.push([c[0],v])}):p.push(c),p},[]).map(function(c){return c[1]=encodeURIComponent(c[1]),c.join("=")}).join("&")),queryString}function isFunction(f){return f&&null!==f&&"function"==typeof f}function doCallback(callback,params,context){var returnValue;return isFunction(callback)&&(params||(params=[]),context||(context=this),params.push(context),returnValue=callback.apply(context,params)),returnValue}function getSafeTime(prop){var time;switch(typeof prop){case"undefined":time=Date.now();break;case"number":time=prop;break;case"string":time=isNaN(prop)?Date.parse(prop):parseInt(prop);break;default:time=Date.parse(prop.toString())}return time}var UsergridAuthMode=Object.freeze({NONE:"none",USER:"user",APP:"app"}),UsergridDirection=Object.freeze({IN:"connecting",OUT:"connections"}),UsergridHttpMethod=Object.freeze({GET:"GET",PUT:"PUT",POST:"POST",DELETE:"DELETE"}),UsergridQueryOperator=Object.freeze({EQUAL:"=",GREATER_THAN:">",GREATER_THAN_EQUAL_TO:">=",LESS_THAN:"<",LESS_THAN_EQUAL_TO:"<="}),UsergridQuerySortOrder=Object.freeze({ASC:"asc",DESC:"desc"}),UsergridEventable=function(){throw Error("'UsergridEventable' is not intended to be invoked directly")};UsergridEventable.prototype={bind:function(event,fn){this._events=this._events||{},this._events[event]=this._events[event]||[],this._events[event].push(fn)},unbind:function(event,fn){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fn),1)},trigger:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;ii;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,error,result){var p=new Promise;return null===promises||0===promises.length?p.done(error,result):promises[0](error,result).then(function(res,err){promises.splice(0,1),promises?Promise.chain(promises,res,err).then(function(r,e){p.done(r,e)}):p.done(res,err)}),p},global[name]=Promise,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Promise},global[name]}(this),function(){function partial(){var args=Array.prototype.slice.call(arguments),fn=args.shift();return fn.bind(this,args)}function Ajax(){function encode(data){var result="";if("string"==typeof data)result=data;else{var e=encodeURIComponent;for(var i in data)data.hasOwnProperty(i)&&(result+="&"+e(i)+"="+e(data[i]))}return result}function request(m,u,d){var timeout,p=new Promise;return self.logger.time(m+" "+u),function(xhr){xhr.onreadystatechange=function(){4===this.readyState&&(self.logger.timeEnd(m+" "+u),clearTimeout(timeout),p.done(null,this))},xhr.onerror=function(response){clearTimeout(timeout),p.done(response,null)},xhr.oncomplete=function(response){clearTimeout(timeout),self.logger.timeEnd(m+" "+u),self.info("%s request to %s returned %s",m,u,this.status)},xhr.open(m,u),d&&("object"==typeof d&&(d=JSON.stringify(d)),xhr.setRequestHeader("Content-Type","application/json"),xhr.setRequestHeader("Accept","application/json")),timeout=setTimeout(function(){xhr.abort(),p.done("API Call timed out.",null)},3e4),xhr.send(encode(d))}(new XMLHttpRequest),p}this.logger=new global.Logger(name);var self=this;this.request=request,this.get=partial(request,"GET"),this.post=partial(request,"POST"),this.put=partial(request,"PUT"),this["delete"]=partial(request,"DELETE")}var exports,name="Ajax",global=this,overwrittenName=global[name];return global[name]=new Ajax,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}(),function(){function addMapEntry(map,pair){return map.set(pair[0],pair[1]),map}function addSetEntry(set,value){return set.add(value),set}function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}function arrayAggregator(array,setter,iteratee,accumulator){for(var index=-1,length=array?array.length:0;++index-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1;);return index}function charsEndIndex(strSymbols,chrSymbols){for(var index=strSymbols.length;index--&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1;);return index}function countHolders(array,placeholder){for(var length=array.length,result=0;length--;)array[length]===placeholder&&++result;return result}function escapeStringChar(chr){return"\\"+stringEscapes[chr]}function getValue(object,key){return null==object?undefined:object[key]}function hasUnicode(string){return reHasUnicode.test(string)}function hasUnicodeWord(string){return reHasUnicodeWord.test(string)}function iteratorToArray(iterator){for(var data,result=[];!(data=iterator.next()).done;)result.push(data.value);return result}function mapToArray(map){var index=-1,result=Array(map.size);return map.forEach(function(value,key){result[++index]=[key,value]}),result}function overArg(func,transform){return function(arg){return func(transform(arg))}}function replaceHolders(array,placeholder){for(var index=-1,length=array.length,resIndex=0,result=[];++indexdir,arrLength=isArr?array.length:0,view=getView(0,arrLength,this.__views__),start=view.start,end=view.end,length=end-start,index=isRight?end:start-1,iteratees=this.__iteratees__,iterLength=iteratees.length,resIndex=0,takeCount=nativeMin(length,this.__takeCount__);if(!isArr||LARGE_ARRAY_SIZE>arrLength||arrLength==length&&takeCount==length)return baseWrapperValue(array,this.__actions__);var result=[];outer:for(;length--&&takeCount>resIndex;){index+=dir;for(var iterIndex=-1,value=array[index];++iterIndexindex)return!1;var lastIndex=data.length-1;return index==lastIndex?data.pop():splice.call(data,index,1),--this.size,!0}function listCacheGet(key){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?undefined:data[index][1]}function listCacheHas(key){return assocIndexOf(this.__data__,key)>-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?(++this.size,data.push([key,value])):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index=number?number:upper),lower!==undefined&&(number=number>=lower?number:lower)),number}function baseClone(value,isDeep,isFull,customizer,key,object,stack){var result;if(customizer&&(result=object?customizer(value,key,object,stack):customizer(value)),result!==undefined)return result;if(!isObject(value))return value;var isArr=isArray(value);if(isArr){if(result=initCloneArray(value),!isDeep)return copyArray(value,result)}else{var tag=getTag(value),isFunc=tag==funcTag||tag==genTag;if(isBuffer(value))return cloneBuffer(value,isDeep);if(tag==objectTag||tag==argsTag||isFunc&&!object){if(result=initCloneObject(isFunc?{}:value),!isDeep)return copySymbols(value,baseAssign(result,value))}else{if(!cloneableTags[tag])return object?value:{};result=initCloneByTag(value,tag,baseClone,isDeep)}}stack||(stack=new Stack);var stacked=stack.get(value);if(stacked)return stacked;if(stack.set(value,result),!isArr)var props=isFull?getAllKeys(value):keys(value);return arrayEach(props||value,function(subValue,key){props&&(key=subValue,subValue=value[key]),assignValue(result,key,baseClone(subValue,isDeep,isFull,customizer,key,value,stack))}),result}function baseConforms(source){var props=keys(source);return function(object){return baseConformsTo(object,source,props)}}function baseConformsTo(object,source,props){var length=props.length;if(null==object)return!length;for(object=Object(object);length--;){var key=props[length],predicate=source[key],value=object[key];if(value===undefined&&!(key in object)||!predicate(value))return!1}return!0}function baseCreate(proto){return isObject(proto)?objectCreate(proto):{}}function baseDelay(func,wait,args){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return setTimeout(function(){func.apply(undefined,args)},wait)}function baseDifference(array,values,iteratee,comparator){var index=-1,includes=arrayIncludes,isCommon=!0,length=array.length,result=[],valuesLength=values.length;if(!length)return result;iteratee&&(values=arrayMap(values,baseUnary(iteratee))),comparator?(includes=arrayIncludesWith,isCommon=!1):values.length>=LARGE_ARRAY_SIZE&&(includes=cacheHas,isCommon=!1,values=new SetCache(values));outer:for(;++indexstart&&(start=-start>length?0:length+start),end=end===undefined||end>length?length:toInteger(end),0>end&&(end+=length),end=start>end?0:toLength(end);end>start;)array[start++]=value;return array}function baseFilter(collection,predicate){var result=[];return baseEach(collection,function(value,index,collection){predicate(value,index,collection)&&result.push(value)}),result}function baseFlatten(array,depth,predicate,isStrict,result){var index=-1,length=array.length;for(predicate||(predicate=isFlattenable),result||(result=[]);++index0&&predicate(value)?depth>1?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}function baseForOwn(object,iteratee){return object&&baseFor(object,iteratee,keys)}function baseForOwnRight(object,iteratee){return object&&baseForRight(object,iteratee,keys)}function baseFunctions(object,props){return arrayFilter(props,function(key){return isFunction(object[key])})}function baseGet(object,path){path=isKey(path,object)?[path]:castPath(path);for(var index=0,length=path.length;null!=object&&length>index;)object=object[toKey(path[index++])];return index&&index==length?object:undefined}function baseGetAllKeys(object,keysFunc,symbolsFunc){var result=keysFunc(object);return isArray(object)?result:arrayPush(result,symbolsFunc(object))}function baseGetTag(value){return objectToString.call(value)}function baseGt(value,other){return value>other}function baseHas(object,key){return null!=object&&hasOwnProperty.call(object,key)}function baseHasIn(object,key){return null!=object&&key in Object(object)}function baseInRange(number,start,end){return number>=nativeMin(start,end)&&number=120&&array.length>=120)?new SetCache(othIndex&&array):undefined}array=arrays[0];var index=-1,seen=caches[0];outer:for(;++indexvalue}function baseMap(collection,iteratee){var index=-1,result=isArrayLike(collection)?Array(collection.length):[];return baseEach(collection,function(value,key,collection){result[++index]=iteratee(value,key,collection)}),result}function baseMatches(source){var matchData=getMatchData(source);return 1==matchData.length&&matchData[0][2]?matchesStrictComparable(matchData[0][0],matchData[0][1]):function(object){return object===source||baseIsMatch(object,source,matchData)}}function baseMatchesProperty(path,srcValue){return isKey(path)&&isStrictComparable(srcValue)?matchesStrictComparable(toKey(path),srcValue):function(object){var objValue=get(object,path);return objValue===undefined&&objValue===srcValue?hasIn(object,path):baseIsEqual(srcValue,objValue,undefined,UNORDERED_COMPARE_FLAG|PARTIAL_COMPARE_FLAG)}}function baseMerge(object,source,srcIndex,customizer,stack){if(object!==source){if(!isArray(source)&&!isTypedArray(source))var props=baseKeysIn(source);arrayEach(props||source,function(srcValue,key){if(props&&(key=srcValue,srcValue=source[key]),isObject(srcValue))stack||(stack=new Stack),baseMergeDeep(object,source,key,srcIndex,baseMerge,customizer,stack);else{var newValue=customizer?customizer(object[key],srcValue,key+"",object,source,stack):undefined;newValue===undefined&&(newValue=srcValue),assignMergeValue(object,key,newValue)}})}}function baseMergeDeep(object,source,key,srcIndex,mergeFunc,customizer,stack){var objValue=object[key],srcValue=source[key],stacked=stack.get(srcValue);if(stacked)return void assignMergeValue(object,key,stacked);var newValue=customizer?customizer(objValue,srcValue,key+"",object,source,stack):undefined,isCommon=newValue===undefined;isCommon&&(newValue=srcValue,isArray(srcValue)||isTypedArray(srcValue)?isArray(objValue)?newValue=objValue:isArrayLikeObject(objValue)?newValue=copyArray(objValue):(isCommon=!1,newValue=baseClone(srcValue,!0)):isPlainObject(srcValue)||isArguments(srcValue)?isArguments(objValue)?newValue=toPlainObject(objValue):!isObject(objValue)||srcIndex&&isFunction(objValue)?(isCommon=!1,newValue=baseClone(srcValue,!0)):newValue=objValue:isCommon=!1),isCommon&&(stack.set(srcValue,newValue),mergeFunc(newValue,srcValue,srcIndex,customizer,stack),stack["delete"](srcValue)),assignMergeValue(object,key,newValue)}function baseNth(array,n){var length=array.length;if(length)return n+=0>n?length:0,isIndex(n,length)?array[n]:undefined}function baseOrderBy(collection,iteratees,orders){var index=-1;iteratees=arrayMap(iteratees.length?iteratees:[identity],baseUnary(getIteratee()));var result=baseMap(collection,function(value,key,collection){var criteria=arrayMap(iteratees,function(iteratee){return iteratee(value)});return{criteria:criteria,index:++index,value:value}});return baseSortBy(result,function(object,other){return compareMultiple(object,other,orders)})}function basePick(object,props){return object=Object(object),basePickBy(object,props,function(value,key){return key in object})}function basePickBy(object,props,predicate){for(var index=-1,length=props.length,result={};++index-1;)seen!==array&&splice.call(seen,fromIndex,1),splice.call(array,fromIndex,1);return array}function basePullAt(array,indexes){for(var length=array?indexes.length:0,lastIndex=length-1;length--;){var index=indexes[length];if(length==lastIndex||index!==previous){var previous=index;if(isIndex(index))splice.call(array,index,1);else if(isKey(index,array))delete array[toKey(index)];else{var path=castPath(index),object=parent(array,path);null!=object&&delete object[toKey(last(path))]}}}return array}function baseRandom(lower,upper){return lower+nativeFloor(nativeRandom()*(upper-lower+1))}function baseRange(start,end,step,fromRight){for(var index=-1,length=nativeMax(nativeCeil((end-start)/(step||1)),0),result=Array(length);length--;)result[fromRight?length:++index]=start,start+=step;return result}function baseRepeat(string,n){var result="";if(!string||1>n||n>MAX_SAFE_INTEGER)return result;do n%2&&(result+=string),n=nativeFloor(n/2),n&&(string+=string);while(n);return result}function baseRest(func,start){return setToString(overRest(func,start,identity),func+"")}function baseSet(object,path,value,customizer){if(!isObject(object))return object;path=isKey(path,object)?[path]:castPath(path);for(var index=-1,length=path.length,lastIndex=length-1,nested=object;null!=nested&&++indexstart&&(start=-start>length?0:length+start),end=end>length?length:end,0>end&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index=high){for(;high>low;){var mid=low+high>>>1,computed=array[mid];null!==computed&&!isSymbol(computed)&&(retHighest?value>=computed:value>computed)?low=mid+1:high=mid}return high}return baseSortedIndexBy(array,value,identity,retHighest)}function baseSortedIndexBy(array,value,iteratee,retHighest){value=iteratee(value);for(var low=0,high=array?array.length:0,valIsNaN=value!==value,valIsNull=null===value,valIsSymbol=isSymbol(value),valIsUndefined=value===undefined;high>low;){var mid=nativeFloor((low+high)/2),computed=iteratee(array[mid]),othIsDefined=computed!==undefined,othIsNull=null===computed,othIsReflexive=computed===computed,othIsSymbol=isSymbol(computed);if(valIsNaN)var setLow=retHighest||othIsReflexive;else setLow=valIsUndefined?othIsReflexive&&(retHighest||othIsDefined):valIsNull?othIsReflexive&&othIsDefined&&(retHighest||!othIsNull):valIsSymbol?othIsReflexive&&othIsDefined&&!othIsNull&&(retHighest||!othIsSymbol):othIsNull||othIsSymbol?!1:retHighest?value>=computed:value>computed;setLow?low=mid+1:high=mid}return nativeMin(high,MAX_ARRAY_INDEX)}function baseSortedUniq(array,iteratee){for(var index=-1,length=array.length,resIndex=0,result=[];++index=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++indexindex?values[index]:undefined;assignFunc(result,props[index],value)}return result}function castArrayLikeObject(value){return isArrayLikeObject(value)?value:[]}function castFunction(value){return"function"==typeof value?value:identity}function castPath(value){return isArray(value)?value:stringToPath(value)}function castSlice(array,start,end){var length=array.length;return end=end===undefined?length:end,!start&&end>=length?array:baseSlice(array,start,end)}function cloneBuffer(buffer,isDeep){if(isDeep)return buffer.slice();var result=new buffer.constructor(buffer.length);return buffer.copy(result),result}function cloneArrayBuffer(arrayBuffer){var result=new arrayBuffer.constructor(arrayBuffer.byteLength);return new Uint8Array(result).set(new Uint8Array(arrayBuffer)),result}function cloneDataView(dataView,isDeep){var buffer=isDeep?cloneArrayBuffer(dataView.buffer):dataView.buffer;return new dataView.constructor(buffer,dataView.byteOffset,dataView.byteLength)}function cloneMap(map,isDeep,cloneFunc){var array=isDeep?cloneFunc(mapToArray(map),!0):mapToArray(map);return arrayReduce(array,addMapEntry,new map.constructor)}function cloneRegExp(regexp){var result=new regexp.constructor(regexp.source,reFlags.exec(regexp));return result.lastIndex=regexp.lastIndex,result}function cloneSet(set,isDeep,cloneFunc){var array=isDeep?cloneFunc(setToArray(set),!0):setToArray(set);return arrayReduce(array,addSetEntry,new set.constructor)}function cloneSymbol(symbol){return symbolValueOf?Object(symbolValueOf.call(symbol)):{}}function cloneTypedArray(typedArray,isDeep){var buffer=isDeep?cloneArrayBuffer(typedArray.buffer):typedArray.buffer;return new typedArray.constructor(buffer,typedArray.byteOffset,typedArray.length)}function compareAscending(value,other){if(value!==other){var valIsDefined=value!==undefined,valIsNull=null===value,valIsReflexive=value===value,valIsSymbol=isSymbol(value),othIsDefined=other!==undefined,othIsNull=null===other,othIsReflexive=other===other,othIsSymbol=isSymbol(other);if(!othIsNull&&!othIsSymbol&&!valIsSymbol&&value>other||valIsSymbol&&othIsDefined&&othIsReflexive&&!othIsNull&&!othIsSymbol||valIsNull&&othIsDefined&&othIsReflexive||!valIsDefined&&othIsReflexive||!valIsReflexive)return 1;if(!valIsNull&&!valIsSymbol&&!othIsSymbol&&other>value||othIsSymbol&&valIsDefined&&valIsReflexive&&!valIsNull&&!valIsSymbol||othIsNull&&valIsDefined&&valIsReflexive||!othIsDefined&&valIsReflexive||!othIsReflexive)return-1}return 0}function compareMultiple(object,other,orders){for(var index=-1,objCriteria=object.criteria,othCriteria=other.criteria,length=objCriteria.length,ordersLength=orders.length;++index=ordersLength)return result;var order=orders[index];return result*("desc"==order?-1:1)}}return object.index-other.index}function composeArgs(args,partials,holders,isCurried){for(var argsIndex=-1,argsLength=args.length,holdersLength=holders.length,leftIndex=-1,leftLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(leftLength+rangeLength),isUncurried=!isCurried;++leftIndexargsIndex)&&(result[holders[argsIndex]]=args[argsIndex]);for(;rangeLength--;)result[leftIndex++]=args[argsIndex++];return result}function composeArgsRight(args,partials,holders,isCurried){for(var argsIndex=-1,argsLength=args.length,holdersIndex=-1,holdersLength=holders.length,rightIndex=-1,rightLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(rangeLength+rightLength),isUncurried=!isCurried;++argsIndexargsIndex)&&(result[offset+holders[holdersIndex]]=args[argsIndex++]);return result}function copyArray(source,array){var index=-1,length=source.length;for(array||(array=Array(length));++index1?sources[length-1]:undefined,guard=length>2?sources[2]:undefined;for(customizer=assigner.length>3&&"function"==typeof customizer?(length--,customizer):undefined,guard&&isIterateeCall(sources[0],sources[1],guard)&&(customizer=3>length?undefined:customizer,length=1),object=Object(object);++indexlength&&args[0]!==placeholder&&args[length-1]!==placeholder?[]:replaceHolders(args,placeholder);if(length-=holders.length,arity>length)return createRecurry(func,bitmask,createHybrid,wrapper.placeholder,undefined,args,holders,undefined,undefined,arity-length);var fn=this&&this!==root&&this instanceof wrapper?Ctor:func;return apply(fn,this,args)}var Ctor=createCtor(func);return wrapper}function createFind(findIndexFunc){return function(collection,predicate,fromIndex){var iterable=Object(collection);if(!isArrayLike(collection)){var iteratee=getIteratee(predicate,3);collection=keys(collection),predicate=function(key){return iteratee(iterable[key],key,iterable)}}var index=findIndexFunc(collection,predicate,fromIndex);return index>-1?iterable[iteratee?collection[index]:index]:undefined}}function createFlow(fromRight){return flatRest(function(funcs){var length=funcs.length,index=length,prereq=LodashWrapper.prototype.thru;for(fromRight&&funcs.reverse();index--;){var func=funcs[index];if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);if(prereq&&!wrapper&&"wrapper"==getFuncName(func))var wrapper=new LodashWrapper([],!0)}for(index=wrapper?index:length;++index=LARGE_ARRAY_SIZE)return wrapper.plant(value).value();for(var index=0,result=length?funcs[index].apply(this,args):value;++indexlength){var newHolders=replaceHolders(args,placeholder);return createRecurry(func,bitmask,createHybrid,wrapper.placeholder,thisArg,args,newHolders,argPos,ary,arity-length)}var thisBinding=isBind?thisArg:this,fn=isBindKey?thisBinding[func]:func;return length=args.length,argPos?args=reorder(args,argPos):isFlip&&length>1&&args.reverse(),isAry&&length>ary&&(args.length=ary),this&&this!==root&&this instanceof wrapper&&(fn=Ctor||createCtor(fn)),fn.apply(thisBinding,args)}var isAry=bitmask&ARY_FLAG,isBind=bitmask&BIND_FLAG,isBindKey=bitmask&BIND_KEY_FLAG,isCurried=bitmask&(CURRY_FLAG|CURRY_RIGHT_FLAG),isFlip=bitmask&FLIP_FLAG,Ctor=isBindKey?undefined:createCtor(func);return wrapper}function createInverter(setter,toIteratee){return function(object,iteratee){return baseInverter(object,setter,toIteratee(iteratee),{})}}function createMathOperation(operator,defaultValue){return function(value,other){var result;if(value===undefined&&other===undefined)return defaultValue;if(value!==undefined&&(result=value),other!==undefined){if(result===undefined)return other;"string"==typeof value||"string"==typeof other?(value=baseToString(value),other=baseToString(other)):(value=baseToNumber(value),other=baseToNumber(other)),result=operator(value,other)}return result}}function createOver(arrayFunc){return flatRest(function(iteratees){return iteratees=arrayMap(iteratees,baseUnary(getIteratee())),baseRest(function(args){var thisArg=this;return arrayFunc(iteratees,function(iteratee){return apply(iteratee,thisArg,args)})})})}function createPadding(length,chars){chars=chars===undefined?" ":baseToString(chars);var charsLength=chars.length;if(2>charsLength)return charsLength?baseRepeat(chars,length):chars;var result=baseRepeat(chars,nativeCeil(length/stringSize(chars)));return hasUnicode(chars)?castSlice(stringToArray(result),0,length).join(""):result.slice(0,length)}function createPartial(func,bitmask,thisArg,partials){function wrapper(){for(var argsIndex=-1,argsLength=arguments.length,leftIndex=-1,leftLength=partials.length,args=Array(leftLength+argsLength),fn=this&&this!==root&&this instanceof wrapper?Ctor:func;++leftIndexstart?1:-1:toFinite(step),baseRange(start,end,step,fromRight)}}function createRelationalOperation(operator){return function(value,other){return("string"!=typeof value||"string"!=typeof other)&&(value=toNumber(value),other=toNumber(other)),operator(value,other)}}function createRecurry(func,bitmask,wrapFunc,placeholder,thisArg,partials,holders,argPos,ary,arity){var isCurry=bitmask&CURRY_FLAG,newHolders=isCurry?holders:undefined,newHoldersRight=isCurry?undefined:holders,newPartials=isCurry?partials:undefined,newPartialsRight=isCurry?undefined:partials;bitmask|=isCurry?PARTIAL_FLAG:PARTIAL_RIGHT_FLAG,bitmask&=~(isCurry?PARTIAL_RIGHT_FLAG:PARTIAL_FLAG),bitmask&CURRY_BOUND_FLAG||(bitmask&=~(BIND_FLAG|BIND_KEY_FLAG));var newData=[func,bitmask,thisArg,newPartials,newHolders,newPartialsRight,newHoldersRight,argPos,ary,arity],result=wrapFunc.apply(undefined,newData);return isLaziable(func)&&setData(result,newData),result.placeholder=placeholder,setWrapToString(result,func,bitmask)}function createRound(methodName){var func=Math[methodName];return function(number,precision){if(number=toNumber(number),precision=nativeMin(toInteger(precision),292)){var pair=(toString(number)+"e").split("e"),value=func(pair[0]+"e"+(+pair[1]+precision));return pair=(toString(value)+"e").split("e"),+(pair[0]+"e"+(+pair[1]-precision))}return func(number)}}function createToPairs(keysFunc){return function(object){var tag=getTag(object);return tag==mapTag?mapToArray(object):tag==setTag?setToPairs(object):baseToPairs(object,keysFunc(object))}}function createWrap(func,bitmask,thisArg,partials,holders,argPos,ary,arity){var isBindKey=bitmask&BIND_KEY_FLAG;if(!isBindKey&&"function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);var length=partials?partials.length:0;if(length||(bitmask&=~(PARTIAL_FLAG|PARTIAL_RIGHT_FLAG),partials=holders=undefined),ary=ary===undefined?ary:nativeMax(toInteger(ary),0),arity=arity===undefined?arity:toInteger(arity),length-=holders?holders.length:0,bitmask&PARTIAL_RIGHT_FLAG){var partialsRight=partials,holdersRight=holders;partials=holders=undefined}var data=isBindKey?undefined:getData(func),newData=[func,bitmask,thisArg,partials,holders,partialsRight,holdersRight,argPos,ary,arity];if(data&&mergeData(newData,data),func=newData[0],bitmask=newData[1],thisArg=newData[2],partials=newData[3],holders=newData[4],arity=newData[9]=null==newData[9]?isBindKey?0:func.length:nativeMax(newData[9]-length,0),!arity&&bitmask&(CURRY_FLAG|CURRY_RIGHT_FLAG)&&(bitmask&=~(CURRY_FLAG|CURRY_RIGHT_FLAG)),bitmask&&bitmask!=BIND_FLAG)result=bitmask==CURRY_FLAG||bitmask==CURRY_RIGHT_FLAG?createCurry(func,bitmask,arity):bitmask!=PARTIAL_FLAG&&bitmask!=(BIND_FLAG|PARTIAL_FLAG)||holders.length?createHybrid.apply(undefined,newData):createPartial(func,bitmask,thisArg,partials);else var result=createBind(func,bitmask,thisArg);var setter=data?baseSetData:setData;return setWrapToString(setter(result,newData),func,bitmask)}function equalArrays(array,other,equalFunc,customizer,bitmask,stack){var isPartial=bitmask&PARTIAL_COMPARE_FLAG,arrLength=array.length,othLength=other.length;if(arrLength!=othLength&&!(isPartial&&othLength>arrLength))return!1;var stacked=stack.get(array);if(stacked&&stack.get(other))return stacked==other;var index=-1,result=!0,seen=bitmask&UNORDERED_COMPARE_FLAG?new SetCache:undefined;for(stack.set(array,other),stack.set(other,array);++index1?"& ":"")+details[lastIndex],details=details.join(length>2?", ":" "),source.replace(reWrapComment,"{\n/* [wrapped with "+details+"] */\n")}function isFlattenable(value){return isArray(value)||isArguments(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol])}function isIndex(value,length){return length=null==length?MAX_SAFE_INTEGER:length,!!length&&("number"==typeof value||reIsUint.test(value))&&value>-1&&value%1==0&&length>value}function isIterateeCall(value,index,object){if(!isObject(object))return!1;var type=typeof index;return("number"==type?isArrayLike(object)&&isIndex(index,object.length):"string"==type&&index in object)?eq(object[index],value):!1}function isKey(value,object){if(isArray(value))return!1;var type=typeof value;return"number"==type||"symbol"==type||"boolean"==type||null==value||isSymbol(value)?!0:reIsPlainProp.test(value)||!reIsDeepProp.test(value)||null!=object&&value in Object(object)}function isKeyable(value){var type=typeof value;return"string"==type||"number"==type||"symbol"==type||"boolean"==type?"__proto__"!==value:null===value}function isLaziable(func){var funcName=getFuncName(func),other=lodash[funcName];if("function"!=typeof other||!(funcName in LazyWrapper.prototype))return!1;if(func===other)return!0;var data=getData(other);return!!data&&func===data[0]}function isMasked(func){return!!maskSrcKey&&maskSrcKey in func}function isPrototype(value){var Ctor=value&&value.constructor,proto="function"==typeof Ctor&&Ctor.prototype||objectProto;return value===proto}function isStrictComparable(value){return value===value&&!isObject(value)}function matchesStrictComparable(key,srcValue){return function(object){return null==object?!1:object[key]===srcValue&&(srcValue!==undefined||key in Object(object))}}function memoizeCapped(func){var result=memoize(func,function(key){return cache.size===MAX_MEMOIZE_SIZE&&cache.clear(),key}),cache=result.cache;return result}function mergeData(data,source){var bitmask=data[1],srcBitmask=source[1],newBitmask=bitmask|srcBitmask,isCommon=(BIND_FLAG|BIND_KEY_FLAG|ARY_FLAG)>newBitmask,isCombo=srcBitmask==ARY_FLAG&&bitmask==CURRY_FLAG||srcBitmask==ARY_FLAG&&bitmask==REARG_FLAG&&data[7].length<=source[8]||srcBitmask==(ARY_FLAG|REARG_FLAG)&&source[7].length<=source[8]&&bitmask==CURRY_FLAG;if(!isCommon&&!isCombo)return data;srcBitmask&BIND_FLAG&&(data[2]=source[2],newBitmask|=bitmask&BIND_FLAG?0:CURRY_BOUND_FLAG);var value=source[3];if(value){var partials=data[3];data[3]=partials?composeArgs(partials,value,source[4]):value,data[4]=partials?replaceHolders(data[3],PLACEHOLDER):source[4]}return value=source[5],value&&(partials=data[5],data[5]=partials?composeArgsRight(partials,value,source[6]):value,data[6]=partials?replaceHolders(data[5],PLACEHOLDER):source[6]),value=source[7],value&&(data[7]=value),srcBitmask&ARY_FLAG&&(data[8]=null==data[8]?source[8]:nativeMin(data[8],source[8])),null==data[9]&&(data[9]=source[9]),data[0]=source[0],data[1]=newBitmask,data}function mergeDefaults(objValue,srcValue,key,object,source,stack){return isObject(objValue)&&isObject(srcValue)&&(stack.set(srcValue,objValue),baseMerge(objValue,srcValue,undefined,mergeDefaults,stack),stack["delete"](srcValue)),objValue}function nativeKeysIn(object){var result=[];if(null!=object)for(var key in Object(object))result.push(key);return result}function overRest(func,start,transform){return start=nativeMax(start===undefined?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index0){if(++count>=HOT_COUNT)return arguments[0]}else count=0;return func.apply(undefined,arguments)}}function shuffleSelf(array){for(var index=-1,length=array.length,lastIndex=length-1;++indexsize)return[];for(var index=0,resIndex=0,result=Array(nativeCeil(length/size));length>index;)result[resIndex++]=baseSlice(array,index,index+=size);return result}function compact(array){for(var index=-1,length=array?array.length:0,resIndex=0,result=[];++indexn?0:n,length)):[]}function dropRight(array,n,guard){var length=array?array.length:0;return length?(n=guard||n===undefined?1:toInteger(n),n=length-n,baseSlice(array,0,0>n?0:n)):[]}function dropRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!0,!0):[]}function dropWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!0):[]}function fill(array,value,start,end){var length=array?array.length:0;return length?(start&&"number"!=typeof start&&isIterateeCall(array,value,start)&&(start=0,end=length),baseFill(array,value,start,end)):[]}function findIndex(array,predicate,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=null==fromIndex?0:toInteger(fromIndex);return 0>index&&(index=nativeMax(length+index,0)),baseFindIndex(array,getIteratee(predicate,3),index)}function findLastIndex(array,predicate,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=length-1;return fromIndex!==undefined&&(index=toInteger(fromIndex),index=0>fromIndex?nativeMax(length+index,0):nativeMin(index,length-1)),baseFindIndex(array,getIteratee(predicate,3),index,!0)}function flatten(array){var length=array?array.length:0;return length?baseFlatten(array,1):[]}function flattenDeep(array){var length=array?array.length:0;return length?baseFlatten(array,INFINITY):[]}function flattenDepth(array,depth){var length=array?array.length:0;return length?(depth=depth===undefined?1:toInteger(depth),baseFlatten(array,depth)):[]}function fromPairs(pairs){for(var index=-1,length=pairs?pairs.length:0,result={};++indexindex&&(index=nativeMax(length+index,0)),baseIndexOf(array,value,index)}function initial(array){var length=array?array.length:0;return length?baseSlice(array,0,-1):[]}function join(array,separator){return array?nativeJoin.call(array,separator):""}function last(array){var length=array?array.length:0;return length?array[length-1]:undefined}function lastIndexOf(array,value,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=length;return fromIndex!==undefined&&(index=toInteger(fromIndex),index=0>index?nativeMax(length+index,0):nativeMin(index,length-1)),value===value?strictLastIndexOf(array,value,index):baseFindIndex(array,baseIsNaN,index,!0)}function nth(array,n){return array&&array.length?baseNth(array,toInteger(n)):undefined}function pullAll(array,values){return array&&array.length&&values&&values.length?basePullAll(array,values):array}function pullAllBy(array,values,iteratee){return array&&array.length&&values&&values.length?basePullAll(array,values,getIteratee(iteratee,2)):array}function pullAllWith(array,values,comparator){return array&&array.length&&values&&values.length?basePullAll(array,values,undefined,comparator):array}function remove(array,predicate){var result=[];if(!array||!array.length)return result;var index=-1,indexes=[],length=array.length;for(predicate=getIteratee(predicate,3);++indexindex&&eq(array[index],value))return index}return-1}function sortedLastIndex(array,value){return baseSortedIndex(array,value,!0)}function sortedLastIndexBy(array,value,iteratee){return baseSortedIndexBy(array,value,getIteratee(iteratee,2),!0)}function sortedLastIndexOf(array,value){var length=array?array.length:0;if(length){var index=baseSortedIndex(array,value,!0)-1;if(eq(array[index],value))return index}return-1}function sortedUniq(array){return array&&array.length?baseSortedUniq(array):[]}function sortedUniqBy(array,iteratee){return array&&array.length?baseSortedUniq(array,getIteratee(iteratee,2)):[]}function tail(array){var length=array?array.length:0;return length?baseSlice(array,1,length):[]}function take(array,n,guard){return array&&array.length?(n=guard||n===undefined?1:toInteger(n),baseSlice(array,0,0>n?0:n)):[]}function takeRight(array,n,guard){var length=array?array.length:0;return length?(n=guard||n===undefined?1:toInteger(n),n=length-n,baseSlice(array,0>n?0:n,length)):[]}function takeRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!1,!0):[]}function takeWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3)):[]}function uniq(array){return array&&array.length?baseUniq(array):[]}function uniqBy(array,iteratee){return array&&array.length?baseUniq(array,getIteratee(iteratee,2)):[]}function uniqWith(array,comparator){return array&&array.length?baseUniq(array,undefined,comparator):[]}function unzip(array){if(!array||!array.length)return[];var length=0;return array=arrayFilter(array,function(group){return isArrayLikeObject(group)?(length=nativeMax(group.length,length),!0):void 0}),baseTimes(length,function(index){return arrayMap(array,baseProperty(index))})}function unzipWith(array,iteratee){if(!array||!array.length)return[];var result=unzip(array);return null==iteratee?result:arrayMap(result,function(group){return apply(iteratee,undefined,group)})}function zipObject(props,values){return baseZipObject(props||[],values||[],assignValue)}function zipObjectDeep(props,values){return baseZipObject(props||[],values||[],baseSet)}function chain(value){var result=lodash(value);return result.__chain__=!0,result}function tap(value,interceptor){return interceptor(value),value}function thru(value,interceptor){return interceptor(value)}function wrapperChain(){return chain(this)}function wrapperCommit(){return new LodashWrapper(this.value(),this.__chain__)}function wrapperNext(){this.__values__===undefined&&(this.__values__=toArray(this.value()));var done=this.__index__>=this.__values__.length,value=done?undefined:this.__values__[this.__index__++];return{done:done,value:value}}function wrapperToIterator(){return this}function wrapperPlant(value){for(var result,parent=this;parent instanceof baseLodash;){var clone=wrapperClone(parent);clone.__index__=0,clone.__values__=undefined,result?previous.__wrapped__=clone:result=clone;var previous=clone;parent=parent.__wrapped__}return previous.__wrapped__=value,result}function wrapperReverse(){var value=this.__wrapped__;if(value instanceof LazyWrapper){var wrapped=value;return this.__actions__.length&&(wrapped=new LazyWrapper(this)),wrapped=wrapped.reverse(),wrapped.__actions__.push({func:thru,args:[reverse],thisArg:undefined}),new LodashWrapper(wrapped,this.__chain__)}return this.thru(reverse)}function wrapperValue(){return baseWrapperValue(this.__wrapped__,this.__actions__)}function every(collection,predicate,guard){var func=isArray(collection)?arrayEvery:baseEvery;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=undefined),func(collection,getIteratee(predicate,3))}function filter(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,getIteratee(predicate,3))}function flatMap(collection,iteratee){return baseFlatten(map(collection,iteratee),1)}function flatMapDeep(collection,iteratee){return baseFlatten(map(collection,iteratee),INFINITY)}function flatMapDepth(collection,iteratee,depth){return depth=depth===undefined?1:toInteger(depth),baseFlatten(map(collection,iteratee),depth)}function forEach(collection,iteratee){var func=isArray(collection)?arrayEach:baseEach;return func(collection,getIteratee(iteratee,3))}function forEachRight(collection,iteratee){var func=isArray(collection)?arrayEachRight:baseEachRight;return func(collection,getIteratee(iteratee,3))}function includes(collection,value,fromIndex,guard){collection=isArrayLike(collection)?collection:values(collection),fromIndex=fromIndex&&!guard?toInteger(fromIndex):0;var length=collection.length;return 0>fromIndex&&(fromIndex=nativeMax(length+fromIndex,0)),isString(collection)?length>=fromIndex&&collection.indexOf(value,fromIndex)>-1:!!length&&baseIndexOf(collection,value,fromIndex)>-1}function map(collection,iteratee){var func=isArray(collection)?arrayMap:baseMap;return func(collection,getIteratee(iteratee,3))}function orderBy(collection,iteratees,orders,guard){return null==collection?[]:(isArray(iteratees)||(iteratees=null==iteratees?[]:[iteratees]),orders=guard?undefined:orders,isArray(orders)||(orders=null==orders?[]:[orders]),baseOrderBy(collection,iteratees,orders))}function reduce(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduce:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEach)}function reduceRight(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduceRight:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEachRight)}function reject(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,negate(getIteratee(predicate,3)))}function sample(collection){return arraySample(isArrayLike(collection)?collection:values(collection))}function sampleSize(collection,n,guard){return n=(guard?isIterateeCall(collection,n,guard):n===undefined)?1:toInteger(n),arraySampleSize(isArrayLike(collection)?collection:values(collection),n)}function shuffle(collection){return shuffleSelf(isArrayLike(collection)?copyArray(collection):values(collection))}function size(collection){if(null==collection)return 0;if(isArrayLike(collection))return isString(collection)?stringSize(collection):collection.length;var tag=getTag(collection);return tag==mapTag||tag==setTag?collection.size:baseKeys(collection).length}function some(collection,predicate,guard){var func=isArray(collection)?arraySome:baseSome;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=undefined),func(collection,getIteratee(predicate,3))}function after(n,func){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return n=toInteger(n),function(){return--n<1?func.apply(this,arguments):void 0}}function ary(func,n,guard){return n=guard?undefined:n,n=func&&null==n?func.length:n,createWrap(func,ARY_FLAG,undefined,undefined,undefined,undefined,n)}function before(n,func){var result;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return n=toInteger(n),function(){return--n>0&&(result=func.apply(this,arguments)),1>=n&&(func=undefined),result}}function curry(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,CURRY_FLAG,undefined,undefined,undefined,undefined,undefined,arity);return result.placeholder=curry.placeholder,result}function curryRight(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,CURRY_RIGHT_FLAG,undefined,undefined,undefined,undefined,undefined,arity);return result.placeholder=curryRight.placeholder,result}function debounce(func,wait,options){function invokeFunc(time){var args=lastArgs,thisArg=lastThis;return lastArgs=lastThis=undefined,lastInvokeTime=time,result=func.apply(thisArg,args)}function leadingEdge(time){return lastInvokeTime=time,timerId=setTimeout(timerExpired,wait),leading?invokeFunc(time):result}function remainingWait(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime,result=wait-timeSinceLastCall;return maxing?nativeMin(result,maxWait-timeSinceLastInvoke):result}function shouldInvoke(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime;return lastCallTime===undefined||timeSinceLastCall>=wait||0>timeSinceLastCall||maxing&&timeSinceLastInvoke>=maxWait}function timerExpired(){var time=now();return shouldInvoke(time)?trailingEdge(time):void(timerId=setTimeout(timerExpired,remainingWait(time)))}function trailingEdge(time){return timerId=undefined,trailing&&lastArgs?invokeFunc(time):(lastArgs=lastThis=undefined,result)}function cancel(){timerId!==undefined&&clearTimeout(timerId),lastInvokeTime=0,lastArgs=lastCallTime=lastThis=timerId=undefined}function flush(){return timerId===undefined?result:trailingEdge(now())}function debounced(){var time=now(),isInvoking=shouldInvoke(time);if(lastArgs=arguments,lastThis=this,lastCallTime=time,isInvoking){if(timerId===undefined)return leadingEdge(lastCallTime);if(maxing)return timerId=setTimeout(timerExpired,wait),invokeFunc(lastCallTime)}return timerId===undefined&&(timerId=setTimeout(timerExpired,wait)),result}var lastArgs,lastThis,maxWait,result,timerId,lastCallTime,lastInvokeTime=0,leading=!1,maxing=!1,trailing=!0;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return wait=toNumber(wait)||0,isObject(options)&&(leading=!!options.leading,maxing="maxWait"in options,maxWait=maxing?nativeMax(toNumber(options.maxWait)||0,wait):maxWait,trailing="trailing"in options?!!options.trailing:trailing),debounced.cancel=cancel,debounced.flush=flush,debounced}function flip(func){return createWrap(func,FLIP_FLAG)}function memoize(func,resolver){if("function"!=typeof func||resolver&&"function"!=typeof resolver)throw new TypeError(FUNC_ERROR_TEXT);var memoized=function(){var args=arguments,key=resolver?resolver.apply(this,args):args[0],cache=memoized.cache;if(cache.has(key))return cache.get(key);var result=func.apply(this,args);return memoized.cache=cache.set(key,result)||cache,result};return memoized.cache=new(memoize.Cache||MapCache),memoized}function negate(predicate){if("function"!=typeof predicate)throw new TypeError(FUNC_ERROR_TEXT);return function(){var args=arguments;switch(args.length){case 0:return!predicate.call(this);case 1:return!predicate.call(this,args[0]);case 2:return!predicate.call(this,args[0],args[1]);case 3:return!predicate.call(this,args[0],args[1],args[2])}return!predicate.apply(this,args)}}function once(func){return before(2,func)}function rest(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=start===undefined?start:toInteger(start),baseRest(func,start)}function spread(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=start===undefined?0:nativeMax(toInteger(start),0),baseRest(function(args){var array=args[start],otherArgs=castSlice(args,0,start);return array&&arrayPush(otherArgs,array),apply(func,this,otherArgs)})}function throttle(func,wait,options){var leading=!0,trailing=!0;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return isObject(options)&&(leading="leading"in options?!!options.leading:leading,trailing="trailing"in options?!!options.trailing:trailing),debounce(func,wait,{leading:leading,maxWait:wait,trailing:trailing})}function unary(func){return ary(func,1)}function wrap(value,wrapper){return wrapper=null==wrapper?identity:wrapper,partial(wrapper,value)}function castArray(){if(!arguments.length)return[];var value=arguments[0];return isArray(value)?value:[value]}function clone(value){return baseClone(value,!1,!0)}function cloneWith(value,customizer){return baseClone(value,!1,!0,customizer)}function cloneDeep(value){return baseClone(value,!0,!0)}function cloneDeepWith(value,customizer){return baseClone(value,!0,!0,customizer)}function conformsTo(object,source){return null==source||baseConformsTo(object,source,keys(source))}function eq(value,other){return value===other||value!==value&&other!==other}function isArguments(value){return isArrayLikeObject(value)&&hasOwnProperty.call(value,"callee")&&(!propertyIsEnumerable.call(value,"callee")||objectToString.call(value)==argsTag)}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value)}function isBoolean(value){return value===!0||value===!1||isObjectLike(value)&&objectToString.call(value)==boolTag}function isElement(value){return null!=value&&1===value.nodeType&&isObjectLike(value)&&!isPlainObject(value)}function isEmpty(value){if(isArrayLike(value)&&(isArray(value)||"string"==typeof value||"function"==typeof value.splice||isBuffer(value)||isArguments(value)))return!value.length;var tag=getTag(value);if(tag==mapTag||tag==setTag)return!value.size;if(isPrototype(value))return!nativeKeys(value).length;for(var key in value)if(hasOwnProperty.call(value,key))return!1;return!0}function isEqual(value,other){return baseIsEqual(value,other)}function isEqualWith(value,other,customizer){customizer="function"==typeof customizer?customizer:undefined;var result=customizer?customizer(value,other):undefined;return result===undefined?baseIsEqual(value,other,customizer):!!result}function isError(value){return isObjectLike(value)?objectToString.call(value)==errorTag||"string"==typeof value.message&&"string"==typeof value.name:!1}function isFinite(value){return"number"==typeof value&&nativeIsFinite(value)}function isFunction(value){var tag=isObject(value)?objectToString.call(value):"";return tag==funcTag||tag==genTag}function isInteger(value){return"number"==typeof value&&value==toInteger(value)}function isLength(value){return"number"==typeof value&&value>-1&&value%1==0&&MAX_SAFE_INTEGER>=value}function isObject(value){var type=typeof value;return null!=value&&("object"==type||"function"==type)}function isObjectLike(value){return null!=value&&"object"==typeof value}function isMatch(object,source){return object===source||baseIsMatch(object,source,getMatchData(source))}function isMatchWith(object,source,customizer){return customizer="function"==typeof customizer?customizer:undefined,baseIsMatch(object,source,getMatchData(source),customizer)}function isNaN(value){return isNumber(value)&&value!=+value}function isNative(value){if(isMaskable(value))throw new Error("This method is not supported with core-js. Try https://github.com/es-shims.");return baseIsNative(value)}function isNull(value){return null===value}function isNil(value){return null==value}function isNumber(value){return"number"==typeof value||isObjectLike(value)&&objectToString.call(value)==numberTag}function isPlainObject(value){if(!isObjectLike(value)||objectToString.call(value)!=objectTag)return!1;var proto=getPrototype(value);if(null===proto)return!0;var Ctor=hasOwnProperty.call(proto,"constructor")&&proto.constructor;return"function"==typeof Ctor&&Ctor instanceof Ctor&&funcToString.call(Ctor)==objectCtorString}function isSafeInteger(value){return isInteger(value)&&value>=-MAX_SAFE_INTEGER&&MAX_SAFE_INTEGER>=value}function isString(value){return"string"==typeof value||!isArray(value)&&isObjectLike(value)&&objectToString.call(value)==stringTag}function isSymbol(value){return"symbol"==typeof value||isObjectLike(value)&&objectToString.call(value)==symbolTag}function isUndefined(value){return value===undefined}function isWeakMap(value){return isObjectLike(value)&&getTag(value)==weakMapTag}function isWeakSet(value){return isObjectLike(value)&&objectToString.call(value)==weakSetTag}function toArray(value){if(!value)return[];if(isArrayLike(value))return isString(value)?stringToArray(value):copyArray(value);if(iteratorSymbol&&value[iteratorSymbol])return iteratorToArray(value[iteratorSymbol]());var tag=getTag(value),func=tag==mapTag?mapToArray:tag==setTag?setToArray:values;return func(value)}function toFinite(value){if(!value)return 0===value?value:0;if(value=toNumber(value),value===INFINITY||value===-INFINITY){var sign=0>value?-1:1;return sign*MAX_INTEGER}return value===value?value:0}function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0}function toLength(value){return value?baseClamp(toInteger(value),0,MAX_ARRAY_LENGTH):0}function toNumber(value){if("number"==typeof value)return value;if(isSymbol(value))return NAN;if(isObject(value)){var other="function"==typeof value.valueOf?value.valueOf():value;value=isObject(other)?other+"":other}if("string"!=typeof value)return 0===value?value:+value;value=value.replace(reTrim,"");var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value}function toPlainObject(value){return copyObject(value,keysIn(value))}function toSafeInteger(value){return baseClamp(toInteger(value),-MAX_SAFE_INTEGER,MAX_SAFE_INTEGER)}function toString(value){return null==value?"":baseToString(value)}function create(prototype,properties){var result=baseCreate(prototype);return properties?baseAssign(result,properties):result}function findKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwn)}function findLastKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwnRight)}function forIn(object,iteratee){return null==object?object:baseFor(object,getIteratee(iteratee,3),keysIn)}function forInRight(object,iteratee){return null==object?object:baseForRight(object,getIteratee(iteratee,3),keysIn)}function forOwn(object,iteratee){return object&&baseForOwn(object,getIteratee(iteratee,3))}function forOwnRight(object,iteratee){return object&&baseForOwnRight(object,getIteratee(iteratee,3))}function functions(object){return null==object?[]:baseFunctions(object,keys(object))}function functionsIn(object){return null==object?[]:baseFunctions(object,keysIn(object))}function get(object,path,defaultValue){var result=null==object?undefined:baseGet(object,path);return result===undefined?defaultValue:result}function has(object,path){return null!=object&&hasPath(object,path,baseHas)}function hasIn(object,path){return null!=object&&hasPath(object,path,baseHasIn)}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function keysIn(object){return isArrayLike(object)?arrayLikeKeys(object,!0):baseKeysIn(object)}function mapKeys(object,iteratee){var result={};return iteratee=getIteratee(iteratee,3),baseForOwn(object,function(value,key,object){baseAssignValue(result,iteratee(value,key,object),value)}),result}function mapValues(object,iteratee){var result={};return iteratee=getIteratee(iteratee,3),baseForOwn(object,function(value,key,object){baseAssignValue(result,key,iteratee(value,key,object))}),result}function omitBy(object,predicate){return pickBy(object,negate(getIteratee(predicate)))}function pickBy(object,predicate){return null==object?{}:basePickBy(object,getAllKeysIn(object),getIteratee(predicate))}function result(object,path,defaultValue){path=isKey(path,object)?[path]:castPath(path);var index=-1,length=path.length;for(length||(object=undefined,length=1);++indexupper){var temp=lower;lower=upper,upper=temp}if(floating||lower%1||upper%1){var rand=nativeRandom();return nativeMin(lower+rand*(upper-lower+freeParseFloat("1e-"+((rand+"").length-1))),upper)}return baseRandom(lower,upper)}function capitalize(string){return upperFirst(toString(string).toLowerCase())}function deburr(string){return string=toString(string),string&&string.replace(reLatin,deburrLetter).replace(reComboMark,"")}function endsWith(string,target,position){string=toString(string),target=baseToString(target);var length=string.length;position=position===undefined?length:baseClamp(toInteger(position),0,length);var end=position;return position-=target.length,position>=0&&string.slice(position,end)==target}function escape(string){return string=toString(string),string&&reHasUnescapedHtml.test(string)?string.replace(reUnescapedHtml,escapeHtmlChar):string}function escapeRegExp(string){return string=toString(string),string&&reHasRegExpChar.test(string)?string.replace(reRegExpChar,"\\$&"):string}function pad(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;if(!length||strLength>=length)return string;var mid=(length-strLength)/2;return createPadding(nativeFloor(mid),chars)+string+createPadding(nativeCeil(mid),chars)}function padEnd(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;return length&&length>strLength?string+createPadding(length-strLength,chars):string}function padStart(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;return length&&length>strLength?createPadding(length-strLength,chars)+string:string}function parseInt(string,radix,guard){return guard||null==radix?radix=0:radix&&(radix=+radix),nativeParseInt(toString(string),radix||0)}function repeat(string,n,guard){return n=(guard?isIterateeCall(string,n,guard):n===undefined)?1:toInteger(n),baseRepeat(toString(string),n)}function replace(){var args=arguments,string=toString(args[0]);return args.length<3?string:string.replace(args[1],args[2])}function split(string,separator,limit){return limit&&"number"!=typeof limit&&isIterateeCall(string,separator,limit)&&(separator=limit=undefined),(limit=limit===undefined?MAX_ARRAY_LENGTH:limit>>>0)?(string=toString(string),string&&("string"==typeof separator||null!=separator&&!isRegExp(separator))&&(separator=baseToString(separator),!separator&&hasUnicode(string))?castSlice(stringToArray(string),0,limit):string.split(separator,limit)):[]}function startsWith(string,target,position){return string=toString(string),position=baseClamp(toInteger(position),0,string.length),target=baseToString(target),string.slice(position,position+target.length)==target}function template(string,options,guard){var settings=lodash.templateSettings;guard&&isIterateeCall(string,options,guard)&&(options=undefined),string=toString(string),options=assignInWith({},options,settings,assignInDefaults);var isEscaping,isEvaluating,imports=assignInWith({},options.imports,settings.imports,assignInDefaults),importsKeys=keys(imports),importsValues=baseValues(imports,importsKeys),index=0,interpolate=options.interpolate||reNoMatch,source="__p += '",reDelimiters=RegExp((options.escape||reNoMatch).source+"|"+interpolate.source+"|"+(interpolate===reInterpolate?reEsTemplate:reNoMatch).source+"|"+(options.evaluate||reNoMatch).source+"|$","g"),sourceURL="//# sourceURL="+("sourceURL"in options?options.sourceURL:"lodash.templateSources["+ ++templateCounter+"]")+"\n";string.replace(reDelimiters,function(match,escapeValue,interpolateValue,esTemplateValue,evaluateValue,offset){return interpolateValue||(interpolateValue=esTemplateValue),source+=string.slice(index,offset).replace(reUnescapedString,escapeStringChar),escapeValue&&(isEscaping=!0,source+="' +\n__e("+escapeValue+") +\n'"),evaluateValue&&(isEvaluating=!0,source+="';\n"+evaluateValue+";\n__p += '"),interpolateValue&&(source+="' +\n((__t = ("+interpolateValue+")) == null ? '' : __t) +\n'"),index=offset+match.length,match}),source+="';\n";var variable=options.variable;variable||(source="with (obj) {\n"+source+"\n}\n"),source=(isEvaluating?source.replace(reEmptyStringLeading,""):source).replace(reEmptyStringMiddle,"$1").replace(reEmptyStringTrailing,"$1;"),source="function("+(variable||"obj")+") {\n"+(variable?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(isEscaping?", __e = _.escape":"")+(isEvaluating?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+source+"return __p\n}";var result=attempt(function(){return Function(importsKeys,sourceURL+"return "+source).apply(undefined,importsValues)});if(result.source=source,isError(result))throw result;return result}function toLower(value){return toString(value).toLowerCase()}function toUpper(value){return toString(value).toUpperCase()}function trim(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrim,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),chrSymbols=stringToArray(chars),start=charsStartIndex(strSymbols,chrSymbols),end=charsEndIndex(strSymbols,chrSymbols)+1;return castSlice(strSymbols,start,end).join("")}function trimEnd(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrimEnd,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),end=charsEndIndex(strSymbols,stringToArray(chars))+1;return castSlice(strSymbols,0,end).join("")}function trimStart(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrimStart,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),start=charsStartIndex(strSymbols,stringToArray(chars));return castSlice(strSymbols,start).join("")}function truncate(string,options){var length=DEFAULT_TRUNC_LENGTH,omission=DEFAULT_TRUNC_OMISSION;if(isObject(options)){var separator="separator"in options?options.separator:separator;length="length"in options?toInteger(options.length):length,omission="omission"in options?baseToString(options.omission):omission}string=toString(string);var strLength=string.length;if(hasUnicode(string)){var strSymbols=stringToArray(string);strLength=strSymbols.length}if(length>=strLength)return string;var end=length-stringSize(omission);if(1>end)return omission;var result=strSymbols?castSlice(strSymbols,0,end).join(""):string.slice(0,end);if(separator===undefined)return result+omission;if(strSymbols&&(end+=result.length-end),isRegExp(separator)){if(string.slice(end).search(separator)){var match,substring=result;for(separator.global||(separator=RegExp(separator.source,toString(reFlags.exec(separator))+"g")),separator.lastIndex=0;match=separator.exec(substring);)var newEnd=match.index;result=result.slice(0,newEnd===undefined?end:newEnd)}}else if(string.indexOf(baseToString(separator),end)!=end){var index=result.lastIndexOf(separator);index>-1&&(result=result.slice(0,index))}return result+omission}function unescape(string){return string=toString(string),string&&reHasEscapedHtml.test(string)?string.replace(reEscapedHtml,unescapeHtmlChar):string}function words(string,pattern,guard){return string=toString(string),pattern=guard?undefined:pattern,pattern===undefined?hasUnicodeWord(string)?unicodeWords(string):asciiWords(string):string.match(pattern)||[]}function cond(pairs){var length=pairs?pairs.length:0,toIteratee=getIteratee();return pairs=length?arrayMap(pairs,function(pair){if("function"!=typeof pair[1])throw new TypeError(FUNC_ERROR_TEXT);return[toIteratee(pair[0]),pair[1]]}):[],baseRest(function(args){for(var index=-1;++indexn||n>MAX_SAFE_INTEGER)return[];var index=MAX_ARRAY_LENGTH,length=nativeMin(n,MAX_ARRAY_LENGTH);iteratee=getIteratee(iteratee),n-=MAX_ARRAY_LENGTH;for(var result=baseTimes(length,iteratee);++index1?arrays[length-1]:undefined;return iteratee="function"==typeof iteratee?(arrays.pop(),iteratee):undefined,unzipWith(arrays,iteratee)}),wrapperAt=flatRest(function(paths){var length=paths.length,start=length?paths[0]:0,value=this.__wrapped__,interceptor=function(object){return baseAt(object,paths)};return!(length>1||this.__actions__.length)&&value instanceof LazyWrapper&&isIndex(start)?(value=value.slice(start,+start+(length?1:0)),value.__actions__.push({func:thru,args:[interceptor],thisArg:undefined}),new LodashWrapper(value,this.__chain__).thru(function(array){return length&&!array.length&&array.push(undefined),array})):this.thru(interceptor)}),countBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?++result[key]:baseAssignValue(result,key,1)}),find=createFind(findIndex),findLast=createFind(findLastIndex),groupBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?result[key].push(value):baseAssignValue(result,key,[value])}),invokeMap=baseRest(function(collection,path,args){var index=-1,isFunc="function"==typeof path,isProp=isKey(path),result=isArrayLike(collection)?Array(collection.length):[];return baseEach(collection,function(value){var func=isFunc?path:isProp&&null!=value?value[path]:undefined;result[++index]=func?apply(func,value,args):baseInvoke(value,path,args)}),result}),keyBy=createAggregator(function(result,value,key){baseAssignValue(result,key,value)}),partition=createAggregator(function(result,value,key){result[key?0:1].push(value)},function(){return[[],[]]}),sortBy=baseRest(function(collection,iteratees){if(null==collection)return[];var length=iteratees.length;return length>1&&isIterateeCall(collection,iteratees[0],iteratees[1])?iteratees=[]:length>2&&isIterateeCall(iteratees[0],iteratees[1],iteratees[2])&&(iteratees=[iteratees[0]]),baseOrderBy(collection,baseFlatten(iteratees,1),[])}),now=ctxNow||function(){return root.Date.now()},bind=baseRest(function(func,thisArg,partials){var bitmask=BIND_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bind));bitmask|=PARTIAL_FLAG}return createWrap(func,bitmask,thisArg,partials,holders)}),bindKey=baseRest(function(object,key,partials){var bitmask=BIND_FLAG|BIND_KEY_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bindKey));bitmask|=PARTIAL_FLAG}return createWrap(key,bitmask,object,partials,holders)}),defer=baseRest(function(func,args){return baseDelay(func,1,args)}),delay=baseRest(function(func,wait,args){return baseDelay(func,toNumber(wait)||0,args)});memoize.Cache=MapCache;var overArgs=castRest(function(func,transforms){transforms=1==transforms.length&&isArray(transforms[0])?arrayMap(transforms[0],baseUnary(getIteratee())):arrayMap(baseFlatten(transforms,1),baseUnary(getIteratee()));var funcsLength=transforms.length;return baseRest(function(args){for(var index=-1,length=nativeMin(args.length,funcsLength);++index=other}),isArray=Array.isArray,isArrayBuffer=nodeIsArrayBuffer?baseUnary(nodeIsArrayBuffer):baseIsArrayBuffer,isBuffer=nativeIsBuffer||stubFalse,isDate=nodeIsDate?baseUnary(nodeIsDate):baseIsDate,isMap=nodeIsMap?baseUnary(nodeIsMap):baseIsMap,isRegExp=nodeIsRegExp?baseUnary(nodeIsRegExp):baseIsRegExp,isSet=nodeIsSet?baseUnary(nodeIsSet):baseIsSet,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray,lt=createRelationalOperation(baseLt),lte=createRelationalOperation(function(value,other){return other>=value}),assign=createAssigner(function(object,source){if(isPrototype(source)||isArrayLike(source))return void copyObject(source,keys(source),object);for(var key in source)hasOwnProperty.call(source,key)&&assignValue(object,key,source[key])}),assignIn=createAssigner(function(object,source){copyObject(source,keysIn(source),object)}),assignInWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keysIn(source),object,customizer)}),assignWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keys(source),object,customizer)}),at=flatRest(baseAt),defaults=baseRest(function(args){return args.push(undefined,assignInDefaults),apply(assignInWith,undefined,args)}),defaultsDeep=baseRest(function(args){return args.push(undefined,mergeDefaults),apply(mergeWith,undefined,args)}),invert=createInverter(function(result,value,key){result[value]=key},constant(identity)),invertBy=createInverter(function(result,value,key){hasOwnProperty.call(result,value)?result[value].push(key):result[value]=[key]},getIteratee),invoke=baseRest(baseInvoke),merge=createAssigner(function(object,source,srcIndex){baseMerge(object,source,srcIndex)}),mergeWith=createAssigner(function(object,source,srcIndex,customizer){baseMerge(object,source,srcIndex,customizer)}),omit=flatRest(function(object,props){return null==object?{}:(props=arrayMap(props,toKey),basePick(object,baseDifference(getAllKeysIn(object),props)))}),pick=flatRest(function(object,props){return null==object?{}:basePick(object,arrayMap(props,toKey))}),toPairs=createToPairs(keys),toPairsIn=createToPairs(keysIn),camelCase=createCompounder(function(result,word,index){return word=word.toLowerCase(),result+(index?capitalize(word):word)}),kebabCase=createCompounder(function(result,word,index){return result+(index?"-":"")+word.toLowerCase()}),lowerCase=createCompounder(function(result,word,index){return result+(index?" ":"")+word.toLowerCase()}),lowerFirst=createCaseFirst("toLowerCase"),snakeCase=createCompounder(function(result,word,index){return result+(index?"_":"")+word.toLowerCase()}),startCase=createCompounder(function(result,word,index){return result+(index?" ":"")+upperFirst(word)}),upperCase=createCompounder(function(result,word,index){return result+(index?" ":"")+word.toUpperCase()}),upperFirst=createCaseFirst("toUpperCase"),attempt=baseRest(function(func,args){try{return apply(func,undefined,args)}catch(e){return isError(e)?e:new Error(e)}}),bindAll=flatRest(function(object,methodNames){return arrayEach(methodNames,function(key){key=toKey(key),baseAssignValue(object,key,bind(object[key],object))}),object}),flow=createFlow(),flowRight=createFlow(!0),method=baseRest(function(path,args){return function(object){return baseInvoke(object,path,args)}}),methodOf=baseRest(function(object,args){return function(path){return baseInvoke(object,path,args)}}),over=createOver(arrayMap),overEvery=createOver(arrayEvery),overSome=createOver(arraySome),range=createRange(),rangeRight=createRange(!0),add=createMathOperation(function(augend,addend){return augend+addend},0),ceil=createRound("ceil"),divide=createMathOperation(function(dividend,divisor){return dividend/divisor},1),floor=createRound("floor"),multiply=createMathOperation(function(multiplier,multiplicand){return multiplier*multiplicand},1),round=createRound("round"),subtract=createMathOperation(function(minuend,subtrahend){return minuend-subtrahend},0);return lodash.after=after,lodash.ary=ary,lodash.assign=assign,lodash.assignIn=assignIn,lodash.assignInWith=assignInWith,lodash.assignWith=assignWith,lodash.at=at,lodash.before=before,lodash.bind=bind,lodash.bindAll=bindAll,lodash.bindKey=bindKey,lodash.castArray=castArray,lodash.chain=chain,lodash.chunk=chunk,lodash.compact=compact,lodash.concat=concat,lodash.cond=cond,lodash.conforms=conforms,lodash.constant=constant,lodash.countBy=countBy,lodash.create=create,lodash.curry=curry,lodash.curryRight=curryRight,lodash.debounce=debounce,lodash.defaults=defaults,lodash.defaultsDeep=defaultsDeep,lodash.defer=defer,lodash.delay=delay,lodash.difference=difference,lodash.differenceBy=differenceBy,lodash.differenceWith=differenceWith,lodash.drop=drop,lodash.dropRight=dropRight,lodash.dropRightWhile=dropRightWhile,lodash.dropWhile=dropWhile,lodash.fill=fill,lodash.filter=filter,lodash.flatMap=flatMap,lodash.flatMapDeep=flatMapDeep,lodash.flatMapDepth=flatMapDepth,lodash.flatten=flatten,lodash.flattenDeep=flattenDeep,lodash.flattenDepth=flattenDepth,lodash.flip=flip,lodash.flow=flow,lodash.flowRight=flowRight,lodash.fromPairs=fromPairs,lodash.functions=functions,lodash.functionsIn=functionsIn,lodash.groupBy=groupBy,lodash.initial=initial,lodash.intersection=intersection,lodash.intersectionBy=intersectionBy,lodash.intersectionWith=intersectionWith,lodash.invert=invert,lodash.invertBy=invertBy,lodash.invokeMap=invokeMap,lodash.iteratee=iteratee,lodash.keyBy=keyBy,lodash.keys=keys,lodash.keysIn=keysIn,lodash.map=map,lodash.mapKeys=mapKeys,lodash.mapValues=mapValues,lodash.matches=matches,lodash.matchesProperty=matchesProperty,lodash.memoize=memoize,lodash.merge=merge,lodash.mergeWith=mergeWith,lodash.method=method,lodash.methodOf=methodOf,lodash.mixin=mixin,lodash.negate=negate,lodash.nthArg=nthArg,lodash.omit=omit,lodash.omitBy=omitBy,lodash.once=once,lodash.orderBy=orderBy,lodash.over=over,lodash.overArgs=overArgs,lodash.overEvery=overEvery,lodash.overSome=overSome,lodash.partial=partial,lodash.partialRight=partialRight,lodash.partition=partition,lodash.pick=pick,lodash.pickBy=pickBy,lodash.property=property,lodash.propertyOf=propertyOf,lodash.pull=pull,lodash.pullAll=pullAll,lodash.pullAllBy=pullAllBy,lodash.pullAllWith=pullAllWith,lodash.pullAt=pullAt,lodash.range=range,lodash.rangeRight=rangeRight,lodash.rearg=rearg,lodash.reject=reject,lodash.remove=remove,lodash.rest=rest,lodash.reverse=reverse,lodash.sampleSize=sampleSize,lodash.set=set,lodash.setWith=setWith,lodash.shuffle=shuffle,lodash.slice=slice,lodash.sortBy=sortBy,lodash.sortedUniq=sortedUniq,lodash.sortedUniqBy=sortedUniqBy,lodash.split=split,lodash.spread=spread,lodash.tail=tail,lodash.take=take,lodash.takeRight=takeRight,lodash.takeRightWhile=takeRightWhile,lodash.takeWhile=takeWhile,lodash.tap=tap,lodash.throttle=throttle,lodash.thru=thru,lodash.toArray=toArray,lodash.toPairs=toPairs,lodash.toPairsIn=toPairsIn,lodash.toPath=toPath,lodash.toPlainObject=toPlainObject,lodash.transform=transform,lodash.unary=unary,lodash.union=union,lodash.unionBy=unionBy,lodash.unionWith=unionWith,lodash.uniq=uniq,lodash.uniqBy=uniqBy,lodash.uniqWith=uniqWith,lodash.unset=unset,lodash.unzip=unzip,lodash.unzipWith=unzipWith,lodash.update=update,lodash.updateWith=updateWith,lodash.values=values,lodash.valuesIn=valuesIn,lodash.without=without,lodash.words=words,lodash.wrap=wrap,lodash.xor=xor,lodash.xorBy=xorBy,lodash.xorWith=xorWith,lodash.zip=zip,lodash.zipObject=zipObject,lodash.zipObjectDeep=zipObjectDeep,lodash.zipWith=zipWith,lodash.entries=toPairs,lodash.entriesIn=toPairsIn,lodash.extend=assignIn,lodash.extendWith=assignInWith,mixin(lodash,lodash),lodash.add=add,lodash.attempt=attempt,lodash.camelCase=camelCase,lodash.capitalize=capitalize,lodash.ceil=ceil,lodash.clamp=clamp,lodash.clone=clone,lodash.cloneDeep=cloneDeep,lodash.cloneDeepWith=cloneDeepWith,lodash.cloneWith=cloneWith,lodash.conformsTo=conformsTo,lodash.deburr=deburr,lodash.defaultTo=defaultTo,lodash.divide=divide,lodash.endsWith=endsWith,lodash.eq=eq,lodash.escape=escape,lodash.escapeRegExp=escapeRegExp,lodash.every=every,lodash.find=find,lodash.findIndex=findIndex,lodash.findKey=findKey,lodash.findLast=findLast,lodash.findLastIndex=findLastIndex,lodash.findLastKey=findLastKey,lodash.floor=floor,lodash.forEach=forEach,lodash.forEachRight=forEachRight,lodash.forIn=forIn, -lodash.forInRight=forInRight,lodash.forOwn=forOwn,lodash.forOwnRight=forOwnRight,lodash.get=get,lodash.gt=gt,lodash.gte=gte,lodash.has=has,lodash.hasIn=hasIn,lodash.head=head,lodash.identity=identity,lodash.includes=includes,lodash.indexOf=indexOf,lodash.inRange=inRange,lodash.invoke=invoke,lodash.isArguments=isArguments,lodash.isArray=isArray,lodash.isArrayBuffer=isArrayBuffer,lodash.isArrayLike=isArrayLike,lodash.isArrayLikeObject=isArrayLikeObject,lodash.isBoolean=isBoolean,lodash.isBuffer=isBuffer,lodash.isDate=isDate,lodash.isElement=isElement,lodash.isEmpty=isEmpty,lodash.isEqual=isEqual,lodash.isEqualWith=isEqualWith,lodash.isError=isError,lodash.isFinite=isFinite,lodash.isFunction=isFunction,lodash.isInteger=isInteger,lodash.isLength=isLength,lodash.isMap=isMap,lodash.isMatch=isMatch,lodash.isMatchWith=isMatchWith,lodash.isNaN=isNaN,lodash.isNative=isNative,lodash.isNil=isNil,lodash.isNull=isNull,lodash.isNumber=isNumber,lodash.isObject=isObject,lodash.isObjectLike=isObjectLike,lodash.isPlainObject=isPlainObject,lodash.isRegExp=isRegExp,lodash.isSafeInteger=isSafeInteger,lodash.isSet=isSet,lodash.isString=isString,lodash.isSymbol=isSymbol,lodash.isTypedArray=isTypedArray,lodash.isUndefined=isUndefined,lodash.isWeakMap=isWeakMap,lodash.isWeakSet=isWeakSet,lodash.join=join,lodash.kebabCase=kebabCase,lodash.last=last,lodash.lastIndexOf=lastIndexOf,lodash.lowerCase=lowerCase,lodash.lowerFirst=lowerFirst,lodash.lt=lt,lodash.lte=lte,lodash.max=max,lodash.maxBy=maxBy,lodash.mean=mean,lodash.meanBy=meanBy,lodash.min=min,lodash.minBy=minBy,lodash.stubArray=stubArray,lodash.stubFalse=stubFalse,lodash.stubObject=stubObject,lodash.stubString=stubString,lodash.stubTrue=stubTrue,lodash.multiply=multiply,lodash.nth=nth,lodash.noConflict=noConflict,lodash.noop=noop,lodash.now=now,lodash.pad=pad,lodash.padEnd=padEnd,lodash.padStart=padStart,lodash.parseInt=parseInt,lodash.random=random,lodash.reduce=reduce,lodash.reduceRight=reduceRight,lodash.repeat=repeat,lodash.replace=replace,lodash.result=result,lodash.round=round,lodash.runInContext=runInContext,lodash.sample=sample,lodash.size=size,lodash.snakeCase=snakeCase,lodash.some=some,lodash.sortedIndex=sortedIndex,lodash.sortedIndexBy=sortedIndexBy,lodash.sortedIndexOf=sortedIndexOf,lodash.sortedLastIndex=sortedLastIndex,lodash.sortedLastIndexBy=sortedLastIndexBy,lodash.sortedLastIndexOf=sortedLastIndexOf,lodash.startCase=startCase,lodash.startsWith=startsWith,lodash.subtract=subtract,lodash.sum=sum,lodash.sumBy=sumBy,lodash.template=template,lodash.times=times,lodash.toFinite=toFinite,lodash.toInteger=toInteger,lodash.toLength=toLength,lodash.toLower=toLower,lodash.toNumber=toNumber,lodash.toSafeInteger=toSafeInteger,lodash.toString=toString,lodash.toUpper=toUpper,lodash.trim=trim,lodash.trimEnd=trimEnd,lodash.trimStart=trimStart,lodash.truncate=truncate,lodash.unescape=unescape,lodash.uniqueId=uniqueId,lodash.upperCase=upperCase,lodash.upperFirst=upperFirst,lodash.each=forEach,lodash.eachRight=forEachRight,lodash.first=head,mixin(lodash,function(){var source={};return baseForOwn(lodash,function(func,methodName){hasOwnProperty.call(lodash.prototype,methodName)||(source[methodName]=func)}),source}(),{chain:!1}),lodash.VERSION=VERSION,arrayEach(["bind","bindKey","curry","curryRight","partial","partialRight"],function(methodName){lodash[methodName].placeholder=lodash}),arrayEach(["drop","take"],function(methodName,index){LazyWrapper.prototype[methodName]=function(n){var filtered=this.__filtered__;if(filtered&&!index)return new LazyWrapper(this);n=n===undefined?1:nativeMax(toInteger(n),0);var result=this.clone();return filtered?result.__takeCount__=nativeMin(n,result.__takeCount__):result.__views__.push({size:nativeMin(n,MAX_ARRAY_LENGTH),type:methodName+(result.__dir__<0?"Right":"")}),result},LazyWrapper.prototype[methodName+"Right"]=function(n){return this.reverse()[methodName](n).reverse()}}),arrayEach(["filter","map","takeWhile"],function(methodName,index){var type=index+1,isFilter=type==LAZY_FILTER_FLAG||type==LAZY_WHILE_FLAG;LazyWrapper.prototype[methodName]=function(iteratee){var result=this.clone();return result.__iteratees__.push({iteratee:getIteratee(iteratee,3),type:type}),result.__filtered__=result.__filtered__||isFilter,result}}),arrayEach(["head","last"],function(methodName,index){var takeName="take"+(index?"Right":"");LazyWrapper.prototype[methodName]=function(){return this[takeName](1).value()[0]}}),arrayEach(["initial","tail"],function(methodName,index){var dropName="drop"+(index?"":"Right");LazyWrapper.prototype[methodName]=function(){return this.__filtered__?new LazyWrapper(this):this[dropName](1)}}),LazyWrapper.prototype.compact=function(){return this.filter(identity)},LazyWrapper.prototype.find=function(predicate){return this.filter(predicate).head()},LazyWrapper.prototype.findLast=function(predicate){return this.reverse().find(predicate)},LazyWrapper.prototype.invokeMap=baseRest(function(path,args){return"function"==typeof path?new LazyWrapper(this):this.map(function(value){return baseInvoke(value,path,args)})}),LazyWrapper.prototype.reject=function(predicate){return this.filter(negate(getIteratee(predicate)))},LazyWrapper.prototype.slice=function(start,end){start=toInteger(start);var result=this;return result.__filtered__&&(start>0||0>end)?new LazyWrapper(result):(0>start?result=result.takeRight(-start):start&&(result=result.drop(start)),end!==undefined&&(end=toInteger(end),result=0>end?result.dropRight(-end):result.take(end-start)),result)},LazyWrapper.prototype.takeRightWhile=function(predicate){return this.reverse().takeWhile(predicate).reverse()},LazyWrapper.prototype.toArray=function(){return this.take(MAX_ARRAY_LENGTH)},baseForOwn(LazyWrapper.prototype,function(func,methodName){var checkIteratee=/^(?:filter|find|map|reject)|While$/.test(methodName),isTaker=/^(?:head|last)$/.test(methodName),lodashFunc=lodash[isTaker?"take"+("last"==methodName?"Right":""):methodName],retUnwrapped=isTaker||/^find/.test(methodName);lodashFunc&&(lodash.prototype[methodName]=function(){var value=this.__wrapped__,args=isTaker?[1]:arguments,isLazy=value instanceof LazyWrapper,iteratee=args[0],useLazy=isLazy||isArray(value),interceptor=function(value){var result=lodashFunc.apply(lodash,arrayPush([value],args));return isTaker&&chainAll?result[0]:result};useLazy&&checkIteratee&&"function"==typeof iteratee&&1!=iteratee.length&&(isLazy=useLazy=!1);var chainAll=this.__chain__,isHybrid=!!this.__actions__.length,isUnwrapped=retUnwrapped&&!chainAll,onlyLazy=isLazy&&!isHybrid;if(!retUnwrapped&&useLazy){value=onlyLazy?value:new LazyWrapper(this);var result=func.apply(value,args);return result.__actions__.push({func:thru,args:[interceptor],thisArg:undefined}),new LodashWrapper(result,chainAll)}return isUnwrapped&&onlyLazy?func.apply(this,args):(result=this.thru(interceptor),isUnwrapped?isTaker?result.value()[0]:result.value():result)})}),arrayEach(["pop","push","shift","sort","splice","unshift"],function(methodName){var func=arrayProto[methodName],chainName=/^(?:push|sort|unshift)$/.test(methodName)?"tap":"thru",retUnwrapped=/^(?:pop|shift)$/.test(methodName);lodash.prototype[methodName]=function(){var args=arguments;if(retUnwrapped&&!this.__chain__){var value=this.value();return func.apply(isArray(value)?value:[],args)}return this[chainName](function(value){return func.apply(isArray(value)?value:[],args)})}}),baseForOwn(LazyWrapper.prototype,function(func,methodName){var lodashFunc=lodash[methodName];if(lodashFunc){var key=lodashFunc.name+"",names=realNames[key]||(realNames[key]=[]);names.push({name:methodName,func:lodashFunc})}}),realNames[createHybrid(undefined,BIND_KEY_FLAG).name]=[{name:"wrapper",func:undefined}],LazyWrapper.prototype.clone=lazyClone,LazyWrapper.prototype.reverse=lazyReverse,LazyWrapper.prototype.value=lazyValue,lodash.prototype.at=wrapperAt,lodash.prototype.chain=wrapperChain,lodash.prototype.commit=wrapperCommit,lodash.prototype.next=wrapperNext,lodash.prototype.plant=wrapperPlant,lodash.prototype.reverse=wrapperReverse,lodash.prototype.toJSON=lodash.prototype.valueOf=lodash.prototype.value=wrapperValue,lodash.prototype.first=lodash.prototype.head,iteratorSymbol&&(lodash.prototype[iteratorSymbol]=wrapperToIterator),lodash}var undefined,VERSION="4.16.0",LARGE_ARRAY_SIZE=200,FUNC_ERROR_TEXT="Expected a function",HASH_UNDEFINED="__lodash_hash_undefined__",MAX_MEMOIZE_SIZE=500,PLACEHOLDER="__lodash_placeholder__",BIND_FLAG=1,BIND_KEY_FLAG=2,CURRY_BOUND_FLAG=4,CURRY_FLAG=8,CURRY_RIGHT_FLAG=16,PARTIAL_FLAG=32,PARTIAL_RIGHT_FLAG=64,ARY_FLAG=128,REARG_FLAG=256,FLIP_FLAG=512,UNORDERED_COMPARE_FLAG=1,PARTIAL_COMPARE_FLAG=2,DEFAULT_TRUNC_LENGTH=30,DEFAULT_TRUNC_OMISSION="...",HOT_COUNT=500,HOT_SPAN=16,LAZY_FILTER_FLAG=1,LAZY_MAP_FLAG=2,LAZY_WHILE_FLAG=3,INFINITY=1/0,MAX_SAFE_INTEGER=9007199254740991,MAX_INTEGER=1.7976931348623157e308,NAN=NaN,MAX_ARRAY_LENGTH=4294967295,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH-1,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH>>>1,wrapFlags=[["ary",ARY_FLAG],["bind",BIND_FLAG],["bindKey",BIND_KEY_FLAG],["curry",CURRY_FLAG],["curryRight",CURRY_RIGHT_FLAG],["flip",FLIP_FLAG],["partial",PARTIAL_FLAG],["partialRight",PARTIAL_RIGHT_FLAG],["rearg",REARG_FLAG]],argsTag="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",genTag="[object GeneratorFunction]",mapTag="[object Map]",numberTag="[object Number]",objectTag="[object Object]",promiseTag="[object Promise]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]",weakMapTag="[object WeakMap]",weakSetTag="[object WeakSet]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]",reEmptyStringLeading=/\b__p \+= '';/g,reEmptyStringMiddle=/\b(__p \+=) '' \+/g,reEmptyStringTrailing=/(__e\(.*?\)|\b__t\)) \+\n'';/g,reEscapedHtml=/&(?:amp|lt|gt|quot|#39|#96);/g,reUnescapedHtml=/[&<>"'`]/g,reHasEscapedHtml=RegExp(reEscapedHtml.source),reHasUnescapedHtml=RegExp(reUnescapedHtml.source),reEscape=/<%-([\s\S]+?)%>/g,reEvaluate=/<%([\s\S]+?)%>/g,reInterpolate=/<%=([\s\S]+?)%>/g,reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/,reLeadingDot=/^\./,rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reHasRegExpChar=RegExp(reRegExpChar.source),reTrim=/^\s+|\s+$/g,reTrimStart=/^\s+/,reTrimEnd=/\s+$/,reWrapComment=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,reWrapDetails=/\{\n\/\* \[wrapped with (.+)\] \*/,reSplitDetails=/,? & /,reAsciiWord=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,reEscapeChar=/\\(\\)?/g,reEsTemplate=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,reFlags=/\w*$/,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsHostCtor=/^\[object .+?Constructor\]$/,reIsOctal=/^0o[0-7]+$/i,reIsUint=/^(?:0|[1-9]\d*)$/,reLatin=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,reNoMatch=/($^)/,reUnescapedString=/['\n\r\u2028\u2029\\]/g,rsAstralRange="\\ud800-\\udfff",rsComboMarksRange="\\u0300-\\u036f\\ufe20-\\ufe23",rsComboSymbolsRange="\\u20d0-\\u20f0",rsDingbatRange="\\u2700-\\u27bf",rsLowerRange="a-z\\xdf-\\xf6\\xf8-\\xff",rsMathOpRange="\\xac\\xb1\\xd7\\xf7",rsNonCharRange="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",rsPunctuationRange="\\u2000-\\u206f",rsSpaceRange=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",rsUpperRange="A-Z\\xc0-\\xd6\\xd8-\\xde",rsVarRange="\\ufe0e\\ufe0f",rsBreakRange=rsMathOpRange+rsNonCharRange+rsPunctuationRange+rsSpaceRange,rsApos="['’]",rsAstral="["+rsAstralRange+"]",rsBreak="["+rsBreakRange+"]",rsCombo="["+rsComboMarksRange+rsComboSymbolsRange+"]",rsDigits="\\d+",rsDingbat="["+rsDingbatRange+"]",rsLower="["+rsLowerRange+"]",rsMisc="[^"+rsAstralRange+rsBreakRange+rsDigits+rsDingbatRange+rsLowerRange+rsUpperRange+"]",rsFitz="\\ud83c[\\udffb-\\udfff]",rsModifier="(?:"+rsCombo+"|"+rsFitz+")",rsNonAstral="[^"+rsAstralRange+"]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",rsUpper="["+rsUpperRange+"]",rsZWJ="\\u200d",rsLowerMisc="(?:"+rsLower+"|"+rsMisc+")",rsUpperMisc="(?:"+rsUpper+"|"+rsMisc+")",rsOptLowerContr="(?:"+rsApos+"(?:d|ll|m|re|s|t|ve))?",rsOptUpperContr="(?:"+rsApos+"(?:D|LL|M|RE|S|T|VE))?",reOptMod=rsModifier+"?",rsOptVar="["+rsVarRange+"]?",rsOptJoin="(?:"+rsZWJ+"(?:"+[rsNonAstral,rsRegional,rsSurrPair].join("|")+")"+rsOptVar+reOptMod+")*",rsSeq=rsOptVar+reOptMod+rsOptJoin,rsEmoji="(?:"+[rsDingbat,rsRegional,rsSurrPair].join("|")+")"+rsSeq,rsSymbol="(?:"+[rsNonAstral+rsCombo+"?",rsCombo,rsRegional,rsSurrPair,rsAstral].join("|")+")",reApos=RegExp(rsApos,"g"),reComboMark=RegExp(rsCombo,"g"),reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g"),reUnicodeWord=RegExp([rsUpper+"?"+rsLower+"+"+rsOptLowerContr+"(?="+[rsBreak,rsUpper,"$"].join("|")+")",rsUpperMisc+"+"+rsOptUpperContr+"(?="+[rsBreak,rsUpper+rsLowerMisc,"$"].join("|")+")",rsUpper+"?"+rsLowerMisc+"+"+rsOptLowerContr,rsUpper+"+"+rsOptUpperContr,rsDigits,rsEmoji].join("|"),"g"),reHasUnicode=RegExp("["+rsZWJ+rsAstralRange+rsComboMarksRange+rsComboSymbolsRange+rsVarRange+"]"),reHasUnicodeWord=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,contextProps=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],templateCounter=-1,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[dataViewTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[mapTag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[setTag]=cloneableTags[stringTag]=cloneableTags[symbolTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=!0,cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[weakMapTag]=!1;var deburredLetters={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"},htmlEscapes={"&":"&","<":"<",">":">",'"':""","'":"'"},htmlUnescapes={"&":"&","<":"<",">":">",""":'"',"'":"'"},stringEscapes={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},freeParseFloat=parseFloat,freeParseInt=parseInt,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,freeProcess=moduleExports&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding("util")}catch(e){}}(),nodeIsArrayBuffer=nodeUtil&&nodeUtil.isArrayBuffer,nodeIsDate=nodeUtil&&nodeUtil.isDate,nodeIsMap=nodeUtil&&nodeUtil.isMap,nodeIsRegExp=nodeUtil&&nodeUtil.isRegExp,nodeIsSet=nodeUtil&&nodeUtil.isSet,nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,asciiSize=baseProperty("length"),deburrLetter=basePropertyOf(deburredLetters),escapeHtmlChar=basePropertyOf(htmlEscapes),unescapeHtmlChar=basePropertyOf(htmlUnescapes),_=runInContext();"function"==typeof define&&"object"==typeof define.amd&&define.amd?(root._=_,define(function(){return _})):freeModule?((freeModule.exports=_)._=_,freeExports._=_):root._=_}.call(this);var UsergridQuery=function(type){var queryString,sort,self=this,query="",__nextIsNot=!1;return _.assign(self,{type:function(value){return self._type=value,self},collection:function(value){return self._type=value,self},limit:function(value){return self._limit=value,self},cursor:function(value){return self._cursor=value,self},eq:function(key,value){return query=self.andJoin(key+" = "+useQuotesIfRequired(value)),self},equal:this.eq,gt:function(key,value){return query=self.andJoin(key+" > "+useQuotesIfRequired(value)),self},greaterThan:this.gt,gte:function(key,value){return query=self.andJoin(key+" >= "+useQuotesIfRequired(value)),self},greaterThanOrEqual:this.gte,lt:function(key,value){return query=self.andJoin(key+" < "+useQuotesIfRequired(value)),self},lessThan:this.lt,lte:function(key,value){return query=self.andJoin(key+" <= "+useQuotesIfRequired(value)),self},lessThanOrEqual:this.lte,contains:function(key,value){return query=self.andJoin(key+" contains "+useQuotesIfRequired(value)),self},locationWithin:function(distanceInMeters,lat,lng){return query=self.andJoin("location within "+distanceInMeters+" of "+lat+", "+lng),self},asc:function(key){return self.sort(key,"asc"),self},desc:function(key){return self.sort(key,"desc"),self},sort:function(key,order){return sort=key&&order?" order by "+key+" "+order:"",self},fromString:function(string){return queryString=string,self},andJoin:function(append){return __nextIsNot&&(append="not "+append,__nextIsNot=!1),append?0===query.length?append:_.endsWith(query,"and")||_.endsWith(query,"or")?query+" "+append:query+" and "+append:query},orJoin:function(){return query.length>0&&!_.endsWith(query,"or")?query+" or":query}}),self._type=self._type||type,Object.defineProperty(self,"_ql",{get:function(){return void 0!==queryString?queryString:query.length>0||void 0!==sort?"select * where "+(query||"")+(sort||""):""}}),Object.defineProperty(self,"and",{get:function(){return query=self.andJoin(""),self}}),Object.defineProperty(self,"or",{get:function(){return query=self.orJoin(),self}}),Object.defineProperty(self,"not",{get:function(){return __nextIsNot=!0,self}}),self};window.console=window.console||{},window.console.log=window.console.log||function(){};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;!function(global){function Usergrid(){this.logger=new Logger(name)}var name="Usergrid",overwrittenName=global[name],VALID_REQUEST_METHODS=["GET","POST","PUT","DELETE"];return Usergrid.initSharedInstance=function(options){return console.warn("TRYING TO INITIALIZING SHARED INSTANCE"),this.isInitialized||(console.warn("INITIALIZING SHARED INSTANCE"),this.__sharedInstance=new Usergrid.Client(options),this.isInitialized=!0),this.__sharedInstance},Usergrid.getInstance=function(){return this.__sharedInstance},Usergrid.isValidEndpoint=function(endpoint){return!0},Usergrid.Request=function(method,endpoint,query_params,data,callback){var p=new Promise;if(this.logger=new global.Logger("Usergrid.Request"),this.logger.time("process request "+method+" "+endpoint),this.endpoint=endpoint+"?"+encodeParams(query_params),this.method=method.toUpperCase(),this.data="object"==typeof data?JSON.stringify(data):data,-1===VALID_REQUEST_METHODS.indexOf(this.method))throw new UsergridInvalidHTTPMethodError("invalid request method '"+this.method+"'");if(!isValidUrl(this.endpoint))throw this.logger.error(endpoint,this.endpoint,/^https:\/\//.test(endpoint)),new UsergridInvalidURIError("The provided endpoint is not valid: "+this.endpoint);var request=function(){return Ajax.request(this.method,this.endpoint,this.data)}.bind(this),response=function(err,request){return new Usergrid.Response(err,request)}.bind(this),oncomplete=function(err,response){p.done(err,response),this.logger.info("REQUEST",err,response),doCallback(callback,[err,response]),this.logger.timeEnd("process request "+method+" "+endpoint)}.bind(this);return Promise.chain([request,response]).then(oncomplete),p},Usergrid.Response=function(err,response){var p=new Promise,data=null;try{data=JSON.parse(response.responseText)}catch(e){data={}}switch(Object.keys(data).forEach(function(key){Object.defineProperty(this,key,{value:data[key],enumerable:!0})}.bind(this)),Object.defineProperty(this,"logger",{enumerable:!1,configurable:!1,writable:!1,value:new global.Logger(name)}),Object.defineProperty(this,"success",{enumerable:!1,configurable:!1,writable:!0,value:!0}),Object.defineProperty(this,"err",{enumerable:!1,configurable:!1,writable:!0,value:err}),Object.defineProperty(this,"status",{enumerable:!1,configurable:!1,writable:!0,value:parseInt(response.status)}),Object.defineProperty(this,"statusGroup",{enumerable:!1,configurable:!1,writable:!0,value:this.status-this.status%100}),this.statusGroup){case 200:this.success=!0;break;case 400:case 500:case 300:case 100:default:this.success=!1}return this.success?p.done(null,this):p.done(UsergridError.fromResponse(data),this),p},Usergrid.Response.prototype.getEntities=function(){var entities;return this.success&&(entities=this.data?this.data.entities:this.entities),entities||[]},Usergrid.Response.prototype.getEntity=function(){var entities=this.getEntities();return entities[0]},Usergrid.VERSION=Usergrid.USERGRID_SDK_VERSION="0.11.0",global[name]=Usergrid,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Usergrid},global[name]}(this);var defaultOptions={baseUrl:"https://api.usergrid.com",authMode:UsergridAuthMode.USER};!function(){var exports,name="Client",global=this,overwrittenName=global[name];return Usergrid.Client=function(options){var self=this;if(!options.orgId||!options.appId)throw new Error('"orgId" and "appId" parameters are required when instantiating UsergridClient');_.defaults(this,options,defaultOptions),self.clientAppURL=[self.baseUrl,self.orgId,self.appId].join("/"),self.isSharedInstance=!1,self.currentUser=void 0,self.__appAuth=void 0,Object.defineProperty(self,"appAuth",{get:function(){return self.__appAuth},set:function(options){options instanceof UsergridAppAuth?self.__appAuth=options:"undefined"!=typeof options&&(self.__appAuth=new UsergridAppAuth(options))}}),this.userAuth=void 0,options.qs&&this.setObject("default_qs",options.qs),this.buildCurl=options.buildCurl||!1,this.logging=options.logging||!1},Usergrid.Client.prototype.request=function(options,callback){var uri,method=options.method||"GET",endpoint=options.endpoint,body=options.body||{},qs=options.qs||{},mQuery=options.mQuery||!1,orgId=this.get("orgId"),appId=this.get("appId"),default_qs=this.getObject("default_qs");if(!mQuery&&!orgId&&!appId)return logoutCallback();uri=mQuery?this.baseUrl+"/"+endpoint:this.baseUrl+"/"+orgId+"/"+appId+"/"+endpoint,this.getToken()&&(qs.access_token=this.getToken()),default_qs&&(qs=propCopy(qs,default_qs));var self=this;new Usergrid.Request(method,uri,qs,body,function(err,response){err?doCallback(callback,[err,response,self],self):doCallback(callback,[null,response,self],self)})},Usergrid.Client.prototype.buildAssetURL=function(uuid){var self=this,qs={},assetURL=this.baseUrl+"/"+this.orgId+"/"+this.appId+"/assets/"+uuid+"/data";self.getToken()&&(qs.access_token=self.getToken());var encoded_params=encodeParams(qs);return encoded_params&&(assetURL+="?"+encoded_params),assetURL},Usergrid.Client.prototype.createGroup=function(options,callback){var group=new Usergrid.Group({path:options.path,client:this,data:options});group.save(function(err,response){doCallback(callback,[err,response,group],group)})},Usergrid.Client.prototype.createEntity=function(options,callback){var entity=new Usergrid.Entity({client:this,data:options});entity.save(function(err,response){doCallback(callback,[err,response,entity],entity)})},Usergrid.Client.prototype.getEntity=function(options,callback){var entity=new Usergrid.Entity({client:this,data:options});entity.fetch(function(err,response){doCallback(callback,[err,response,entity],entity)})},Usergrid.Client.prototype.restoreEntity=function(serializedObject){var data=JSON.parse(serializedObject),options={client:this,data:data},entity=new Usergrid.Entity(options);return entity},Usergrid.Client.prototype.createCounter=function(options,callback){var counter=new Usergrid.Counter({client:this,data:options});counter.save(callback)},Usergrid.Client.prototype.createAsset=function(options,callback){var file=options.file;file&&(options.name=options.name||file.name,options["content-type"]=options["content-type"]||file.type,options.path=options.path||"/",delete options.file);var asset=new Usergrid.Asset({client:this,data:options});asset.save(function(err,response,asset){file&&!err?asset.upload(file,callback):doCallback(callback,[err,response,asset],asset)})},Usergrid.Client.prototype.createCollection=function(options,callback){options.client=this;var collection=new Usergrid.Collection(options);this.request({method:"POST",endpoint:options.type},function(err,data){err?doCallback(callback,[err,data,collection],self):collection.fetch(function(err,response,collection){doCallback(callback,[err,response,collection],self)})})},Usergrid.Client.prototype.restoreCollection=function(serializedObject){var data=JSON.parse(serializedObject);data.client=this;var collection=new Usergrid.Collection(data);return collection},Usergrid.Client.prototype.getFeedForUser=function(username,callback){var options={method:"GET",endpoint:"users/"+username+"/feed"};this.request(options,function(err,data){err?doCallback(callback,[err]):doCallback(callback,[err,data,data.getEntities()])})},Usergrid.Client.prototype.createUserActivity=function(user,options,callback){options.type="users/"+user+"/activities",options={client:this,data:options};var entity=new Usergrid.Entity(options);entity.save(function(err,data){doCallback(callback,[err,data,entity])})},Usergrid.Client.prototype.createUserActivityWithEntity=function(user,content,callback){var username=user.get("username"),options={actor:{displayName:username,uuid:user.get("uuid"),username:username,email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80}},verb:"post",content:content};this.createUserActivity(username,options,callback)},Usergrid.Client.prototype.calcTimeDiff=function(){var seconds=0,time=this._end-this._start;try{seconds=(time/10/60).toFixed(2)}catch(e){return 0}return seconds},Usergrid.Client.prototype.setToken=function(token){this.set("token",token)},Usergrid.Client.prototype.getToken=function(){return this.get("token")},Usergrid.Client.prototype.setObject=function(key,value){value&&(value=JSON.stringify(value)),this.set(key,value)},Usergrid.Client.prototype.set=function(key,value){var keyStore="apigee_"+key;this[key]=value,"undefined"!=typeof Storage&&(value?localStorage.setItem(keyStore,value):localStorage.removeItem(keyStore))},Usergrid.Client.prototype.getObject=function(key){return JSON.parse(this.get(key))},Usergrid.Client.prototype.get=function(key){var keyStore="apigee_"+key,value=null;return this[key]?value=this[key]:"undefined"!=typeof Storage&&(value=localStorage.getItem(keyStore)),value},Usergrid.Client.prototype.signup=function(username,password,email,name,callback){var options={type:"users",username:username,password:password,email:email,name:name};this.createEntity(options,callback)},Usergrid.Client.prototype.login=function(username,password,callback){var self=this,options={method:"POST",endpoint:"token",body:{username:username,password:password,grant_type:"password"}};self.request(options,function(err,response){var user={};if(err)self.logging&&console.log("error trying to log user in");else{var options={client:self,data:response.user};user=new Usergrid.Entity(options),self.setToken(response.access_token)}doCallback(callback,[err,response,user])})},Usergrid.Client.prototype.adminlogin=function(username,password,callback){var self=this,options={method:"POST",endpoint:"management/token",body:{username:username,password:password,grant_type:"password"},mQuery:!0};self.request(options,function(err,response){var user={};if(err)self.logging&&console.log("error trying to log adminuser in");else{var options={client:self,data:response.user};user=new Usergrid.Entity(options),self.setToken(response.access_token)}doCallback(callback,[err,response,user])})},Usergrid.Client.prototype.reAuthenticateLite=function(callback){var self=this,options={method:"GET",endpoint:"management/me",mQuery:!0};this.request(options,function(err,response){err&&self.logging?console.log("error trying to re-authenticate user"):self.setToken(response.data.access_token),doCallback(callback,[err])})},Usergrid.Client.prototype.reAuthenticate=function(email,callback){var self=this,options={method:"GET",endpoint:"management/users/"+email,mQuery:!0};this.request(options,function(err,response){var data,organizations={},applications={},user={};if(err&&self.logging)console.log("error trying to full authenticate user");else{data=response.data,self.setToken(data.token),self.set("email",data.email),localStorage.setItem("accessToken",data.token),localStorage.setItem("userUUID",data.uuid),localStorage.setItem("userEmail",data.email);var userData={username:data.username,email:data.email,name:data.name,uuid:data.uuid},options={client:self,data:userData};user=new Usergrid.Entity(options),organizations=data.organizations;var org="";try{var existingOrg=self.get("orgName");org=organizations[existingOrg]?organizations[existingOrg]:organizations[Object.keys(organizations)[0]],self.set("orgName",org.name)}catch(e){err=!0,self.logging&&console.log("error selecting org")}applications=self.parseApplicationsArray(org),self.selectFirstApp(applications),self.setObject("organizations",organizations),self.setObject("applications",applications); -}doCallback(callback,[err,data,user,organizations,applications],self)})},Usergrid.Client.prototype.loginFacebook=function(facebookToken,callback){var self=this,options={method:"GET",endpoint:"auth/facebook",qs:{fb_access_token:facebookToken}};this.request(options,function(err,data){var user={};if(err&&self.logging)console.log("error trying to log user in");else{var options={client:self,data:data.user};user=new Usergrid.Entity(options),self.setToken(data.access_token)}doCallback(callback,[err,data,user],self)})},Usergrid.Client.prototype.getLoggedInUser=function(callback){var self=this;if(this.getToken()){var options={method:"GET",endpoint:"users/me"};this.request(options,function(err,response){if(err)self.logging&&console.log("error trying to log user in"),console.error(err,response),doCallback(callback,[err,response,self],self);else{var options={client:self,data:response.getEntity()},user=new Usergrid.Entity(options);doCallback(callback,[null,response,user],self)}})}else doCallback(callback,[new UsergridError("Access Token not set"),null,self],self)},Usergrid.Client.prototype.isLoggedIn=function(){var token=this.getToken();return"undefined"!=typeof token&&null!==token},Usergrid.Client.prototype.logout=function(){this.setToken()},Usergrid.Client.prototype.destroyToken=function(username,token,revokeAll,callback){var options={client:self,method:"PUT"};revokeAll===!0?options.endpoint="users/"+username+"/revoketokens":null===token?options.endpoint="users/"+username+"/revoketoken?token="+this.getToken():options.endpoint="users/"+username+"/revoketoken?token="+token,this.request(options,function(err,data){err?(self.logging&&console.log("error destroying access token"),doCallback(callback,[err,data,null],self)):(revokeAll===!0?console.log("all user tokens invalidated"):console.log("token invalidated"),doCallback(callback,[err,data,null],self))})},Usergrid.Client.prototype.logoutAndDestroyToken=function(username,token,revokeAll,callback){null===username?console.log("username required to revoke tokens"):(this.destroyToken(username,token,revokeAll,callback),(revokeAll===!0||token===this.getToken()||null===token)&&this.setToken(null))},Usergrid.Client.prototype.buildCurlCall=function(options){var curl=["curl"],method=(options.method||"GET").toUpperCase(),body=options.body,uri=options.uri;return curl.push("-X"),curl.push(["POST","PUT","DELETE"].indexOf(method)>=0?method:"GET"),curl.push(uri),"object"==typeof body&&Object.keys(body).length>0&&-1!==["POST","PUT"].indexOf(method)&&(curl.push("-d"),curl.push("'"+JSON.stringify(body)+"'")),curl=curl.join(" "),console.log(curl),curl},Usergrid.Client.prototype.getDisplayImage=function(email,picture,size){size=size||50;var image="https://apigee.com/usergrid/images/user_profile.png";try{picture?image=picture:email.length&&(image="https://secure.gravatar.com/avatar/"+MD5(email)+"?s="+size+encodeURI("&d=https://apigee.com/usergrid/images/user_profile.png"))}catch(e){}finally{return image}},global[name]=Usergrid.Client,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}();var ENTITY_SYSTEM_PROPERTIES=["metadata","created","modified","oldpassword","newpassword","type","activated","uuid"];Usergrid.Entity=function(options){this._data={},this._client=void 0,options&&(this.set(options.data||{}),this._client=options.client||{})},Usergrid.Entity.isEntity=function(obj){return obj&&obj instanceof Usergrid.Entity},Usergrid.Entity.isPersistedEntity=function(obj){return isEntity(obj)&&isUUID(obj.get("uuid"))},Usergrid.Entity.prototype.serialize=function(){return JSON.stringify(this._data)},Usergrid.Entity.prototype.get=function(key){var value;if(0===arguments.length?value=this._data:arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c,i,a){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(value=this._data[key]);return value},Usergrid.Entity.prototype.set=function(key,value){if("object"==typeof key)for(var field in key)this._data[field]=key[field];else"string"==typeof key?null===value?delete this._data[key]:this._data[key]=value:this._data={}},Usergrid.Entity.prototype.getEndpoint=function(){var name,type=this.get("type"),nameProperties=["uuid","name"];if(void 0===type)throw new UsergridError("cannot fetch entity, no entity type specified","no_type_specified");return/^users?$/.test(type)&&nameProperties.unshift("username"),name=this.get(nameProperties).filter(function(x){return null!==x&&"undefined"!=typeof x}).shift(),name?[type,name].join("/"):type},Usergrid.Entity.prototype.save=function(callback){var self=this,type=this.get("type"),method="POST",entityId=this.get("uuid"),entityData=this.get(),options={method:method,endpoint:type};entityId&&(options.method="PUT",options.endpoint+="/"+entityId),options.body=Object.keys(entityData).filter(function(key){return-1===ENTITY_SYSTEM_PROPERTIES.indexOf(key)}).reduce(function(data,key){return data[key]=entityData[key],data},{}),self._client.request(options,function(err,response){var entity=response.getEntity();entity&&(self.set(entity),self.set("type",/^\//.test(response.path)?response.path.substring(1):response.path)),err&&self._client.logging&&console.log("could not save entity"),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.changePassword=function(oldpassword,newpassword,callback){var self=this;if("function"==typeof oldpassword&&void 0===callback&&(callback=oldpassword,oldpassword=self.get("oldpassword"),newpassword=self.get("newpassword")),self.set({password:null,oldpassword:null,newpassword:null}),!(/^users?$/.test(self.get("type"))&&oldpassword&&newpassword))throw new UsergridInvalidArgumentError("Invalid arguments passed to 'changePassword'");var options={method:"PUT",endpoint:"users/"+self.get("uuid")+"/password",body:{uuid:self.get("uuid"),username:self.get("username"),oldpassword:oldpassword,newpassword:newpassword}};self._client.request(options,function(err,response){err&&self._client.logging&&console.log("could not update user"),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.fetch=function(callback){var endpoint,self=this;endpoint=this.getEndpoint();var options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,response){var entity=response.getEntity();entity&&self.set(entity),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.destroy=function(callback){var self=this,endpoint=this.getEndpoint(),options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,response){err||self.set(null),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.connect=function(connection,entity,callback){this.addOrRemoveConnection("POST",connection,entity,callback)},Usergrid.Entity.prototype.disconnect=function(connection,entity,callback){this.addOrRemoveConnection("DELETE",connection,entity,callback)},Usergrid.Entity.prototype.addOrRemoveConnection=function(method,connection,entity,callback){var self=this;if(-1==["POST","DELETE"].indexOf(method.toUpperCase()))throw new UsergridInvalidArgumentError("invalid method for connection call. must be 'POST' or 'DELETE'");var connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)throw new UsergridInvalidArgumentError("connectee could not be identified");var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)throw new UsergridInvalidArgumentError("connector could not be identified");var endpoint=[connectorType,connector,connection,connecteeType,connectee].join("/"),options={method:method,endpoint:endpoint};this._client.request(options,function(err,response){err&&self._client.logging&&console.log("There was an error with the connection call"),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.getEntityId=function(entity){var id;return id=isUUID(entity.get("uuid"))?entity.get("uuid"):"users"===this.get("type")||"user"===this.get("type")?entity.get("username"):entity.get("name")},Usergrid.Entity.prototype.getConnections=function(connection,callback){var self=this,connectorType=this.get("type"),connector=this.getEntityId(this);if(connector){var endpoint=connectorType+"/"+connector+"/"+connection+"/",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self[connection]={};for(var length=data&&data.entities?data.entities.length:0,i=0;length>i;i++)"user"===data.entities[i].type?self[connection][data.entities[i].username]=data.entities[i]:self[connection][data.entities[i].name]=data.entities[i];doCallback(callback,[err,data,data.entities],self)})}else if("function"==typeof callback){var error="Error in getConnections - no uuid specified.";self._client.logging&&console.log(error),doCallback(callback,[!0,error],self)}},Usergrid.Entity.prototype.getGroups=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/groups",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self.groups=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Entity.prototype.getActivities=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/activities",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected");for(var entity in data.entities)data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();self.activities=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Entity.prototype.getFollowing=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/following",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user following");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.following=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Entity.prototype.getFollowers=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/followers",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user followers");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.followers=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Client.prototype.createRole=function(roleName,permissions,callback){var options={type:"role",name:roleName};this.createEntity(options,function(err,response,entity){err?doCallback(callback,[err,response,self]):entity.assignPermissions(permissions,function(err,data){err?doCallback(callback,[err,response,self]):doCallback(callback,[err,data,data.data],self)})})},Usergrid.Entity.prototype.getRoles=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/roles",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user roles"),self.roles=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Entity.prototype.assignRole=function(roleName,callback){var entityID,self=this,type=self.get("type"),collection=type+"s";"user"==type&&null!=this.get("username")?entityID=self.get("username"):"group"==type&&null!=this.get("name")?entityID=self.get("name"):null!=this.get("uuid")&&(entityID=self.get("uuid")),"users"!=type&&"groups"!=type&&doCallback(callback,[new UsergridError("entity must be a group or user","invalid_entity_type"),null,this],this);var endpoint="roles/"+roleName+"/"+collection+"/"+entityID,options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,response){err&&console.log("Could not assign role."),doCallback(callback,[err,response,self])})},Usergrid.Entity.prototype.removeRole=function(roleName,callback){var entityID,self=this,type=self.get("type"),collection=type+"s";"user"==type&&null!=this.get("username")?entityID=this.get("username"):"group"==type&&null!=this.get("name")?entityID=this.get("name"):null!=this.get("uuid")&&(entityID=this.get("uuid")),"users"!=type&&"groups"!=type&&doCallback(callback,[new UsergridError("entity must be a group or user","invalid_entity_type"),null,this],this);var endpoint="roles/"+roleName+"/"+collection+"/"+entityID,options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,response){err&&console.log("Could not assign role."),doCallback(callback,[err,response,self])})},Usergrid.Entity.prototype.assignPermissions=function(permissions,callback){var entityID,self=this,type=this.get("type");"user"!=type&&"users"!=type&&"group"!=type&&"groups"!=type&&"role"!=type&&"roles"!=type&&doCallback(callback,[new UsergridError("entity must be a group, user, or role","invalid_entity_type"),null,this],this),"user"==type&&null!=this.get("username")?entityID=this.get("username"):"group"==type&&null!=this.get("name")?entityID=this.get("name"):null!=this.get("uuid")&&(entityID=this.get("uuid"));var endpoint=type+"/"+entityID+"/permissions",options={method:"POST",endpoint:endpoint,body:{permission:permissions}};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not assign permissions"),doCallback(callback,[err,data,data.data],self)})},Usergrid.Entity.prototype.removePermissions=function(permissions,callback){var entityID,self=this,type=this.get("type");"user"!=type&&"users"!=type&&"group"!=type&&"groups"!=type&&"role"!=type&&"roles"!=type&&doCallback(callback,[new UsergridError("entity must be a group, user, or role","invalid_entity_type"),null,this],this),"user"==type&&null!=this.get("username")?entityID=this.get("username"):"group"==type&&null!=this.get("name")?entityID=this.get("name"):null!=this.get("uuid")&&(entityID=this.get("uuid"));var endpoint=type+"/"+entityID+"/permissions",options={method:"DELETE",endpoint:endpoint,qs:{permission:permissions}};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not remove permissions"),doCallback(callback,[err,data,data.params.permission],self)})},Usergrid.Entity.prototype.getPermissions=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/permissions",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user permissions");var permissions=[];if(data.data){var perms=data.data,count=0;for(var i in perms){count++;var perm=perms[i],parts=perm.split(":"),ops_part="",path_part=parts[0];parts.length>1&&(ops_part=parts[0],path_part=parts[1]),ops_part=ops_part.replace("*","get,post,put,delete");var ops=ops_part.split(","),ops_object={};ops_object.get="no",ops_object.post="no",ops_object.put="no",ops_object["delete"]="no";for(var j in ops)ops_object[ops[j]]="yes";permissions.push({operations:ops_object,path:path_part,perm:perm})}}self.permissions=permissions,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Collection=function(options){if(options&&(this._client=options.client,this._type=options.type,this.qs=options.qs||{},this._list=options.list||[],this._iterator=options.iterator||-1,this._previous=options.previous||[],this._next=options.next||null,this._cursor=options.cursor||null,options.list))for(var count=options.list.length,i=0;count>i;i++){var entity=this._client.restoreEntity(options.list[i]);this._list[i]=entity}},Usergrid.isCollection=function(obj){return obj&&obj instanceof Usergrid.Collection},Usergrid.Collection.prototype.serialize=function(){var data={};data.type=this._type,data.qs=this.qs,data.iterator=this._iterator,data.previous=this._previous,data.next=this._next,data.cursor=this._cursor,this.resetEntityPointer();var i=0;for(data.list=[];this.hasNextEntity();){var entity=this.getNextEntity();data.list[i]=entity.serialize(),i++}return data=JSON.stringify(data)},Usergrid.Collection.prototype.fetch=function(callback){var self=this,qs=this.qs;this._cursor?qs.cursor=this._cursor:delete qs.cursor;var options={method:"GET",endpoint:this._type,qs:this.qs};this._client.request(options,function(err,response){err&&self._client.logging?console.log("error getting collection"):(self.saveCursor(response.cursor||null),self.resetEntityPointer(),self._list=response.getEntities().filter(function(entity){return isUUID(entity.uuid)}).map(function(entity){var ent=new Usergrid.Entity({client:self._client});return ent.set(entity),ent.type=self._type,ent})),doCallback(callback,[err,response,self],self)})},Usergrid.Collection.prototype.addEntity=function(entityObject,callback){var self=this;entityObject.type=this._type,this._client.createEntity(entityObject,function(err,response,entity){err||self.addExistingEntity(entity),doCallback(callback,[err,response,self],self)})},Usergrid.Collection.prototype.addExistingEntity=function(entity){var count=this._list.length;this._list[count]=entity},Usergrid.Collection.prototype.destroyEntity=function(entity,callback){var self=this;entity.destroy(function(err,response){err?(self._client.logging&&console.log("could not destroy entity"),doCallback(callback,[err,response,self],self)):self.fetch(callback),self.removeEntity(entity)})},Usergrid.Collection.prototype.getEntitiesByCriteria=function(criteria){return this._list.filter(criteria)},Usergrid.Collection.prototype.getEntityByCriteria=function(criteria){return this.getEntitiesByCriteria(criteria).shift()},Usergrid.Collection.prototype.removeEntity=function(entity){var removedEntity=this.getEntityByCriteria(function(item){return entity.uuid===item.get("uuid")});return delete this._list[this._list.indexOf(removedEntity)],removedEntity},Usergrid.Collection.prototype.getEntityByUUID=function(uuid,callback){var entity=this.getEntityByCriteria(function(item){return item.get("uuid")===uuid});if(entity)doCallback(callback,[null,entity,entity],this);else{var options={data:{type:this._type,uuid:uuid},client:this._client};entity=new Usergrid.Entity(options),entity.fetch(callback)}},Usergrid.Collection.prototype.getFirstEntity=function(){var count=this._list.length;return count>0?this._list[0]:null},Usergrid.Collection.prototype.getLastEntity=function(){var count=this._list.length;return count>0?this._list[count-1]:null},Usergrid.Collection.prototype.hasNextEntity=function(){var next=this._iterator+1,hasNextElement=next>=0&&next=0&&this._iterator<=this._list.length;return hasNextElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.hasPrevEntity=function(){var previous=this._iterator-1,hasPreviousElement=previous>=0&&previous=0&&this._iterator<=this._list.length;return hasPreviousElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.resetEntityPointer=function(){this._iterator=-1},Usergrid.Collection.prototype.saveCursor=function(cursor){this._next!==cursor&&(this._next=cursor)},Usergrid.Collection.prototype.resetPaging=function(){this._previous=[],this._next=null,this._cursor=null},Usergrid.Collection.prototype.hasNextPage=function(){return this._next},Usergrid.Collection.prototype.getNextPage=function(callback){this.hasNextPage()&&(this._previous.push(this._cursor),this._cursor=this._next,this._list=[],this.fetch(callback))},Usergrid.Collection.prototype.hasPreviousPage=function(){return this._previous.length>0},Usergrid.Collection.prototype.getPreviousPage=function(callback){this.hasPreviousPage()&&(this._next=null,this._cursor=this._previous.pop(),this._list=[],this.fetch(callback))},Usergrid.Group=function(options,callback){this._path=options.path,this._list=[],this._client=options.client,this._data=options.data||{},this._data.type="groups"},Usergrid.Group.prototype=new Usergrid.Entity,Usergrid.Group.prototype.fetch=function(callback){var self=this,groupEndpoint="groups/"+this._path,memberEndpoint="groups/"+this._path+"/users",groupOptions={method:"GET",endpoint:groupEndpoint},memberOptions={method:"GET",endpoint:memberEndpoint};this._client.request(groupOptions,function(err,response){if(err)self._client.logging&&console.log("error getting group"),doCallback(callback,[err,response],self);else{var entities=response.getEntities();if(entities&&entities.length){entities.shift();self._client.request(memberOptions,function(err,response){err&&self._client.logging?console.log("error getting group users"):self._list=response.getEntities().filter(function(entity){return isUUID(entity.uuid)}).map(function(entity){return new Usergrid.Entity({type:entity.type,client:self._client,uuid:entity.uuid,response:entity})}),doCallback(callback,[err,response,self],self)})}}})},Usergrid.Group.prototype.members=function(callback){return this._list},Usergrid.Group.prototype.add=function(options,callback){var self=this;options.user?(options={method:"POST",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")},this._client.request(options,function(error,response){error?doCallback(callback,[error,response,self],self):self.fetch(callback)})):doCallback(callback,[new UsergridError("no user specified","no_user_specified"),null,this],this)},Usergrid.Group.prototype.remove=function(options,callback){var self=this;options.user?(options={method:"DELETE",endpoint:"groups/"+this._path+"/users/"+options.user.username},this._client.request(options,function(error,response){error?doCallback(callback,[error,response,self],self):self.fetch(callback)})):doCallback(callback,[new UsergridError("no user specified","no_user_specified"),null,this],this)},Usergrid.Group.prototype.feed=function(callback){var self=this,options={method:"GET",endpoint:"groups/"+this._path+"/feed"};this._client.request(options,function(err,response){doCallback(callback,[err,response,self],self)})},Usergrid.Group.prototype.createGroupActivity=function(options,callback){var self=this,user=options.user,entity=new Usergrid.Entity({client:this._client,data:{actor:{displayName:user.get("username"),uuid:user.get("uuid"),username:user.get("username"),email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80}},verb:"post",content:options.content,type:"groups/"+this._path+"/activities"}});entity.save(function(err,response,entity){doCallback(callback,[err,response,self])})},Usergrid.Counter=function(options){this._client=options.client,this._data=options.data||{},this._data.category=options.category||"UNKNOWN",this._data.timestamp=options.timestamp||0,this._data.type="events",this._data.counters=options.counters||{}};var COUNTER_RESOLUTIONS=["all","minute","five_minutes","half_hour","hour","six_day","day","week","month"];Usergrid.Counter.prototype=new Usergrid.Entity,Usergrid.Counter.prototype.fetch=function(callback){this.getData({},callback)},Usergrid.Counter.prototype.increment=function(options,callback){var self=this,name=options.name,value=options.value;return name?isNaN(value)?doCallback(callback,[new UsergridInvalidArgumentError("'value' for increment, decrement must be a number"),null,self],self):(self._data.counters[name]=parseInt(value)||1,self.save(callback)):doCallback(callback,[new UsergridInvalidArgumentError("'name' for increment, decrement must be a number"),null,self],self)},Usergrid.Counter.prototype.decrement=function(options,callback){var self=this,name=options.name,value=options.value;self.increment({name:name,value:-(parseInt(value)||1)},callback)},Usergrid.Counter.prototype.reset=function(options,callback){var self=this,name=options.name;self.increment({name:name,value:0},callback)},Usergrid.Counter.prototype.getData=function(options,callback){var start_time,end_time,start=options.start||0,end=options.end||Date.now(),resolution=(options.resolution||"all").toLowerCase(),counters=options.counters||Object.keys(this._data.counters),res=(resolution||"all").toLowerCase();-1===COUNTER_RESOLUTIONS.indexOf(res)&&(res="all"),start_time=getSafeTime(start),end_time=getSafeTime(end);var self=this,params=Object.keys(counters).map(function(counter){return["counter",encodeURIComponent(counters[counter])].join("=")});params.push("resolution="+res),params.push("start_time="+String(start_time)),params.push("end_time="+String(end_time));var endpoint="counters?"+params.join("&");this._client.request({endpoint:endpoint},function(err,data){return data.counters&&data.counters.length&&data.counters.forEach(function(counter){self._data.counters[counter.name]=counter.value||counter.values}),doCallback(callback,[err,data,self],self)})},Usergrid.Folder=function(options,callback){var self=this;console.log("FOLDER OPTIONS",options),self._client=options.client,self._data=options.data||{},self._data.type="folders";var missingData=["name","owner","path"].some(function(required){return!(required in self._data)});return missingData?doCallback(callback,[new UsergridInvalidArgumentError("Invalid asset data: 'name', 'owner', and 'path' are required properties."),null,self],self):void self.save(function(err,response){err?doCallback(callback,[new UsergridError(response),response,self],self):(response&&response.entities&&response.entities.length&&self.set(response.entities[0]),doCallback(callback,[null,response,self],self))})},Usergrid.Folder.prototype=new Usergrid.Entity,Usergrid.Folder.prototype.fetch=function(callback){var self=this;Usergrid.Entity.prototype.fetch.call(self,function(err,data){console.log("self",self.get()),console.log("data",data),err?doCallback(callback,[null,data,self],self):self.getAssets(function(err,response){err?doCallback(callback,[new UsergridError(response),resonse,self],self):doCallback(callback,[null,self],self)})})},Usergrid.Folder.prototype.addAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset,asset instanceof Usergrid.Entity||(asset=new Usergrid.Asset(asset));break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}asset&&asset instanceof Usergrid.Entity&&asset.fetch(function(err,data){if(err)doCallback(callback,[new UsergridError(data),data,self],self);else{var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/"),options={method:"POST",endpoint:endpoint};self._client.request(options,callback)}})}else doCallback(callback,[new UsergridInvalidArgumentError("No asset specified"),null,self],self)},Usergrid.Folder.prototype.removeAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset;break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}if(asset&&null!==asset){var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/");self._client.request({method:"DELETE",endpoint:endpoint},function(err,response){err?doCallback(callback,[new UsergridError(response),response,self],self):doCallback(callback,[null,response,self],self)})}}else doCallback(callback,[new UsergridInvalidArgumentError("No asset specified"),null,self],self)},Usergrid.Folder.prototype.getAssets=function(callback){return this.getConnections("assets",callback)},XMLHttpRequest.prototype.sendAsBinary||(XMLHttpRequest.prototype.sendAsBinary=function(sData){for(var nBytes=sData.length,ui8Data=new Uint8Array(nBytes),nIdx=0;nBytes>nIdx;nIdx++)ui8Data[nIdx]=255&sData.charCodeAt(nIdx);this.send(ui8Data)}),Usergrid.Asset=function(options,callback){var self=this;self._client=options.client,self._data=options.data||{},self._data.type="assets";var missingData=["name","owner","path"].some(function(required){return!(required in self._data)});missingData?doCallback(callback,[new UsergridError("Invalid asset data: 'name', 'owner', and 'path' are required properties."),null,self],self):self.save(function(err,data){err?doCallback(callback,[new UsergridError(data),data,self],self):(data&&data.entities&&data.entities.length&&self.set(data.entities[0]),doCallback(callback,[null,data,self],self))})},Usergrid.Asset.prototype=new Usergrid.Entity,Usergrid.Asset.prototype.addToFolder=function(options,callback){var self=this;if("folder"in options&&isUUID(options.folder)){Usergrid.Folder({uuid:options.folder},function(err,folder){if(err)doCallback(callback,[UsergridError.fromResponse(folder),folder,self],self);else{var endpoint=["folders",folder.get("uuid"),"assets",self.get("uuid")].join("/"),options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,response){err?doCallback(callback,[UsergridError.fromResponse(folder),response,self],self):doCallback(callback,[null,folder,self],self)})}})}else doCallback(callback,[new UsergridError("folder not specified"),null,self],self)},Usergrid.Entity.prototype.attachAsset=function(file,callback){if(!(window.File&&window.FileReader&&window.FileList&&window.Blob))return void doCallback(callback,[new UsergridError("The File APIs are not fully supported by your browser."),null,this],this);var self=this,args=arguments,type=this._data.type,attempts=self.get("attempts");if(isNaN(attempts)&&(attempts=3),"assets"!=type&&"asset"!=type)var endpoint=[this._client.clientAppURL,type,self.get("uuid")].join("/");else{self.set("content-type",file.type),self.set("size",file.size);var endpoint=[this._client.clientAppURL,"assets",self.get("uuid"),"data"].join("/")}var xhr=new XMLHttpRequest;xhr.open("POST",endpoint,!0),xhr.onerror=function(err){doCallback(callback,[new UsergridError("The File APIs are not fully supported by your browser.")],xhr,self)},xhr.onload=function(ev){xhr.status>=500&&attempts>0?(self.set("attempts",--attempts),setTimeout(function(){self.attachAsset.apply(self,args)},100)):xhr.status>=300?(self.set("attempts"),doCallback(callback,[new UsergridError(JSON.parse(xhr.responseText)),xhr,self],self)):(self.set("attempts"),self.fetch(),doCallback(callback,[null,xhr,self],self))};var fr=new FileReader;fr.onload=function(){var binary=fr.result;("assets"===type||"asset"===type)&&(xhr.overrideMimeType("application/octet-stream"),xhr.setRequestHeader("Content-Type","application/octet-stream")),xhr.sendAsBinary(binary)},fr.readAsBinaryString(file)},Usergrid.Asset.prototype.upload=function(data,callback){this.attachAsset(data,function(err,response){err?doCallback(callback,[new UsergridError(err),response,self],self):doCallback(callback,[null,response,self],self)})},Usergrid.Entity.prototype.downloadAsset=function(callback){var endpoint,self=this,type=this._data.type,xhr=new XMLHttpRequest;endpoint="assets"!=type&&"asset"!=type?[this._client.clientAppURL,type,self.get("uuid")].join("/"):[this._client.clientAppURL,"assets",self.get("uuid"),"data"].join("/"),xhr.open("GET",endpoint,!0),xhr.responseType="blob",xhr.onload=function(ev){var blob=xhr.response;"assets"!=type&&"asset"!=type?doCallback(callback,[null,blob,xhr],self):doCallback(callback,[null,xhr,self],self)},xhr.onerror=function(err){callback(!0,err),doCallback(callback,[new UsergridError(err),xhr,self],self)},"assets"!=type&&"asset"!=type?xhr.setRequestHeader("Accept",self._data["file-metadata"]["content-type"]):xhr.overrideMimeType(self.get("content-type")), -xhr.send()},Usergrid.Asset.prototype.download=function(callback){this.downloadAsset(function(err,response){err?doCallback(callback,[new UsergridError(err),response,self],self):doCallback(callback,[null,response,self],self)})},function(global){function UsergridError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridHTTPResponseError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidHTTPMethodError(message,name,timestamp,duration,exception){this.message=message,this.name=name||"invalid_http_method",this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidURIError(message,name,timestamp,duration,exception){this.message=message,this.name=name||"invalid_uri",this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidArgumentError(message,name,timestamp,duration,exception){this.message=message,this.name=name||"invalid_argument",this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridKeystoreDatabaseUpgradeNeededError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}var short,name="UsergridError",_name=global[name],_short=short&&void 0!==short?global[short]:void 0;return UsergridError.prototype=new Error,UsergridError.prototype.constructor=UsergridError,UsergridError.fromResponse=function(response){return response&&"undefined"!=typeof response?new UsergridError(response.error_description,response.error,response.timestamp,response.duration,response.exception):new UsergridError},UsergridError.createSubClass=function(name){return name in global&&global[name]?global[name]:(global[name]=function(){},global[name].name=name,global[name].prototype=new UsergridError,global[name])},UsergridHTTPResponseError.prototype=new UsergridError,UsergridInvalidHTTPMethodError.prototype=new UsergridError,UsergridInvalidURIError.prototype=new UsergridError,UsergridInvalidArgumentError.prototype=new UsergridError,UsergridKeystoreDatabaseUpgradeNeededError.prototype=new UsergridError,global.UsergridHTTPResponseError=UsergridHTTPResponseError,global.UsergridInvalidHTTPMethodError=UsergridInvalidHTTPMethodError,global.UsergridInvalidURIError=UsergridInvalidURIError,global.UsergridInvalidArgumentError=UsergridInvalidArgumentError,global.UsergridKeystoreDatabaseUpgradeNeededError=UsergridKeystoreDatabaseUpgradeNeededError,global[name]=UsergridError,void 0!==short&&(global[short]=UsergridError),global[name].noConflict=function(){return _name&&(global[name]=_name),void 0!==short&&(global[short]=_short),UsergridError},global[name]}(this);var UsergridAuth=function(token,expiry){var self=this;self.token=token,self.expiry=expiry||0;var usingToken=token?!0:!1;return Object.defineProperty(self,"hasToken",{get:function(){return self.token?!0:!1},configurable:!0}),Object.defineProperty(self,"isExpired",{get:function(){return usingToken?!1:Date.now()>=self.expiry},configurable:!0}),Object.defineProperty(self,"isValid",{get:function(){return!self.isExpired&&self.hasToken},configurable:!0}),Object.defineProperty(self,"tokenTtl",{configurable:!0,writable:!0}),_.assign(self,{destroy:function(){self.token=void 0,self.expiry=0,self.tokenTtl=void 0}}),self},UsergridAppAuth=function(){var self=this,args=flattenArgs(arguments);return _.isPlainObject(args[0])?(self.clientId=args[0].clientId,self.clientSecret=args[0].clientSecret,self.tokenTtl=args[0].tokenTtl):(self.clientId=args[0],self.clientSecret=args[1],self.tokenTtl=args[2]),UsergridAuth.call(self),_.assign(self,UsergridAuth),self};inherits(UsergridAppAuth,UsergridAuth);var UsergridUserAuth=function(){var self=this,args=flattenArgs(arguments);return _.isPlainObject(args[0])?(self.username=args[0].username,self.email=args[0].email,self.tokenTtl=args[0].tokenTtl):(self.username=args[0],self.email=args[1],self.tokenTtl=args[2]),UsergridAuth.call(self),_.assign(self,UsergridAuth),self};inherits(UsergridUserAuth,UsergridAuth); \ No newline at end of file +"use strict";function extend(subClass,superClass){var F=function(){};return F.prototype=superClass.prototype,subClass.prototype=new F,subClass.prototype.constructor=subClass,subClass.superclass=superClass.prototype,superClass.prototype.constructor==Object.prototype.constructor&&(superClass.prototype.constructor=superClass),subClass}function propCopy(from,to){for(var prop in from)from.hasOwnProperty(prop)&&("object"==typeof from[prop]&&"object"==typeof to[prop]?to[prop]=propCopy(from[prop],to[prop]):to[prop]=from[prop]);return to}function NOOP(){}function isValidUrl(url){if(!url)return!1;var doc,base,anchor,isValid=!1;try{doc=document.implementation.createHTMLDocument(""),base=doc.createElement("base"),base.href=base||window.lo,doc.head.appendChild(base),anchor=doc.createElement("a"),anchor.href=url,doc.body.appendChild(anchor),isValid=!(""===anchor.href)}catch(e){console.error(e)}finally{return doc.head.removeChild(base),doc.body.removeChild(anchor),base=null,anchor=null,doc=null,isValid}}function isUUID(uuid){return uuid?uuidValueRegex.test(uuid):!1}function encodeParams(params){var queryString;return params&&Object.keys(params)&&(queryString=[].slice.call(arguments).reduce(function(a,b){return a.concat(b instanceof Array?b:[b])},[]).filter(function(c){return"object"==typeof c}).reduce(function(p,c){return c instanceof Array?p.push(c):p=p.concat(Object.keys(c).map(function(key){return[key,c[key]]})),p},[]).reduce(function(p,c){return 2===c.length?p.push(c):p=p.concat(c),p},[]).reduce(function(p,c){return c[1]instanceof Array?c[1].forEach(function(v){p.push([c[0],v])}):p.push(c),p},[]).map(function(c){return c[1]=encodeURIComponent(c[1]),c.join("=")}).join("&")),queryString}function isFunction(f){return f&&null!==f&&"function"==typeof f}function doCallback(callback,params,context){var returnValue;return isFunction(callback)&&(params||(params=[]),context||(context=this),params.push(context),returnValue=callback.apply(context,params)),returnValue}function updateEntityFromRemote(usergridResponse){UsergridHelpers.setWritable(this,["uuid","name","type","created"]),_.assign(this,usergridResponse.entity),UsergridHelpers.setReadOnly(this,["uuid","name","type","created"])}function getSafeTime(prop){var time;switch(typeof prop){case"undefined":time=Date.now();break;case"number":time=prop;break;case"string":time=isNaN(prop)?Date.parse(prop):parseInt(prop);break;default:time=Date.parse(prop.toString())}return time}var UsergridAuthMode=Object.freeze({NONE:"none",USER:"user",APP:"app"}),UsergridDirection=Object.freeze({IN:"connecting",OUT:"connections"}),UsergridHttpMethod=Object.freeze({GET:"GET",PUT:"PUT",POST:"POST",DELETE:"DELETE"}),UsergridQueryOperator=Object.freeze({EQUAL:"=",GREATER_THAN:">",GREATER_THAN_EQUAL_TO:">=",LESS_THAN:"<",LESS_THAN_EQUAL_TO:"<="}),UsergridQuerySortOrder=Object.freeze({ASC:"asc",DESC:"desc"}),UsergridEventable=function(){throw Error("'UsergridEventable' is not intended to be invoked directly")};UsergridEventable.prototype={bind:function(event,fn){this._events=this._events||{},this._events[event]=this._events[event]||[],this._events[event].push(fn)},unbind:function(event,fn){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fn),1)},trigger:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;ii;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,result){var p=new Promise;return null===promises||0===promises.length?p.done(result):promises[0](result).then(function(res){promises.splice(0,1),promises?Promise.chain(promises,res).then(function(r){p.done(r)}):p.done(res)}),p},global[name]=Promise,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Promise},global[name]}(this),function(){function partial(){var args=Array.prototype.slice.call(arguments),fn=args.shift();return fn.bind(this,args)}function Ajax(){function encode(data){var result="";if("string"==typeof data)result=data;else{var e=encodeURIComponent;for(var i in data)data.hasOwnProperty(i)&&(result+="&"+e(i)+"="+e(data[i]))}return result}function request(m,u,d){var timeout,p=new Promise;return self.logger.time(m+" "+u),function(xhr){xhr.onreadystatechange=function(){4===this.readyState&&(self.logger.timeEnd(m+" "+u),clearTimeout(timeout),p.done(this))},xhr.onerror=function(response){clearTimeout(timeout),p.done(response)},xhr.oncomplete=function(response){clearTimeout(timeout),self.logger.timeEnd(m+" "+u),self.info("%s request to %s returned %s",m,u,this.status)},xhr.open(m,u),d&&("object"==typeof d&&(d=JSON.stringify(d)),xhr.setRequestHeader("Content-Type","application/json"),xhr.setRequestHeader("Accept","application/json")),timeout=setTimeout(function(){xhr.abort(),p.done("API Call timed out.",null)},3e4),xhr.send(encode(d))}(new XMLHttpRequest),p}this.logger=new global.Logger(name);var self=this;this.request=request,this.get=partial(request,"GET"),this.post=partial(request,"POST"),this.put=partial(request,"PUT"),this["delete"]=partial(request,"DELETE")}var exports,name="Ajax",global=this,overwrittenName=global[name];return global[name]=new Ajax,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}(),function(){function addMapEntry(map,pair){return map.set(pair[0],pair[1]),map}function addSetEntry(set,value){return set.add(value),set}function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}function arrayAggregator(array,setter,iteratee,accumulator){for(var index=-1,length=array?array.length:0;++index-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1;);return index}function charsEndIndex(strSymbols,chrSymbols){for(var index=strSymbols.length;index--&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1;);return index}function countHolders(array,placeholder){for(var length=array.length,result=0;length--;)array[length]===placeholder&&++result;return result}function escapeStringChar(chr){return"\\"+stringEscapes[chr]}function getValue(object,key){return null==object?undefined:object[key]}function hasUnicode(string){return reHasUnicode.test(string)}function hasUnicodeWord(string){return reHasUnicodeWord.test(string)}function iteratorToArray(iterator){for(var data,result=[];!(data=iterator.next()).done;)result.push(data.value);return result}function mapToArray(map){var index=-1,result=Array(map.size);return map.forEach(function(value,key){result[++index]=[key,value]}),result}function overArg(func,transform){return function(arg){return func(transform(arg))}}function replaceHolders(array,placeholder){for(var index=-1,length=array.length,resIndex=0,result=[];++indexdir,arrLength=isArr?array.length:0,view=getView(0,arrLength,this.__views__),start=view.start,end=view.end,length=end-start,index=isRight?end:start-1,iteratees=this.__iteratees__,iterLength=iteratees.length,resIndex=0,takeCount=nativeMin(length,this.__takeCount__);if(!isArr||LARGE_ARRAY_SIZE>arrLength||arrLength==length&&takeCount==length)return baseWrapperValue(array,this.__actions__);var result=[];outer:for(;length--&&takeCount>resIndex;){index+=dir;for(var iterIndex=-1,value=array[index];++iterIndexindex)return!1;var lastIndex=data.length-1;return index==lastIndex?data.pop():splice.call(data,index,1),--this.size,!0}function listCacheGet(key){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?undefined:data[index][1]}function listCacheHas(key){return assocIndexOf(this.__data__,key)>-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?(++this.size,data.push([key,value])):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index=number?number:upper),lower!==undefined&&(number=number>=lower?number:lower)),number}function baseClone(value,isDeep,isFull,customizer,key,object,stack){var result;if(customizer&&(result=object?customizer(value,key,object,stack):customizer(value)),result!==undefined)return result;if(!isObject(value))return value;var isArr=isArray(value);if(isArr){if(result=initCloneArray(value),!isDeep)return copyArray(value,result)}else{var tag=getTag(value),isFunc=tag==funcTag||tag==genTag;if(isBuffer(value))return cloneBuffer(value,isDeep);if(tag==objectTag||tag==argsTag||isFunc&&!object){if(result=initCloneObject(isFunc?{}:value),!isDeep)return copySymbols(value,baseAssign(result,value))}else{if(!cloneableTags[tag])return object?value:{};result=initCloneByTag(value,tag,baseClone,isDeep)}}stack||(stack=new Stack);var stacked=stack.get(value);if(stacked)return stacked;if(stack.set(value,result),!isArr)var props=isFull?getAllKeys(value):keys(value);return arrayEach(props||value,function(subValue,key){props&&(key=subValue,subValue=value[key]),assignValue(result,key,baseClone(subValue,isDeep,isFull,customizer,key,value,stack))}),result}function baseConforms(source){var props=keys(source);return function(object){return baseConformsTo(object,source,props)}}function baseConformsTo(object,source,props){var length=props.length;if(null==object)return!length;for(object=Object(object);length--;){var key=props[length],predicate=source[key],value=object[key];if(value===undefined&&!(key in object)||!predicate(value))return!1}return!0}function baseCreate(proto){return isObject(proto)?objectCreate(proto):{}}function baseDelay(func,wait,args){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return setTimeout(function(){func.apply(undefined,args)},wait)}function baseDifference(array,values,iteratee,comparator){var index=-1,includes=arrayIncludes,isCommon=!0,length=array.length,result=[],valuesLength=values.length;if(!length)return result;iteratee&&(values=arrayMap(values,baseUnary(iteratee))),comparator?(includes=arrayIncludesWith,isCommon=!1):values.length>=LARGE_ARRAY_SIZE&&(includes=cacheHas,isCommon=!1,values=new SetCache(values));outer:for(;++indexstart&&(start=-start>length?0:length+start),end=end===undefined||end>length?length:toInteger(end),0>end&&(end+=length),end=start>end?0:toLength(end);end>start;)array[start++]=value;return array}function baseFilter(collection,predicate){var result=[];return baseEach(collection,function(value,index,collection){predicate(value,index,collection)&&result.push(value)}),result}function baseFlatten(array,depth,predicate,isStrict,result){var index=-1,length=array.length;for(predicate||(predicate=isFlattenable),result||(result=[]);++index0&&predicate(value)?depth>1?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}function baseForOwn(object,iteratee){return object&&baseFor(object,iteratee,keys)}function baseForOwnRight(object,iteratee){return object&&baseForRight(object,iteratee,keys)}function baseFunctions(object,props){return arrayFilter(props,function(key){return isFunction(object[key])})}function baseGet(object,path){path=isKey(path,object)?[path]:castPath(path);for(var index=0,length=path.length;null!=object&&length>index;)object=object[toKey(path[index++])];return index&&index==length?object:undefined}function baseGetAllKeys(object,keysFunc,symbolsFunc){var result=keysFunc(object);return isArray(object)?result:arrayPush(result,symbolsFunc(object))}function baseGetTag(value){return objectToString.call(value)}function baseGt(value,other){return value>other}function baseHas(object,key){return null!=object&&hasOwnProperty.call(object,key)}function baseHasIn(object,key){return null!=object&&key in Object(object)}function baseInRange(number,start,end){return number>=nativeMin(start,end)&&number=120&&array.length>=120)?new SetCache(othIndex&&array):undefined}array=arrays[0];var index=-1,seen=caches[0];outer:for(;++indexvalue}function baseMap(collection,iteratee){var index=-1,result=isArrayLike(collection)?Array(collection.length):[];return baseEach(collection,function(value,key,collection){result[++index]=iteratee(value,key,collection)}),result}function baseMatches(source){var matchData=getMatchData(source);return 1==matchData.length&&matchData[0][2]?matchesStrictComparable(matchData[0][0],matchData[0][1]):function(object){return object===source||baseIsMatch(object,source,matchData)}}function baseMatchesProperty(path,srcValue){return isKey(path)&&isStrictComparable(srcValue)?matchesStrictComparable(toKey(path),srcValue):function(object){var objValue=get(object,path);return objValue===undefined&&objValue===srcValue?hasIn(object,path):baseIsEqual(srcValue,objValue,undefined,UNORDERED_COMPARE_FLAG|PARTIAL_COMPARE_FLAG)}}function baseMerge(object,source,srcIndex,customizer,stack){if(object!==source){if(!isArray(source)&&!isTypedArray(source))var props=baseKeysIn(source);arrayEach(props||source,function(srcValue,key){if(props&&(key=srcValue,srcValue=source[key]),isObject(srcValue))stack||(stack=new Stack),baseMergeDeep(object,source,key,srcIndex,baseMerge,customizer,stack);else{var newValue=customizer?customizer(object[key],srcValue,key+"",object,source,stack):undefined;newValue===undefined&&(newValue=srcValue),assignMergeValue(object,key,newValue)}})}}function baseMergeDeep(object,source,key,srcIndex,mergeFunc,customizer,stack){var objValue=object[key],srcValue=source[key],stacked=stack.get(srcValue);if(stacked)return void assignMergeValue(object,key,stacked);var newValue=customizer?customizer(objValue,srcValue,key+"",object,source,stack):undefined,isCommon=newValue===undefined;isCommon&&(newValue=srcValue,isArray(srcValue)||isTypedArray(srcValue)?isArray(objValue)?newValue=objValue:isArrayLikeObject(objValue)?newValue=copyArray(objValue):(isCommon=!1,newValue=baseClone(srcValue,!0)):isPlainObject(srcValue)||isArguments(srcValue)?isArguments(objValue)?newValue=toPlainObject(objValue):!isObject(objValue)||srcIndex&&isFunction(objValue)?(isCommon=!1,newValue=baseClone(srcValue,!0)):newValue=objValue:isCommon=!1),isCommon&&(stack.set(srcValue,newValue),mergeFunc(newValue,srcValue,srcIndex,customizer,stack),stack["delete"](srcValue)),assignMergeValue(object,key,newValue)}function baseNth(array,n){var length=array.length;if(length)return n+=0>n?length:0,isIndex(n,length)?array[n]:undefined}function baseOrderBy(collection,iteratees,orders){var index=-1;iteratees=arrayMap(iteratees.length?iteratees:[identity],baseUnary(getIteratee()));var result=baseMap(collection,function(value,key,collection){var criteria=arrayMap(iteratees,function(iteratee){return iteratee(value)});return{criteria:criteria,index:++index,value:value}});return baseSortBy(result,function(object,other){return compareMultiple(object,other,orders)})}function basePick(object,props){return object=Object(object),basePickBy(object,props,function(value,key){return key in object})}function basePickBy(object,props,predicate){for(var index=-1,length=props.length,result={};++index-1;)seen!==array&&splice.call(seen,fromIndex,1),splice.call(array,fromIndex,1);return array}function basePullAt(array,indexes){for(var length=array?indexes.length:0,lastIndex=length-1;length--;){var index=indexes[length];if(length==lastIndex||index!==previous){var previous=index;if(isIndex(index))splice.call(array,index,1);else if(isKey(index,array))delete array[toKey(index)];else{var path=castPath(index),object=parent(array,path);null!=object&&delete object[toKey(last(path))]}}}return array}function baseRandom(lower,upper){return lower+nativeFloor(nativeRandom()*(upper-lower+1))}function baseRange(start,end,step,fromRight){for(var index=-1,length=nativeMax(nativeCeil((end-start)/(step||1)),0),result=Array(length);length--;)result[fromRight?length:++index]=start,start+=step;return result}function baseRepeat(string,n){var result="";if(!string||1>n||n>MAX_SAFE_INTEGER)return result;do n%2&&(result+=string),n=nativeFloor(n/2),n&&(string+=string);while(n);return result}function baseRest(func,start){return setToString(overRest(func,start,identity),func+"")}function baseSet(object,path,value,customizer){if(!isObject(object))return object;path=isKey(path,object)?[path]:castPath(path);for(var index=-1,length=path.length,lastIndex=length-1,nested=object;null!=nested&&++indexstart&&(start=-start>length?0:length+start),end=end>length?length:end,0>end&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index=high){for(;high>low;){var mid=low+high>>>1,computed=array[mid];null!==computed&&!isSymbol(computed)&&(retHighest?value>=computed:value>computed)?low=mid+1:high=mid}return high}return baseSortedIndexBy(array,value,identity,retHighest)}function baseSortedIndexBy(array,value,iteratee,retHighest){value=iteratee(value);for(var low=0,high=array?array.length:0,valIsNaN=value!==value,valIsNull=null===value,valIsSymbol=isSymbol(value),valIsUndefined=value===undefined;high>low;){var mid=nativeFloor((low+high)/2),computed=iteratee(array[mid]),othIsDefined=computed!==undefined,othIsNull=null===computed,othIsReflexive=computed===computed,othIsSymbol=isSymbol(computed);if(valIsNaN)var setLow=retHighest||othIsReflexive;else setLow=valIsUndefined?othIsReflexive&&(retHighest||othIsDefined):valIsNull?othIsReflexive&&othIsDefined&&(retHighest||!othIsNull):valIsSymbol?othIsReflexive&&othIsDefined&&!othIsNull&&(retHighest||!othIsSymbol):othIsNull||othIsSymbol?!1:retHighest?value>=computed:value>computed;setLow?low=mid+1:high=mid}return nativeMin(high,MAX_ARRAY_INDEX)}function baseSortedUniq(array,iteratee){for(var index=-1,length=array.length,resIndex=0,result=[];++index=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++indexindex?values[index]:undefined;assignFunc(result,props[index],value)}return result}function castArrayLikeObject(value){return isArrayLikeObject(value)?value:[]}function castFunction(value){return"function"==typeof value?value:identity}function castPath(value){return isArray(value)?value:stringToPath(value)}function castSlice(array,start,end){var length=array.length;return end=end===undefined?length:end,!start&&end>=length?array:baseSlice(array,start,end)}function cloneBuffer(buffer,isDeep){if(isDeep)return buffer.slice();var result=new buffer.constructor(buffer.length);return buffer.copy(result),result}function cloneArrayBuffer(arrayBuffer){var result=new arrayBuffer.constructor(arrayBuffer.byteLength);return new Uint8Array(result).set(new Uint8Array(arrayBuffer)),result}function cloneDataView(dataView,isDeep){var buffer=isDeep?cloneArrayBuffer(dataView.buffer):dataView.buffer;return new dataView.constructor(buffer,dataView.byteOffset,dataView.byteLength)}function cloneMap(map,isDeep,cloneFunc){var array=isDeep?cloneFunc(mapToArray(map),!0):mapToArray(map);return arrayReduce(array,addMapEntry,new map.constructor)}function cloneRegExp(regexp){var result=new regexp.constructor(regexp.source,reFlags.exec(regexp));return result.lastIndex=regexp.lastIndex,result}function cloneSet(set,isDeep,cloneFunc){var array=isDeep?cloneFunc(setToArray(set),!0):setToArray(set);return arrayReduce(array,addSetEntry,new set.constructor)}function cloneSymbol(symbol){return symbolValueOf?Object(symbolValueOf.call(symbol)):{}}function cloneTypedArray(typedArray,isDeep){var buffer=isDeep?cloneArrayBuffer(typedArray.buffer):typedArray.buffer;return new typedArray.constructor(buffer,typedArray.byteOffset,typedArray.length)}function compareAscending(value,other){if(value!==other){var valIsDefined=value!==undefined,valIsNull=null===value,valIsReflexive=value===value,valIsSymbol=isSymbol(value),othIsDefined=other!==undefined,othIsNull=null===other,othIsReflexive=other===other,othIsSymbol=isSymbol(other);if(!othIsNull&&!othIsSymbol&&!valIsSymbol&&value>other||valIsSymbol&&othIsDefined&&othIsReflexive&&!othIsNull&&!othIsSymbol||valIsNull&&othIsDefined&&othIsReflexive||!valIsDefined&&othIsReflexive||!valIsReflexive)return 1;if(!valIsNull&&!valIsSymbol&&!othIsSymbol&&other>value||othIsSymbol&&valIsDefined&&valIsReflexive&&!valIsNull&&!valIsSymbol||othIsNull&&valIsDefined&&valIsReflexive||!othIsDefined&&valIsReflexive||!othIsReflexive)return-1}return 0}function compareMultiple(object,other,orders){for(var index=-1,objCriteria=object.criteria,othCriteria=other.criteria,length=objCriteria.length,ordersLength=orders.length;++index=ordersLength)return result;var order=orders[index];return result*("desc"==order?-1:1)}}return object.index-other.index}function composeArgs(args,partials,holders,isCurried){for(var argsIndex=-1,argsLength=args.length,holdersLength=holders.length,leftIndex=-1,leftLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(leftLength+rangeLength),isUncurried=!isCurried;++leftIndexargsIndex)&&(result[holders[argsIndex]]=args[argsIndex]);for(;rangeLength--;)result[leftIndex++]=args[argsIndex++];return result}function composeArgsRight(args,partials,holders,isCurried){for(var argsIndex=-1,argsLength=args.length,holdersIndex=-1,holdersLength=holders.length,rightIndex=-1,rightLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(rangeLength+rightLength),isUncurried=!isCurried;++argsIndexargsIndex)&&(result[offset+holders[holdersIndex]]=args[argsIndex++]);return result}function copyArray(source,array){var index=-1,length=source.length;for(array||(array=Array(length));++index1?sources[length-1]:undefined,guard=length>2?sources[2]:undefined;for(customizer=assigner.length>3&&"function"==typeof customizer?(length--,customizer):undefined,guard&&isIterateeCall(sources[0],sources[1],guard)&&(customizer=3>length?undefined:customizer,length=1),object=Object(object);++indexlength&&args[0]!==placeholder&&args[length-1]!==placeholder?[]:replaceHolders(args,placeholder);if(length-=holders.length,arity>length)return createRecurry(func,bitmask,createHybrid,wrapper.placeholder,undefined,args,holders,undefined,undefined,arity-length);var fn=this&&this!==root&&this instanceof wrapper?Ctor:func;return apply(fn,this,args)}var Ctor=createCtor(func);return wrapper}function createFind(findIndexFunc){return function(collection,predicate,fromIndex){var iterable=Object(collection);if(!isArrayLike(collection)){var iteratee=getIteratee(predicate,3);collection=keys(collection),predicate=function(key){return iteratee(iterable[key],key,iterable)}}var index=findIndexFunc(collection,predicate,fromIndex);return index>-1?iterable[iteratee?collection[index]:index]:undefined}}function createFlow(fromRight){return flatRest(function(funcs){var length=funcs.length,index=length,prereq=LodashWrapper.prototype.thru;for(fromRight&&funcs.reverse();index--;){var func=funcs[index];if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);if(prereq&&!wrapper&&"wrapper"==getFuncName(func))var wrapper=new LodashWrapper([],!0)}for(index=wrapper?index:length;++index=LARGE_ARRAY_SIZE)return wrapper.plant(value).value();for(var index=0,result=length?funcs[index].apply(this,args):value;++indexlength){var newHolders=replaceHolders(args,placeholder);return createRecurry(func,bitmask,createHybrid,wrapper.placeholder,thisArg,args,newHolders,argPos,ary,arity-length)}var thisBinding=isBind?thisArg:this,fn=isBindKey?thisBinding[func]:func;return length=args.length,argPos?args=reorder(args,argPos):isFlip&&length>1&&args.reverse(),isAry&&length>ary&&(args.length=ary),this&&this!==root&&this instanceof wrapper&&(fn=Ctor||createCtor(fn)),fn.apply(thisBinding,args)}var isAry=bitmask&ARY_FLAG,isBind=bitmask&BIND_FLAG,isBindKey=bitmask&BIND_KEY_FLAG,isCurried=bitmask&(CURRY_FLAG|CURRY_RIGHT_FLAG),isFlip=bitmask&FLIP_FLAG,Ctor=isBindKey?undefined:createCtor(func);return wrapper}function createInverter(setter,toIteratee){return function(object,iteratee){return baseInverter(object,setter,toIteratee(iteratee),{})}}function createMathOperation(operator,defaultValue){return function(value,other){var result;if(value===undefined&&other===undefined)return defaultValue;if(value!==undefined&&(result=value),other!==undefined){if(result===undefined)return other;"string"==typeof value||"string"==typeof other?(value=baseToString(value),other=baseToString(other)):(value=baseToNumber(value),other=baseToNumber(other)),result=operator(value,other)}return result}}function createOver(arrayFunc){return flatRest(function(iteratees){return iteratees=arrayMap(iteratees,baseUnary(getIteratee())),baseRest(function(args){var thisArg=this;return arrayFunc(iteratees,function(iteratee){return apply(iteratee,thisArg,args)})})})}function createPadding(length,chars){chars=chars===undefined?" ":baseToString(chars);var charsLength=chars.length;if(2>charsLength)return charsLength?baseRepeat(chars,length):chars;var result=baseRepeat(chars,nativeCeil(length/stringSize(chars)));return hasUnicode(chars)?castSlice(stringToArray(result),0,length).join(""):result.slice(0,length)}function createPartial(func,bitmask,thisArg,partials){function wrapper(){for(var argsIndex=-1,argsLength=arguments.length,leftIndex=-1,leftLength=partials.length,args=Array(leftLength+argsLength),fn=this&&this!==root&&this instanceof wrapper?Ctor:func;++leftIndexstart?1:-1:toFinite(step),baseRange(start,end,step,fromRight)}}function createRelationalOperation(operator){return function(value,other){return("string"!=typeof value||"string"!=typeof other)&&(value=toNumber(value),other=toNumber(other)),operator(value,other)}}function createRecurry(func,bitmask,wrapFunc,placeholder,thisArg,partials,holders,argPos,ary,arity){var isCurry=bitmask&CURRY_FLAG,newHolders=isCurry?holders:undefined,newHoldersRight=isCurry?undefined:holders,newPartials=isCurry?partials:undefined,newPartialsRight=isCurry?undefined:partials;bitmask|=isCurry?PARTIAL_FLAG:PARTIAL_RIGHT_FLAG,bitmask&=~(isCurry?PARTIAL_RIGHT_FLAG:PARTIAL_FLAG),bitmask&CURRY_BOUND_FLAG||(bitmask&=~(BIND_FLAG|BIND_KEY_FLAG));var newData=[func,bitmask,thisArg,newPartials,newHolders,newPartialsRight,newHoldersRight,argPos,ary,arity],result=wrapFunc.apply(undefined,newData);return isLaziable(func)&&setData(result,newData),result.placeholder=placeholder,setWrapToString(result,func,bitmask)}function createRound(methodName){var func=Math[methodName];return function(number,precision){if(number=toNumber(number),precision=nativeMin(toInteger(precision),292)){var pair=(toString(number)+"e").split("e"),value=func(pair[0]+"e"+(+pair[1]+precision));return pair=(toString(value)+"e").split("e"),+(pair[0]+"e"+(+pair[1]-precision))}return func(number)}}function createToPairs(keysFunc){return function(object){var tag=getTag(object);return tag==mapTag?mapToArray(object):tag==setTag?setToPairs(object):baseToPairs(object,keysFunc(object))}}function createWrap(func,bitmask,thisArg,partials,holders,argPos,ary,arity){var isBindKey=bitmask&BIND_KEY_FLAG;if(!isBindKey&&"function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);var length=partials?partials.length:0;if(length||(bitmask&=~(PARTIAL_FLAG|PARTIAL_RIGHT_FLAG),partials=holders=undefined),ary=ary===undefined?ary:nativeMax(toInteger(ary),0),arity=arity===undefined?arity:toInteger(arity),length-=holders?holders.length:0,bitmask&PARTIAL_RIGHT_FLAG){var partialsRight=partials,holdersRight=holders;partials=holders=undefined}var data=isBindKey?undefined:getData(func),newData=[func,bitmask,thisArg,partials,holders,partialsRight,holdersRight,argPos,ary,arity];if(data&&mergeData(newData,data),func=newData[0],bitmask=newData[1],thisArg=newData[2],partials=newData[3],holders=newData[4],arity=newData[9]=null==newData[9]?isBindKey?0:func.length:nativeMax(newData[9]-length,0),!arity&&bitmask&(CURRY_FLAG|CURRY_RIGHT_FLAG)&&(bitmask&=~(CURRY_FLAG|CURRY_RIGHT_FLAG)),bitmask&&bitmask!=BIND_FLAG)result=bitmask==CURRY_FLAG||bitmask==CURRY_RIGHT_FLAG?createCurry(func,bitmask,arity):bitmask!=PARTIAL_FLAG&&bitmask!=(BIND_FLAG|PARTIAL_FLAG)||holders.length?createHybrid.apply(undefined,newData):createPartial(func,bitmask,thisArg,partials);else var result=createBind(func,bitmask,thisArg);var setter=data?baseSetData:setData;return setWrapToString(setter(result,newData),func,bitmask)}function equalArrays(array,other,equalFunc,customizer,bitmask,stack){var isPartial=bitmask&PARTIAL_COMPARE_FLAG,arrLength=array.length,othLength=other.length;if(arrLength!=othLength&&!(isPartial&&othLength>arrLength))return!1;var stacked=stack.get(array);if(stacked&&stack.get(other))return stacked==other;var index=-1,result=!0,seen=bitmask&UNORDERED_COMPARE_FLAG?new SetCache:undefined;for(stack.set(array,other),stack.set(other,array);++index1?"& ":"")+details[lastIndex],details=details.join(length>2?", ":" "),source.replace(reWrapComment,"{\n/* [wrapped with "+details+"] */\n")}function isFlattenable(value){return isArray(value)||isArguments(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol])}function isIndex(value,length){return length=null==length?MAX_SAFE_INTEGER:length,!!length&&("number"==typeof value||reIsUint.test(value))&&value>-1&&value%1==0&&length>value}function isIterateeCall(value,index,object){if(!isObject(object))return!1;var type=typeof index;return("number"==type?isArrayLike(object)&&isIndex(index,object.length):"string"==type&&index in object)?eq(object[index],value):!1}function isKey(value,object){if(isArray(value))return!1;var type=typeof value;return"number"==type||"symbol"==type||"boolean"==type||null==value||isSymbol(value)?!0:reIsPlainProp.test(value)||!reIsDeepProp.test(value)||null!=object&&value in Object(object)}function isKeyable(value){var type=typeof value;return"string"==type||"number"==type||"symbol"==type||"boolean"==type?"__proto__"!==value:null===value}function isLaziable(func){var funcName=getFuncName(func),other=lodash[funcName];if("function"!=typeof other||!(funcName in LazyWrapper.prototype))return!1;if(func===other)return!0;var data=getData(other);return!!data&&func===data[0]}function isMasked(func){return!!maskSrcKey&&maskSrcKey in func}function isPrototype(value){var Ctor=value&&value.constructor,proto="function"==typeof Ctor&&Ctor.prototype||objectProto;return value===proto}function isStrictComparable(value){return value===value&&!isObject(value)}function matchesStrictComparable(key,srcValue){return function(object){return null==object?!1:object[key]===srcValue&&(srcValue!==undefined||key in Object(object))}}function memoizeCapped(func){var result=memoize(func,function(key){return cache.size===MAX_MEMOIZE_SIZE&&cache.clear(),key}),cache=result.cache;return result}function mergeData(data,source){var bitmask=data[1],srcBitmask=source[1],newBitmask=bitmask|srcBitmask,isCommon=(BIND_FLAG|BIND_KEY_FLAG|ARY_FLAG)>newBitmask,isCombo=srcBitmask==ARY_FLAG&&bitmask==CURRY_FLAG||srcBitmask==ARY_FLAG&&bitmask==REARG_FLAG&&data[7].length<=source[8]||srcBitmask==(ARY_FLAG|REARG_FLAG)&&source[7].length<=source[8]&&bitmask==CURRY_FLAG;if(!isCommon&&!isCombo)return data;srcBitmask&BIND_FLAG&&(data[2]=source[2],newBitmask|=bitmask&BIND_FLAG?0:CURRY_BOUND_FLAG);var value=source[3];if(value){var partials=data[3];data[3]=partials?composeArgs(partials,value,source[4]):value,data[4]=partials?replaceHolders(data[3],PLACEHOLDER):source[4]}return value=source[5],value&&(partials=data[5],data[5]=partials?composeArgsRight(partials,value,source[6]):value,data[6]=partials?replaceHolders(data[5],PLACEHOLDER):source[6]),value=source[7],value&&(data[7]=value),srcBitmask&ARY_FLAG&&(data[8]=null==data[8]?source[8]:nativeMin(data[8],source[8])),null==data[9]&&(data[9]=source[9]),data[0]=source[0],data[1]=newBitmask,data}function mergeDefaults(objValue,srcValue,key,object,source,stack){return isObject(objValue)&&isObject(srcValue)&&(stack.set(srcValue,objValue),baseMerge(objValue,srcValue,undefined,mergeDefaults,stack),stack["delete"](srcValue)),objValue}function nativeKeysIn(object){var result=[];if(null!=object)for(var key in Object(object))result.push(key);return result}function overRest(func,start,transform){return start=nativeMax(start===undefined?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index0){if(++count>=HOT_COUNT)return arguments[0]}else count=0;return func.apply(undefined,arguments)}}function shuffleSelf(array){for(var index=-1,length=array.length,lastIndex=length-1;++indexsize)return[];for(var index=0,resIndex=0,result=Array(nativeCeil(length/size));length>index;)result[resIndex++]=baseSlice(array,index,index+=size);return result}function compact(array){for(var index=-1,length=array?array.length:0,resIndex=0,result=[];++indexn?0:n,length)):[]}function dropRight(array,n,guard){var length=array?array.length:0;return length?(n=guard||n===undefined?1:toInteger(n),n=length-n,baseSlice(array,0,0>n?0:n)):[]}function dropRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!0,!0):[]}function dropWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!0):[]}function fill(array,value,start,end){var length=array?array.length:0;return length?(start&&"number"!=typeof start&&isIterateeCall(array,value,start)&&(start=0,end=length),baseFill(array,value,start,end)):[]}function findIndex(array,predicate,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=null==fromIndex?0:toInteger(fromIndex);return 0>index&&(index=nativeMax(length+index,0)),baseFindIndex(array,getIteratee(predicate,3),index)}function findLastIndex(array,predicate,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=length-1;return fromIndex!==undefined&&(index=toInteger(fromIndex),index=0>fromIndex?nativeMax(length+index,0):nativeMin(index,length-1)),baseFindIndex(array,getIteratee(predicate,3),index,!0)}function flatten(array){var length=array?array.length:0;return length?baseFlatten(array,1):[]}function flattenDeep(array){var length=array?array.length:0;return length?baseFlatten(array,INFINITY):[]}function flattenDepth(array,depth){var length=array?array.length:0;return length?(depth=depth===undefined?1:toInteger(depth),baseFlatten(array,depth)):[]}function fromPairs(pairs){for(var index=-1,length=pairs?pairs.length:0,result={};++indexindex&&(index=nativeMax(length+index,0)),baseIndexOf(array,value,index)}function initial(array){var length=array?array.length:0;return length?baseSlice(array,0,-1):[]}function join(array,separator){return array?nativeJoin.call(array,separator):""}function last(array){var length=array?array.length:0;return length?array[length-1]:undefined}function lastIndexOf(array,value,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=length;return fromIndex!==undefined&&(index=toInteger(fromIndex),index=0>index?nativeMax(length+index,0):nativeMin(index,length-1)),value===value?strictLastIndexOf(array,value,index):baseFindIndex(array,baseIsNaN,index,!0)}function nth(array,n){return array&&array.length?baseNth(array,toInteger(n)):undefined}function pullAll(array,values){return array&&array.length&&values&&values.length?basePullAll(array,values):array}function pullAllBy(array,values,iteratee){return array&&array.length&&values&&values.length?basePullAll(array,values,getIteratee(iteratee,2)):array}function pullAllWith(array,values,comparator){return array&&array.length&&values&&values.length?basePullAll(array,values,undefined,comparator):array}function remove(array,predicate){var result=[];if(!array||!array.length)return result;var index=-1,indexes=[],length=array.length;for(predicate=getIteratee(predicate,3);++indexindex&&eq(array[index],value))return index}return-1}function sortedLastIndex(array,value){return baseSortedIndex(array,value,!0)}function sortedLastIndexBy(array,value,iteratee){return baseSortedIndexBy(array,value,getIteratee(iteratee,2),!0)}function sortedLastIndexOf(array,value){var length=array?array.length:0;if(length){var index=baseSortedIndex(array,value,!0)-1;if(eq(array[index],value))return index}return-1}function sortedUniq(array){return array&&array.length?baseSortedUniq(array):[]}function sortedUniqBy(array,iteratee){return array&&array.length?baseSortedUniq(array,getIteratee(iteratee,2)):[]}function tail(array){var length=array?array.length:0;return length?baseSlice(array,1,length):[]}function take(array,n,guard){return array&&array.length?(n=guard||n===undefined?1:toInteger(n),baseSlice(array,0,0>n?0:n)):[]}function takeRight(array,n,guard){var length=array?array.length:0;return length?(n=guard||n===undefined?1:toInteger(n),n=length-n,baseSlice(array,0>n?0:n,length)):[]}function takeRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!1,!0):[]}function takeWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3)):[]}function uniq(array){return array&&array.length?baseUniq(array):[]}function uniqBy(array,iteratee){return array&&array.length?baseUniq(array,getIteratee(iteratee,2)):[]}function uniqWith(array,comparator){return array&&array.length?baseUniq(array,undefined,comparator):[]}function unzip(array){if(!array||!array.length)return[];var length=0;return array=arrayFilter(array,function(group){return isArrayLikeObject(group)?(length=nativeMax(group.length,length),!0):void 0}),baseTimes(length,function(index){return arrayMap(array,baseProperty(index))})}function unzipWith(array,iteratee){if(!array||!array.length)return[];var result=unzip(array);return null==iteratee?result:arrayMap(result,function(group){return apply(iteratee,undefined,group)})}function zipObject(props,values){return baseZipObject(props||[],values||[],assignValue)}function zipObjectDeep(props,values){return baseZipObject(props||[],values||[],baseSet)}function chain(value){var result=lodash(value);return result.__chain__=!0,result}function tap(value,interceptor){return interceptor(value),value}function thru(value,interceptor){return interceptor(value)}function wrapperChain(){return chain(this)}function wrapperCommit(){return new LodashWrapper(this.value(),this.__chain__)}function wrapperNext(){this.__values__===undefined&&(this.__values__=toArray(this.value()));var done=this.__index__>=this.__values__.length,value=done?undefined:this.__values__[this.__index__++];return{done:done,value:value}}function wrapperToIterator(){return this}function wrapperPlant(value){for(var result,parent=this;parent instanceof baseLodash;){var clone=wrapperClone(parent);clone.__index__=0,clone.__values__=undefined,result?previous.__wrapped__=clone:result=clone;var previous=clone;parent=parent.__wrapped__}return previous.__wrapped__=value,result}function wrapperReverse(){var value=this.__wrapped__;if(value instanceof LazyWrapper){var wrapped=value;return this.__actions__.length&&(wrapped=new LazyWrapper(this)),wrapped=wrapped.reverse(),wrapped.__actions__.push({func:thru,args:[reverse],thisArg:undefined}),new LodashWrapper(wrapped,this.__chain__)}return this.thru(reverse)}function wrapperValue(){return baseWrapperValue(this.__wrapped__,this.__actions__)}function every(collection,predicate,guard){var func=isArray(collection)?arrayEvery:baseEvery;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=undefined),func(collection,getIteratee(predicate,3))}function filter(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,getIteratee(predicate,3))}function flatMap(collection,iteratee){return baseFlatten(map(collection,iteratee),1)}function flatMapDeep(collection,iteratee){return baseFlatten(map(collection,iteratee),INFINITY)}function flatMapDepth(collection,iteratee,depth){return depth=depth===undefined?1:toInteger(depth),baseFlatten(map(collection,iteratee),depth)}function forEach(collection,iteratee){var func=isArray(collection)?arrayEach:baseEach;return func(collection,getIteratee(iteratee,3))}function forEachRight(collection,iteratee){var func=isArray(collection)?arrayEachRight:baseEachRight;return func(collection,getIteratee(iteratee,3))}function includes(collection,value,fromIndex,guard){collection=isArrayLike(collection)?collection:values(collection),fromIndex=fromIndex&&!guard?toInteger(fromIndex):0;var length=collection.length;return 0>fromIndex&&(fromIndex=nativeMax(length+fromIndex,0)),isString(collection)?length>=fromIndex&&collection.indexOf(value,fromIndex)>-1:!!length&&baseIndexOf(collection,value,fromIndex)>-1}function map(collection,iteratee){var func=isArray(collection)?arrayMap:baseMap;return func(collection,getIteratee(iteratee,3))}function orderBy(collection,iteratees,orders,guard){return null==collection?[]:(isArray(iteratees)||(iteratees=null==iteratees?[]:[iteratees]),orders=guard?undefined:orders,isArray(orders)||(orders=null==orders?[]:[orders]),baseOrderBy(collection,iteratees,orders))}function reduce(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduce:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEach)}function reduceRight(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduceRight:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEachRight)}function reject(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,negate(getIteratee(predicate,3)))}function sample(collection){return arraySample(isArrayLike(collection)?collection:values(collection))}function sampleSize(collection,n,guard){return n=(guard?isIterateeCall(collection,n,guard):n===undefined)?1:toInteger(n),arraySampleSize(isArrayLike(collection)?collection:values(collection),n)}function shuffle(collection){return shuffleSelf(isArrayLike(collection)?copyArray(collection):values(collection))}function size(collection){if(null==collection)return 0;if(isArrayLike(collection))return isString(collection)?stringSize(collection):collection.length;var tag=getTag(collection);return tag==mapTag||tag==setTag?collection.size:baseKeys(collection).length}function some(collection,predicate,guard){var func=isArray(collection)?arraySome:baseSome;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=undefined),func(collection,getIteratee(predicate,3))}function after(n,func){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return n=toInteger(n),function(){return--n<1?func.apply(this,arguments):void 0}}function ary(func,n,guard){return n=guard?undefined:n,n=func&&null==n?func.length:n,createWrap(func,ARY_FLAG,undefined,undefined,undefined,undefined,n)}function before(n,func){var result;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return n=toInteger(n),function(){return--n>0&&(result=func.apply(this,arguments)),1>=n&&(func=undefined),result}}function curry(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,CURRY_FLAG,undefined,undefined,undefined,undefined,undefined,arity);return result.placeholder=curry.placeholder,result}function curryRight(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,CURRY_RIGHT_FLAG,undefined,undefined,undefined,undefined,undefined,arity);return result.placeholder=curryRight.placeholder,result}function debounce(func,wait,options){function invokeFunc(time){var args=lastArgs,thisArg=lastThis;return lastArgs=lastThis=undefined,lastInvokeTime=time,result=func.apply(thisArg,args)}function leadingEdge(time){return lastInvokeTime=time,timerId=setTimeout(timerExpired,wait),leading?invokeFunc(time):result}function remainingWait(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime,result=wait-timeSinceLastCall;return maxing?nativeMin(result,maxWait-timeSinceLastInvoke):result}function shouldInvoke(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime;return lastCallTime===undefined||timeSinceLastCall>=wait||0>timeSinceLastCall||maxing&&timeSinceLastInvoke>=maxWait}function timerExpired(){var time=now();return shouldInvoke(time)?trailingEdge(time):void(timerId=setTimeout(timerExpired,remainingWait(time)))}function trailingEdge(time){return timerId=undefined,trailing&&lastArgs?invokeFunc(time):(lastArgs=lastThis=undefined,result)}function cancel(){timerId!==undefined&&clearTimeout(timerId),lastInvokeTime=0,lastArgs=lastCallTime=lastThis=timerId=undefined}function flush(){return timerId===undefined?result:trailingEdge(now())}function debounced(){var time=now(),isInvoking=shouldInvoke(time);if(lastArgs=arguments,lastThis=this,lastCallTime=time,isInvoking){if(timerId===undefined)return leadingEdge(lastCallTime);if(maxing)return timerId=setTimeout(timerExpired,wait),invokeFunc(lastCallTime)}return timerId===undefined&&(timerId=setTimeout(timerExpired,wait)),result}var lastArgs,lastThis,maxWait,result,timerId,lastCallTime,lastInvokeTime=0,leading=!1,maxing=!1,trailing=!0;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return wait=toNumber(wait)||0,isObject(options)&&(leading=!!options.leading,maxing="maxWait"in options,maxWait=maxing?nativeMax(toNumber(options.maxWait)||0,wait):maxWait,trailing="trailing"in options?!!options.trailing:trailing),debounced.cancel=cancel,debounced.flush=flush,debounced}function flip(func){return createWrap(func,FLIP_FLAG)}function memoize(func,resolver){if("function"!=typeof func||resolver&&"function"!=typeof resolver)throw new TypeError(FUNC_ERROR_TEXT);var memoized=function(){var args=arguments,key=resolver?resolver.apply(this,args):args[0],cache=memoized.cache;if(cache.has(key))return cache.get(key);var result=func.apply(this,args);return memoized.cache=cache.set(key,result)||cache,result};return memoized.cache=new(memoize.Cache||MapCache),memoized}function negate(predicate){if("function"!=typeof predicate)throw new TypeError(FUNC_ERROR_TEXT);return function(){var args=arguments;switch(args.length){case 0:return!predicate.call(this);case 1:return!predicate.call(this,args[0]);case 2:return!predicate.call(this,args[0],args[1]);case 3:return!predicate.call(this,args[0],args[1],args[2])}return!predicate.apply(this,args)}}function once(func){return before(2,func)}function rest(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=start===undefined?start:toInteger(start),baseRest(func,start)}function spread(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=start===undefined?0:nativeMax(toInteger(start),0),baseRest(function(args){var array=args[start],otherArgs=castSlice(args,0,start);return array&&arrayPush(otherArgs,array),apply(func,this,otherArgs)})}function throttle(func,wait,options){var leading=!0,trailing=!0;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return isObject(options)&&(leading="leading"in options?!!options.leading:leading,trailing="trailing"in options?!!options.trailing:trailing),debounce(func,wait,{leading:leading,maxWait:wait,trailing:trailing})}function unary(func){return ary(func,1)}function wrap(value,wrapper){return wrapper=null==wrapper?identity:wrapper,partial(wrapper,value)}function castArray(){if(!arguments.length)return[];var value=arguments[0];return isArray(value)?value:[value]}function clone(value){return baseClone(value,!1,!0)}function cloneWith(value,customizer){return baseClone(value,!1,!0,customizer)}function cloneDeep(value){return baseClone(value,!0,!0)}function cloneDeepWith(value,customizer){return baseClone(value,!0,!0,customizer)}function conformsTo(object,source){return null==source||baseConformsTo(object,source,keys(source))}function eq(value,other){return value===other||value!==value&&other!==other}function isArguments(value){return isArrayLikeObject(value)&&hasOwnProperty.call(value,"callee")&&(!propertyIsEnumerable.call(value,"callee")||objectToString.call(value)==argsTag)}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value)}function isBoolean(value){return value===!0||value===!1||isObjectLike(value)&&objectToString.call(value)==boolTag}function isElement(value){return null!=value&&1===value.nodeType&&isObjectLike(value)&&!isPlainObject(value)}function isEmpty(value){if(isArrayLike(value)&&(isArray(value)||"string"==typeof value||"function"==typeof value.splice||isBuffer(value)||isArguments(value)))return!value.length;var tag=getTag(value);if(tag==mapTag||tag==setTag)return!value.size;if(isPrototype(value))return!nativeKeys(value).length;for(var key in value)if(hasOwnProperty.call(value,key))return!1;return!0}function isEqual(value,other){return baseIsEqual(value,other)}function isEqualWith(value,other,customizer){customizer="function"==typeof customizer?customizer:undefined;var result=customizer?customizer(value,other):undefined;return result===undefined?baseIsEqual(value,other,customizer):!!result}function isError(value){return isObjectLike(value)?objectToString.call(value)==errorTag||"string"==typeof value.message&&"string"==typeof value.name:!1}function isFinite(value){return"number"==typeof value&&nativeIsFinite(value)}function isFunction(value){var tag=isObject(value)?objectToString.call(value):"";return tag==funcTag||tag==genTag}function isInteger(value){return"number"==typeof value&&value==toInteger(value)}function isLength(value){return"number"==typeof value&&value>-1&&value%1==0&&MAX_SAFE_INTEGER>=value}function isObject(value){var type=typeof value;return null!=value&&("object"==type||"function"==type)}function isObjectLike(value){return null!=value&&"object"==typeof value}function isMatch(object,source){return object===source||baseIsMatch(object,source,getMatchData(source))}function isMatchWith(object,source,customizer){return customizer="function"==typeof customizer?customizer:undefined,baseIsMatch(object,source,getMatchData(source),customizer)}function isNaN(value){return isNumber(value)&&value!=+value}function isNative(value){if(isMaskable(value))throw new Error("This method is not supported with core-js. Try https://github.com/es-shims.");return baseIsNative(value)}function isNull(value){return null===value}function isNil(value){return null==value}function isNumber(value){return"number"==typeof value||isObjectLike(value)&&objectToString.call(value)==numberTag}function isPlainObject(value){if(!isObjectLike(value)||objectToString.call(value)!=objectTag)return!1;var proto=getPrototype(value);if(null===proto)return!0;var Ctor=hasOwnProperty.call(proto,"constructor")&&proto.constructor;return"function"==typeof Ctor&&Ctor instanceof Ctor&&funcToString.call(Ctor)==objectCtorString}function isSafeInteger(value){return isInteger(value)&&value>=-MAX_SAFE_INTEGER&&MAX_SAFE_INTEGER>=value}function isString(value){return"string"==typeof value||!isArray(value)&&isObjectLike(value)&&objectToString.call(value)==stringTag}function isSymbol(value){return"symbol"==typeof value||isObjectLike(value)&&objectToString.call(value)==symbolTag}function isUndefined(value){return value===undefined}function isWeakMap(value){return isObjectLike(value)&&getTag(value)==weakMapTag}function isWeakSet(value){return isObjectLike(value)&&objectToString.call(value)==weakSetTag}function toArray(value){if(!value)return[];if(isArrayLike(value))return isString(value)?stringToArray(value):copyArray(value);if(iteratorSymbol&&value[iteratorSymbol])return iteratorToArray(value[iteratorSymbol]());var tag=getTag(value),func=tag==mapTag?mapToArray:tag==setTag?setToArray:values;return func(value)}function toFinite(value){if(!value)return 0===value?value:0;if(value=toNumber(value),value===INFINITY||value===-INFINITY){var sign=0>value?-1:1;return sign*MAX_INTEGER}return value===value?value:0}function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0}function toLength(value){return value?baseClamp(toInteger(value),0,MAX_ARRAY_LENGTH):0}function toNumber(value){if("number"==typeof value)return value;if(isSymbol(value))return NAN;if(isObject(value)){var other="function"==typeof value.valueOf?value.valueOf():value;value=isObject(other)?other+"":other}if("string"!=typeof value)return 0===value?value:+value;value=value.replace(reTrim,"");var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value}function toPlainObject(value){return copyObject(value,keysIn(value))}function toSafeInteger(value){return baseClamp(toInteger(value),-MAX_SAFE_INTEGER,MAX_SAFE_INTEGER)}function toString(value){return null==value?"":baseToString(value)}function create(prototype,properties){var result=baseCreate(prototype);return properties?baseAssign(result,properties):result}function findKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwn)}function findLastKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwnRight)}function forIn(object,iteratee){return null==object?object:baseFor(object,getIteratee(iteratee,3),keysIn)}function forInRight(object,iteratee){return null==object?object:baseForRight(object,getIteratee(iteratee,3),keysIn)}function forOwn(object,iteratee){return object&&baseForOwn(object,getIteratee(iteratee,3))}function forOwnRight(object,iteratee){return object&&baseForOwnRight(object,getIteratee(iteratee,3))}function functions(object){return null==object?[]:baseFunctions(object,keys(object))}function functionsIn(object){return null==object?[]:baseFunctions(object,keysIn(object))}function get(object,path,defaultValue){var result=null==object?undefined:baseGet(object,path);return result===undefined?defaultValue:result}function has(object,path){return null!=object&&hasPath(object,path,baseHas)}function hasIn(object,path){return null!=object&&hasPath(object,path,baseHasIn)}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function keysIn(object){return isArrayLike(object)?arrayLikeKeys(object,!0):baseKeysIn(object)}function mapKeys(object,iteratee){var result={};return iteratee=getIteratee(iteratee,3),baseForOwn(object,function(value,key,object){baseAssignValue(result,iteratee(value,key,object),value)}),result}function mapValues(object,iteratee){var result={};return iteratee=getIteratee(iteratee,3),baseForOwn(object,function(value,key,object){baseAssignValue(result,key,iteratee(value,key,object))}),result}function omitBy(object,predicate){return pickBy(object,negate(getIteratee(predicate)))}function pickBy(object,predicate){return null==object?{}:basePickBy(object,getAllKeysIn(object),getIteratee(predicate))}function result(object,path,defaultValue){path=isKey(path,object)?[path]:castPath(path);var index=-1,length=path.length;for(length||(object=undefined,length=1);++indexupper){var temp=lower;lower=upper,upper=temp}if(floating||lower%1||upper%1){var rand=nativeRandom(); +return nativeMin(lower+rand*(upper-lower+freeParseFloat("1e-"+((rand+"").length-1))),upper)}return baseRandom(lower,upper)}function capitalize(string){return upperFirst(toString(string).toLowerCase())}function deburr(string){return string=toString(string),string&&string.replace(reLatin,deburrLetter).replace(reComboMark,"")}function endsWith(string,target,position){string=toString(string),target=baseToString(target);var length=string.length;position=position===undefined?length:baseClamp(toInteger(position),0,length);var end=position;return position-=target.length,position>=0&&string.slice(position,end)==target}function escape(string){return string=toString(string),string&&reHasUnescapedHtml.test(string)?string.replace(reUnescapedHtml,escapeHtmlChar):string}function escapeRegExp(string){return string=toString(string),string&&reHasRegExpChar.test(string)?string.replace(reRegExpChar,"\\$&"):string}function pad(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;if(!length||strLength>=length)return string;var mid=(length-strLength)/2;return createPadding(nativeFloor(mid),chars)+string+createPadding(nativeCeil(mid),chars)}function padEnd(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;return length&&length>strLength?string+createPadding(length-strLength,chars):string}function padStart(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;return length&&length>strLength?createPadding(length-strLength,chars)+string:string}function parseInt(string,radix,guard){return guard||null==radix?radix=0:radix&&(radix=+radix),nativeParseInt(toString(string),radix||0)}function repeat(string,n,guard){return n=(guard?isIterateeCall(string,n,guard):n===undefined)?1:toInteger(n),baseRepeat(toString(string),n)}function replace(){var args=arguments,string=toString(args[0]);return args.length<3?string:string.replace(args[1],args[2])}function split(string,separator,limit){return limit&&"number"!=typeof limit&&isIterateeCall(string,separator,limit)&&(separator=limit=undefined),(limit=limit===undefined?MAX_ARRAY_LENGTH:limit>>>0)?(string=toString(string),string&&("string"==typeof separator||null!=separator&&!isRegExp(separator))&&(separator=baseToString(separator),!separator&&hasUnicode(string))?castSlice(stringToArray(string),0,limit):string.split(separator,limit)):[]}function startsWith(string,target,position){return string=toString(string),position=baseClamp(toInteger(position),0,string.length),target=baseToString(target),string.slice(position,position+target.length)==target}function template(string,options,guard){var settings=lodash.templateSettings;guard&&isIterateeCall(string,options,guard)&&(options=undefined),string=toString(string),options=assignInWith({},options,settings,assignInDefaults);var isEscaping,isEvaluating,imports=assignInWith({},options.imports,settings.imports,assignInDefaults),importsKeys=keys(imports),importsValues=baseValues(imports,importsKeys),index=0,interpolate=options.interpolate||reNoMatch,source="__p += '",reDelimiters=RegExp((options.escape||reNoMatch).source+"|"+interpolate.source+"|"+(interpolate===reInterpolate?reEsTemplate:reNoMatch).source+"|"+(options.evaluate||reNoMatch).source+"|$","g"),sourceURL="//# sourceURL="+("sourceURL"in options?options.sourceURL:"lodash.templateSources["+ ++templateCounter+"]")+"\n";string.replace(reDelimiters,function(match,escapeValue,interpolateValue,esTemplateValue,evaluateValue,offset){return interpolateValue||(interpolateValue=esTemplateValue),source+=string.slice(index,offset).replace(reUnescapedString,escapeStringChar),escapeValue&&(isEscaping=!0,source+="' +\n__e("+escapeValue+") +\n'"),evaluateValue&&(isEvaluating=!0,source+="';\n"+evaluateValue+";\n__p += '"),interpolateValue&&(source+="' +\n((__t = ("+interpolateValue+")) == null ? '' : __t) +\n'"),index=offset+match.length,match}),source+="';\n";var variable=options.variable;variable||(source="with (obj) {\n"+source+"\n}\n"),source=(isEvaluating?source.replace(reEmptyStringLeading,""):source).replace(reEmptyStringMiddle,"$1").replace(reEmptyStringTrailing,"$1;"),source="function("+(variable||"obj")+") {\n"+(variable?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(isEscaping?", __e = _.escape":"")+(isEvaluating?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+source+"return __p\n}";var result=attempt(function(){return Function(importsKeys,sourceURL+"return "+source).apply(undefined,importsValues)});if(result.source=source,isError(result))throw result;return result}function toLower(value){return toString(value).toLowerCase()}function toUpper(value){return toString(value).toUpperCase()}function trim(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrim,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),chrSymbols=stringToArray(chars),start=charsStartIndex(strSymbols,chrSymbols),end=charsEndIndex(strSymbols,chrSymbols)+1;return castSlice(strSymbols,start,end).join("")}function trimEnd(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrimEnd,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),end=charsEndIndex(strSymbols,stringToArray(chars))+1;return castSlice(strSymbols,0,end).join("")}function trimStart(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrimStart,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),start=charsStartIndex(strSymbols,stringToArray(chars));return castSlice(strSymbols,start).join("")}function truncate(string,options){var length=DEFAULT_TRUNC_LENGTH,omission=DEFAULT_TRUNC_OMISSION;if(isObject(options)){var separator="separator"in options?options.separator:separator;length="length"in options?toInteger(options.length):length,omission="omission"in options?baseToString(options.omission):omission}string=toString(string);var strLength=string.length;if(hasUnicode(string)){var strSymbols=stringToArray(string);strLength=strSymbols.length}if(length>=strLength)return string;var end=length-stringSize(omission);if(1>end)return omission;var result=strSymbols?castSlice(strSymbols,0,end).join(""):string.slice(0,end);if(separator===undefined)return result+omission;if(strSymbols&&(end+=result.length-end),isRegExp(separator)){if(string.slice(end).search(separator)){var match,substring=result;for(separator.global||(separator=RegExp(separator.source,toString(reFlags.exec(separator))+"g")),separator.lastIndex=0;match=separator.exec(substring);)var newEnd=match.index;result=result.slice(0,newEnd===undefined?end:newEnd)}}else if(string.indexOf(baseToString(separator),end)!=end){var index=result.lastIndexOf(separator);index>-1&&(result=result.slice(0,index))}return result+omission}function unescape(string){return string=toString(string),string&&reHasEscapedHtml.test(string)?string.replace(reEscapedHtml,unescapeHtmlChar):string}function words(string,pattern,guard){return string=toString(string),pattern=guard?undefined:pattern,pattern===undefined?hasUnicodeWord(string)?unicodeWords(string):asciiWords(string):string.match(pattern)||[]}function cond(pairs){var length=pairs?pairs.length:0,toIteratee=getIteratee();return pairs=length?arrayMap(pairs,function(pair){if("function"!=typeof pair[1])throw new TypeError(FUNC_ERROR_TEXT);return[toIteratee(pair[0]),pair[1]]}):[],baseRest(function(args){for(var index=-1;++indexn||n>MAX_SAFE_INTEGER)return[];var index=MAX_ARRAY_LENGTH,length=nativeMin(n,MAX_ARRAY_LENGTH);iteratee=getIteratee(iteratee),n-=MAX_ARRAY_LENGTH;for(var result=baseTimes(length,iteratee);++index1?arrays[length-1]:undefined;return iteratee="function"==typeof iteratee?(arrays.pop(),iteratee):undefined,unzipWith(arrays,iteratee)}),wrapperAt=flatRest(function(paths){var length=paths.length,start=length?paths[0]:0,value=this.__wrapped__,interceptor=function(object){return baseAt(object,paths)};return!(length>1||this.__actions__.length)&&value instanceof LazyWrapper&&isIndex(start)?(value=value.slice(start,+start+(length?1:0)),value.__actions__.push({func:thru,args:[interceptor],thisArg:undefined}),new LodashWrapper(value,this.__chain__).thru(function(array){return length&&!array.length&&array.push(undefined),array})):this.thru(interceptor)}),countBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?++result[key]:baseAssignValue(result,key,1)}),find=createFind(findIndex),findLast=createFind(findLastIndex),groupBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?result[key].push(value):baseAssignValue(result,key,[value])}),invokeMap=baseRest(function(collection,path,args){var index=-1,isFunc="function"==typeof path,isProp=isKey(path),result=isArrayLike(collection)?Array(collection.length):[];return baseEach(collection,function(value){var func=isFunc?path:isProp&&null!=value?value[path]:undefined;result[++index]=func?apply(func,value,args):baseInvoke(value,path,args)}),result}),keyBy=createAggregator(function(result,value,key){baseAssignValue(result,key,value)}),partition=createAggregator(function(result,value,key){result[key?0:1].push(value)},function(){return[[],[]]}),sortBy=baseRest(function(collection,iteratees){if(null==collection)return[];var length=iteratees.length;return length>1&&isIterateeCall(collection,iteratees[0],iteratees[1])?iteratees=[]:length>2&&isIterateeCall(iteratees[0],iteratees[1],iteratees[2])&&(iteratees=[iteratees[0]]),baseOrderBy(collection,baseFlatten(iteratees,1),[])}),now=ctxNow||function(){return root.Date.now()},bind=baseRest(function(func,thisArg,partials){var bitmask=BIND_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bind));bitmask|=PARTIAL_FLAG}return createWrap(func,bitmask,thisArg,partials,holders)}),bindKey=baseRest(function(object,key,partials){var bitmask=BIND_FLAG|BIND_KEY_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bindKey));bitmask|=PARTIAL_FLAG}return createWrap(key,bitmask,object,partials,holders)}),defer=baseRest(function(func,args){return baseDelay(func,1,args)}),delay=baseRest(function(func,wait,args){return baseDelay(func,toNumber(wait)||0,args)});memoize.Cache=MapCache;var overArgs=castRest(function(func,transforms){transforms=1==transforms.length&&isArray(transforms[0])?arrayMap(transforms[0],baseUnary(getIteratee())):arrayMap(baseFlatten(transforms,1),baseUnary(getIteratee()));var funcsLength=transforms.length;return baseRest(function(args){for(var index=-1,length=nativeMin(args.length,funcsLength);++index=other}),isArray=Array.isArray,isArrayBuffer=nodeIsArrayBuffer?baseUnary(nodeIsArrayBuffer):baseIsArrayBuffer,isBuffer=nativeIsBuffer||stubFalse,isDate=nodeIsDate?baseUnary(nodeIsDate):baseIsDate,isMap=nodeIsMap?baseUnary(nodeIsMap):baseIsMap,isRegExp=nodeIsRegExp?baseUnary(nodeIsRegExp):baseIsRegExp,isSet=nodeIsSet?baseUnary(nodeIsSet):baseIsSet,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray,lt=createRelationalOperation(baseLt),lte=createRelationalOperation(function(value,other){return other>=value}),assign=createAssigner(function(object,source){if(isPrototype(source)||isArrayLike(source))return void copyObject(source,keys(source),object);for(var key in source)hasOwnProperty.call(source,key)&&assignValue(object,key,source[key])}),assignIn=createAssigner(function(object,source){copyObject(source,keysIn(source),object)}),assignInWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keysIn(source),object,customizer)}),assignWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keys(source),object,customizer)}),at=flatRest(baseAt),defaults=baseRest(function(args){return args.push(undefined,assignInDefaults),apply(assignInWith,undefined,args)}),defaultsDeep=baseRest(function(args){return args.push(undefined,mergeDefaults),apply(mergeWith,undefined,args)}),invert=createInverter(function(result,value,key){result[value]=key},constant(identity)),invertBy=createInverter(function(result,value,key){hasOwnProperty.call(result,value)?result[value].push(key):result[value]=[key]},getIteratee),invoke=baseRest(baseInvoke),merge=createAssigner(function(object,source,srcIndex){baseMerge(object,source,srcIndex)}),mergeWith=createAssigner(function(object,source,srcIndex,customizer){baseMerge(object,source,srcIndex,customizer)}),omit=flatRest(function(object,props){return null==object?{}:(props=arrayMap(props,toKey),basePick(object,baseDifference(getAllKeysIn(object),props)))}),pick=flatRest(function(object,props){return null==object?{}:basePick(object,arrayMap(props,toKey))}),toPairs=createToPairs(keys),toPairsIn=createToPairs(keysIn),camelCase=createCompounder(function(result,word,index){return word=word.toLowerCase(),result+(index?capitalize(word):word)}),kebabCase=createCompounder(function(result,word,index){return result+(index?"-":"")+word.toLowerCase()}),lowerCase=createCompounder(function(result,word,index){return result+(index?" ":"")+word.toLowerCase()}),lowerFirst=createCaseFirst("toLowerCase"),snakeCase=createCompounder(function(result,word,index){return result+(index?"_":"")+word.toLowerCase()}),startCase=createCompounder(function(result,word,index){return result+(index?" ":"")+upperFirst(word)}),upperCase=createCompounder(function(result,word,index){return result+(index?" ":"")+word.toUpperCase()}),upperFirst=createCaseFirst("toUpperCase"),attempt=baseRest(function(func,args){try{return apply(func,undefined,args)}catch(e){return isError(e)?e:new Error(e)}}),bindAll=flatRest(function(object,methodNames){return arrayEach(methodNames,function(key){key=toKey(key),baseAssignValue(object,key,bind(object[key],object))}),object}),flow=createFlow(),flowRight=createFlow(!0),method=baseRest(function(path,args){return function(object){return baseInvoke(object,path,args)}}),methodOf=baseRest(function(object,args){return function(path){return baseInvoke(object,path,args)}}),over=createOver(arrayMap),overEvery=createOver(arrayEvery),overSome=createOver(arraySome),range=createRange(),rangeRight=createRange(!0),add=createMathOperation(function(augend,addend){return augend+addend},0),ceil=createRound("ceil"),divide=createMathOperation(function(dividend,divisor){return dividend/divisor},1),floor=createRound("floor"),multiply=createMathOperation(function(multiplier,multiplicand){return multiplier*multiplicand},1),round=createRound("round"),subtract=createMathOperation(function(minuend,subtrahend){return minuend-subtrahend},0);return lodash.after=after,lodash.ary=ary,lodash.assign=assign,lodash.assignIn=assignIn,lodash.assignInWith=assignInWith,lodash.assignWith=assignWith,lodash.at=at,lodash.before=before,lodash.bind=bind,lodash.bindAll=bindAll,lodash.bindKey=bindKey,lodash.castArray=castArray,lodash.chain=chain,lodash.chunk=chunk,lodash.compact=compact,lodash.concat=concat,lodash.cond=cond,lodash.conforms=conforms,lodash.constant=constant,lodash.countBy=countBy,lodash.create=create,lodash.curry=curry,lodash.curryRight=curryRight,lodash.debounce=debounce,lodash.defaults=defaults,lodash.defaultsDeep=defaultsDeep,lodash.defer=defer,lodash.delay=delay,lodash.difference=difference,lodash.differenceBy=differenceBy,lodash.differenceWith=differenceWith,lodash.drop=drop,lodash.dropRight=dropRight,lodash.dropRightWhile=dropRightWhile,lodash.dropWhile=dropWhile,lodash.fill=fill,lodash.filter=filter,lodash.flatMap=flatMap,lodash.flatMapDeep=flatMapDeep,lodash.flatMapDepth=flatMapDepth,lodash.flatten=flatten,lodash.flattenDeep=flattenDeep,lodash.flattenDepth=flattenDepth,lodash.flip=flip,lodash.flow=flow,lodash.flowRight=flowRight,lodash.fromPairs=fromPairs,lodash.functions=functions,lodash.functionsIn=functionsIn,lodash.groupBy=groupBy,lodash.initial=initial,lodash.intersection=intersection,lodash.intersectionBy=intersectionBy,lodash.intersectionWith=intersectionWith,lodash.invert=invert,lodash.invertBy=invertBy,lodash.invokeMap=invokeMap,lodash.iteratee=iteratee,lodash.keyBy=keyBy,lodash.keys=keys,lodash.keysIn=keysIn,lodash.map=map,lodash.mapKeys=mapKeys,lodash.mapValues=mapValues,lodash.matches=matches,lodash.matchesProperty=matchesProperty,lodash.memoize=memoize,lodash.merge=merge,lodash.mergeWith=mergeWith,lodash.method=method,lodash.methodOf=methodOf,lodash.mixin=mixin,lodash.negate=negate,lodash.nthArg=nthArg,lodash.omit=omit,lodash.omitBy=omitBy,lodash.once=once,lodash.orderBy=orderBy,lodash.over=over,lodash.overArgs=overArgs,lodash.overEvery=overEvery,lodash.overSome=overSome,lodash.partial=partial,lodash.partialRight=partialRight,lodash.partition=partition,lodash.pick=pick,lodash.pickBy=pickBy,lodash.property=property,lodash.propertyOf=propertyOf,lodash.pull=pull,lodash.pullAll=pullAll,lodash.pullAllBy=pullAllBy,lodash.pullAllWith=pullAllWith,lodash.pullAt=pullAt,lodash.range=range,lodash.rangeRight=rangeRight,lodash.rearg=rearg,lodash.reject=reject,lodash.remove=remove,lodash.rest=rest,lodash.reverse=reverse,lodash.sampleSize=sampleSize,lodash.set=set,lodash.setWith=setWith,lodash.shuffle=shuffle,lodash.slice=slice,lodash.sortBy=sortBy,lodash.sortedUniq=sortedUniq,lodash.sortedUniqBy=sortedUniqBy,lodash.split=split,lodash.spread=spread,lodash.tail=tail,lodash.take=take,lodash.takeRight=takeRight,lodash.takeRightWhile=takeRightWhile,lodash.takeWhile=takeWhile,lodash.tap=tap,lodash.throttle=throttle,lodash.thru=thru,lodash.toArray=toArray,lodash.toPairs=toPairs,lodash.toPairsIn=toPairsIn,lodash.toPath=toPath,lodash.toPlainObject=toPlainObject,lodash.transform=transform,lodash.unary=unary,lodash.union=union,lodash.unionBy=unionBy,lodash.unionWith=unionWith,lodash.uniq=uniq,lodash.uniqBy=uniqBy,lodash.uniqWith=uniqWith,lodash.unset=unset,lodash.unzip=unzip,lodash.unzipWith=unzipWith,lodash.update=update,lodash.updateWith=updateWith,lodash.values=values,lodash.valuesIn=valuesIn,lodash.without=without,lodash.words=words,lodash.wrap=wrap,lodash.xor=xor,lodash.xorBy=xorBy,lodash.xorWith=xorWith,lodash.zip=zip,lodash.zipObject=zipObject,lodash.zipObjectDeep=zipObjectDeep,lodash.zipWith=zipWith,lodash.entries=toPairs,lodash.entriesIn=toPairsIn,lodash.extend=assignIn,lodash.extendWith=assignInWith,mixin(lodash,lodash),lodash.add=add,lodash.attempt=attempt,lodash.camelCase=camelCase,lodash.capitalize=capitalize,lodash.ceil=ceil,lodash.clamp=clamp,lodash.clone=clone,lodash.cloneDeep=cloneDeep,lodash.cloneDeepWith=cloneDeepWith,lodash.cloneWith=cloneWith,lodash.conformsTo=conformsTo,lodash.deburr=deburr,lodash.defaultTo=defaultTo,lodash.divide=divide,lodash.endsWith=endsWith,lodash.eq=eq,lodash.escape=escape,lodash.escapeRegExp=escapeRegExp,lodash.every=every,lodash.find=find,lodash.findIndex=findIndex,lodash.findKey=findKey,lodash.findLast=findLast,lodash.findLastIndex=findLastIndex,lodash.findLastKey=findLastKey,lodash.floor=floor,lodash.forEach=forEach,lodash.forEachRight=forEachRight,lodash.forIn=forIn,lodash.forInRight=forInRight,lodash.forOwn=forOwn,lodash.forOwnRight=forOwnRight,lodash.get=get,lodash.gt=gt,lodash.gte=gte,lodash.has=has,lodash.hasIn=hasIn,lodash.head=head,lodash.identity=identity,lodash.includes=includes,lodash.indexOf=indexOf,lodash.inRange=inRange,lodash.invoke=invoke,lodash.isArguments=isArguments,lodash.isArray=isArray,lodash.isArrayBuffer=isArrayBuffer,lodash.isArrayLike=isArrayLike,lodash.isArrayLikeObject=isArrayLikeObject,lodash.isBoolean=isBoolean,lodash.isBuffer=isBuffer,lodash.isDate=isDate,lodash.isElement=isElement,lodash.isEmpty=isEmpty,lodash.isEqual=isEqual,lodash.isEqualWith=isEqualWith,lodash.isError=isError,lodash.isFinite=isFinite,lodash.isFunction=isFunction,lodash.isInteger=isInteger,lodash.isLength=isLength,lodash.isMap=isMap,lodash.isMatch=isMatch,lodash.isMatchWith=isMatchWith,lodash.isNaN=isNaN,lodash.isNative=isNative, +lodash.isNil=isNil,lodash.isNull=isNull,lodash.isNumber=isNumber,lodash.isObject=isObject,lodash.isObjectLike=isObjectLike,lodash.isPlainObject=isPlainObject,lodash.isRegExp=isRegExp,lodash.isSafeInteger=isSafeInteger,lodash.isSet=isSet,lodash.isString=isString,lodash.isSymbol=isSymbol,lodash.isTypedArray=isTypedArray,lodash.isUndefined=isUndefined,lodash.isWeakMap=isWeakMap,lodash.isWeakSet=isWeakSet,lodash.join=join,lodash.kebabCase=kebabCase,lodash.last=last,lodash.lastIndexOf=lastIndexOf,lodash.lowerCase=lowerCase,lodash.lowerFirst=lowerFirst,lodash.lt=lt,lodash.lte=lte,lodash.max=max,lodash.maxBy=maxBy,lodash.mean=mean,lodash.meanBy=meanBy,lodash.min=min,lodash.minBy=minBy,lodash.stubArray=stubArray,lodash.stubFalse=stubFalse,lodash.stubObject=stubObject,lodash.stubString=stubString,lodash.stubTrue=stubTrue,lodash.multiply=multiply,lodash.nth=nth,lodash.noConflict=noConflict,lodash.noop=noop,lodash.now=now,lodash.pad=pad,lodash.padEnd=padEnd,lodash.padStart=padStart,lodash.parseInt=parseInt,lodash.random=random,lodash.reduce=reduce,lodash.reduceRight=reduceRight,lodash.repeat=repeat,lodash.replace=replace,lodash.result=result,lodash.round=round,lodash.runInContext=runInContext,lodash.sample=sample,lodash.size=size,lodash.snakeCase=snakeCase,lodash.some=some,lodash.sortedIndex=sortedIndex,lodash.sortedIndexBy=sortedIndexBy,lodash.sortedIndexOf=sortedIndexOf,lodash.sortedLastIndex=sortedLastIndex,lodash.sortedLastIndexBy=sortedLastIndexBy,lodash.sortedLastIndexOf=sortedLastIndexOf,lodash.startCase=startCase,lodash.startsWith=startsWith,lodash.subtract=subtract,lodash.sum=sum,lodash.sumBy=sumBy,lodash.template=template,lodash.times=times,lodash.toFinite=toFinite,lodash.toInteger=toInteger,lodash.toLength=toLength,lodash.toLower=toLower,lodash.toNumber=toNumber,lodash.toSafeInteger=toSafeInteger,lodash.toString=toString,lodash.toUpper=toUpper,lodash.trim=trim,lodash.trimEnd=trimEnd,lodash.trimStart=trimStart,lodash.truncate=truncate,lodash.unescape=unescape,lodash.uniqueId=uniqueId,lodash.upperCase=upperCase,lodash.upperFirst=upperFirst,lodash.each=forEach,lodash.eachRight=forEachRight,lodash.first=head,mixin(lodash,function(){var source={};return baseForOwn(lodash,function(func,methodName){hasOwnProperty.call(lodash.prototype,methodName)||(source[methodName]=func)}),source}(),{chain:!1}),lodash.VERSION=VERSION,arrayEach(["bind","bindKey","curry","curryRight","partial","partialRight"],function(methodName){lodash[methodName].placeholder=lodash}),arrayEach(["drop","take"],function(methodName,index){LazyWrapper.prototype[methodName]=function(n){var filtered=this.__filtered__;if(filtered&&!index)return new LazyWrapper(this);n=n===undefined?1:nativeMax(toInteger(n),0);var result=this.clone();return filtered?result.__takeCount__=nativeMin(n,result.__takeCount__):result.__views__.push({size:nativeMin(n,MAX_ARRAY_LENGTH),type:methodName+(result.__dir__<0?"Right":"")}),result},LazyWrapper.prototype[methodName+"Right"]=function(n){return this.reverse()[methodName](n).reverse()}}),arrayEach(["filter","map","takeWhile"],function(methodName,index){var type=index+1,isFilter=type==LAZY_FILTER_FLAG||type==LAZY_WHILE_FLAG;LazyWrapper.prototype[methodName]=function(iteratee){var result=this.clone();return result.__iteratees__.push({iteratee:getIteratee(iteratee,3),type:type}),result.__filtered__=result.__filtered__||isFilter,result}}),arrayEach(["head","last"],function(methodName,index){var takeName="take"+(index?"Right":"");LazyWrapper.prototype[methodName]=function(){return this[takeName](1).value()[0]}}),arrayEach(["initial","tail"],function(methodName,index){var dropName="drop"+(index?"":"Right");LazyWrapper.prototype[methodName]=function(){return this.__filtered__?new LazyWrapper(this):this[dropName](1)}}),LazyWrapper.prototype.compact=function(){return this.filter(identity)},LazyWrapper.prototype.find=function(predicate){return this.filter(predicate).head()},LazyWrapper.prototype.findLast=function(predicate){return this.reverse().find(predicate)},LazyWrapper.prototype.invokeMap=baseRest(function(path,args){return"function"==typeof path?new LazyWrapper(this):this.map(function(value){return baseInvoke(value,path,args)})}),LazyWrapper.prototype.reject=function(predicate){return this.filter(negate(getIteratee(predicate)))},LazyWrapper.prototype.slice=function(start,end){start=toInteger(start);var result=this;return result.__filtered__&&(start>0||0>end)?new LazyWrapper(result):(0>start?result=result.takeRight(-start):start&&(result=result.drop(start)),end!==undefined&&(end=toInteger(end),result=0>end?result.dropRight(-end):result.take(end-start)),result)},LazyWrapper.prototype.takeRightWhile=function(predicate){return this.reverse().takeWhile(predicate).reverse()},LazyWrapper.prototype.toArray=function(){return this.take(MAX_ARRAY_LENGTH)},baseForOwn(LazyWrapper.prototype,function(func,methodName){var checkIteratee=/^(?:filter|find|map|reject)|While$/.test(methodName),isTaker=/^(?:head|last)$/.test(methodName),lodashFunc=lodash[isTaker?"take"+("last"==methodName?"Right":""):methodName],retUnwrapped=isTaker||/^find/.test(methodName);lodashFunc&&(lodash.prototype[methodName]=function(){var value=this.__wrapped__,args=isTaker?[1]:arguments,isLazy=value instanceof LazyWrapper,iteratee=args[0],useLazy=isLazy||isArray(value),interceptor=function(value){var result=lodashFunc.apply(lodash,arrayPush([value],args));return isTaker&&chainAll?result[0]:result};useLazy&&checkIteratee&&"function"==typeof iteratee&&1!=iteratee.length&&(isLazy=useLazy=!1);var chainAll=this.__chain__,isHybrid=!!this.__actions__.length,isUnwrapped=retUnwrapped&&!chainAll,onlyLazy=isLazy&&!isHybrid;if(!retUnwrapped&&useLazy){value=onlyLazy?value:new LazyWrapper(this);var result=func.apply(value,args);return result.__actions__.push({func:thru,args:[interceptor],thisArg:undefined}),new LodashWrapper(result,chainAll)}return isUnwrapped&&onlyLazy?func.apply(this,args):(result=this.thru(interceptor),isUnwrapped?isTaker?result.value()[0]:result.value():result)})}),arrayEach(["pop","push","shift","sort","splice","unshift"],function(methodName){var func=arrayProto[methodName],chainName=/^(?:push|sort|unshift)$/.test(methodName)?"tap":"thru",retUnwrapped=/^(?:pop|shift)$/.test(methodName);lodash.prototype[methodName]=function(){var args=arguments;if(retUnwrapped&&!this.__chain__){var value=this.value();return func.apply(isArray(value)?value:[],args)}return this[chainName](function(value){return func.apply(isArray(value)?value:[],args)})}}),baseForOwn(LazyWrapper.prototype,function(func,methodName){var lodashFunc=lodash[methodName];if(lodashFunc){var key=lodashFunc.name+"",names=realNames[key]||(realNames[key]=[]);names.push({name:methodName,func:lodashFunc})}}),realNames[createHybrid(undefined,BIND_KEY_FLAG).name]=[{name:"wrapper",func:undefined}],LazyWrapper.prototype.clone=lazyClone,LazyWrapper.prototype.reverse=lazyReverse,LazyWrapper.prototype.value=lazyValue,lodash.prototype.at=wrapperAt,lodash.prototype.chain=wrapperChain,lodash.prototype.commit=wrapperCommit,lodash.prototype.next=wrapperNext,lodash.prototype.plant=wrapperPlant,lodash.prototype.reverse=wrapperReverse,lodash.prototype.toJSON=lodash.prototype.valueOf=lodash.prototype.value=wrapperValue,lodash.prototype.first=lodash.prototype.head,iteratorSymbol&&(lodash.prototype[iteratorSymbol]=wrapperToIterator),lodash}var undefined,VERSION="4.16.0",LARGE_ARRAY_SIZE=200,FUNC_ERROR_TEXT="Expected a function",HASH_UNDEFINED="__lodash_hash_undefined__",MAX_MEMOIZE_SIZE=500,PLACEHOLDER="__lodash_placeholder__",BIND_FLAG=1,BIND_KEY_FLAG=2,CURRY_BOUND_FLAG=4,CURRY_FLAG=8,CURRY_RIGHT_FLAG=16,PARTIAL_FLAG=32,PARTIAL_RIGHT_FLAG=64,ARY_FLAG=128,REARG_FLAG=256,FLIP_FLAG=512,UNORDERED_COMPARE_FLAG=1,PARTIAL_COMPARE_FLAG=2,DEFAULT_TRUNC_LENGTH=30,DEFAULT_TRUNC_OMISSION="...",HOT_COUNT=500,HOT_SPAN=16,LAZY_FILTER_FLAG=1,LAZY_MAP_FLAG=2,LAZY_WHILE_FLAG=3,INFINITY=1/0,MAX_SAFE_INTEGER=9007199254740991,MAX_INTEGER=1.7976931348623157e308,NAN=NaN,MAX_ARRAY_LENGTH=4294967295,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH-1,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH>>>1,wrapFlags=[["ary",ARY_FLAG],["bind",BIND_FLAG],["bindKey",BIND_KEY_FLAG],["curry",CURRY_FLAG],["curryRight",CURRY_RIGHT_FLAG],["flip",FLIP_FLAG],["partial",PARTIAL_FLAG],["partialRight",PARTIAL_RIGHT_FLAG],["rearg",REARG_FLAG]],argsTag="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",genTag="[object GeneratorFunction]",mapTag="[object Map]",numberTag="[object Number]",objectTag="[object Object]",promiseTag="[object Promise]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]",weakMapTag="[object WeakMap]",weakSetTag="[object WeakSet]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]",reEmptyStringLeading=/\b__p \+= '';/g,reEmptyStringMiddle=/\b(__p \+=) '' \+/g,reEmptyStringTrailing=/(__e\(.*?\)|\b__t\)) \+\n'';/g,reEscapedHtml=/&(?:amp|lt|gt|quot|#39|#96);/g,reUnescapedHtml=/[&<>"'`]/g,reHasEscapedHtml=RegExp(reEscapedHtml.source),reHasUnescapedHtml=RegExp(reUnescapedHtml.source),reEscape=/<%-([\s\S]+?)%>/g,reEvaluate=/<%([\s\S]+?)%>/g,reInterpolate=/<%=([\s\S]+?)%>/g,reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/,reLeadingDot=/^\./,rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reHasRegExpChar=RegExp(reRegExpChar.source),reTrim=/^\s+|\s+$/g,reTrimStart=/^\s+/,reTrimEnd=/\s+$/,reWrapComment=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,reWrapDetails=/\{\n\/\* \[wrapped with (.+)\] \*/,reSplitDetails=/,? & /,reAsciiWord=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,reEscapeChar=/\\(\\)?/g,reEsTemplate=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,reFlags=/\w*$/,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsHostCtor=/^\[object .+?Constructor\]$/,reIsOctal=/^0o[0-7]+$/i,reIsUint=/^(?:0|[1-9]\d*)$/,reLatin=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,reNoMatch=/($^)/,reUnescapedString=/['\n\r\u2028\u2029\\]/g,rsAstralRange="\\ud800-\\udfff",rsComboMarksRange="\\u0300-\\u036f\\ufe20-\\ufe23",rsComboSymbolsRange="\\u20d0-\\u20f0",rsDingbatRange="\\u2700-\\u27bf",rsLowerRange="a-z\\xdf-\\xf6\\xf8-\\xff",rsMathOpRange="\\xac\\xb1\\xd7\\xf7",rsNonCharRange="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",rsPunctuationRange="\\u2000-\\u206f",rsSpaceRange=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",rsUpperRange="A-Z\\xc0-\\xd6\\xd8-\\xde",rsVarRange="\\ufe0e\\ufe0f",rsBreakRange=rsMathOpRange+rsNonCharRange+rsPunctuationRange+rsSpaceRange,rsApos="['’]",rsAstral="["+rsAstralRange+"]",rsBreak="["+rsBreakRange+"]",rsCombo="["+rsComboMarksRange+rsComboSymbolsRange+"]",rsDigits="\\d+",rsDingbat="["+rsDingbatRange+"]",rsLower="["+rsLowerRange+"]",rsMisc="[^"+rsAstralRange+rsBreakRange+rsDigits+rsDingbatRange+rsLowerRange+rsUpperRange+"]",rsFitz="\\ud83c[\\udffb-\\udfff]",rsModifier="(?:"+rsCombo+"|"+rsFitz+")",rsNonAstral="[^"+rsAstralRange+"]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",rsUpper="["+rsUpperRange+"]",rsZWJ="\\u200d",rsLowerMisc="(?:"+rsLower+"|"+rsMisc+")",rsUpperMisc="(?:"+rsUpper+"|"+rsMisc+")",rsOptLowerContr="(?:"+rsApos+"(?:d|ll|m|re|s|t|ve))?",rsOptUpperContr="(?:"+rsApos+"(?:D|LL|M|RE|S|T|VE))?",reOptMod=rsModifier+"?",rsOptVar="["+rsVarRange+"]?",rsOptJoin="(?:"+rsZWJ+"(?:"+[rsNonAstral,rsRegional,rsSurrPair].join("|")+")"+rsOptVar+reOptMod+")*",rsSeq=rsOptVar+reOptMod+rsOptJoin,rsEmoji="(?:"+[rsDingbat,rsRegional,rsSurrPair].join("|")+")"+rsSeq,rsSymbol="(?:"+[rsNonAstral+rsCombo+"?",rsCombo,rsRegional,rsSurrPair,rsAstral].join("|")+")",reApos=RegExp(rsApos,"g"),reComboMark=RegExp(rsCombo,"g"),reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g"),reUnicodeWord=RegExp([rsUpper+"?"+rsLower+"+"+rsOptLowerContr+"(?="+[rsBreak,rsUpper,"$"].join("|")+")",rsUpperMisc+"+"+rsOptUpperContr+"(?="+[rsBreak,rsUpper+rsLowerMisc,"$"].join("|")+")",rsUpper+"?"+rsLowerMisc+"+"+rsOptLowerContr,rsUpper+"+"+rsOptUpperContr,rsDigits,rsEmoji].join("|"),"g"),reHasUnicode=RegExp("["+rsZWJ+rsAstralRange+rsComboMarksRange+rsComboSymbolsRange+rsVarRange+"]"),reHasUnicodeWord=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,contextProps=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],templateCounter=-1,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[dataViewTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[mapTag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[setTag]=cloneableTags[stringTag]=cloneableTags[symbolTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=!0,cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[weakMapTag]=!1;var deburredLetters={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"},htmlEscapes={"&":"&","<":"<",">":">",'"':""","'":"'"},htmlUnescapes={"&":"&","<":"<",">":">",""":'"',"'":"'"},stringEscapes={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},freeParseFloat=parseFloat,freeParseInt=parseInt,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,freeProcess=moduleExports&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding("util")}catch(e){}}(),nodeIsArrayBuffer=nodeUtil&&nodeUtil.isArrayBuffer,nodeIsDate=nodeUtil&&nodeUtil.isDate,nodeIsMap=nodeUtil&&nodeUtil.isMap,nodeIsRegExp=nodeUtil&&nodeUtil.isRegExp,nodeIsSet=nodeUtil&&nodeUtil.isSet,nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,asciiSize=baseProperty("length"),deburrLetter=basePropertyOf(deburredLetters),escapeHtmlChar=basePropertyOf(htmlEscapes),unescapeHtmlChar=basePropertyOf(htmlUnescapes),_=runInContext();"function"==typeof define&&"object"==typeof define.amd&&define.amd?(root._=_,define(function(){return _})):freeModule?((freeModule.exports=_)._=_,freeExports._=_):root._=_}.call(this),function(global){function UsergridHelpers(){}var name="UsergridHelpers",overwrittenName=global[name];return UsergridHelpers.inherits=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})},UsergridHelpers.flattenArgs=function(args){return _.flattenDeep(Array.prototype.slice.call(args))},UsergridHelpers.callback=function(){var args=_.flattenDeep(Array.prototype.slice.call(arguments)).reverse(),emptyFunc=function(){};return _.first(_.flattenDeep([args,_.get(args,"0.callback"),emptyFunc]).filter(_.isFunction))},UsergridHelpers.configureTempAuth=function(auth){return _.isString(auth)&&auth!==UsergridAuthMode.NONE?new UsergridAuth(auth):auth&&auth!==UsergridAuthMode.NONE&&auth instanceof UsergridAuth?auth:void 0},UsergridHelpers.userLoginBody=function(options){var body={grant_type:"password",password:options.password};return options.tokenTtl&&(body.ttl=options.tokenTtl),body[options.username?"username":"email"]=options.username?options.username:options.email,body},UsergridHelpers.appLoginBody=function(options){var body={grant_type:"client_credentials",client_id:options.clientId,client_secret:options.clientSecret};return options.tokenTtl&&(body.ttl=options.tokenTtl),body},UsergridHelpers.useQuotesIfRequired=function(value){return _.isFinite(value)||isUUID(value)||_.isBoolean(value)||_.isObject(value)&&!_.isFunction(value)||_.isArray(value)?value:"'"+value+"'"},UsergridHelpers.setReadOnly=function(obj,key){return _.isArray(key)?key.forEach(function(k){UsergridHelpers.setReadOnly(obj,k)}):_.isPlainObject(obj[key])?Object.freeze(obj[key]):_.isPlainObject(obj)&&void 0===key?Object.freeze(obj):_.has(obj,key)?Object.defineProperty(obj,key,{writable:!1}):obj},UsergridHelpers.setWritable=function(obj,key){return _.isArray(key)?key.forEach(function(k){UsergridHelpers.setWritable(obj,k)}):_.isPlainObject(obj[key])?_.clone(obj[key]):_.isPlainObject(obj)&&void 0===key?_.clone(obj):_.has(obj,key)?Object.defineProperty(obj,key,{writable:!0}):obj},UsergridHelpers.normalize=function(str,options){return str=str.replace(/:\//g,"://"),str=str.replace(/([^:\s])\/+/g,"$1/"),str=str.replace(/\/(\?|&|#[^!])/g,"$1"),str=str.replace(/(\?.+)\?/g,"$1&")},UsergridHelpers.urljoin=function(){var input=arguments,options={};"object"==typeof arguments[0]&&(input=arguments[0],options=arguments[1]||{});var joined=[].slice.call(input,0).join("/");return UsergridHelpers.normalize(joined,options)},UsergridHelpers.uri=function(client,options){return UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,options.path||options.type,"POST"!==options.method?_.first([options.uuidOrName,options.uuid,options.name,_.get(options,"entity.uuid"),_.get(options,"entity.name"),""].filter(_.isString)):"")},UsergridHelpers.headers=function(client,options){var headers={"User-Agent":"usergrid-js/v"+Usergrid.USERGRID_SDK_VERSION};_.assign(headers,options.headers);var token;return _.get(client,"tempAuth.isValid")?(token=client.tempAuth.token,client.tempAuth=void 0):_.get(client,"currentUser.auth.isValid")?token=client.currentUser.auth.token:_.get(client,"authFallback")===UsergridAuthMode.APP&&_.get(client,"appAuth.isValid")&&(token=client.appAuth.token),token&&_.assign(headers,{authorization:"Bearer "+token}),headers},UsergridHelpers.qs=function(options){return options.query instanceof UsergridQuery?{ql:options.query._ql||void 0,limit:options.query._limit,cursor:options.query._cursor}:options.qs},UsergridHelpers.formData=function(options){if(_.get(options,"asset.data")){var formData={};return formData.file={value:options.asset.data,options:{filename:_.get(options,"asset.filename")||"",contentType:_.get(options,"asset.contentType")||"application/octet-stream"}},_.has(options,"asset.name")&&(formData.name=options.asset.name),formData}return void 0},UsergridHelpers.encode=function(data){var result="";if("string"==typeof data)result=data;else{var e=encodeURIComponent;for(var i in data)data.hasOwnProperty(i)&&(result+="&"+e(i)+"="+e(data[i]))}return result},global[name]=UsergridHelpers,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),UsergridHelpers},global[name]}(this);var UsergridQuery=function(type){var queryString,sort,self=this,query="",__nextIsNot=!1;return _.assign(self,{type:function(value){return self._type=value,self},collection:function(value){return self._type=value,self},limit:function(value){return self._limit=value,self},cursor:function(value){return self._cursor=value,self},eq:function(key,value){return query=self.andJoin(key+" = "+UsergridHelpers.useQuotesIfRequired(value)),self},equal:this.eq,gt:function(key,value){return query=self.andJoin(key+" > "+UsergridHelpers.useQuotesIfRequired(value)),self},greaterThan:this.gt,gte:function(key,value){return query=self.andJoin(key+" >= "+UsergridHelpers.useQuotesIfRequired(value)),self},greaterThanOrEqual:this.gte,lt:function(key,value){return query=self.andJoin(key+" < "+UsergridHelpers.useQuotesIfRequired(value)),self},lessThan:this.lt,lte:function(key,value){return query=self.andJoin(key+" <= "+UsergridHelpers.useQuotesIfRequired(value)),self},lessThanOrEqual:this.lte,contains:function(key,value){return query=self.andJoin(key+" contains "+UsergridHelpers.useQuotesIfRequired(value)),self},locationWithin:function(distanceInMeters,lat,lng){return query=self.andJoin("location within "+distanceInMeters+" of "+lat+", "+lng),self},asc:function(key){return self.sort(key,"asc"),self},desc:function(key){return self.sort(key,"desc"),self},sort:function(key,order){return sort=key&&order?" order by "+key+" "+order:"",self},fromString:function(string){return queryString=string,self},andJoin:function(append){return __nextIsNot&&(append="not "+append,__nextIsNot=!1),append?0===query.length?append:_.endsWith(query,"and")||_.endsWith(query,"or")?query+" "+append:query+" and "+append:query},orJoin:function(){return query.length>0&&!_.endsWith(query,"or")?query+" or":query}}),self._type=self._type||type,Object.defineProperty(self,"_ql",{get:function(){return void 0!==queryString?queryString:query.length>0||void 0!==sort?"select * where "+(query||"")+(sort||""):""}}),Object.defineProperty(self,"and",{get:function(){return query=self.andJoin(""),self}}),Object.defineProperty(self,"or",{get:function(){return query=self.orJoin(),self}}),Object.defineProperty(self,"not",{get:function(){return __nextIsNot=!0,self}}),self};window.console=window.console||{},window.console.log=window.console.log||function(){};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;!function(global){function Usergrid(){this.logger=new Logger(name)}var name="Usergrid",overwrittenName=global[name],VALID_REQUEST_METHODS=["GET","POST","PUT","DELETE"];return Usergrid.initSharedInstance=function(options){return console.warn("TRYING TO INITIALIZING SHARED INSTANCE"),this.isInitialized||(console.warn("INITIALIZING SHARED INSTANCE"),this.__sharedInstance=new Usergrid.Client(options),this.isInitialized=!0),this.__sharedInstance},Usergrid.getInstance=function(){return this.__sharedInstance},Usergrid.isValidEndpoint=function(endpoint){return!0},Usergrid.validateAndRetrieveClient=function(args){var client=void 0;if(args instanceof Usergrid.Client)client=args;else if(args[0]instanceof Usergrid.Client)client=args[0];else{if(!Usergrid.isInitialized)throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument");client=Usergrid.getInstance()}return client},Usergrid.calculateExpiry=function(expires_in){return Date.now()+1e3*(expires_in?expires_in-5:0)},Usergrid.Request=function(method,endpoint,query_params,data,callback){var p=new Promise;if(this.logger=new global.Logger("Usergrid.Request"),this.logger.time("process request "+method+" "+endpoint),this.endpoint=endpoint+"?"+encodeParams(query_params),this.method=method.toUpperCase(),this.data="object"==typeof data?JSON.stringify(data):data,-1===VALID_REQUEST_METHODS.indexOf(this.method))throw new UsergridInvalidHTTPMethodError("invalid request method '"+this.method+"'");if(!isValidUrl(this.endpoint))throw this.logger.error(endpoint,this.endpoint,/^https:\/\//.test(endpoint)),new UsergridInvalidURIError("The provided endpoint is not valid: "+this.endpoint);var request=function(){return new UsergridRequest({method:this.method,uri:this.endpoint,body:this.data})}.bind(this),response=function(request){return new UsergridResponse(request)}.bind(this),oncomplete=function(response){p.done(response),doCallback(callback,[response])}.bind(this);return Promise.chain([request,response]).then(oncomplete),p},Usergrid.Response=function(err,response){var p=new Promise,data=null;try{data=JSON.parse(response.responseText)}catch(e){data={}}switch(Object.keys(data).forEach(function(key){Object.defineProperty(this,key,{value:data[key],enumerable:!0})}.bind(this)),Object.defineProperty(this,"logger",{enumerable:!1,configurable:!1,writable:!1,value:new global.Logger(name)}),Object.defineProperty(this,"success",{enumerable:!1,configurable:!1,writable:!0,value:!0}),Object.defineProperty(this,"err",{enumerable:!1,configurable:!1,writable:!0,value:err}),Object.defineProperty(this,"status",{enumerable:!1,configurable:!1,writable:!0,value:parseInt(response.status)}),Object.defineProperty(this,"statusGroup",{enumerable:!1,configurable:!1,writable:!0,value:this.status-this.status%100}),this.statusGroup){case 200:this.success=!0;break;case 400:case 500:case 300:case 100:default:this.success=!1}return this.success?p.done(null,this):p.done(UsergridError.fromResponse(data),this),p},Usergrid.Response.prototype.getEntities=function(){var entities;return this.success&&(entities=this.data?this.data.entities:this.entities),entities||[]},Usergrid.Response.prototype.getEntity=function(){var entities=this.getEntities();return entities[0]},Usergrid.VERSION=Usergrid.USERGRID_SDK_VERSION="0.11.0",global[name]=Usergrid,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Usergrid},global[name]}(this);var defaultOptions={baseUrl:"https://api.usergrid.com",authMode:UsergridAuthMode.USER};!function(){var exports,name="Client",global=this,overwrittenName=global[name];return Usergrid.Client=function(options){var self=this;if(!options.orgId||!options.appId)throw new Error('"orgId" and "appId" parameters are required when instantiating UsergridClient');_.defaults(this,options,defaultOptions),self.clientAppURL=[self.baseUrl,self.orgId,self.appId].join("/"),self.isSharedInstance=!1,self.currentUser=void 0,self.__appAuth=void 0,Object.defineProperty(self,"appAuth",{get:function(){return self.__appAuth},set:function(options){options instanceof UsergridAppAuth?self.__appAuth=options:"undefined"!=typeof options&&(self.__appAuth=new UsergridAppAuth(options))}}),this.userAuth=void 0,options.qs&&this.setObject("default_qs",options.qs),this.buildCurl=options.buildCurl||!1,this.logging=options.logging||!1},Usergrid.Client.prototype.request=function(options,callback){var uri,method=options.method||"GET",endpoint=options.endpoint,body=options.body||{},qs=options.qs||{},mQuery=options.mQuery||!1,orgId=this.get("orgId"),appId=this.get("appId"),default_qs=this.getObject("default_qs");if(!mQuery&&!orgId&&!appId)return logoutCallback();uri=mQuery?this.baseUrl+"/"+endpoint:this.baseUrl+"/"+orgId+"/"+appId+"/"+endpoint,this.getToken()&&(qs.access_token=this.getToken()),default_qs&&(qs=propCopy(qs,default_qs));var self=this;new Usergrid.Request(method,uri,qs,body,function(response){doCallback(callback,[response,self],self)})},Usergrid.Client.prototype.buildAssetURL=function(uuid){var self=this,qs={},assetURL=this.baseUrl+"/"+this.orgId+"/"+this.appId+"/assets/"+uuid+"/data";self.getToken()&&(qs.access_token=self.getToken());var encoded_params=encodeParams(qs);return encoded_params&&(assetURL+="?"+encoded_params),assetURL},Usergrid.Client.prototype.createGroup=function(options,callback){var group=new Usergrid.Group({path:options.path,client:this,data:options});group.save(function(err,response){doCallback(callback,[err,response,group],group)})},Usergrid.Client.prototype.createEntity=function(options,callback){var entity=new Usergrid.Entity({client:this,data:options});entity.save(function(err,response){doCallback(callback,[err,response,entity],entity)})},Usergrid.Client.prototype.getEntity=function(options,callback){var entity=new Usergrid.Entity({client:this,data:options});entity.fetch(function(err,response){doCallback(callback,[err,response,entity],entity)})},Usergrid.Client.prototype.restoreEntity=function(serializedObject){var data=JSON.parse(serializedObject),options={client:this,data:data},entity=new Usergrid.Entity(options);return entity},Usergrid.Client.prototype.createCounter=function(options,callback){var counter=new Usergrid.Counter({client:this,data:options});counter.save(callback)},Usergrid.Client.prototype.createAsset=function(options,callback){var file=options.file;file&&(options.name=options.name||file.name,options["content-type"]=options["content-type"]||file.type,options.path=options.path||"/",delete options.file);var asset=new Usergrid.Asset({client:this,data:options});asset.save(function(err,response,asset){file&&!err?asset.upload(file,callback):doCallback(callback,[err,response,asset],asset)})},Usergrid.Client.prototype.createCollection=function(options,callback){options.client=this;var collection=new Usergrid.Collection(options);this.request({method:"POST",endpoint:options.type},function(err,data){err?doCallback(callback,[err,data,collection],self):collection.fetch(function(err,response,collection){doCallback(callback,[err,response,collection],self)})})},Usergrid.Client.prototype.restoreCollection=function(serializedObject){var data=JSON.parse(serializedObject);data.client=this;var collection=new Usergrid.Collection(data);return collection},Usergrid.Client.prototype.getFeedForUser=function(username,callback){var options={method:"GET",endpoint:"users/"+username+"/feed"};this.request(options,function(err,data){err?doCallback(callback,[err]):doCallback(callback,[err,data,data.getEntities()])})},Usergrid.Client.prototype.createUserActivity=function(user,options,callback){options.type="users/"+user+"/activities",options={client:this,data:options};var entity=new Usergrid.Entity(options);entity.save(function(err,data){doCallback(callback,[err,data,entity])})},Usergrid.Client.prototype.createUserActivityWithEntity=function(user,content,callback){var username=user.get("username"),options={ +actor:{displayName:username,uuid:user.get("uuid"),username:username,email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80}},verb:"post",content:content};this.createUserActivity(username,options,callback)},Usergrid.Client.prototype.calcTimeDiff=function(){var seconds=0,time=this._end-this._start;try{seconds=(time/10/60).toFixed(2)}catch(e){return 0}return seconds},Usergrid.Client.prototype.setToken=function(token){this.set("token",token)},Usergrid.Client.prototype.getToken=function(){return this.get("token")},Usergrid.Client.prototype.setObject=function(key,value){value&&(value=JSON.stringify(value)),this.set(key,value)},Usergrid.Client.prototype.set=function(key,value){var keyStore="apigee_"+key;this[key]=value,"undefined"!=typeof Storage&&(value?localStorage.setItem(keyStore,value):localStorage.removeItem(keyStore))},Usergrid.Client.prototype.getObject=function(key){return JSON.parse(this.get(key))},Usergrid.Client.prototype.get=function(key){var keyStore="apigee_"+key,value=null;return this[key]?value=this[key]:"undefined"!=typeof Storage&&(value=localStorage.getItem(keyStore)),value},Usergrid.Client.prototype.signup=function(username,password,email,name,callback){var options={type:"users",username:username,password:password,email:email,name:name};this.createEntity(options,callback)},Usergrid.Client.prototype.login=function(username,password,callback){var self=this,options={method:"POST",endpoint:"token",body:{username:username,password:password,grant_type:"password"}};self.request(options,function(err,response){var user={};if(err)self.logging&&console.log("error trying to log user in");else{var options={client:self,data:response.user};user=new Usergrid.Entity(options),self.setToken(response.access_token)}doCallback(callback,[err,response,user])})},Usergrid.Client.prototype.adminlogin=function(username,password,callback){var self=this,options={method:"POST",endpoint:"management/token",body:{username:username,password:password,grant_type:"password"},mQuery:!0};self.request(options,function(err,response){var user={};if(err)self.logging&&console.log("error trying to log adminuser in");else{var options={client:self,data:response.user};user=new Usergrid.Entity(options),self.setToken(response.access_token)}doCallback(callback,[err,response,user])})},Usergrid.Client.prototype.reAuthenticateLite=function(callback){var self=this,options={method:"GET",endpoint:"management/me",mQuery:!0};this.request(options,function(err,response){err&&self.logging?console.log("error trying to re-authenticate user"):self.setToken(response.data.access_token),doCallback(callback,[err])})},Usergrid.Client.prototype.reAuthenticate=function(email,callback){var self=this,options={method:"GET",endpoint:"management/users/"+email,mQuery:!0};this.request(options,function(err,response){var data,organizations={},applications={},user={};if(err&&self.logging)console.log("error trying to full authenticate user");else{data=response.data,self.setToken(data.token),self.set("email",data.email),localStorage.setItem("accessToken",data.token),localStorage.setItem("userUUID",data.uuid),localStorage.setItem("userEmail",data.email);var userData={username:data.username,email:data.email,name:data.name,uuid:data.uuid},options={client:self,data:userData};user=new Usergrid.Entity(options),organizations=data.organizations;var org="";try{var existingOrg=self.get("orgName");org=organizations[existingOrg]?organizations[existingOrg]:organizations[Object.keys(organizations)[0]],self.set("orgName",org.name)}catch(e){err=!0,self.logging&&console.log("error selecting org")}applications=self.parseApplicationsArray(org),self.selectFirstApp(applications),self.setObject("organizations",organizations),self.setObject("applications",applications)}doCallback(callback,[err,data,user,organizations,applications],self)})},Usergrid.Client.prototype.loginFacebook=function(facebookToken,callback){var self=this,options={method:"GET",endpoint:"auth/facebook",qs:{fb_access_token:facebookToken}};this.request(options,function(err,data){var user={};if(err&&self.logging)console.log("error trying to log user in");else{var options={client:self,data:data.user};user=new Usergrid.Entity(options),self.setToken(data.access_token)}doCallback(callback,[err,data,user],self)})},Usergrid.Client.prototype.getLoggedInUser=function(callback){var self=this;if(this.getToken()){var options={method:"GET",endpoint:"users/me"};this.request(options,function(err,response){if(err)self.logging&&console.log("error trying to log user in"),console.error(err,response),doCallback(callback,[err,response,self],self);else{var options={client:self,data:response.getEntity()},user=new Usergrid.Entity(options);doCallback(callback,[null,response,user],self)}})}else doCallback(callback,[new UsergridError("Access Token not set"),null,self],self)},Usergrid.Client.prototype.isLoggedIn=function(){var token=this.getToken();return"undefined"!=typeof token&&null!==token},Usergrid.Client.prototype.logout=function(){this.setToken()},Usergrid.Client.prototype.destroyToken=function(username,token,revokeAll,callback){var options={client:self,method:"PUT"};revokeAll===!0?options.endpoint="users/"+username+"/revoketokens":null===token?options.endpoint="users/"+username+"/revoketoken?token="+this.getToken():options.endpoint="users/"+username+"/revoketoken?token="+token,this.request(options,function(err,data){err?(self.logging&&console.log("error destroying access token"),doCallback(callback,[err,data,null],self)):(revokeAll===!0?console.log("all user tokens invalidated"):console.log("token invalidated"),doCallback(callback,[err,data,null],self))})},Usergrid.Client.prototype.logoutAndDestroyToken=function(username,token,revokeAll,callback){null===username?console.log("username required to revoke tokens"):(this.destroyToken(username,token,revokeAll,callback),(revokeAll===!0||token===this.getToken()||null===token)&&this.setToken(null))},Usergrid.Client.prototype.buildCurlCall=function(options){var curl=["curl"],method=(options.method||"GET").toUpperCase(),body=options.body,uri=options.uri;return curl.push("-X"),curl.push(["POST","PUT","DELETE"].indexOf(method)>=0?method:"GET"),curl.push(uri),"object"==typeof body&&Object.keys(body).length>0&&-1!==["POST","PUT"].indexOf(method)&&(curl.push("-d"),curl.push("'"+JSON.stringify(body)+"'")),curl=curl.join(" "),console.log(curl),curl},Usergrid.Client.prototype.getDisplayImage=function(email,picture,size){size=size||50;var image="https://apigee.com/usergrid/images/user_profile.png";try{picture?image=picture:email.length&&(image="https://secure.gravatar.com/avatar/"+MD5(email)+"?s="+size+encodeURI("&d=https://apigee.com/usergrid/images/user_profile.png"))}catch(e){}finally{return image}},global[name]=Usergrid.Client,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}();var UsergridRequest=function(options){var self=this,client=Usergrid.validateAndRetrieveClient(Usergrid.getInstance());if(!_.isString(options.type)&&!_.isString(options.path)&&!_.isString(options.uri))throw new Error('one of "type" (collection name), "path", or "uri" parameters are required when initializing a UsergridRequest');if(!_.includes(["GET","PUT","POST","DELETE"],options.method))throw new Error('"method" parameter is required when initializing a UsergridRequest');self.method=options.method,self.uri=options.uri||UsergridHelpers.uri(client,options),self.headers=UsergridHelpers.headers(client,options),self.body=options.body||void 0,self.encoding=options.encoding||null,self.qs=UsergridHelpers.qs(options),_.isPlainObject(self.body)&&(self.body=JSON.stringify(self.body));var promise=new Promise,request=new XMLHttpRequest;return request.open(self.method,self.uri),request.open=function(m,u){for(var header in self.headers)self.headers.hasOwnProperty(header)&&request.setRequestHeader(header,self.headers[header]);void 0!==self.body&&(request.setRequestHeader("Content-Type","application/json"),request.setRequestHeader("Accept","application/json"))},request.onreadystatechange=function(){this.readyState===XMLHttpRequest.DONE&&promise.done(request)},request.send(UsergridHelpers.encode(self.body)),promise},ENTITY_SYSTEM_PROPERTIES=["metadata","created","modified","oldpassword","newpassword","type","activated","uuid"];Usergrid.Entity=function(options){this._data={},this._client=void 0,options&&(this.set(options.data||{}),this._client=options.client||{})},Usergrid.Entity.isEntity=function(obj){return obj&&obj instanceof Usergrid.Entity},Usergrid.Entity.isPersistedEntity=function(obj){return isEntity(obj)&&isUUID(obj.get("uuid"))},Usergrid.Entity.prototype.serialize=function(){return JSON.stringify(this._data)},Usergrid.Entity.prototype.get=function(key){var value;if(0===arguments.length?value=this._data:arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c,i,a){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(value=this._data[key]);return value},Usergrid.Entity.prototype.set=function(key,value){if("object"==typeof key)for(var field in key)this._data[field]=key[field];else"string"==typeof key?null===value?delete this._data[key]:this._data[key]=value:this._data={}},Usergrid.Entity.prototype.getEndpoint=function(){var name,type=this.get("type"),nameProperties=["uuid","name"];if(void 0===type)throw new UsergridError("cannot fetch entity, no entity type specified","no_type_specified");return/^users?$/.test(type)&&nameProperties.unshift("username"),name=this.get(nameProperties).filter(function(x){return null!==x&&"undefined"!=typeof x}).shift(),name?[type,name].join("/"):type},Usergrid.Entity.prototype.save=function(callback){var self=this,type=this.get("type"),method="POST",entityId=this.get("uuid"),entityData=this.get(),options={method:method,endpoint:type};entityId&&(options.method="PUT",options.endpoint+="/"+entityId),options.body=Object.keys(entityData).filter(function(key){return-1===ENTITY_SYSTEM_PROPERTIES.indexOf(key)}).reduce(function(data,key){return data[key]=entityData[key],data},{}),self._client.request(options,function(err,response){var entity=response.getEntity();entity&&(self.set(entity),self.set("type",/^\//.test(response.path)?response.path.substring(1):response.path)),err&&self._client.logging&&console.log("could not save entity"),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.changePassword=function(oldpassword,newpassword,callback){var self=this;if("function"==typeof oldpassword&&void 0===callback&&(callback=oldpassword,oldpassword=self.get("oldpassword"),newpassword=self.get("newpassword")),self.set({password:null,oldpassword:null,newpassword:null}),!(/^users?$/.test(self.get("type"))&&oldpassword&&newpassword))throw new UsergridInvalidArgumentError("Invalid arguments passed to 'changePassword'");var options={method:"PUT",endpoint:"users/"+self.get("uuid")+"/password",body:{uuid:self.get("uuid"),username:self.get("username"),oldpassword:oldpassword,newpassword:newpassword}};self._client.request(options,function(err,response){err&&self._client.logging&&console.log("could not update user"),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.fetch=function(callback){var endpoint,self=this;endpoint=this.getEndpoint();var options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,response){var entity=response.getEntity();entity&&self.set(entity),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.destroy=function(callback){var self=this,endpoint=this.getEndpoint(),options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,response){err||self.set(null),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.connect=function(connection,entity,callback){this.addOrRemoveConnection("POST",connection,entity,callback)},Usergrid.Entity.prototype.disconnect=function(connection,entity,callback){this.addOrRemoveConnection("DELETE",connection,entity,callback)},Usergrid.Entity.prototype.addOrRemoveConnection=function(method,connection,entity,callback){var self=this;if(-1==["POST","DELETE"].indexOf(method.toUpperCase()))throw new UsergridInvalidArgumentError("invalid method for connection call. must be 'POST' or 'DELETE'");var connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)throw new UsergridInvalidArgumentError("connectee could not be identified");var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)throw new UsergridInvalidArgumentError("connector could not be identified");var endpoint=[connectorType,connector,connection,connecteeType,connectee].join("/"),options={method:method,endpoint:endpoint};this._client.request(options,function(err,response){err&&self._client.logging&&console.log("There was an error with the connection call"),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.getEntityId=function(entity){var id;return id=isUUID(entity.get("uuid"))?entity.get("uuid"):"users"===this.get("type")||"user"===this.get("type")?entity.get("username"):entity.get("name")},Usergrid.Entity.prototype.getConnections=function(connection,callback){var self=this,connectorType=this.get("type"),connector=this.getEntityId(this);if(connector){var endpoint=connectorType+"/"+connector+"/"+connection+"/",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self[connection]={};for(var length=data&&data.entities?data.entities.length:0,i=0;length>i;i++)"user"===data.entities[i].type?self[connection][data.entities[i].username]=data.entities[i]:self[connection][data.entities[i].name]=data.entities[i];doCallback(callback,[err,data,data.entities],self)})}else if("function"==typeof callback){var error="Error in getConnections - no uuid specified.";self._client.logging&&console.log(error),doCallback(callback,[!0,error],self)}},Usergrid.Entity.prototype.getGroups=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/groups",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self.groups=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Entity.prototype.getActivities=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/activities",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected");for(var entity in data.entities)data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();self.activities=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Entity.prototype.getFollowing=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/following",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user following");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.following=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Entity.prototype.getFollowers=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/followers",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user followers");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.followers=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Client.prototype.createRole=function(roleName,permissions,callback){var options={type:"role",name:roleName};this.createEntity(options,function(err,response,entity){err?doCallback(callback,[err,response,self]):entity.assignPermissions(permissions,function(err,data){err?doCallback(callback,[err,response,self]):doCallback(callback,[err,data,data.data],self)})})},Usergrid.Entity.prototype.getRoles=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/roles",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user roles"),self.roles=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Entity.prototype.assignRole=function(roleName,callback){var entityID,self=this,type=self.get("type"),collection=type+"s";"user"==type&&null!=this.get("username")?entityID=self.get("username"):"group"==type&&null!=this.get("name")?entityID=self.get("name"):null!=this.get("uuid")&&(entityID=self.get("uuid")),"users"!=type&&"groups"!=type&&doCallback(callback,[new UsergridError("entity must be a group or user","invalid_entity_type"),null,this],this);var endpoint="roles/"+roleName+"/"+collection+"/"+entityID,options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,response){err&&console.log("Could not assign role."),doCallback(callback,[err,response,self])})},Usergrid.Entity.prototype.removeRole=function(roleName,callback){var entityID,self=this,type=self.get("type"),collection=type+"s";"user"==type&&null!=this.get("username")?entityID=this.get("username"):"group"==type&&null!=this.get("name")?entityID=this.get("name"):null!=this.get("uuid")&&(entityID=this.get("uuid")),"users"!=type&&"groups"!=type&&doCallback(callback,[new UsergridError("entity must be a group or user","invalid_entity_type"),null,this],this);var endpoint="roles/"+roleName+"/"+collection+"/"+entityID,options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,response){err&&console.log("Could not assign role."),doCallback(callback,[err,response,self])})},Usergrid.Entity.prototype.assignPermissions=function(permissions,callback){var entityID,self=this,type=this.get("type");"user"!=type&&"users"!=type&&"group"!=type&&"groups"!=type&&"role"!=type&&"roles"!=type&&doCallback(callback,[new UsergridError("entity must be a group, user, or role","invalid_entity_type"),null,this],this),"user"==type&&null!=this.get("username")?entityID=this.get("username"):"group"==type&&null!=this.get("name")?entityID=this.get("name"):null!=this.get("uuid")&&(entityID=this.get("uuid"));var endpoint=type+"/"+entityID+"/permissions",options={method:"POST",endpoint:endpoint,body:{permission:permissions}};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not assign permissions"),doCallback(callback,[err,data,data.data],self)})},Usergrid.Entity.prototype.removePermissions=function(permissions,callback){var entityID,self=this,type=this.get("type");"user"!=type&&"users"!=type&&"group"!=type&&"groups"!=type&&"role"!=type&&"roles"!=type&&doCallback(callback,[new UsergridError("entity must be a group, user, or role","invalid_entity_type"),null,this],this),"user"==type&&null!=this.get("username")?entityID=this.get("username"):"group"==type&&null!=this.get("name")?entityID=this.get("name"):null!=this.get("uuid")&&(entityID=this.get("uuid"));var endpoint=type+"/"+entityID+"/permissions",options={method:"DELETE",endpoint:endpoint,qs:{permission:permissions}};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not remove permissions"),doCallback(callback,[err,data,data.params.permission],self)})},Usergrid.Entity.prototype.getPermissions=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/permissions",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user permissions");var permissions=[];if(data.data){var perms=data.data,count=0;for(var i in perms){count++;var perm=perms[i],parts=perm.split(":"),ops_part="",path_part=parts[0];parts.length>1&&(ops_part=parts[0],path_part=parts[1]),ops_part=ops_part.replace("*","get,post,put,delete");var ops=ops_part.split(","),ops_object={};ops_object.get="no",ops_object.post="no",ops_object.put="no",ops_object["delete"]="no";for(var j in ops)ops_object[ops[j]]="yes";permissions.push({operations:ops_object,path:path_part,perm:perm})}}self.permissions=permissions,doCallback(callback,[err,data,data.entities],self)})};var UsergridAuth=function(token,expiry){var self=this;self.token=token,self.expiry=expiry||0;var usingToken=token?!0:!1;return Object.defineProperty(self,"hasToken",{get:function(){return self.token?!0:!1},configurable:!0}),Object.defineProperty(self,"isExpired",{get:function(){return usingToken?!1:Date.now()>=self.expiry},configurable:!0}),Object.defineProperty(self,"isValid",{get:function(){return!self.isExpired&&self.hasToken},configurable:!0}),Object.defineProperty(self,"tokenTtl",{configurable:!0,writable:!0}),_.assign(self,{destroy:function(){self.token=void 0,self.expiry=0,self.tokenTtl=void 0}}),self},UsergridAppAuth=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments);return _.isPlainObject(args[0])?(self.clientId=args[0].clientId,self.clientSecret=args[0].clientSecret,self.tokenTtl=args[0].tokenTtl):(self.clientId=args[0],self.clientSecret=args[1],self.tokenTtl=args[2]),UsergridAuth.call(self),_.assign(self,UsergridAuth),self};UsergridHelpers.inherits(UsergridAppAuth,UsergridAuth);var UsergridUserAuth=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments);return _.isPlainObject(args[0])?(self.username=args[0].username,self.email=args[0].email,self.tokenTtl=args[0].tokenTtl):(self.username=args[0],self.email=args[1],self.tokenTtl=args[2]),UsergridAuth.call(self),_.assign(self,UsergridAuth),self};UsergridHelpers.inherits(UsergridUserAuth,UsergridAuth);var UsergridEntity=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments);if(0===args.length)throw new Error("A UsergridEntity object cannot be initialized without passing one or more arguments");if(_.isPlainObject(args[0])?_.assign(self,args[0]):(self.type=_.isString(args[0])?args[0]:void 0,self.name=_.isString(args[1])?args[1]:void 0),!_.isString(self.type))throw new Error('"type" (or "collection") parameter is required when initializing a UsergridEntity object');return Object.defineProperty(self,"tempAuth",{enumerable:!1,configurable:!0,writable:!0}),Object.defineProperty(self,"isUser",{get:function(){return"user"===self.type.toLowerCase()}}),Object.defineProperty(self,"hasAsset",{get:function(){return _.has(self,"file-metadata")}}),self.asset=void 0,UsergridHelpers.setReadOnly(self,["uuid","name","type","created"]),self};UsergridEntity.prototype={putProperty:function(key,value){this[key]=value},putProperties:function(obj){_.assign(this,obj)},removeProperty:function(key){this.removeProperties([key])},removeProperties:function(keys){var self=this;keys.forEach(function(key){delete self[key]})},insert:function(key,value,idx){_.isArray(this[key])||(this[key]=this[key]?[this[key]]:[]),this[key].splice.apply(this[key],[idx,0].concat(value))},append:function(key,value){this.insert(key,value,Number.MAX_SAFE_INTEGER)},prepend:function(key,value){this.insert(key,value,0)},pop:function(key){_.isArray(this[key])&&this[key].pop()},shift:function(key){_.isArray(this[key])&&this[key].shift()},reload:function(){var args=helpers.args(arguments),client=helpers.client.validate(args),callback=UsergridHelpers.callback(args);client.tempAuth=this.tempAuth,this.tempAuth=void 0,client.GET(this,function(error,usergridResponse){updateEntityFromRemote.call(this,usergridResponse),callback(error,usergridResponse,this)}.bind(this))},save:function(){var args=UsergridHelpers.flattenArgs(arguments),client=Usergrid.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.tempAuth=this.tempAuth,this.tempAuth=void 0,client.PUT(this,function(error,usergridResponse){updateEntityFromRemote.call(this,usergridResponse),callback(error,usergridResponse,this)}.bind(this))},remove:function(){var args=UsergridHelpers.flattenArgs(arguments),client=Usergrid.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.tempAuth=this.tempAuth,this.tempAuth=void 0,client.DELETE(this,function(error,usergridResponse){callback(error,usergridResponse,this)}.bind(this))},attachAsset:function(asset){this.asset=asset},uploadAsset:function(){var args=UsergridHelpers.flattenArgs(arguments),client=Usergrid.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.POST(this,this.asset,function(error,usergridResponse){updateEntityFromRemote.call(this,usergridResponse),callback(error,usergridResponse,this)}.bind(this))},downloadAsset:function(){var args=UsergridHelpers.flattenArgs(arguments),client=Usergrid.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args),self=this;if(_.has(self,"asset.contentType")){var options={client:client,entity:self,type:this.type,method:"GET",encoding:null,headers:{Accept:self.asset.contentType||_.first(args.filter(_.isString))}};return options.uri=helpers.build.uri(client,options),new UsergridRequest(options,function(error,usergridResponse){usergridResponse.ok&&self.attachAsset(new UsergridAsset(new Buffer(usergridResponse.body))),callback(error,usergridResponse,self)})}callback({name:"asset_not_found",description:"The specified entity does not have a valid asset attached"})},connect:function(){var args=UsergridHelpers.flattenArgs(arguments),client=Usergrid.validateAndRetrieveClient(args);return client.tempAuth=this.tempAuth,this.tempAuth=void 0,args[0]=this,client.connect.apply(client,args)},disconnect:function(){var args=UsergridHelpers.flattenArgs(arguments),client=Usergrid.validateAndRetrieveClient(args);return client.tempAuth=this.tempAuth,this.tempAuth=void 0,args[0]=this,client.disconnect.apply(client,args)},getConnections:function(){var args=UsergridHelpers.flattenArgs(arguments),client=Usergrid.validateAndRetrieveClient(args);return client.tempAuth=this.tempAuth,this.tempAuth=void 0,args.shift(),args.splice(1,0,this),client.getConnections.apply(client,args)},usingAuth:function(auth){return this.tempAuth=helpers.client.configureTempAuth(auth),this}},Usergrid.Collection=function(options){if(options&&(this._client=options.client,this._type=options.type,this.qs=options.qs||{},this._list=options.list||[],this._iterator=options.iterator||-1,this._previous=options.previous||[],this._next=options.next||null,this._cursor=options.cursor||null,options.list))for(var count=options.list.length,i=0;count>i;i++){var entity=this._client.restoreEntity(options.list[i]);this._list[i]=entity}},Usergrid.isCollection=function(obj){return obj&&obj instanceof Usergrid.Collection},Usergrid.Collection.prototype.serialize=function(){var data={};data.type=this._type,data.qs=this.qs,data.iterator=this._iterator,data.previous=this._previous,data.next=this._next,data.cursor=this._cursor,this.resetEntityPointer();var i=0;for(data.list=[];this.hasNextEntity();){var entity=this.getNextEntity();data.list[i]=entity.serialize(),i++}return data=JSON.stringify(data)},Usergrid.Collection.prototype.fetch=function(callback){var self=this,qs=this.qs;this._cursor?qs.cursor=this._cursor:delete qs.cursor;var options={method:"GET",endpoint:this._type,qs:this.qs};this._client.request(options,function(err,response){err&&self._client.logging?console.log("error getting collection"):(self.saveCursor(response.cursor||null),self.resetEntityPointer(),self._list=response.getEntities().filter(function(entity){return isUUID(entity.uuid)}).map(function(entity){var ent=new Usergrid.Entity({client:self._client});return ent.set(entity),ent.type=self._type,ent})),doCallback(callback,[err,response,self],self)})},Usergrid.Collection.prototype.addEntity=function(entityObject,callback){var self=this;entityObject.type=this._type,this._client.createEntity(entityObject,function(err,response,entity){err||self.addExistingEntity(entity),doCallback(callback,[err,response,self],self)})},Usergrid.Collection.prototype.addExistingEntity=function(entity){var count=this._list.length;this._list[count]=entity},Usergrid.Collection.prototype.destroyEntity=function(entity,callback){var self=this;entity.destroy(function(err,response){err?(self._client.logging&&console.log("could not destroy entity"),doCallback(callback,[err,response,self],self)):self.fetch(callback),self.removeEntity(entity)})},Usergrid.Collection.prototype.getEntitiesByCriteria=function(criteria){return this._list.filter(criteria)},Usergrid.Collection.prototype.getEntityByCriteria=function(criteria){return this.getEntitiesByCriteria(criteria).shift()},Usergrid.Collection.prototype.removeEntity=function(entity){var removedEntity=this.getEntityByCriteria(function(item){return entity.uuid===item.get("uuid")});return delete this._list[this._list.indexOf(removedEntity)],removedEntity},Usergrid.Collection.prototype.getEntityByUUID=function(uuid,callback){var entity=this.getEntityByCriteria(function(item){return item.get("uuid")===uuid});if(entity)doCallback(callback,[null,entity,entity],this);else{var options={data:{type:this._type,uuid:uuid},client:this._client};entity=new Usergrid.Entity(options),entity.fetch(callback)}},Usergrid.Collection.prototype.getFirstEntity=function(){var count=this._list.length;return count>0?this._list[0]:null},Usergrid.Collection.prototype.getLastEntity=function(){var count=this._list.length;return count>0?this._list[count-1]:null},Usergrid.Collection.prototype.hasNextEntity=function(){var next=this._iterator+1,hasNextElement=next>=0&&next=0&&this._iterator<=this._list.length;return hasNextElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.hasPrevEntity=function(){var previous=this._iterator-1,hasPreviousElement=previous>=0&&previous=0&&this._iterator<=this._list.length;return hasPreviousElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.resetEntityPointer=function(){this._iterator=-1},Usergrid.Collection.prototype.saveCursor=function(cursor){this._next!==cursor&&(this._next=cursor)},Usergrid.Collection.prototype.resetPaging=function(){this._previous=[],this._next=null,this._cursor=null},Usergrid.Collection.prototype.hasNextPage=function(){return this._next},Usergrid.Collection.prototype.getNextPage=function(callback){this.hasNextPage()&&(this._previous.push(this._cursor),this._cursor=this._next,this._list=[],this.fetch(callback))},Usergrid.Collection.prototype.hasPreviousPage=function(){return this._previous.length>0},Usergrid.Collection.prototype.getPreviousPage=function(callback){this.hasPreviousPage()&&(this._next=null,this._cursor=this._previous.pop(),this._list=[],this.fetch(callback))},Usergrid.Group=function(options,callback){this._path=options.path,this._list=[],this._client=options.client,this._data=options.data||{},this._data.type="groups"},Usergrid.Group.prototype=new Usergrid.Entity,Usergrid.Group.prototype.fetch=function(callback){var self=this,groupEndpoint="groups/"+this._path,memberEndpoint="groups/"+this._path+"/users",groupOptions={method:"GET",endpoint:groupEndpoint},memberOptions={method:"GET",endpoint:memberEndpoint};this._client.request(groupOptions,function(err,response){if(err)self._client.logging&&console.log("error getting group"), +doCallback(callback,[err,response],self);else{var entities=response.getEntities();if(entities&&entities.length){entities.shift();self._client.request(memberOptions,function(err,response){err&&self._client.logging?console.log("error getting group users"):self._list=response.getEntities().filter(function(entity){return isUUID(entity.uuid)}).map(function(entity){return new Usergrid.Entity({type:entity.type,client:self._client,uuid:entity.uuid,response:entity})}),doCallback(callback,[err,response,self],self)})}}})},Usergrid.Group.prototype.members=function(callback){return this._list},Usergrid.Group.prototype.add=function(options,callback){var self=this;options.user?(options={method:"POST",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")},this._client.request(options,function(error,response){error?doCallback(callback,[error,response,self],self):self.fetch(callback)})):doCallback(callback,[new UsergridError("no user specified","no_user_specified"),null,this],this)},Usergrid.Group.prototype.remove=function(options,callback){var self=this;options.user?(options={method:"DELETE",endpoint:"groups/"+this._path+"/users/"+options.user.username},this._client.request(options,function(error,response){error?doCallback(callback,[error,response,self],self):self.fetch(callback)})):doCallback(callback,[new UsergridError("no user specified","no_user_specified"),null,this],this)},Usergrid.Group.prototype.feed=function(callback){var self=this,options={method:"GET",endpoint:"groups/"+this._path+"/feed"};this._client.request(options,function(err,response){doCallback(callback,[err,response,self],self)})},Usergrid.Group.prototype.createGroupActivity=function(options,callback){var self=this,user=options.user,entity=new Usergrid.Entity({client:this._client,data:{actor:{displayName:user.get("username"),uuid:user.get("uuid"),username:user.get("username"),email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80}},verb:"post",content:options.content,type:"groups/"+this._path+"/activities"}});entity.save(function(err,response,entity){doCallback(callback,[err,response,self])})},Usergrid.Counter=function(options){this._client=options.client,this._data=options.data||{},this._data.category=options.category||"UNKNOWN",this._data.timestamp=options.timestamp||0,this._data.type="events",this._data.counters=options.counters||{}};var COUNTER_RESOLUTIONS=["all","minute","five_minutes","half_hour","hour","six_day","day","week","month"];Usergrid.Counter.prototype=new Usergrid.Entity,Usergrid.Counter.prototype.fetch=function(callback){this.getData({},callback)},Usergrid.Counter.prototype.increment=function(options,callback){var self=this,name=options.name,value=options.value;return name?isNaN(value)?doCallback(callback,[new UsergridInvalidArgumentError("'value' for increment, decrement must be a number"),null,self],self):(self._data.counters[name]=parseInt(value)||1,self.save(callback)):doCallback(callback,[new UsergridInvalidArgumentError("'name' for increment, decrement must be a number"),null,self],self)},Usergrid.Counter.prototype.decrement=function(options,callback){var self=this,name=options.name,value=options.value;self.increment({name:name,value:-(parseInt(value)||1)},callback)},Usergrid.Counter.prototype.reset=function(options,callback){var self=this,name=options.name;self.increment({name:name,value:0},callback)},Usergrid.Counter.prototype.getData=function(options,callback){var start_time,end_time,start=options.start||0,end=options.end||Date.now(),resolution=(options.resolution||"all").toLowerCase(),counters=options.counters||Object.keys(this._data.counters),res=(resolution||"all").toLowerCase();-1===COUNTER_RESOLUTIONS.indexOf(res)&&(res="all"),start_time=getSafeTime(start),end_time=getSafeTime(end);var self=this,params=Object.keys(counters).map(function(counter){return["counter",encodeURIComponent(counters[counter])].join("=")});params.push("resolution="+res),params.push("start_time="+String(start_time)),params.push("end_time="+String(end_time));var endpoint="counters?"+params.join("&");this._client.request({endpoint:endpoint},function(err,data){return data.counters&&data.counters.length&&data.counters.forEach(function(counter){self._data.counters[counter.name]=counter.value||counter.values}),doCallback(callback,[err,data,self],self)})},Usergrid.Folder=function(options,callback){var self=this;console.log("FOLDER OPTIONS",options),self._client=options.client,self._data=options.data||{},self._data.type="folders";var missingData=["name","owner","path"].some(function(required){return!(required in self._data)});return missingData?doCallback(callback,[new UsergridInvalidArgumentError("Invalid asset data: 'name', 'owner', and 'path' are required properties."),null,self],self):void self.save(function(err,response){err?doCallback(callback,[new UsergridError(response),response,self],self):(response&&response.entities&&response.entities.length&&self.set(response.entities[0]),doCallback(callback,[null,response,self],self))})},Usergrid.Folder.prototype=new Usergrid.Entity,Usergrid.Folder.prototype.fetch=function(callback){var self=this;Usergrid.Entity.prototype.fetch.call(self,function(err,data){console.log("self",self.get()),console.log("data",data),err?doCallback(callback,[null,data,self],self):self.getAssets(function(err,response){err?doCallback(callback,[new UsergridError(response),resonse,self],self):doCallback(callback,[null,self],self)})})},Usergrid.Folder.prototype.addAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset,asset instanceof Usergrid.Entity||(asset=new Usergrid.Asset(asset));break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}asset&&asset instanceof Usergrid.Entity&&asset.fetch(function(err,data){if(err)doCallback(callback,[new UsergridError(data),data,self],self);else{var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/"),options={method:"POST",endpoint:endpoint};self._client.request(options,callback)}})}else doCallback(callback,[new UsergridInvalidArgumentError("No asset specified"),null,self],self)},Usergrid.Folder.prototype.removeAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset;break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}if(asset&&null!==asset){var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/");self._client.request({method:"DELETE",endpoint:endpoint},function(err,response){err?doCallback(callback,[new UsergridError(response),response,self],self):doCallback(callback,[null,response,self],self)})}}else doCallback(callback,[new UsergridInvalidArgumentError("No asset specified"),null,self],self)},Usergrid.Folder.prototype.getAssets=function(callback){return this.getConnections("assets",callback)};var UsergridResponseError=function(responseErrorObject){var self=this;if(_.has(responseErrorObject,"error")!==!1)return self.name=responseErrorObject.error,self.description=responseErrorObject.error_description||responseErrorObject.description,self.exception=responseErrorObject.exception,self},UsergridResponse=function(request){var p=new Promise,self=this;if(self.ok=!1,request){self.statusCode=parseInt(request.status);var responseJSON;try{var responseText=request.responseText;responseJSON=JSON.parse(responseText)}catch(e){responseJSON={}}if(self.statusCode<400){if(self.ok=!0,_.has(responseJSON,"entities")){var entities=responseJSON.entities.map(function(en){var entity=new UsergridEntity(en);return entity.isUser&&(entity=new UsergridUser(entity)),entity});_.assign(self,{metadata:_.cloneDeep(responseJSON),entities:entities}),delete self.metadata.entities,self.first=_.first(entities)||void 0,self.entity=self.first,self.last=_.last(entities)||void 0,"/users"===_.get(self,"metadata.path")&&(self.user=self.first,self.users=self.entities),Object.defineProperty(self,"hasNextPage",{get:function(){return _.has(self,"metadata.cursor")}}),UsergridHelpers.setReadOnly(self.metadata)}}else _.assign(self,{error:new UsergridResponseError(responseJSON)});return this.success?p.done(this):p.done(this),p}};UsergridResponse.prototype={loadNextPage:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args);self.metadata.cursor||callback();var client=Usergrid.validateAndRetrieveClient(args),type=_.last(_.get(self,"metadata.path").split("/")),limit=_.first(_.get(this,"metadata.params.limit")),query=new UsergridQuery(type).cursor(this.metadata.cursor).limit(limit);return client.GET(query,callback)}},XMLHttpRequest.prototype.sendAsBinary||(XMLHttpRequest.prototype.sendAsBinary=function(sData){for(var nBytes=sData.length,ui8Data=new Uint8Array(nBytes),nIdx=0;nBytes>nIdx;nIdx++)ui8Data[nIdx]=255&sData.charCodeAt(nIdx);this.send(ui8Data)}),Usergrid.Asset=function(options,callback){var self=this;self._client=options.client,self._data=options.data||{},self._data.type="assets";var missingData=["name","owner","path"].some(function(required){return!(required in self._data)});missingData?doCallback(callback,[new UsergridError("Invalid asset data: 'name', 'owner', and 'path' are required properties."),null,self],self):self.save(function(err,data){err?doCallback(callback,[new UsergridError(data),data,self],self):(data&&data.entities&&data.entities.length&&self.set(data.entities[0]),doCallback(callback,[null,data,self],self))})},Usergrid.Asset.prototype=new Usergrid.Entity,Usergrid.Asset.prototype.addToFolder=function(options,callback){var self=this;if("folder"in options&&isUUID(options.folder)){Usergrid.Folder({uuid:options.folder},function(err,folder){if(err)doCallback(callback,[UsergridError.fromResponse(folder),folder,self],self);else{var endpoint=["folders",folder.get("uuid"),"assets",self.get("uuid")].join("/"),options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,response){err?doCallback(callback,[UsergridError.fromResponse(folder),response,self],self):doCallback(callback,[null,folder,self],self)})}})}else doCallback(callback,[new UsergridError("folder not specified"),null,self],self)},Usergrid.Entity.prototype.attachAsset=function(file,callback){if(!(window.File&&window.FileReader&&window.FileList&&window.Blob))return void doCallback(callback,[new UsergridError("The File APIs are not fully supported by your browser."),null,this],this);var self=this,args=arguments,type=this._data.type,attempts=self.get("attempts");if(isNaN(attempts)&&(attempts=3),"assets"!=type&&"asset"!=type)var endpoint=[this._client.clientAppURL,type,self.get("uuid")].join("/");else{self.set("content-type",file.type),self.set("size",file.size);var endpoint=[this._client.clientAppURL,"assets",self.get("uuid"),"data"].join("/")}var xhr=new XMLHttpRequest;xhr.open("POST",endpoint,!0),xhr.onerror=function(err){doCallback(callback,[new UsergridError("The File APIs are not fully supported by your browser.")],xhr,self)},xhr.onload=function(ev){xhr.status>=500&&attempts>0?(self.set("attempts",--attempts),setTimeout(function(){self.attachAsset.apply(self,args)},100)):xhr.status>=300?(self.set("attempts"),doCallback(callback,[new UsergridError(JSON.parse(xhr.responseText)),xhr,self],self)):(self.set("attempts"),self.fetch(),doCallback(callback,[null,xhr,self],self))};var fr=new FileReader;fr.onload=function(){var binary=fr.result;("assets"===type||"asset"===type)&&(xhr.overrideMimeType("application/octet-stream"),xhr.setRequestHeader("Content-Type","application/octet-stream")),xhr.sendAsBinary(binary)},fr.readAsBinaryString(file)},Usergrid.Asset.prototype.upload=function(data,callback){this.attachAsset(data,function(err,response){err?doCallback(callback,[new UsergridError(err),response,self],self):doCallback(callback,[null,response,self],self)})},Usergrid.Entity.prototype.downloadAsset=function(callback){var endpoint,self=this,type=this._data.type,xhr=new XMLHttpRequest;endpoint="assets"!=type&&"asset"!=type?[this._client.clientAppURL,type,self.get("uuid")].join("/"):[this._client.clientAppURL,"assets",self.get("uuid"),"data"].join("/"),xhr.open("GET",endpoint,!0),xhr.responseType="blob",xhr.onload=function(ev){var blob=xhr.response;"assets"!=type&&"asset"!=type?doCallback(callback,[null,blob,xhr],self):doCallback(callback,[null,xhr,self],self)},xhr.onerror=function(err){callback(!0,err),doCallback(callback,[new UsergridError(err),xhr,self],self)},"assets"!=type&&"asset"!=type?xhr.setRequestHeader("Accept",self._data["file-metadata"]["content-type"]):xhr.overrideMimeType(self.get("content-type")),xhr.send()},Usergrid.Asset.prototype.download=function(callback){this.downloadAsset(function(err,response){err?doCallback(callback,[new UsergridError(err),response,self],self):doCallback(callback,[null,response,self],self)})},function(global){function UsergridError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridHTTPResponseError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidHTTPMethodError(message,name,timestamp,duration,exception){this.message=message,this.name=name||"invalid_http_method",this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidURIError(message,name,timestamp,duration,exception){this.message=message,this.name=name||"invalid_uri",this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidArgumentError(message,name,timestamp,duration,exception){this.message=message,this.name=name||"invalid_argument",this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridKeystoreDatabaseUpgradeNeededError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}var short,name="UsergridError",_name=global[name],_short=short&&void 0!==short?global[short]:void 0;return UsergridError.prototype=new Error,UsergridError.prototype.constructor=UsergridError,UsergridError.fromResponse=function(response){return response&&"undefined"!=typeof response?new UsergridError(response.error_description,response.error,response.timestamp,response.duration,response.exception):new UsergridError},UsergridError.createSubClass=function(name){return name in global&&global[name]?global[name]:(global[name]=function(){},global[name].name=name,global[name].prototype=new UsergridError,global[name])},UsergridHTTPResponseError.prototype=new UsergridError,UsergridInvalidHTTPMethodError.prototype=new UsergridError,UsergridInvalidURIError.prototype=new UsergridError,UsergridInvalidArgumentError.prototype=new UsergridError,UsergridKeystoreDatabaseUpgradeNeededError.prototype=new UsergridError,global.UsergridHTTPResponseError=UsergridHTTPResponseError,global.UsergridInvalidHTTPMethodError=UsergridInvalidHTTPMethodError,global.UsergridInvalidURIError=UsergridInvalidURIError,global.UsergridInvalidArgumentError=UsergridInvalidArgumentError,global.UsergridKeystoreDatabaseUpgradeNeededError=UsergridKeystoreDatabaseUpgradeNeededError,global[name]=UsergridError,void 0!==short&&(global[short]=UsergridError),global[name].noConflict=function(){return _name&&(global[name]=_name),void 0!==short&&(global[short]=_short),UsergridError},global[name]}(this); \ No newline at end of file From 15a315aab85e8b53bb9aca9403470c2ecfee7260 Mon Sep 17 00:00:00 2001 From: Robert Walsh Date: Mon, 3 Oct 2016 19:14:06 -0500 Subject: [PATCH 08/36] Lots of updates and fixes. The Javascript files that start with Usergrid are currently being worked on and will be used in production. All other files are there just for now. --- Gruntfile.js | 12 +- lib/Usergrid.js | 136 +- lib/modules/Client.js | 205 +- lib/modules/UsergridClient.js | 188 ++ lib/modules/UsergridEntity.js | 85 +- lib/modules/{Enums.js => UsergridEnums.js} | 14 + lib/modules/{Query.js => UsergridQuery.js} | 44 +- .../{request.js => UsergridRequest.js} | 9 +- .../{Response.js => UsergridResponse.js} | 34 +- lib/modules/UsergridUser.js | 68 +- .../util/{Helpers.js => UsergridHelpers.js} | 101 +- tests/mocha/index.html | 3 +- tests/mocha/test.js | 1947 ++++++++--------- tests/mocha/test_entity.js | 309 +++ usergrid.js | 760 ++++--- usergrid.min.js | 8 +- 16 files changed, 2249 insertions(+), 1674 deletions(-) create mode 100644 lib/modules/UsergridClient.js rename lib/modules/{Enums.js => UsergridEnums.js} (53%) rename lib/modules/{Query.js => UsergridQuery.js} (76%) rename lib/modules/{request.js => UsergridRequest.js} (87%) rename lib/modules/{Response.js => UsergridResponse.js} (75%) rename lib/modules/util/{Helpers.js => UsergridHelpers.js} (75%) create mode 100644 tests/mocha/test_entity.js diff --git a/Gruntfile.js b/Gruntfile.js index d57a750..df2bb7d 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -1,24 +1,26 @@ module.exports = function(grunt) { var files = [ - "lib/modules/Enums.js", + "lib/modules/UsergridEnums.js", "lib/modules/util/Event.js", "lib/modules/util/Logger.js", "lib/modules/util/Promise.js", "lib/modules/util/Ajax.js", "lib/modules/util/lodash.js", - "lib/modules/util/Helpers.js", - "lib/modules/Query.js", + "lib/modules/util/UsergridHelpers.js", + "lib/modules/UsergridQuery.js", "lib/Usergrid.js", + "lib/modules/UsergridClient.js", "lib/modules/Client.js", - "lib/modules/request.js", + "lib/modules/UsergridRequest.js", "lib/modules/Entity.js", "lib/modules/Auth.js", "lib/modules/UsergridEntity.js", + "lib/modules/UsergridUser.js", "lib/modules/Collection.js", "lib/modules/Group.js", "lib/modules/Counter.js", "lib/modules/Folder.js", - "lib/modules/Response.js", + "lib/modules/UsergridResponse.js", "lib/modules/Asset.js", "lib/modules/Error.js" ]; diff --git a/lib/Usergrid.js b/lib/Usergrid.js index 6e6b05a..1a7bbca 100644 --- a/lib/Usergrid.js +++ b/lib/Usergrid.js @@ -186,7 +186,7 @@ function doCallback(callback, params, context) { console.warn("TRYING TO INITIALIZING SHARED INSTANCE") if( !this.isInitialized ) { console.warn("INITIALIZING SHARED INSTANCE") - this.__sharedInstance = new Usergrid.Client(options) + this.__sharedInstance = new UsergridClient(options) this.isInitialized = true } return this.__sharedInstance @@ -203,8 +203,8 @@ function doCallback(callback, params, context) { Usergrid.validateAndRetrieveClient = function(args) { var client = undefined; - if (args instanceof Usergrid.Client) { client = args } - else if (args[0] instanceof Usergrid.Client) { client = args[0] } + if (args instanceof UsergridClient) { client = args } + else if (args[0] instanceof UsergridClient) { client = args[0] } else if (Usergrid.isInitialized) { client = Usergrid.getInstance() } else { throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument") } return client @@ -214,136 +214,6 @@ function doCallback(callback, params, context) { return Date.now() + ((expires_in ? expires_in - 5 : 0) * 1000) }; - - Usergrid.Request = function(method, endpoint, query_params, data, callback) { - var p = new Promise(); - /* - Create a logger - */ - this.logger = new global.Logger("Usergrid.Request"); - this.logger.time("process request " + method + " " + endpoint); - /* - Validate our input - */ - this.endpoint = endpoint + '?' + encodeParams(query_params); - this.method = method.toUpperCase(); - //this.query_params = query_params; - this.data = ("object" === typeof data) ? JSON.stringify(data) : data; - - if (VALID_REQUEST_METHODS.indexOf(this.method) === -1) { - throw new UsergridInvalidHTTPMethodError("invalid request method '" + this.method + "'"); - } - - /* - Prepare our request - */ - if (!isValidUrl(this.endpoint)) { - this.logger.error(endpoint, this.endpoint, /^https:\/\//.test(endpoint)); - throw new UsergridInvalidURIError("The provided endpoint is not valid: " + this.endpoint); - } - - /* a callback to make the request */ - var request = function() { - return new UsergridRequest({method:this.method,uri:this.endpoint,body:this.data}) - // return Ajax.request(this.method, this.endpoint, this.data) - }.bind(this); - - /* a callback to process the response */ - var response = function(request) { - return new UsergridResponse(request) - }.bind(this); - - /* a callback to clean up and return data to the client */ - var oncomplete = function(response) { - p.done(response); - // this.logger.info("REQUEST", response); - doCallback(callback, [response]); - // this.logger.timeEnd("process request " + method + " " + endpoint); - }.bind(this); - - /* and a promise to chain them all together */ - Promise.chain([request, response]).then(oncomplete); - - return p; - }; - //TODO more granular handling of statusCodes - Usergrid.Response = function(err, response) { - var p = new Promise(); - var data = null; - try { - data = JSON.parse(response.responseText); - } catch (e) { - //this.logger.error("Error parsing response text: ",this.text); - //this.logger.error("Caught error ", e.message); - data = {} - } - Object.keys(data).forEach(function(key) { - Object.defineProperty(this, key, { - value: data[key], - enumerable: true - }); - }.bind(this)); - Object.defineProperty(this, "logger", { - enumerable: false, - configurable: false, - writable: false, - value: new global.Logger(name) - }); - Object.defineProperty(this, "success", { - enumerable: false, - configurable: false, - writable: true, - value: true - }); - Object.defineProperty(this, "err", { - enumerable: false, - configurable: false, - writable: true, - value: err - }); - Object.defineProperty(this, "status", { - enumerable: false, - configurable: false, - writable: true, - value: parseInt(response.status) - }); - Object.defineProperty(this, "statusGroup", { - enumerable: false, - configurable: false, - writable: true, - value: (this.status - this.status % 100) - }); - switch (this.statusGroup) { - case 200: //success - this.success = true; - break; - case 400: //user error - case 500: //server error - case 300: //cache and redirects - case 100: //upgrade - default: - //server error - this.success = false; - break; - } - if (this.success) { - p.done(null, this); - } else { - p.done(UsergridError.fromResponse(data), this); - } - return p; - }; - Usergrid.Response.prototype.getEntities = function() { - var entities; - if (this.success) { - entities = (this.data) ? this.data.entities : this.entities; - } - return entities || []; - } - Usergrid.Response.prototype.getEntity = function() { - var entities = this.getEntities(); - return entities[0]; - } Usergrid.VERSION = Usergrid.USERGRID_SDK_VERSION = '0.11.0'; global[name] = Usergrid; diff --git a/lib/modules/Client.js b/lib/modules/Client.js index 9d18ba8..a5b5c02 100644 --- a/lib/modules/Client.js +++ b/lib/modules/Client.js @@ -46,7 +46,7 @@ var defaultOptions = { self.clientAppURL = [self.baseUrl, self.orgId, self.appId].join("/"); self.isSharedInstance = false; self.currentUser = undefined; - + self.__appAuth = undefined; Object.defineProperty(self, 'appAuth', { get: function() { @@ -72,92 +72,118 @@ var defaultOptions = { this.logging = options.logging || false; }; - /* - * Main function for making requests to the API. Can be called directly. - * - * options object: - * `method` - http method (GET, POST, PUT, or DELETE), defaults to GET - * `qs` - object containing querystring values to be appended to the uri - * `body` - object containing entity body for POST and PUT requests - * `endpoint` - API endpoint, for example 'users/fred' - * `mQuery` - boolean, set to true if running management query, defaults to false - * - * @method request - * @public - * @params {object} options - * @param {function} callback - * @return {callback} callback(err, data) - */ - Usergrid.Client.prototype.request = function(options, callback) { - var method = options.method || 'GET'; - var endpoint = options.endpoint; - var body = options.body || {}; - var qs = options.qs || {}; - var mQuery = options.mQuery || false; //is this a query to the management endpoint? - var orgId = this.get('orgId'); - var appId = this.get('appId'); - var default_qs = this.getObject('default_qs'); - var uri; - /*var logoutCallback=function(){ - if (typeof(this.logoutCallback) === 'function') { - return this.logoutCallback(true, 'no_org_or_app_name_specified'); - } - }.bind(this);*/ - if (!mQuery && !orgId && !appId) { - return logoutCallback(); - } - if (mQuery) { - uri = this.baseUrl + '/' + endpoint; - } else { - uri = this.baseUrl + '/' + orgId + '/' + appId + '/' + endpoint; - } - if (this.getToken()) { - qs.access_token = this.getToken(); - /* - **NOTE** The token can also be passed as a header on the request - - xhr.setRequestHeader("Authorization", "Bearer " + self.getToken()); - xhr.withCredentials = true; - */ - } - if (default_qs) { - qs = propCopy(qs, default_qs); - } - var self=this; - var req = new Usergrid.Request(method, uri, qs, body, function(response) { - /*if (AUTH_ERRORS.indexOf(response.error) !== -1) { - return logoutCallback(); - }*/ - doCallback(callback, [response, self], self); - //p.done(err, response); - }); - }; - - /* - * function for building asset urls - * - * @method buildAssetURL - * @public - * @params {string} uuid - * @return {string} assetURL - */ - Usergrid.Client.prototype.buildAssetURL = function(uuid) { - var self = this; - var qs = {}; - var assetURL = this.baseUrl + '/' + this.orgId + '/' + this.appId + '/assets/' + uuid + '/data'; - - if (self.getToken()) { - qs.access_token = self.getToken(); - } - - //append params to the path - var encoded_params = encodeParams(qs); - if (encoded_params) { - assetURL += "?" + encoded_params; - } - - return assetURL; - }; + // Usergrid.Client.prototype.request = function(options, callback) { + // var self = this; + // var method = options.method || 'GET'; + // var uri = UsergridHelpers.urljoin(this.baseUrl,self.orgId,self.appId,options.endpoint); + // var qs = options.qs || {}; + // var body = options.body || {}; + // + // var request = function() { + // return new UsergridRequest({ method:method, uri:uri, body:body, qs:qs }); + // }.bind(this); + // + // var response = function(request) { + // return new UsergridResponse(request); + // }.bind(self); + // + // var p = new Promise(); + // var onComplete = function(response) { + // p.done(response); + // doCallback(callback, [response]); + // }.bind(self); + // + // /* and a promise to chain them all together */ + // Promise.chain([request, response]).then(onComplete); + // return p; + // }; + // + // Usergrid.Client.prototype.performRequest = function(request, callback) { + // var self = this; + // var requestFunc = function() { + // return request + // }.bind(this); + // + // var response = function(createdRequest) { + // return new UsergridResponse(createdRequest); + // }.bind(self); + // + // var p = new Promise(); + // var onComplete = function (response) { + // p.done(response); + // doCallback(callback, [response]); + // }.bind(self); + // + // /* and a promise to chain them all together */ + // Promise.chain([requestFunc,response]).then(onComplete); + // return p; + // }; + // + // Usergrid.Client.prototype.GET = function(options, callback) { + // var self = this; + // return self.performRequest(new UsergridRequest({ + // method: UsergridHttpMethod.GET, + // uri: UsergridHelpers.urljoin(self.baseUrl, self.orgId, self.appId, options.endpoint), + // qs: options.qs || {}, + // body: options.body || {} + // }), callback) + // }; + // + // Usergrid.Client.prototype.PUT = function(options, callback) { + // var self = this; + // return self.performRequest(new UsergridRequest({ + // method: UsergridHttpMethod.PUT, + // uri: UsergridHelpers.urljoin(self.baseUrl, self.orgId, self.appId, options.endpoint), + // qs: options.qs || {}, + // body: options.body || {} + // }), callback) + // }; + // + // Usergrid.Client.prototype.POST = function(options, callback) { + // var self = this; + // return self.performRequest(new UsergridRequest({ + // method: UsergridHttpMethod.POST, + // uri: UsergridHelpers.urljoin(self.baseUrl, self.orgId, self.appId, options.endpoint), + // qs: options.qs || {}, + // body: options.body || {} + // }), callback) + // }; + // + // Usergrid.Client.prototype.DELETE = function(options, callback) { + // var self = this; + // return self.performRequest(new UsergridRequest({ + // method: UsergridHttpMethod.DELETE, + // uri: UsergridHelpers.urljoin(self.baseUrl, self.orgId, self.appId, options.endpoint), + // qs: options.qs || {}, + // body: options.body || {} + // }), callback) + // }; + // + // /* + // * function for building asset urls + // * + // * @method buildAssetURL + // * @public + // * @params {string} uuid + // * @return {string} assetURL + // */ + // Usergrid.Client.prototype.buildAssetURL = function(uuid) { + // var self = this; + // var qs = {}; + // var assetURL = this.baseUrl + '/' + this.orgId + '/' + this.appId + '/assets/' + uuid + '/data'; + // + // if (self.getToken()) { + // qs.access_token = self.getToken(); + // } + // + // //append params to the path + // var encoded_params = encodeParams(qs); + // if (encoded_params) { + // assetURL += "?" + encoded_params; + // } + // + // return assetURL; + // }; /* * Main function for creating new groups. Call this directly. @@ -191,10 +217,7 @@ var defaultOptions = { * @return {callback} callback(err, data) */ Usergrid.Client.prototype.createEntity = function(options, callback) { - var entity = new Usergrid.Entity({ - client: this, - data: options - }); + var entity = new UsergridEntity(options); entity.save(function(err, response) { doCallback(callback, [err, response, entity], entity); }); diff --git a/lib/modules/UsergridClient.js b/lib/modules/UsergridClient.js new file mode 100644 index 0000000..33f5ae2 --- /dev/null +++ b/lib/modules/UsergridClient.js @@ -0,0 +1,188 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +'use strict' + +var defaultOptions = { + baseUrl: 'https://api.usergrid.com', + authMode: UsergridAuthMode.USER +} + +var UsergridClient = function(options) { + var self = this + + var __appAuth + self.tempAuth = undefined + self.isSharedInstance = false + + if (arguments.length === 2) { + self.orgId = arguments[0] + self.appId = arguments[1] + } + + _.defaults(self, options, defaultOptions) + + if (!self.orgId || !self.appId) { + throw new Error('"orgId" and "appId" parameters are required when instantiating UsergridClient') + } + + Object.defineProperty(self, 'clientId', { + enumerable: false + }) + + Object.defineProperty(self, 'clientSecret', { + enumerable: false + }) + + Object.defineProperty(self, 'appAuth', { + get: function() { + return __appAuth + }, + set: function(options) { + if (options instanceof UsergridAppAuth) { + __appAuth = options + } else if (typeof options !== "undefined") { + __appAuth = new UsergridAppAuth(options) + } + } + }) + + // if client ID and secret are defined on initialization, initialize appAuth + if (self.clientId && self.clientSecret) { + self.setAppAuth(self.clientId, self.clientSecret) + } + return self +} + +UsergridClient.prototype = { + performRequest: function(request,callback) { + var self = this; + + var requestPromise = function() { + return request + }.bind(self); + + var responsePromise = function(xmlRequest) { + return new UsergridResponse(xmlRequest); + }.bind(self); + + var p = new Promise(); + var onComplete = function(response) { + p.done(response); + doCallback(callback, [response]); + }.bind(self); + + /* and a promise to chain them all together */ + Promise.chain([requestPromise, responsePromise]).then(onComplete); + return p; + }, + GET: function(options,callback) { + var self = this; + return self.performRequest(new UsergridRequest({ client:self, + method:UsergridHttpMethod.GET, + uri:UsergridHelpers.uri(self,UsergridHttpMethod.GET,options), + query:(options instanceof UsergridQuery ? options : options.query), + body:UsergridHelpers.body(options) }), callback) + }, + PUT: function(options,callback) { + var self = this; + return self.performRequest(new UsergridRequest({ client:self, + method:UsergridHttpMethod.PUT, + uri:UsergridHelpers.uri(self,UsergridHttpMethod.PUT,options), + query:(options instanceof UsergridQuery ? options : options.query), + body:UsergridHelpers.body(options) }), callback) + }, + POST: function(options,callback) { + var self = this; + return self.performRequest(new UsergridRequest({client:self, + method:UsergridHttpMethod.POST, + uri:UsergridHelpers.uri(self,UsergridHttpMethod.POST,options), + query:(options instanceof UsergridQuery ? options : options.query), + body:UsergridHelpers.body(options)}), callback) + }, + DELETE: function(options,callback) { + var self = this; + return self.performRequest(new UsergridRequest({client:self, + method:UsergridHttpMethod.DELETE, + uri:UsergridHelpers.uri(self,UsergridHttpMethod.DELETE,options), + query:(options instanceof UsergridQuery ? options : options.query), + body:UsergridHelpers.body(options)}), callback) + }, + connect: function() { + var self = this; + return self.performRequest(new UsergridRequest({client:self, + method:UsergridHttpMethod.POST, + uri:UsergridHelpers.uri(self,UsergridHttpMethod.POST,options), + query:(options instanceof UsergridQuery ? options : options.query), + body:UsergridHelpers.body(options)}), callback) + }, + disconnect: function() { + return this.request(new UsergridRequest(helpers.build.connection(this, 'DELETE', helpers.args(arguments)))) + }, + getConnections: function() { + return this.request(new UsergridRequest(helpers.build.getConnections(this, helpers.args(arguments)))) + }, + setAppAuth: function() { + this.appAuth = new UsergridAppAuth(helpers.args(arguments)) + }, + authenticateApp: function(options) { + var self = this + var callback = helpers.cb(helpers.args(arguments)) + console.log(self.appAuth)//, self.appAuth, new UsergridAppAuth(options), new UsergridAppAuth(self.clientId, self.clientSecret)) + var auth = _.first([options, self.appAuth, new UsergridAppAuth(options), new UsergridAppAuth(self.clientId, self.clientSecret)].filter(function(p) { + return p instanceof UsergridAppAuth + })) + + if (!(auth instanceof UsergridAppAuth)) { + throw new Error('App auth context was not defined when attempting to call .authenticateApp()') + } else if (!auth.clientId || !auth.clientSecret) { + throw new Error('authenticateApp() failed because clientId or clientSecret are missing') + } + + self.performRequest(new UsergridRequest({ + client: self, + path: 'token', + method: 'POST', + body: UsergridHelpers.appLoginBody(auth) + }, function(usergridResponse) { + if (usergridResponse.ok) { + if (!self.appAuth) { + self.appAuth = auth + } + self.appAuth.token = usergridResponse.responseJSON.access_token + self.appAuth.expiry = UsergridHelpers.expiry(body.expires_in) + self.appAuth.tokenTtl = usergridResponse.responseJSON.expires_in + } + callback(error, usergridResponse, usergridResponse.responseJSON.access_token) + })) + }, + authenticateUser: function(options) { + var self = this + var args = helpers.args(arguments) + var callback = helpers.cb(args) + var setAsCurrentUser = (_.last(args.filter(_.isBoolean))) !== undefined ? _.last(args.filter(_.isBoolean)) : true + var UsergridUser = require('./user') + var currentUser = new UsergridUser(options) + currentUser.login(self, function(error, usergridResponse, token) { + if (usergridResponse.ok && setAsCurrentUser) { + self.currentUser = currentUser + } + callback(error, usergridResponse, token) + }) + }, + usingAuth: function(auth) { + this.tempAuth = helpers.client.configureTempAuth(auth) + return this + } +} \ No newline at end of file diff --git a/lib/modules/UsergridEntity.js b/lib/modules/UsergridEntity.js index 6853522..aa6d3b9 100644 --- a/lib/modules/UsergridEntity.js +++ b/lib/modules/UsergridEntity.js @@ -1,3 +1,19 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +'use strict'; + function updateEntityFromRemote(usergridResponse) { UsergridHelpers.setWritable(this, ['uuid', 'name', 'type', 'created']) _.assign(this, usergridResponse.entity) @@ -12,23 +28,23 @@ var UsergridEntity = function() { throw new Error('A UsergridEntity object cannot be initialized without passing one or more arguments') } + self.asset = undefined; + if (_.isPlainObject(args[0])) { _.assign(self, args[0]) } else { - self.type = _.isString(args[0]) ? args[0] : undefined - self.name = _.isString(args[1]) ? args[1] : undefined + if( !self.type ) { + self.type = _.isString(args[0]) ? args[0] : undefined + } + if( !self.name ) { + self.name = _.isString(args[1]) ? args[1] : undefined + } } if (!_.isString(self.type)) { throw new Error('"type" (or "collection") parameter is required when initializing a UsergridEntity object') } - Object.defineProperty(self, 'tempAuth', { - enumerable: false, - configurable: true, - writable: true - }) - Object.defineProperty(self, 'isUser', { get: function() { return (self.type.toLowerCase() === 'user') @@ -41,14 +57,19 @@ var UsergridEntity = function() { } }) - self.asset = undefined - UsergridHelpers.setReadOnly(self, ['uuid', 'name', 'type', 'created']) return self } UsergridEntity.prototype = { + jsonValue: function() { + var jsonValue = {}; + _.forOwn(this, function(value,key) { + jsonValue[key] = value + }); + return jsonValue + }, putProperty: function(key, value) { this[key] = value }, @@ -93,9 +114,9 @@ UsergridEntity.prototype = { client.tempAuth = this.tempAuth this.tempAuth = undefined - client.GET(this, function(error, usergridResponse) { + client.GET(this, function(usergridResponse) { updateEntityFromRemote.call(this, usergridResponse) - callback(error, usergridResponse, this) + callback(usergridResponse, this) }.bind(this)) }, save: function() { @@ -103,22 +124,26 @@ UsergridEntity.prototype = { var client = Usergrid.validateAndRetrieveClient(args) var callback = UsergridHelpers.callback(args) - client.tempAuth = this.tempAuth - this.tempAuth = undefined - client.PUT(this, function(error, usergridResponse) { - updateEntityFromRemote.call(this, usergridResponse) - callback(error, usergridResponse, this) - }.bind(this)) + var uuid = this.uuid + if( uuid === undefined ) { + client.POST(this,function(usergridResponse) { + updateEntityFromRemote.call(this, usergridResponse) + callback(usergridResponse, this) + }.bind(this)) + } else { + client.PUT(this, function(usergridResponse) { + updateEntityFromRemote.call(this, usergridResponse) + callback(usergridResponse, this) + }.bind(this)) + } }, remove: function() { var args = UsergridHelpers.flattenArgs(arguments) var client = Usergrid.validateAndRetrieveClient(args) var callback = UsergridHelpers.callback(args) - client.tempAuth = this.tempAuth - this.tempAuth = undefined - client.DELETE(this, function(error, usergridResponse) { - callback(error, usergridResponse, this) + client.DELETE(this, function(usergridResponse) { + callback(usergridResponse, this) }.bind(this)) }, attachAsset: function(asset) { @@ -128,9 +153,9 @@ UsergridEntity.prototype = { var args = UsergridHelpers.flattenArgs(arguments) var client = Usergrid.validateAndRetrieveClient(args) var callback = UsergridHelpers.callback(args) - client.POST(this, this.asset, function(error, usergridResponse) { + client.POST(this, this.asset, function(usergridResponse) { updateEntityFromRemote.call(this, usergridResponse) - callback(error, usergridResponse, this) + callback(usergridResponse, this) }.bind(this)) }, downloadAsset: function() { @@ -151,7 +176,7 @@ UsergridEntity.prototype = { } } options.uri = helpers.build.uri(client, options) // FIXME!!!! - return new UsergridRequest(options, function(error, usergridResponse) { + return new UsergridRequest(options, function(usergridResponse) { if (usergridResponse.ok) { self.attachAsset(new UsergridAsset(new Buffer(usergridResponse.body))) } @@ -167,30 +192,20 @@ UsergridEntity.prototype = { connect: function() { var args = UsergridHelpers.flattenArgs(arguments) var client = Usergrid.validateAndRetrieveClient(args) - client.tempAuth = this.tempAuth - this.tempAuth = undefined args[0] = this return client.connect.apply(client, args) }, disconnect: function() { var args = UsergridHelpers.flattenArgs(arguments) var client = Usergrid.validateAndRetrieveClient(args) - client.tempAuth = this.tempAuth - this.tempAuth = undefined args[0] = this return client.disconnect.apply(client, args) }, getConnections: function() { var args = UsergridHelpers.flattenArgs(arguments) var client = Usergrid.validateAndRetrieveClient(args) - client.tempAuth = this.tempAuth - this.tempAuth = undefined args.shift() args.splice(1, 0, this) return client.getConnections.apply(client, args) - }, - usingAuth: function(auth) { - this.tempAuth = helpers.client.configureTempAuth(auth) - return this } } \ No newline at end of file diff --git a/lib/modules/Enums.js b/lib/modules/UsergridEnums.js similarity index 53% rename from lib/modules/Enums.js rename to lib/modules/UsergridEnums.js index 786e2a5..c86f8a0 100644 --- a/lib/modules/Enums.js +++ b/lib/modules/UsergridEnums.js @@ -1,3 +1,17 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + var UsergridAuthMode = Object.freeze({ NONE: "none", USER: "user", diff --git a/lib/modules/Query.js b/lib/modules/UsergridQuery.js similarity index 76% rename from lib/modules/Query.js rename to lib/modules/UsergridQuery.js index 1cbb81a..dd92f11 100644 --- a/lib/modules/Query.js +++ b/lib/modules/UsergridQuery.js @@ -23,6 +23,8 @@ var UsergridQuery = function(type) { sort, __nextIsNot = false + self._type = type + // builder pattern _.assign(self, { type: function(value) { @@ -75,11 +77,11 @@ var UsergridQuery = function(type) { return self }, asc: function(key) { - self.sort(key, 'asc') + self.sort(key, UsergridQuerySortOrder.ASC) return self }, desc: function(key) { - self.sort(key, 'desc') + self.sort(key, UsergridQuerySortOrder.DESC) return self }, sort: function(key, order) { @@ -108,9 +110,6 @@ var UsergridQuery = function(type) { } }) - // required properties - self._type = self._type || type - // public accessors Object.defineProperty(self, '_ql', { get: function() { @@ -122,6 +121,41 @@ var UsergridQuery = function(type) { } }) + Object.defineProperty(self, 'encodedStringValue', { + get: function() { + var self = this + var limit = self._limit + var cursor = self._cursor + var requirementsString = self._ql + var encodedStringValue = undefined; + + if( !_.isEmpty(limit) ) { + queryString = 'limit=' + limit + } + if( !_.isEmpty(cursor) ) { + var cursorString = 'cursor=' + cursor + if( _.isEmpty(queryString) ) { + queryString = cursorString + } else { + queryString += '&' + cursorString + } + } + if( !_.isEmpty(requirementsString) ) { + var qLString = 'ql=' + encodeURIComponent(requirementsString) + if( _.isEmpty(queryString) ) { + queryString = qLString + } else { + queryString += '&' + qLString + } + } + + if( !_.isEmpty(queryString) ) { + queryString = '?' + queryString + } + return !_.isEmpty(queryString) ? queryString : undefined + } + }) + Object.defineProperty(self, 'and', { get: function() { query = self.andJoin('') diff --git a/lib/modules/request.js b/lib/modules/UsergridRequest.js similarity index 87% rename from lib/modules/request.js rename to lib/modules/UsergridRequest.js index b0ea7f0..b5ba8bd 100644 --- a/lib/modules/request.js +++ b/lib/modules/UsergridRequest.js @@ -16,7 +16,7 @@ var UsergridRequest = function(options) { var self = this; - var client = Usergrid.validateAndRetrieveClient(Usergrid.getInstance()); + var client = Usergrid.validateAndRetrieveClient(options); if (!_.isString(options.type) && !_.isString(options.path) && !_.isString(options.uri)) { throw new Error('one of "type" (collection name), "path", or "uri" parameters are required when initializing a UsergridRequest') @@ -32,7 +32,10 @@ var UsergridRequest = function(options) { self.body = options.body || undefined self.encoding = options.encoding || null // FIXME: deal with this - self.qs = UsergridHelpers.qs(options) // FIXME: deal with this + self.query = options.query // FIXME: deal with this + if( self.query !== undefined ) { + self.uri += UsergridHelpers.normalize(self.query.encodedStringValue, {}) + } if( _.isPlainObject(self.body) ) { self.body = JSON.stringify(self.body) @@ -41,7 +44,7 @@ var UsergridRequest = function(options) { var promise = new Promise(); var request = new XMLHttpRequest(); - request.open(self.method,self.uri) + request.open(self.method.toString(),self.uri) request.open = function(m, u) { for (var header in self.headers) { if( self.headers.hasOwnProperty(header) ) { diff --git a/lib/modules/Response.js b/lib/modules/UsergridResponse.js similarity index 75% rename from lib/modules/Response.js rename to lib/modules/UsergridResponse.js index 6e786b1..bd932e3 100644 --- a/lib/modules/Response.js +++ b/lib/modules/UsergridResponse.js @@ -29,15 +29,15 @@ var UsergridResponse = function(request) { var p = new Promise(); var self = this self.ok = false + self.error = undefined if (!request) { - return + return p } else { self.statusCode = parseInt(request.status) - var responseJSON; try { var responseText = request.responseText - responseJSON = JSON.parse(responseText); + var responseJSON = JSON.parse(responseText); } catch (e) { responseJSON = {} } @@ -54,39 +54,33 @@ var UsergridResponse = function(request) { }) _.assign(self, { - metadata: _.cloneDeep(responseJSON), + responseJSON: _.cloneDeep(responseJSON), entities: entities }) - delete self.metadata.entities + delete self.responseJSON.entities self.first = _.first(entities) || undefined self.entity = self.first self.last = _.last(entities) || undefined - if (_.get(self, 'metadata.path') === '/users') { + if (_.get(self, 'responseJSON.path') === '/users') { self.user = self.first self.users = self.entities } Object.defineProperty(self, 'hasNextPage', { get: function () { - return _.has(self, 'metadata.cursor') + return _.has(self, 'responseJSON.cursor') } }) - UsergridHelpers.setReadOnly(self.metadata) + UsergridHelpers.setReadOnly(self.responseJSON) } } else { - _.assign(self, { - error: new UsergridResponseError(responseJSON) - }) + self.error = new UsergridResponseError(responseJSON) } } - if (this.success) { - p.done(this); - } else { - p.done(this); - } + p.done(this); return p; } @@ -95,13 +89,13 @@ UsergridResponse.prototype = { var self = this var args = UsergridHelpers.flattenArgs(arguments) var callback = UsergridHelpers.callback(args) - if (!self.metadata.cursor) { + if (!self.responseJSON.cursor) { callback() } var client = Usergrid.validateAndRetrieveClient(args) - var type = _.last(_.get(self,'metadata.path').split('/')) - var limit = _.first(_.get(this,'metadata.params.limit')) - var query = new UsergridQuery(type).cursor(this.metadata.cursor).limit(limit) + var type = _.last(_.get(self,'responseJSON.path').split('/')) + var limit = _.first(_.get(this,'responseJSON.params.limit')) + var query = new UsergridQuery(type).cursor(this.responseJSON.cursor).limit(limit) return client.GET(query, callback) } } \ No newline at end of file diff --git a/lib/modules/UsergridUser.js b/lib/modules/UsergridUser.js index 2ae9487..2e49e05 100644 --- a/lib/modules/UsergridUser.js +++ b/lib/modules/UsergridUser.js @@ -22,17 +22,15 @@ var UsergridUser = function(obj) { } var self = this - self.type = "user" _.assign(self, obj, UsergridEntity) - UsergridEntity.call(self, self) + UsergridEntity.call(self, "user") UsergridHelpers.setWritable(self, 'name') return self } -var CheckAvailable = function() { - var self = this +UsergridUser.CheckAvailable = function() { var args = UsergridHelpers.flattenArgs(arguments) var client = Usergrid.validateAndRetrieveClient(args) if (args[0] instanceof UsergridClient) { @@ -51,9 +49,9 @@ var CheckAvailable = function() { throw new Error("'username' or 'email' property is required when checking for available users") } - client.GET(checkQuery, function(error, usergridResponse) { - callback(error, usergridResponse, (usergridResponse.entities.length > 0)) - }.bind(self)) + client.GET(checkQuery, function(usergridResponse) { + callback(usergridResponse, !(usergridResponse.entities.length > 0)) + }) } UsergridUser.prototype = { @@ -66,31 +64,34 @@ UsergridUser.prototype = { var args = UsergridHelpers.flattenArgs(arguments) var client = UsergridHelpers.flattenArgs(args) var callback = UsergridHelpers.callback(args) - client.POST(self, function(error, usergridResponse) { + client.POST(self, function(usergridResponse) { delete self.password _.assign(self, usergridResponse.user) - callback(error, usergridResponse, usergridResponse.user) + callback(usergridResponse) }.bind(self)) }, login: function() { var self = this var args = UsergridHelpers.flattenArgs(arguments) var callback = UsergridHelpers.callback(args) - return new UsergridRequest({ - client: UsergridHelpers.validate(args), + + var client = Usergrid.validateAndRetrieveClient(args) + client.performRequest(new UsergridRequest({ + client: client, path: 'token', - method: 'POST', + method: UsergridHttpMethod.POST, body: UsergridHelpers.userLoginBody(self) - }, function(error, usergridResponse, body) { + }, function(usergridResponse) { delete self.password if (usergridResponse.ok) { + var responseJSON = usergridResponse.responseJSON self.auth = new UsergridUserAuth(body.user) - self.auth.token = body.access_token - self.auth.expiry = Usergrid.calculateExpiry(body.expires_in) - self.auth.tokenTtl = body.expires_in + self.auth.token = responseJSON.access_token + self.auth.expiry = Usergrid.calculateExpiry(responseJSON.expires_in) + self.auth.tokenTtl = responseJSON.expires_in } - callback(error, usergridResponse, body.access_token) - }) + callback(self.auth, self, usergridResponse.error) + })) }, logout: function() { var self = this @@ -104,18 +105,19 @@ UsergridUser.prototype = { } var revokeAll = _.first(args.filter(_.isBoolean)) || false - - return new UsergridRequest({ - client: Usergrid.validateAndRetrieveClient(args), - path: ['users', self.uniqueId(),('revoketoken' + ((revokeAll) ? "s" : "")) ].join('/'), - method: 'PUT', - qs: (!revokeAll) ? { - token: self.auth.token - } : undefined - }, function(error, usergridResponse, body) { + var revokeTokenPath = ['users', self.uniqueId(),('revoketoken' + ((revokeAll) ? "s" : "")) ].join('/') + if( !revokeAll ) { + revokeTokenPath += '?ql=token=' + self.auth.token + } + var client = Usergrid.validateAndRetrieveClient(args) + client.performRequest(new UsergridRequest({ + client: client, + path: revokeTokenPath, + method: 'PUT' + }, function(usergridResponse) { self.auth.destroy() - callback(error, usergridResponse, usergridResponse.ok) - }) + callback(usergridResponse) + })) }, logoutAllSessions: function() { var args = UsergridHelpers.flattenArgs(arguments) @@ -137,14 +139,14 @@ UsergridUser.prototype = { if (!body.oldpassword || !body.newpassword) { throw new Error('"oldPassword" and "newPassword" properties are required when resetting a user password') } - return new UsergridRequest({ + return client.performRequest(new UsergridRequest({ client: client, path: ['users',self.uniqueId(),'password'].join('/'), method: 'PUT', body: body - }, function(error, usergridResponse, body) { - callback(error, usergridResponse, usergridResponse.ok) - }) + }, function(usergridResponse) { + callback(usergridResponse) + })); } } UsergridHelpers.inherits(UsergridUser, UsergridEntity) \ No newline at end of file diff --git a/lib/modules/util/Helpers.js b/lib/modules/util/UsergridHelpers.js similarity index 75% rename from lib/modules/util/Helpers.js rename to lib/modules/util/UsergridHelpers.js index 4dba691..f7d2f5c 100644 --- a/lib/modules/util/Helpers.js +++ b/lib/modules/util/UsergridHelpers.js @@ -22,8 +22,8 @@ }; UsergridHelpers.callback = function() { - var args = _.flattenDeep(Array.prototype.slice.call(arguments)).reverse() - var emptyFunc = function() {} + var args = _.flattenDeep(Array.prototype.slice.call(arguments)).reverse(); + var emptyFunc = function() {}; return _.first(_.flattenDeep([args, _.get(args,'0.callback'), emptyFunc]).filter(_.isFunction)) }; @@ -43,11 +43,11 @@ var body = { grant_type: 'password', password: options.password - } + }; if (options.tokenTtl) { body.ttl = options.tokenTtl } - body[(options.username) ? "username" : "email"] = (options.username) ? options.username : options.email + body[(options.username) ? "username" : "email"] = (options.username) ? options.username : options.email; return body }; @@ -56,7 +56,7 @@ grant_type: 'client_credentials', client_id: options.clientId, client_secret: options.clientSecret - } + }; if (options.tokenTtl) { body.ttl = options.tokenTtl } @@ -89,7 +89,7 @@ if (_.isArray(key)) { return key.forEach(function(k) { UsergridHelpers.setWritable(obj, k) - }) + }); // Note that once Object.freeze is called on an object, it cannot be unfrozen, so we need to clone it } else if (_.isPlainObject(obj[key])) { return _.clone(obj[key]) @@ -102,7 +102,7 @@ } else { return obj } - } + }; UsergridHelpers.normalize = function(str, options) { @@ -119,7 +119,7 @@ str = str.replace(/(\?.+)\?/g, '$1&'); return str; - } + }; UsergridHelpers.urljoin = function() { var input = arguments; @@ -135,38 +135,71 @@ return UsergridHelpers.normalize(joined, options); }; - UsergridHelpers.uri = function(client, options) { - return UsergridHelpers.urljoin( - client.baseUrl, - client.orgId, - client.appId, - options.path || options.type, - options.method !== "POST" ? _.first([ + UsergridHelpers.uri = function(client, method, options) { + var path = ''; + if( options instanceof UsergridEntity ) { + path = options.type + } else if( options instanceof UsergridQuery ) { + path = options._type + } else { + path = options.path || options.type || _.get(options,"entity.type") || _.get(options,"query._type") + } + + var uuidOrName = ''; + if( method !== UsergridHttpMethod.POST ) { + uuidOrName = _.first([ options.uuidOrName, options.uuid, options.name, _.get(options,'entity.uuid'), _.get(options,'entity.name'), - "" - ].filter(_.isString)) : "" - ) + '' + ].filter(_.isString)) + } + return UsergridHelpers.urljoin(client.baseUrl, client.orgId, client.appId, path, uuidOrName) + }; + + UsergridHelpers.body = function(options) { + var rawBody = undefined; + if( options instanceof UsergridEntity ) { + rawBody = options + } else { + rawBody = options.body || options.entity || options.entities; + if( rawBody === undefined ) { + if( _.isArray(options) ) { + if( options[0] instanceof UsergridEntity ) { + rawBody = options + } + } + } + } + + var returnBody = rawBody; + if( rawBody instanceof UsergridEntity ) { + returnBody = rawBody.jsonValue() + } else if( rawBody instanceof Array ) { + if( rawBody[0] instanceof UsergridEntity ) { + returnBody = _.map(rawBody, function(entity){ return entity.jsonValue(); }) + } + } + return returnBody; } UsergridHelpers.headers = function(client, options) { var headers = { 'User-Agent':'usergrid-js/v' + Usergrid.USERGRID_SDK_VERSION - } - _.assign(headers, options.headers) + }; + _.assign(headers, options.headers); - var token + var token; if (_.get(client,'tempAuth.isValid')) { // if ad-hoc authentication was set in the client, get the token and destroy the auth - token = client.tempAuth.token + token = client.tempAuth.token; client.tempAuth = undefined } else if (_.get(client,'currentUser.auth.isValid')) { // defaults to using the current user's token token = client.currentUser.auth.token - } else if (_.get(client,'authFallback') === UsergridAuthMode.APP && _.get(client,'appAuth.isValid')) { + } else if (client.authMode === UsergridAuthMode.APP && _.get(client,'appAuth.isValid')) { // if auth-fallback is set to APP request will make a call using the application token token = client.appAuth.token } @@ -177,7 +210,7 @@ }) } return headers - } + }; UsergridHelpers.qs = function(options) { return (options.query instanceof UsergridQuery) ? { @@ -185,18 +218,18 @@ limit: options.query._limit, cursor: options.query._cursor } : options.qs - } + }; UsergridHelpers.formData = function(options) { if (_.get(options,'asset.data')) { - var formData = {} + var formData = {}; formData.file = { value: options.asset.data, options: { filename: _.get(options,'asset.filename') || '', // UsergridAsset.DEFAULT_FILE_NAME, //FIXME!!!! contentType: _.get(options,'asset.contentType') || 'application/octet-stream' } - } + }; if (_.has(options,'asset.name')) { formData.name = options.asset.name } @@ -204,22 +237,20 @@ } else { return undefined } - } + }; UsergridHelpers.encode = function(data) { var result = ""; if (typeof data === "string") { result = data; } else { - var e = encodeURIComponent; - for (var i in data) { - if (data.hasOwnProperty(i)) { - result += '&' + e(i) + '=' + e(data[i]); - } - } + var encode = encodeURIComponent; + _.forOwn(data,function(value,key){ + result += '&' + encode(key) + '=' + encode(value); + }) } return result; - } + }; global[name] = UsergridHelpers; global[name].noConflict = function() { diff --git a/tests/mocha/index.html b/tests/mocha/index.html index c521fa5..755df92 100644 --- a/tests/mocha/index.html +++ b/tests/mocha/index.html @@ -30,8 +30,9 @@ } - + + + From 94614c0d3859bc7e461bdc661a2e1884f80c3b07 Mon Sep 17 00:00:00 2001 From: Robert Walsh Date: Wed, 5 Oct 2016 15:08:26 -0500 Subject: [PATCH 12/36] Updates trying to get travis.yml working --- .travis.yml | 2 +- package.json | 4 ++-- tests/mocha/index.html | 12 ++++++++---- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/.travis.yml b/.travis.yml index 8468bb3..6022d27 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,6 @@ language: node_js node_js: - - "0.10" + - "6.1" before_script: - npm install grunt-cli -g diff --git a/package.json b/package.json index 68bf313..568918b 100644 --- a/package.json +++ b/package.json @@ -12,8 +12,8 @@ "author": "", "license": "Apache 2.0", "devDependencies": { - "grunt": "~0.4.2", - "grunt-mocha": "~1.0.2", + "grunt": "~0.4.5", + "grunt-mocha": "~0.4.4", "grunt-contrib-clean": "~0.5.0", "grunt-contrib-watch": "~0.5.3", "grunt-contrib-uglify": "~0.2.7", diff --git a/tests/mocha/index.html b/tests/mocha/index.html index c532ef0..de900ed 100644 --- a/tests/mocha/index.html +++ b/tests/mocha/index.html @@ -29,22 +29,26 @@ if (!expr) throw new Error(msg || 'failed'); } + - From f3574d5ec267881e6a25906a7892d391a44908dd Mon Sep 17 00:00:00 2001 From: Robert Walsh Date: Wed, 5 Oct 2016 15:21:14 -0500 Subject: [PATCH 13/36] update --- tests/mocha/test_query.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/mocha/test_query.js b/tests/mocha/test_query.js index c7487bb..b847c17 100644 --- a/tests/mocha/test_query.js +++ b/tests/mocha/test_query.js @@ -15,7 +15,7 @@ // limitations under the License. // -describe('UsergridQuery', function() { +describe('Usergrid_Query', function() { describe('_type', function() { it('_type should equal "cats" when passing "type" as a parameter to UsergridQuery', function() { From 40fbf62595977b3c833ed8ce3396ec283054fee0 Mon Sep 17 00:00:00 2001 From: Robert Walsh Date: Wed, 5 Oct 2016 16:05:54 -0500 Subject: [PATCH 14/36] Fixing grunt-mocha package --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 568918b..3e25f38 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,7 @@ "license": "Apache 2.0", "devDependencies": { "grunt": "~0.4.5", - "grunt-mocha": "~0.4.4", + "grunt-mocha": "~1.0.2", "grunt-contrib-clean": "~0.5.0", "grunt-contrib-watch": "~0.5.3", "grunt-contrib-uglify": "~0.2.7", From d230e25737c19f03730c54f27086d84b2ab9b563 Mon Sep 17 00:00:00 2001 From: Robert Walsh Date: Wed, 5 Oct 2016 16:08:19 -0500 Subject: [PATCH 15/36] Adding travis ci build status to readme --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 41a2b5a..2896503 100755 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # Usergrid JavaScript SDK +[![Build Status](https://travis-ci.org/RobertWalsh/usergrid-javascript.svg?branch=master)](https://travis-ci.org/RobertWalsh/usergrid-javascript) + ##Quickstart Detailed instructions follow but if you just want a quick example of how to get started with this SDK, here’s a minimal HTML5 file that shows you how to include & initialize the SDK, as well as how to read & write data from Usergrid with it. From cb7668c87459622a7c7bda57f5fb2763557a3828 Mon Sep 17 00:00:00 2001 From: Robert Walsh Date: Fri, 7 Oct 2016 14:27:16 -0500 Subject: [PATCH 16/36] Connections are now working among other fixes UsergridQuery bug fix. UsergridRequest.body fix for array of entities for the body. Added a lot more tests. --- lib/modules/UsergridClient.js | 17 +- lib/modules/UsergridEntity.js | 8 +- lib/modules/UsergridQuery.js | 22 +- lib/modules/UsergridRequest.js | 14 +- lib/modules/util/UsergridHelpers.js | 128 ++++++- tests/mocha/index.html | 6 +- tests/mocha/test_client_auth.js | 45 +-- tests/mocha/test_client_connections.js | 243 +++++++++++++ tests/mocha/test_client_init.js | 33 ++ tests/mocha/test_client_rest.js | 466 +++++++++++++++++++++++++ tests/mocha/test_entity.js | 297 +++++++++++++--- tests/mocha/test_helpers.js | 33 ++ tests/mocha/test_query.js | 2 +- usergrid.js | 145 ++++++-- usergrid.min.js | 8 +- 15 files changed, 1316 insertions(+), 151 deletions(-) create mode 100644 tests/mocha/test_client_connections.js create mode 100644 tests/mocha/test_client_init.js create mode 100644 tests/mocha/test_client_rest.js create mode 100644 tests/mocha/test_helpers.js diff --git a/lib/modules/UsergridClient.js b/lib/modules/UsergridClient.js index 8016f6e..315260f 100644 --- a/lib/modules/UsergridClient.js +++ b/lib/modules/UsergridClient.js @@ -143,20 +143,17 @@ UsergridClient.prototype = { queryParams:options.queryParams, body:UsergridHelpers.body(options)}), callback) }, - connect: function(options,callback) { - var self = this; //FIXME: THIS IS WRONG - return self.performRequest(new UsergridRequest({client:self, - method:UsergridHttpMethod.POST, - uri:UsergridHelpers.uri(self,UsergridHttpMethod.POST,options), - query:(options instanceof UsergridQuery ? options : options.query), - queryParams:options.queryParams, - body:UsergridHelpers.body(options)}), callback) + connect: function() { + var self = this; + return self.performRequest(UsergridHelpers.buildConnectionRequest(this,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments)), UsergridHelpers.callback(arguments)) }, disconnect: function() { - return this.request(new UsergridRequest(helpers.build.connection(this, 'DELETE', UsergridHelpers.flattenArgs(arguments)))) + var self = this; + return self.performRequest(UsergridHelpers.buildConnectionRequest(this,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments)), UsergridHelpers.callback(arguments)) }, getConnections: function() { - return this.request(new UsergridRequest(helpers.build.getConnections(this, UsergridHelpers.flattenArgs(arguments)))) + var self = this + return self.performRequest(UsergridHelpers.buildGetConnectionRequest(this,UsergridHelpers.flattenArgs(arguments)), UsergridHelpers.callback(arguments)) }, setAppAuth: function() { this.appAuth = new UsergridAppAuth(UsergridHelpers.flattenArgs(arguments)) diff --git a/lib/modules/UsergridEntity.js b/lib/modules/UsergridEntity.js index 0076eed..2991e01 100644 --- a/lib/modules/UsergridEntity.js +++ b/lib/modules/UsergridEntity.js @@ -108,15 +108,13 @@ UsergridEntity.prototype = { } }, reload: function() { - var args = helpers.args(arguments) - var client = helpers.client.validate(args) + var args = UsergridHelpers.flattenArgs(arguments) + var client = Usergrid.validateAndRetrieveClient(args) var callback = UsergridHelpers.callback(args) - client.tempAuth = this.tempAuth - this.tempAuth = undefined client.GET(this, function(usergridResponse) { updateEntityFromRemote.call(this, usergridResponse) - callback(usergridResponse, this) + callback(usergridResponse) }.bind(this)) }, save: function() { diff --git a/lib/modules/UsergridQuery.js b/lib/modules/UsergridQuery.js index 7f02a09..e96950e 100644 --- a/lib/modules/UsergridQuery.js +++ b/lib/modules/UsergridQuery.js @@ -129,30 +129,30 @@ var UsergridQuery = function(type) { var requirementsString = self._ql var encodedStringValue = undefined; - if( !_.isEmpty(limit) ) { - queryString = 'limit=' + limit + if( limit !== undefined ) { + encodedStringValue = 'limit=' + limit } if( !_.isEmpty(cursor) ) { var cursorString = 'cursor=' + cursor - if( _.isEmpty(queryString) ) { - queryString = cursorString + if( _.isEmpty(encodedStringValue) ) { + encodedStringValue = cursorString } else { - queryString += '&' + cursorString + encodedStringValue += '&' + cursorString } } if( !_.isEmpty(requirementsString) ) { var qLString = 'ql=' + encodeURIComponent(requirementsString) - if( _.isEmpty(queryString) ) { - queryString = qLString + if( _.isEmpty(encodedStringValue) ) { + encodedStringValue = qLString } else { - queryString += '&' + qLString + encodedStringValue += '&' + qLString } } - if( !_.isEmpty(queryString) ) { - queryString = '?' + queryString + if( !_.isEmpty(encodedStringValue) ) { + encodedStringValue = '?' + encodedStringValue } - return !_.isEmpty(queryString) ? queryString : undefined + return !_.isEmpty(encodedStringValue) ? encodedStringValue : undefined } }) diff --git a/lib/modules/UsergridRequest.js b/lib/modules/UsergridRequest.js index 04d2312..0deb691 100644 --- a/lib/modules/UsergridRequest.js +++ b/lib/modules/UsergridRequest.js @@ -31,8 +31,7 @@ var UsergridRequest = function(options) { self.headers = UsergridHelpers.headers(client, options) self.body = options.body || undefined - self.encoding = options.encoding || null // FIXME: deal with this - self.query = options.query // FIXME: deal with this + self.query = options.query if( self.query !== undefined ) { self.uri += UsergridHelpers.normalize(self.query.encodedStringValue, {}) } @@ -45,9 +44,14 @@ var UsergridRequest = function(options) { self.uri = UsergridHelpers.normalize(self.uri,{}) } - if( _.isPlainObject(self.body) ) { - self.body = JSON.stringify(self.body) - } + try{ + if( _.isPlainObject(self.body) ) { + self.body = JSON.stringify(self.body) + } + if( _.isArray(self.body) ) { + self.body = JSON.stringify(self.body) + } + } catch( exception ) { } return self } \ No newline at end of file diff --git a/lib/modules/util/UsergridHelpers.js b/lib/modules/util/UsergridHelpers.js index 173114a..8278ed0 100644 --- a/lib/modules/util/UsergridHelpers.js +++ b/lib/modules/util/UsergridHelpers.js @@ -105,6 +105,14 @@ } }; + UsergridHelpers.assignPrefabOptions = function(args) { + // if a preformatted options argument passed, assign it to options + if (_.isObject(args[0]) && !_.isFunction(args[0]) && _.has(args,"method")) { + _.assign(this, args[0]) + } + return this + }; + UsergridHelpers.normalize = function(str, options) { // make sure protocol is followed by two slashes @@ -144,8 +152,10 @@ path = options._type } else if( _.isString(options) ) { path = options + } else if( _.isArray(options) ) { + path = _.get(options,'0.type') || _.get(options,'0.path') } else { - path = options.path || options.type || _.get(options,"entity.type") || _.get(options,"query._type") + path = options.path || options.type || _.get(options,"entity.type") || _.get(options,"query._type") || _.get(options,'body.type') || _.get(options,'body.path') } var uuidOrName = ''; @@ -156,6 +166,8 @@ options.name, _.get(options,'entity.uuid'), _.get(options,'entity.name'), + _.get(options,'body.uuid'), + _.get(options,'body.name'), '' ].filter(_.isString)) } @@ -233,6 +245,120 @@ return result; }; + UsergridHelpers.buildConnectionRequest = function(client,method,args) { + var options = { + client: client, + method: method, + entity: {}, + to: {}, + } + + UsergridHelpers.assignPrefabOptions.call(options, args) + + // handle DELETE using "from" preposition + if (_.isObject(options.from)) { + options.to = options.from + } + + if( _.isObject(args[0]) && _.has(args[0],'entity') && _.has(args[0],'to') ) { + _.assign(options.entity,args[0].entity); + options.relationship = _.get(args,'0.relationship') + _.assign(options.to,args[0].to); + } + + // if an entity object or UsergridEntity instance is the first argument (source) + if (_.isObject(args[0]) && !_.isFunction(args[0]) && _.isString(args[1])) { + _.assign(options.entity, args[0]) + options.relationship = _.first([options.relationship, args[1]].filter(_.isString)) + } + + // if an entity object or UsergridEntity instance is the third argument (target) + if (_.isObject(args[2]) && !_.isFunction(args[2])) { + _.assign(options.to, args[2]) + } + + options.entity.uuidOrName = _.first([options.entity.uuidOrName, options.entity.uuid, options.entity.name, args[1]].filter(_.isString)) + if (!options.entity.type) { + options.entity.type = _.first([options.entity.type, args[0]].filter(_.isString)) + } + options.relationship = _.first([options.relationship, args[2]].filter(_.isString)) + + if (_.isString(args[3]) && !isUUID(args[3]) && _.isString(args[4])) { + options.to.type = args[3] + } else if (_.isString(args[2]) && !isUUID(args[2]) && _.isString(args[3]) && _.isObject(args[0]) && !_.isFunction(args[0])) { + options.to.type = args[2] + } + + options.to.uuidOrName = _.first([options.to.uuidOrName, options.to.uuid, options.to.name, args[4], args[3], args[2]].filter(function(property) { + return (_.isString(options.to.type) && _.isString(property) || isUUID(property)) + })) + + if (!_.isString(options.entity.uuidOrName)) { + throw new Error('source entity "uuidOrName" is required when connecting or disconnecting entities') + } + + if (!_.isString(options.to.uuidOrName)) { + throw new Error('target entity "uuidOrName" is required when connecting or disconnecting entities') + } + + if (!_.isString(options.to.type) && !isUUID(options.to.uuidOrName)) { + throw new Error('target "type" (collection name) parameter is required connecting or disconnecting entities by name') + } + + options.uri = UsergridHelpers.urljoin( + client.baseUrl, + client.orgId, + client.appId, + _.isString(options.entity.type) ? options.entity.type : "", + _.isString(options.entity.uuidOrName) ? options.entity.uuidOrName : "", + options.relationship, + _.isString(options.to.type) ? options.to.type : "", + _.isString(options.to.uuidOrName) ? options.to.uuidOrName : "" + ) + + return new UsergridRequest(options) + }; + + UsergridHelpers.buildGetConnectionRequest = function(client,args) { + var options = { + client: client, + method: 'GET' + } + + UsergridHelpers.assignPrefabOptions.call(options, args) + if (_.isObject(args[1]) && !_.isFunction(args[1])) { + _.assign(options, args[1]) + } + + options.direction = _.first([options.direction, args[0]].filter(function(property) { + return (property === UsergridDirection.IN || property === UsergridDirection.OUT) + })) + + options.relationship = _.first([options.relationship, args[3], args[2]].filter(_.isString)) + options.uuidOrName = _.first([options.uuidOrName, options.uuid, options.name, args[2]].filter(_.isString)) + options.type = _.first([options.type, args[1]].filter(_.isString)) + + if (!_.isString(options.type)) { + throw new Error('"type" (collection name) parameter is required when retrieving connections') + } + + if (!_.isString(options.uuidOrName)) { + throw new Error('target entity "uuidOrName" is required when retrieving connections') + } + + options.uri = UsergridHelpers.urljoin( + client.baseUrl, + client.orgId, + client.appId, + _.isString(options.type) ? options.type : "", + _.isString(options.uuidOrName) ? options.uuidOrName : "", + options.direction, + options.relationship + ) + + return new UsergridRequest(options) + }; + global[name] = UsergridHelpers; global[name].noConflict = function() { if (overwrittenName) { diff --git a/tests/mocha/index.html b/tests/mocha/index.html index de900ed..4e2d249 100644 --- a/tests/mocha/index.html +++ b/tests/mocha/index.html @@ -31,10 +31,14 @@ + + + + + - - + + + + + diff --git a/tests/mocha/test.js b/tests/mocha/test.js index 8248416..bd37701 100644 --- a/tests/mocha/test.js +++ b/tests/mocha/test.js @@ -46,66 +46,66 @@ function usergridTestHarness(err, data, done, tests, ignoreError) { } done(); } -describe('Ajax', function() { - var client = getClient(); - var dogName="dog"+Math.floor(Math.random()*10000); - var dogData=JSON.stringify({type:"dog",name:dogName}); - var dogURI=client.clientAppURL + '/dogs'; - - // client.authenticateApp(function(response){ - // assert(response.ok,"response should be ok") - // assert(client.appAuth.isValid,"client appAuth should be valid") - // done() - // }) - // client.logout().destory() - // console.log(client.appAuth instanceof UsergridAuth) - // console.log("BEFORE DESTROY:" + client.appAuth.expiry) - // client.appAuth.destroy() - // console.log("AFTER: DESTROY" + client.appAuth.expiry) - - // console.log("Client Id=" + client.appAuth.clientId + " Client Secret=" + client.appAuth.clientSecret) - - it('should POST to a URI ' + dogURI, function(done){ - // appAuth.destroy() - Ajax.post(dogURI, dogData).then(function(data){ - assert(data, data); - done(); - }) - }) - it('should GET a URI',function(done){ - Ajax.get(dogURI+'/'+dogName).then(function(data){ - assert(data, data); - done(); - }) - }) - it('should PUT to a URI',function(done){ - Ajax.put(dogURI+'/'+dogName, {"favorite":true}).then(function(data){ - assert(data, data); - done(); - }) - }) - it('should DELETE a URI',function(done){ - Ajax.delete(dogURI+'/'+dogName, dogData).then(function(data){ - assert(data, data); - done(); - }) - }) -}); -describe('UsergridError', function() { - var errorResponse={ - "error":"service_resource_not_found", - "timestamp":1392067967144, - "duration":0, - "exception":"org.usergrid.services.exceptions.ServiceResourceNotFoundException", - "error_description":"Service resource not found" - }; - it('should unmarshal a response from Usergrid into a proper Javascript error',function(done){ - var error = UsergridError.fromResponse(errorResponse); - assert(error.name===errorResponse.error, "Error name not set correctly"); - assert(error.message===errorResponse.error_description, "Error message not set correctly"); - done(); - }); -}); +// describe('Ajax', function() { +// var client = getClient(); +// var dogName="dog"+Math.floor(Math.random()*10000); +// var dogData=JSON.stringify({type:"dog",name:dogName}); +// var dogURI=client.clientAppURL + '/dogs'; +// +// // client.authenticateApp(function(response){ +// // assert(response.ok,"response should be ok") +// // assert(client.appAuth.isValid,"client appAuth should be valid") +// // done() +// // }) +// // client.logout().destory() +// // console.log(client.appAuth instanceof UsergridAuth) +// // console.log("BEFORE DESTROY:" + client.appAuth.expiry) +// // client.appAuth.destroy() +// // console.log("AFTER: DESTROY" + client.appAuth.expiry) +// +// // console.log("Client Id=" + client.appAuth.clientId + " Client Secret=" + client.appAuth.clientSecret) +// +// it('should POST to a URI ' + dogURI, function(done){ +// // appAuth.destroy() +// Ajax.post(dogURI, dogData).then(function(data){ +// assert(data, data); +// done(); +// }) +// }) +// it('should GET a URI',function(done){ +// Ajax.get(dogURI+'/'+dogName).then(function(data){ +// assert(data, data); +// done(); +// }) +// }) +// it('should PUT to a URI',function(done){ +// Ajax.put(dogURI+'/'+dogName, {"favorite":true}).then(function(data){ +// assert(data, data); +// done(); +// }) +// }) +// it('should DELETE a URI',function(done){ +// Ajax.delete(dogURI+'/'+dogName, dogData).then(function(data){ +// assert(data, data); +// done(); +// }) +// }) +// }); +// describe('UsergridError', function() { +// var errorResponse={ +// "error":"service_resource_not_found", +// "timestamp":1392067967144, +// "duration":0, +// "exception":"org.usergrid.services.exceptions.ServiceResourceNotFoundException", +// "error_description":"Service resource not found" +// }; +// it('should unmarshal a response from Usergrid into a proper Javascript error',function(done){ +// var error = UsergridError.fromResponse(errorResponse); +// assert(error.name===errorResponse.error, "Error name not set correctly"); +// assert(error.message===errorResponse.error_description, "Error message not set correctly"); +// done(); +// }); +// }); describe('Usergrid', function() { describe('SDK Version', function () { it('should contain a minimum SDK version', function () { diff --git a/tests/mocha/test_user.js b/tests/mocha/test_user.js index a977755..bdc6bcf 100644 --- a/tests/mocha/test_user.js +++ b/tests/mocha/test_user.js @@ -63,7 +63,6 @@ describe('UsergridUser', function() { password: config.test.password }) user.create(client, function (usergridResponse) { - client.isSharedInstance.should.be.false() user.username.should.equal(username) user.should.have.property('uuid')//.which.is.a.uuid() user.should.have.property('created') diff --git a/tests/mocha/test_usergrid_init.js b/tests/mocha/test_usergrid_init.js new file mode 100644 index 0000000..7d85230 --- /dev/null +++ b/tests/mocha/test_usergrid_init.js @@ -0,0 +1,15 @@ +'use strict' + +describe('Usergrid init() / initSharedInstance()', function() { + it('should be an instance of UsergridClient', function(done) { + Usergrid.init(config) + Usergrid.initSharedInstance(config) + Usergrid.should.be.an.instanceof(UsergridClient) + done() + }) + it('should be initialized when defined in another module', function(done) { + Usergrid.should.have.property('isInitialized').which.is.true() + Usergrid.should.have.property('isSharedInstance').which.is.true() + done() + }) +}) \ No newline at end of file diff --git a/usergrid.js b/usergrid.js index bba4495..0b6d9d8 100644 --- a/usergrid.js +++ b/usergrid.js @@ -19,151 +19,6 @@ * * usergrid@0.11.0 2016-10-09 */ -/* - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -var UsergridAuthMode = Object.freeze({ - NONE: "none", - USER: "user", - APP: "app" -}); - -var UsergridDirection = Object.freeze({ - IN: "connecting", - OUT: "connections" -}); - -var UsergridHttpMethod = Object.freeze({ - GET: "GET", - PUT: "PUT", - POST: "POST", - DELETE: "DELETE" -}); - -var UsergridQueryOperator = Object.freeze({ - EQUAL: "=", - GREATER_THAN: ">", - GREATER_THAN_EQUAL_TO: ">=", - LESS_THAN: "<", - LESS_THAN_EQUAL_TO: "<=" -}); - -var UsergridQuerySortOrder = Object.freeze({ - ASC: "asc", - DESC: "desc" -}); - -var UsergridEventable = function() { - throw Error("'UsergridEventable' is not intended to be invoked directly"); -}; - -UsergridEventable.prototype = { - bind: function(event, fn) { - this._events = this._events || {}; - this._events[event] = this._events[event] || []; - this._events[event].push(fn); - }, - unbind: function(event, fn) { - this._events = this._events || {}; - if (event in this._events === false) return; - this._events[event].splice(this._events[event].indexOf(fn), 1); - }, - trigger: function(event) { - this._events = this._events || {}; - if (event in this._events === false) return; - for (var i = 0; i < this._events[event].length; i++) { - this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1)); - } - } -}; - -UsergridEventable.mixin = function(destObject) { - var props = [ "bind", "unbind", "trigger" ]; - for (var i = 0; i < props.length; i++) { - if (props[i] in destObject.prototype) { - console.warn("overwriting '" + props[i] + "' on '" + destObject.name + "'."); - console.warn("the previous version can be found at '_" + props[i] + "' on '" + destObject.name + "'."); - destObject.prototype["_" + props[i]] = destObject.prototype[props[i]]; - } - destObject.prototype[props[i]] = UsergridEventable.prototype[props[i]]; - } -}; - -(function() { - var name = "Logger", global = this, overwrittenName = global[name], exports; - /* logging */ - function Logger(name) { - this.logEnabled = true; - this.init(name, true); - } - Logger.METHODS = [ "log", "error", "warn", "info", "debug", "assert", "clear", "count", "dir", "dirxml", "exception", "group", "groupCollapsed", "groupEnd", "profile", "profileEnd", "table", "time", "timeEnd", "trace" ]; - Logger.prototype.init = function(name, logEnabled) { - this.name = name || "UNKNOWN"; - this.logEnabled = logEnabled || true; - var addMethod = function(method) { - this[method] = this.createLogMethod(method); - }.bind(this); - Logger.METHODS.forEach(addMethod); - }; - Logger.prototype.createLogMethod = function(method) { - return Logger.prototype.log.bind(this, method); - }; - Logger.prototype.prefix = function(method, args) { - var prepend = "[" + method.toUpperCase() + "][" + name + "]: "; - if ([ "log", "error", "warn", "info" ].indexOf(method) !== -1) { - if ("string" === typeof args[0]) { - args[0] = prepend + args[0]; - } else { - args.unshift(prepend); - } - } - return args; - }; - Logger.prototype.log = function() { - var args = [].slice.call(arguments); - var method = args.shift(); - if (Logger.METHODS.indexOf(method) === -1) { - method = "log"; - } - if (!(this.logEnabled && console && console[method])) return; - args = this.prefix(method, args); - console[method].apply(console, args); - }; - Logger.prototype.setLogEnabled = function(logEnabled) { - this.logEnabled = logEnabled || true; - }; - Logger.mixin = function(destObject) { - destObject.__logger = new Logger(destObject.name || "UNKNOWN"); - var addMethod = function(method) { - if (method in destObject.prototype) { - console.warn("overwriting '" + method + "' on '" + destObject.name + "'."); - console.warn("the previous version can be found at '_" + method + "' on '" + destObject.name + "'."); - destObject.prototype["_" + method] = destObject.prototype[method]; - } - destObject.prototype[method] = destObject.__logger.createLogMethod(method); - }; - Logger.METHODS.forEach(addMethod); - }; - global[name] = Logger; - global[name].noConflict = function() { - if (overwrittenName) { - global[name] = overwrittenName; - } - return Logger; - }; - return global[name]; -})(); - (function(global) { var name = "Promise", overwrittenName = global[name], exports; function Promise() { @@ -234,193 +89,59 @@ UsergridEventable.mixin = function(destObject) { })(this); (function() { - var name = "Ajax", global = this, overwrittenName = global[name], exports; - function partial() { - var args = Array.prototype.slice.call(arguments); - var fn = args.shift(); - return fn.bind(this, args); - } - function Ajax() { - this.logger = new global.Logger(name); - var self = this; - function encode(data) { - var result = ""; - if (typeof data === "string") { - result = data; - } else { - var e = encodeURIComponent; - for (var i in data) { - if (data.hasOwnProperty(i)) { - result += "&" + e(i) + "=" + e(data[i]); - } - } - } - return result; - } - function request(m, u, d) { - var p = new Promise(), timeout; - self.logger.time(m + " " + u); - (function(xhr) { - xhr.onreadystatechange = function() { - if (this.readyState === 4) { - self.logger.timeEnd(m + " " + u); - clearTimeout(timeout); - p.done(this); - } - }; - xhr.onerror = function(response) { - clearTimeout(timeout); - p.done(response); - }; - xhr.oncomplete = function(response) { - clearTimeout(timeout); - self.logger.timeEnd(m + " " + u); - self.info("%s request to %s returned %s", m, u, this.status); - }; - xhr.open(m, u); - if (d) { - if ("object" === typeof d) { - d = JSON.stringify(d); - } - xhr.setRequestHeader("Content-Type", "application/json"); - xhr.setRequestHeader("Accept", "application/json"); - } - timeout = setTimeout(function() { - xhr.abort(); - p.done("API Call timed out.", null); - }, 3e4); - xhr.send(encode(d)); - })(new XMLHttpRequest()); - return p; - } - this.request = request; - this.get = partial(request, "GET"); - this.post = partial(request, "POST"); - this.put = partial(request, "PUT"); - this.delete = partial(request, "DELETE"); - } - global[name] = new Ajax(); - global[name].noConflict = function() { - if (overwrittenName) { - global[name] = overwrittenName; - } - return exports; - }; - return global[name]; -})(); - -(function() { - /** Used as a safe reference for `undefined` in pre-ES5 environments. */ var undefined; - /** Used as the semantic version number. */ var VERSION = "4.16.0"; - /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; - /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = "Expected a function"; - /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = "__lodash_hash_undefined__"; - /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; - /** Used as the internal argument placeholder. */ var PLACEHOLDER = "__lodash_placeholder__"; - /** Used to compose bitmasks for function metadata. */ var BIND_FLAG = 1, BIND_KEY_FLAG = 2, CURRY_BOUND_FLAG = 4, CURRY_FLAG = 8, CURRY_RIGHT_FLAG = 16, PARTIAL_FLAG = 32, PARTIAL_RIGHT_FLAG = 64, ARY_FLAG = 128, REARG_FLAG = 256, FLIP_FLAG = 512; - /** Used to compose bitmasks for comparison styles. */ var UNORDERED_COMPARE_FLAG = 1, PARTIAL_COMPARE_FLAG = 2; - /** Used as default options for `_.truncate`. */ var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = "..."; - /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 500, HOT_SPAN = 16; - /** Used to indicate the type of lazy iteratees. */ var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2, LAZY_WHILE_FLAG = 3; - /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991, MAX_INTEGER = 1.7976931348623157e308, NAN = 0 / 0; - /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; - /** Used to associate wrap methods with their bit flags. */ var wrapFlags = [ [ "ary", ARY_FLAG ], [ "bind", BIND_FLAG ], [ "bindKey", BIND_KEY_FLAG ], [ "curry", CURRY_FLAG ], [ "curryRight", CURRY_RIGHT_FLAG ], [ "flip", FLIP_FLAG ], [ "partial", PARTIAL_FLAG ], [ "partialRight", PARTIAL_RIGHT_FLAG ], [ "rearg", REARG_FLAG ] ]; - /** `Object#toString` result references. */ var argsTag = "[object Arguments]", arrayTag = "[object Array]", boolTag = "[object Boolean]", dateTag = "[object Date]", errorTag = "[object Error]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", mapTag = "[object Map]", numberTag = "[object Number]", objectTag = "[object Object]", promiseTag = "[object Promise]", regexpTag = "[object RegExp]", setTag = "[object Set]", stringTag = "[object String]", symbolTag = "[object Symbol]", weakMapTag = "[object WeakMap]", weakSetTag = "[object WeakSet]"; var arrayBufferTag = "[object ArrayBuffer]", dataViewTag = "[object DataView]", float32Tag = "[object Float32Array]", float64Tag = "[object Float64Array]", int8Tag = "[object Int8Array]", int16Tag = "[object Int16Array]", int32Tag = "[object Int32Array]", uint8Tag = "[object Uint8Array]", uint8ClampedTag = "[object Uint8ClampedArray]", uint16Tag = "[object Uint16Array]", uint32Tag = "[object Uint32Array]"; - /** Used to match empty string literals in compiled template source. */ var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; - /** Used to match HTML entities and HTML characters. */ var reEscapedHtml = /&(?:amp|lt|gt|quot|#39|#96);/g, reUnescapedHtml = /[&<>"'`]/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source); - /** Used to match template delimiters. */ var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g; - /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, reLeadingDot = /^\./, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; - /** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source); - /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g, reTrimStart = /^\s+/, reTrimEnd = /\s+$/; - /** Used to match wrap detail comments. */ var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; - /** Used to match words composed of alphanumeric characters. */ var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; - /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; - /** - * Used to match - * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). - */ var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; - /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; - /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; - /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; - /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; - /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; - /** Used to match Latin Unicode letters (excluding mathematical operators). */ var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; - /** Used to ensure capturing order of template delimiters. */ var reNoMatch = /($^)/; - /** Used to match unescaped characters in compiled string literals. */ var reUnescapedString = /['\n\r\u2028\u2029\\]/g; - /** Used to compose unicode character classes. */ var rsAstralRange = "\\ud800-\\udfff", rsComboMarksRange = "\\u0300-\\u036f\\ufe20-\\ufe23", rsComboSymbolsRange = "\\u20d0-\\u20f0", rsDingbatRange = "\\u2700-\\u27bf", rsLowerRange = "a-z\\xdf-\\xf6\\xf8-\\xff", rsMathOpRange = "\\xac\\xb1\\xd7\\xf7", rsNonCharRange = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf", rsPunctuationRange = "\\u2000-\\u206f", rsSpaceRange = " \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000", rsUpperRange = "A-Z\\xc0-\\xd6\\xd8-\\xde", rsVarRange = "\\ufe0e\\ufe0f", rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; - /** Used to compose unicode capture groups. */ var rsApos = "['’]", rsAstral = "[" + rsAstralRange + "]", rsBreak = "[" + rsBreakRange + "]", rsCombo = "[" + rsComboMarksRange + rsComboSymbolsRange + "]", rsDigits = "\\d+", rsDingbat = "[" + rsDingbatRange + "]", rsLower = "[" + rsLowerRange + "]", rsMisc = "[^" + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + "]", rsFitz = "\\ud83c[\\udffb-\\udfff]", rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")", rsNonAstral = "[^" + rsAstralRange + "]", rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}", rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]", rsUpper = "[" + rsUpperRange + "]", rsZWJ = "\\u200d"; - /** Used to compose unicode regexes. */ var rsLowerMisc = "(?:" + rsLower + "|" + rsMisc + ")", rsUpperMisc = "(?:" + rsUpper + "|" + rsMisc + ")", rsOptLowerContr = "(?:" + rsApos + "(?:d|ll|m|re|s|t|ve))?", rsOptUpperContr = "(?:" + rsApos + "(?:D|LL|M|RE|S|T|VE))?", reOptMod = rsModifier + "?", rsOptVar = "[" + rsVarRange + "]?", rsOptJoin = "(?:" + rsZWJ + "(?:" + [ rsNonAstral, rsRegional, rsSurrPair ].join("|") + ")" + rsOptVar + reOptMod + ")*", rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = "(?:" + [ rsDingbat, rsRegional, rsSurrPair ].join("|") + ")" + rsSeq, rsSymbol = "(?:" + [ rsNonAstral + rsCombo + "?", rsCombo, rsRegional, rsSurrPair, rsAstral ].join("|") + ")"; - /** Used to match apostrophes. */ var reApos = RegExp(rsApos, "g"); - /** - * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and - * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). - */ var reComboMark = RegExp(rsCombo, "g"); - /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reUnicode = RegExp(rsFitz + "(?=" + rsFitz + ")|" + rsSymbol + rsSeq, "g"); - /** Used to match complex or compound words. */ var reUnicodeWord = RegExp([ rsUpper + "?" + rsLower + "+" + rsOptLowerContr + "(?=" + [ rsBreak, rsUpper, "$" ].join("|") + ")", rsUpperMisc + "+" + rsOptUpperContr + "(?=" + [ rsBreak, rsUpper + rsLowerMisc, "$" ].join("|") + ")", rsUpper + "?" + rsLowerMisc + "+" + rsOptLowerContr, rsUpper + "+" + rsOptUpperContr, rsDigits, rsEmoji ].join("|"), "g"); - /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ var reHasUnicode = RegExp("[" + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + "]"); - /** Used to detect strings that need a more robust regexp to match words. */ var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; - /** Used to assign default `context` object properties. */ var contextProps = [ "Array", "Buffer", "DataView", "Date", "Error", "Float32Array", "Float64Array", "Function", "Int8Array", "Int16Array", "Int32Array", "Map", "Math", "Object", "Promise", "RegExp", "Set", "String", "Symbol", "TypeError", "Uint8Array", "Uint8ClampedArray", "Uint16Array", "Uint32Array", "WeakMap", "_", "clearTimeout", "isFinite", "parseInt", "setTimeout" ]; - /** Used to make template sourceURLs easier to identify. */ var templateCounter = -1; - /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; - /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; - /** Used to map Latin Unicode letters to basic Latin letters. */ var deburredLetters = { "À": "A", "Á": "A", @@ -613,7 +334,6 @@ UsergridEventable.mixin = function(destObject) { "ʼn": "'n", "ſ": "s" }; - /** Used to map characters to HTML entities. */ var htmlEscapes = { "&": "&", "<": "<", @@ -621,7 +341,6 @@ UsergridEventable.mixin = function(destObject) { '"': """, "'": "'" }; - /** Used to map HTML entities to characters. */ var htmlUnescapes = { "&": "&", "<": "<", @@ -629,7 +348,6 @@ UsergridEventable.mixin = function(destObject) { """: '"', "'": "'" }; - /** Used to escape characters for inclusion in compiled string literals. */ var stringEscapes = { "\\": "\\", "'": "'", @@ -638,65 +356,28 @@ UsergridEventable.mixin = function(destObject) { "\u2028": "u2028", "\u2029": "u2029" }; - /** Built-in method references without a dependency on `root`. */ var freeParseFloat = parseFloat, freeParseInt = parseInt; - /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == "object" && global && global.Object === Object && global; - /** Detect free variable `self`. */ var freeSelf = typeof self == "object" && self && self.Object === Object && self; - /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function("return this")(); - /** Detect free variable `exports`. */ var freeExports = typeof exports == "object" && exports && !exports.nodeType && exports; - /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == "object" && module && !module.nodeType && module; - /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; - /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; - /** Used to access faster Node.js helpers. */ var nodeUtil = function() { try { return freeProcess && freeProcess.binding("util"); } catch (e) {} }(); - /* Node.js helper references. */ var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, nodeIsDate = nodeUtil && nodeUtil.isDate, nodeIsMap = nodeUtil && nodeUtil.isMap, nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, nodeIsSet = nodeUtil && nodeUtil.isSet, nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - /*--------------------------------------------------------------------------*/ - /** - * Adds the key-value `pair` to `map`. - * - * @private - * @param {Object} map The map to modify. - * @param {Array} pair The key-value pair to add. - * @returns {Object} Returns `map`. - */ function addMapEntry(map, pair) { map.set(pair[0], pair[1]); return map; } - /** - * Adds `value` to `set`. - * - * @private - * @param {Object} set The set to modify. - * @param {*} value The value to add. - * @returns {Object} Returns `set`. - */ function addSetEntry(set, value) { set.add(value); return set; } - /** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ function apply(func, thisArg, args) { switch (args.length) { case 0: @@ -713,16 +394,6 @@ UsergridEventable.mixin = function(destObject) { } return func.apply(thisArg, args); } - /** - * A specialized version of `baseAggregator` for arrays. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform keys. - * @param {Object} accumulator The initial aggregated object. - * @returns {Function} Returns `accumulator`. - */ function arrayAggregator(array, setter, iteratee, accumulator) { var index = -1, length = array ? array.length : 0; while (++index < length) { @@ -731,15 +402,6 @@ UsergridEventable.mixin = function(destObject) { } return accumulator; } - /** - * A specialized version of `_.forEach` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ function arrayEach(array, iteratee) { var index = -1, length = array ? array.length : 0; while (++index < length) { @@ -749,15 +411,6 @@ UsergridEventable.mixin = function(destObject) { } return array; } - /** - * A specialized version of `_.forEachRight` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ function arrayEachRight(array, iteratee) { var length = array ? array.length : 0; while (length--) { @@ -767,16 +420,6 @@ UsergridEventable.mixin = function(destObject) { } return array; } - /** - * A specialized version of `_.every` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false`. - */ function arrayEvery(array, predicate) { var index = -1, length = array ? array.length : 0; while (++index < length) { @@ -786,15 +429,6 @@ UsergridEventable.mixin = function(destObject) { } return true; } - /** - * A specialized version of `_.filter` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ function arrayFilter(array, predicate) { var index = -1, length = array ? array.length : 0, resIndex = 0, result = []; while (++index < length) { @@ -805,28 +439,10 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * A specialized version of `_.includes` for arrays without support for - * specifying an index to search from. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ function arrayIncludes(array, value) { var length = array ? array.length : 0; return !!length && baseIndexOf(array, value, 0) > -1; } - /** - * This function is like `arrayIncludes` except that it accepts a comparator. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @param {Function} comparator The comparator invoked per element. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array ? array.length : 0; while (++index < length) { @@ -836,15 +452,6 @@ UsergridEventable.mixin = function(destObject) { } return false; } - /** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ function arrayMap(array, iteratee) { var index = -1, length = array ? array.length : 0, result = Array(length); while (++index < length) { @@ -852,14 +459,6 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { @@ -867,18 +466,6 @@ UsergridEventable.mixin = function(destObject) { } return array; } - /** - * A specialized version of `_.reduce` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the first element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array ? array.length : 0; if (initAccum && length) { @@ -889,18 +476,6 @@ UsergridEventable.mixin = function(destObject) { } return accumulator; } - /** - * A specialized version of `_.reduceRight` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the last element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ function arrayReduceRight(array, iteratee, accumulator, initAccum) { var length = array ? array.length : 0; if (initAccum && length) { @@ -911,16 +486,6 @@ UsergridEventable.mixin = function(destObject) { } return accumulator; } - /** - * A specialized version of `_.some` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ function arraySome(array, predicate) { var index = -1, length = array ? array.length : 0; while (++index < length) { @@ -930,45 +495,13 @@ UsergridEventable.mixin = function(destObject) { } return false; } - /** - * Gets the size of an ASCII `string`. - * - * @private - * @param {string} string The string inspect. - * @returns {number} Returns the string size. - */ var asciiSize = baseProperty("length"); - /** - * Converts an ASCII `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ function asciiToArray(string) { return string.split(""); } - /** - * Splits an ASCII `string` into an array of its words. - * - * @private - * @param {string} The string to inspect. - * @returns {Array} Returns the words of `string`. - */ function asciiWords(string) { return string.match(reAsciiWord) || []; } - /** - * The base implementation of methods like `_.findKey` and `_.findLastKey`, - * without support for iteratee shorthands, which iterates over `collection` - * using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the found element or its key, else `undefined`. - */ function baseFindKey(collection, predicate, eachFunc) { var result; eachFunc(collection, function(value, key, collection) { @@ -979,17 +512,6 @@ UsergridEventable.mixin = function(destObject) { }); return result; } - /** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while (fromRight ? index-- : ++index < length) { @@ -999,28 +521,9 @@ UsergridEventable.mixin = function(destObject) { } return -1; } - /** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ function baseIndexOf(array, value, fromIndex) { return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); } - /** - * This function is like `baseIndexOf` except that it accepts a comparator. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @param {Function} comparator The comparator invoked per element. - * @returns {number} Returns the index of the matched value, else `-1`. - */ function baseIndexOfWith(array, value, fromIndex, comparator) { var index = fromIndex - 1, length = array.length; while (++index < length) { @@ -1030,82 +533,29 @@ UsergridEventable.mixin = function(destObject) { } return -1; } - /** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ function baseIsNaN(value) { return value !== value; } - /** - * The base implementation of `_.mean` and `_.meanBy` without support for - * iteratee shorthands. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {number} Returns the mean. - */ function baseMean(array, iteratee) { var length = array ? array.length : 0; return length ? baseSum(array, iteratee) / length : NAN; } - /** - * The base implementation of `_.property` without support for deep paths. - * - * @private - * @param {string} key The key of the property to get. - * @returns {Function} Returns the new accessor function. - */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } - /** - * The base implementation of `_.propertyOf` without support for deep paths. - * - * @private - * @param {Object} object The object to query. - * @returns {Function} Returns the new accessor function. - */ function basePropertyOf(object) { return function(key) { return object == null ? undefined : object[key]; }; } - /** - * The base implementation of `_.reduce` and `_.reduceRight`, without support - * for iteratee shorthands, which iterates over `collection` using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} accumulator The initial value. - * @param {boolean} initAccum Specify using the first or last element of - * `collection` as the initial value. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the accumulated value. - */ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, function(value, index, collection) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); }); return accumulator; } - /** - * The base implementation of `_.sortBy` which uses `comparer` to define the - * sort order of `array` and replaces criteria objects with their corresponding - * values. - * - * @private - * @param {Array} array The array to sort. - * @param {Function} comparer The function to define sort order. - * @returns {Array} Returns `array`. - */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); @@ -1114,15 +564,6 @@ UsergridEventable.mixin = function(destObject) { } return array; } - /** - * The base implementation of `_.sum` and `_.sumBy` without support for - * iteratee shorthands. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {number} Returns the sum. - */ function baseSum(array, iteratee) { var result, index = -1, length = array.length; while (++index < length) { @@ -1133,15 +574,6 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { @@ -1149,94 +581,34 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array - * of key-value pairs for `object` corresponding to the property names of `props`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} props The property names to get values for. - * @returns {Object} Returns the key-value pairs. - */ function baseToPairs(object, props) { return arrayMap(props, function(key) { return [ key, object[key] ]; }); } - /** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ function baseUnary(func) { return function(value) { return func(value); }; } - /** - * The base implementation of `_.values` and `_.valuesIn` which creates an - * array of `object` property values corresponding to the property names - * of `props`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} props The property names to get values for. - * @returns {Object} Returns the array of property values. - */ function baseValues(object, props) { return arrayMap(props, function(key) { return object[key]; }); } - /** - * Checks if a `cache` value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ function cacheHas(cache, key) { return cache.has(key); } - /** - * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the first unmatched string symbol. - */ function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } - /** - * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the last unmatched string symbol. - */ function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } - /** - * Gets the number of `placeholder` occurrences in `array`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} placeholder The placeholder to search for. - * @returns {number} Returns the placeholder count. - */ function countHolders(array, placeholder) { var length = array.length, result = 0; while (length--) { @@ -1246,71 +618,20 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A - * letters to basic Latin letters. - * - * @private - * @param {string} letter The matched letter to deburr. - * @returns {string} Returns the deburred letter. - */ var deburrLetter = basePropertyOf(deburredLetters); - /** - * Used by `_.escape` to convert characters to HTML entities. - * - * @private - * @param {string} chr The matched character to escape. - * @returns {string} Returns the escaped character. - */ var escapeHtmlChar = basePropertyOf(htmlEscapes); - /** - * Used by `_.template` to escape characters for inclusion in compiled string literals. - * - * @private - * @param {string} chr The matched character to escape. - * @returns {string} Returns the escaped character. - */ function escapeStringChar(chr) { return "\\" + stringEscapes[chr]; } - /** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ function getValue(object, key) { return object == null ? undefined : object[key]; } - /** - * Checks if `string` contains Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a symbol is found, else `false`. - */ function hasUnicode(string) { return reHasUnicode.test(string); } - /** - * Checks if `string` contains a word composed of Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a word is found, else `false`. - */ function hasUnicodeWord(string) { return reHasUnicodeWord.test(string); } - /** - * Converts `iterator` to an array. - * - * @private - * @param {Object} iterator The iterator to convert. - * @returns {Array} Returns the converted array. - */ function iteratorToArray(iterator) { var data, result = []; while (!(data = iterator.next()).done) { @@ -1318,13 +639,6 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * Converts `map` to its key-value pairs. - * - * @private - * @param {Object} map The map to convert. - * @returns {Array} Returns the key-value pairs. - */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { @@ -1332,28 +646,11 @@ UsergridEventable.mixin = function(destObject) { }); return result; } - /** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } - /** - * Replaces all `placeholder` elements in `array` with an internal placeholder - * and returns an array of their indexes. - * - * @private - * @param {Array} array The array to modify. - * @param {*} placeholder The placeholder to replace. - * @returns {Array} Returns the new array of placeholder indexes. - */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { @@ -1365,13 +662,6 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { @@ -1379,13 +669,6 @@ UsergridEventable.mixin = function(destObject) { }); return result; } - /** - * Converts `set` to its value-value pairs. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the value-value pairs. - */ function setToPairs(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { @@ -1393,16 +676,6 @@ UsergridEventable.mixin = function(destObject) { }); return result; } - /** - * A specialized version of `_.indexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { @@ -1412,16 +685,6 @@ UsergridEventable.mixin = function(destObject) { } return -1; } - /** - * A specialized version of `_.lastIndexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ function strictLastIndexOf(array, value, fromIndex) { var index = fromIndex + 1; while (index--) { @@ -1431,41 +694,13 @@ UsergridEventable.mixin = function(destObject) { } return index; } - /** - * Gets the number of symbols in `string`. - * - * @private - * @param {string} string The string to inspect. - * @returns {number} Returns the string size. - */ function stringSize(string) { return hasUnicode(string) ? unicodeSize(string) : asciiSize(string); } - /** - * Converts `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ function stringToArray(string) { return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); } - /** - * Used by `_.unescape` to convert HTML entities to characters. - * - * @private - * @param {string} chr The matched character to unescape. - * @returns {string} Returns the unescaped character. - */ var unescapeHtmlChar = basePropertyOf(htmlUnescapes); - /** - * Gets the size of a Unicode `string`. - * - * @private - * @param {string} string The string inspect. - * @returns {number} Returns the string size. - */ function unicodeSize(string) { var result = reUnicode.lastIndex = 0; while (reUnicode.test(string)) { @@ -1473,221 +708,36 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * Converts a Unicode `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ function unicodeToArray(string) { return string.match(reUnicode) || []; } - /** - * Splits a Unicode `string` into an array of its words. - * - * @private - * @param {string} The string to inspect. - * @returns {Array} Returns the words of `string`. - */ function unicodeWords(string) { return string.match(reUnicodeWord) || []; } - /*--------------------------------------------------------------------------*/ - /** - * Create a new pristine `lodash` function using the `context` object. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Util - * @param {Object} [context=root] The context object. - * @returns {Function} Returns a new `lodash` function. - * @example - * - * _.mixin({ 'foo': _.constant('foo') }); - * - * var lodash = _.runInContext(); - * lodash.mixin({ 'bar': lodash.constant('bar') }); - * - * _.isFunction(_.foo); - * // => true - * _.isFunction(_.bar); - * // => false - * - * lodash.isFunction(lodash.foo); - * // => false - * lodash.isFunction(lodash.bar); - * // => true - * - * // Create a suped-up `defer` in Node.js. - * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; - */ function runInContext(context) { context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root; - /** Built-in constructor references. */ var Array = context.Array, Date = context.Date, Error = context.Error, Function = context.Function, Math = context.Math, Object = context.Object, RegExp = context.RegExp, String = context.String, TypeError = context.TypeError; - /** Used for built-in method references. */ var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; - /** Used to detect overreaching core-js shims. */ var coreJsData = context["__core-js_shared__"]; - /** Used to detect methods masquerading as native. */ var maskSrcKey = function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ""); return uid ? "Symbol(src)_1." + uid : ""; }(); - /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; - /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; - /** Used to generate unique IDs. */ var idCounter = 0; - /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ var objectToString = objectProto.toString; - /** Used to restore the original `_` reference in `_.noConflict`. */ var oldDash = root._; - /** Used to detect if a method is native. */ var reIsNative = RegExp("^" + funcToString.call(hasOwnProperty).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"); - /** Built-in value references. */ var Buffer = moduleExports ? context.Buffer : undefined, Symbol = context.Symbol, Uint8Array = context.Uint8Array, defineProperty = Object.defineProperty, getPrototype = overArg(Object.getPrototypeOf, Object), iteratorSymbol = Symbol ? Symbol.iterator : undefined, objectCreate = Object.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; - /** Mocked built-ins. */ var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, ctxNow = Date && Date.now !== root.Date.now && Date.now, ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; - /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeCeil = Math.ceil, nativeFloor = Math.floor, nativeGetSymbols = Object.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, nativeIsFinite = context.isFinite, nativeJoin = arrayProto.join, nativeKeys = overArg(Object.keys, Object), nativeMax = Math.max, nativeMin = Math.min, nativeNow = Date.now, nativeParseInt = context.parseInt, nativeRandom = Math.random, nativeReverse = arrayProto.reverse; - /* Built-in method references that are verified to be native. */ var DataView = getNative(context, "DataView"), Map = getNative(context, "Map"), Promise = getNative(context, "Promise"), Set = getNative(context, "Set"), WeakMap = getNative(context, "WeakMap"), nativeCreate = getNative(Object, "create"), nativeDefineProperty = getNative(Object, "defineProperty"); - /** Used to store function metadata. */ var metaMap = WeakMap && new WeakMap(); - /** Used to lookup unminified function names. */ var realNames = {}; - /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); - /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; - /*------------------------------------------------------------------------*/ - /** - * Creates a `lodash` object which wraps `value` to enable implicit method - * chain sequences. Methods that operate on and return arrays, collections, - * and functions can be chained together. Methods that retrieve a single value - * or may return a primitive value will automatically end the chain sequence - * and return the unwrapped value. Otherwise, the value must be unwrapped - * with `_#value`. - * - * Explicit chain sequences, which must be unwrapped with `_#value`, may be - * enabled using `_.chain`. - * - * The execution of chained methods is lazy, that is, it's deferred until - * `_#value` is implicitly or explicitly called. - * - * Lazy evaluation allows several methods to support shortcut fusion. - * Shortcut fusion is an optimization to merge iteratee calls; this avoids - * the creation of intermediate arrays and can greatly reduce the number of - * iteratee executions. Sections of a chain sequence qualify for shortcut - * fusion if the section is applied to an array of at least `200` elements - * and any iteratees accept only one argument. The heuristic for whether a - * section qualifies for shortcut fusion is subject to change. - * - * Chaining is supported in custom builds as long as the `_#value` method is - * directly or indirectly included in the build. - * - * In addition to lodash methods, wrappers have `Array` and `String` methods. - * - * The wrapper `Array` methods are: - * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` - * - * The wrapper `String` methods are: - * `replace` and `split` - * - * The wrapper methods that support shortcut fusion are: - * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, - * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, - * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` - * - * The chainable wrapper methods are: - * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, - * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, - * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, - * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, - * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, - * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, - * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, - * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, - * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, - * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, - * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, - * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, - * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, - * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, - * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, - * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, - * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, - * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, - * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, - * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, - * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, - * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, - * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, - * `zipObject`, `zipObjectDeep`, and `zipWith` - * - * The wrapper methods that are **not** chainable by default are: - * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, - * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, - * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, - * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, - * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, - * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, - * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, - * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, - * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, - * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, - * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, - * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, - * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, - * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, - * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, - * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, - * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, - * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, - * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, - * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, - * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, - * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, - * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, - * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, - * `upperFirst`, `value`, and `words` - * - * @name _ - * @constructor - * @category Seq - * @param {*} value The value to wrap in a `lodash` instance. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * function square(n) { - * return n * n; - * } - * - * var wrapped = _([1, 2, 3]); - * - * // Returns an unwrapped value. - * wrapped.reduce(_.add); - * // => 6 - * - * // Returns a wrapped value. - * var squares = wrapped.map(square); - * - * _.isArray(squares); - * // => false - * - * _.isArray(squares.value()); - * // => true - */ function lodash(value) { if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { if (value instanceof LodashWrapper) { @@ -1699,19 +749,7 @@ UsergridEventable.mixin = function(destObject) { } return new LodashWrapper(value); } - /** - * The function whose prototype chain sequence wrappers inherit from. - * - * @private - */ function baseLodash() {} - /** - * The base constructor for creating `lodash` wrapper objects. - * - * @private - * @param {*} value The value to wrap. - * @param {boolean} [chainAll] Enable explicit method chain sequences. - */ function LodashWrapper(value, chainAll) { this.__wrapped__ = value; this.__actions__ = []; @@ -1719,57 +757,12 @@ UsergridEventable.mixin = function(destObject) { this.__index__ = 0; this.__values__ = undefined; } - /** - * By default, the template delimiters used by lodash are like those in - * embedded Ruby (ERB). Change the following template settings to use - * alternative delimiters. - * - * @static - * @memberOf _ - * @type {Object} - */ lodash.templateSettings = { - /** - * Used to detect `data` property values to be HTML-escaped. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ escape: reEscape, - /** - * Used to detect code to be evaluated. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ evaluate: reEvaluate, - /** - * Used to detect `data` property values to inject. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ interpolate: reInterpolate, - /** - * Used to reference the data object in the template text. - * - * @memberOf _.templateSettings - * @type {string} - */ variable: "", - /** - * Used to import variables into the compiled template. - * - * @memberOf _.templateSettings - * @type {Object} - */ imports: { - /** - * A reference to the `lodash` function. - * - * @memberOf _.templateSettings.imports - * @type {Function} - */ _: lodash } }; @@ -1777,14 +770,6 @@ UsergridEventable.mixin = function(destObject) { lodash.prototype.constructor = lodash; LodashWrapper.prototype = baseCreate(baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; - /*------------------------------------------------------------------------*/ - /** - * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. - * - * @private - * @constructor - * @param {*} value The value to wrap. - */ function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = []; @@ -1794,14 +779,6 @@ UsergridEventable.mixin = function(destObject) { this.__takeCount__ = MAX_ARRAY_LENGTH; this.__views__ = []; } - /** - * Creates a clone of the lazy wrapper object. - * - * @private - * @name clone - * @memberOf LazyWrapper - * @returns {Object} Returns the cloned `LazyWrapper` object. - */ function lazyClone() { var result = new LazyWrapper(this.__wrapped__); result.__actions__ = copyArray(this.__actions__); @@ -1812,14 +789,6 @@ UsergridEventable.mixin = function(destObject) { result.__views__ = copyArray(this.__views__); return result; } - /** - * Reverses the direction of lazy iteration. - * - * @private - * @name reverse - * @memberOf LazyWrapper - * @returns {Object} Returns the new reversed `LazyWrapper` object. - */ function lazyReverse() { if (this.__filtered__) { var result = new LazyWrapper(this); @@ -1831,14 +800,6 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * Extracts the unwrapped value from its lazy wrapper. - * - * @private - * @name value - * @memberOf LazyWrapper - * @returns {*} Returns the unwrapped value. - */ function lazyValue() { var array = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray(array), isRight = dir < 0, arrLength = isArr ? array.length : 0, view = getView(0, arrLength, this.__views__), start = view.start, end = view.end, length = end - start, index = isRight ? end : start - 1, iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, this.__takeCount__); if (!isArr || arrLength < LARGE_ARRAY_SIZE || arrLength == length && takeCount == length) { @@ -1866,14 +827,6 @@ UsergridEventable.mixin = function(destObject) { } LazyWrapper.prototype = baseCreate(baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; - /*------------------------------------------------------------------------*/ - /** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ function Hash(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); @@ -1882,41 +835,15 @@ UsergridEventable.mixin = function(destObject) { this.set(entry[0], entry[1]); } } - /** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0; } - /** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } - /** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { @@ -1925,29 +852,10 @@ UsergridEventable.mixin = function(destObject) { } return hasOwnProperty.call(data, key) ? data[key] : undefined; } - /** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ function hashHas(key) { var data = this.__data__; return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); } - /** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; @@ -1959,14 +867,6 @@ UsergridEventable.mixin = function(destObject) { Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; - /*------------------------------------------------------------------------*/ - /** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ function ListCache(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); @@ -1975,26 +875,10 @@ UsergridEventable.mixin = function(destObject) { this.set(entry[0], entry[1]); } } - /** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ function listCacheClear() { this.__data__ = []; this.size = 0; } - /** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { @@ -2009,41 +893,13 @@ UsergridEventable.mixin = function(destObject) { --this.size; return true; } - /** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } - /** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } - /** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { @@ -2059,14 +915,6 @@ UsergridEventable.mixin = function(destObject) { ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; - /*------------------------------------------------------------------------*/ - /** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ function MapCache(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); @@ -2075,13 +923,6 @@ UsergridEventable.mixin = function(destObject) { this.set(entry[0], entry[1]); } } - /** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ function mapCacheClear() { this.size = 0; this.__data__ = { @@ -2090,54 +931,17 @@ UsergridEventable.mixin = function(destObject) { string: new Hash() }; } - /** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ function mapCacheDelete(key) { var result = getMapData(this, key)["delete"](key); this.size -= result ? 1 : 0; return result; } - /** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ function mapCacheGet(key) { return getMapData(this, key).get(key); } - /** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ function mapCacheHas(key) { return getMapData(this, key).has(key); } - /** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ function mapCacheSet(key, value) { var data = getMapData(this, key), size = data.size; data.set(key, value); @@ -2149,15 +953,6 @@ UsergridEventable.mixin = function(destObject) { MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; - /*------------------------------------------------------------------------*/ - /** - * - * Creates an array cache object to store unique values. - * - * @private - * @constructor - * @param {Array} [values] The values to cache. - */ function SetCache(values) { var index = -1, length = values ? values.length : 0; this.__data__ = new MapCache(); @@ -2165,105 +960,34 @@ UsergridEventable.mixin = function(destObject) { this.add(values[index]); } } - /** - * Adds `value` to the array cache. - * - * @private - * @name add - * @memberOf SetCache - * @alias push - * @param {*} value The value to cache. - * @returns {Object} Returns the cache instance. - */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } - /** - * Checks if `value` is in the array cache. - * - * @private - * @name has - * @memberOf SetCache - * @param {*} value The value to search for. - * @returns {number} Returns `true` if `value` is found, else `false`. - */ function setCacheHas(value) { return this.__data__.has(value); } SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; - /*------------------------------------------------------------------------*/ - /** - * Creates a stack cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } - /** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ function stackClear() { this.__data__ = new ListCache(); this.size = 0; } - /** - * Removes `key` and its value from the stack. - * - * @private - * @name delete - * @memberOf Stack - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ function stackDelete(key) { var data = this.__data__, result = data["delete"](key); this.size = data.size; return result; } - /** - * Gets the stack value for `key`. - * - * @private - * @name get - * @memberOf Stack - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ function stackGet(key) { return this.__data__.get(key); } - /** - * Checks if a stack value for `key` exists. - * - * @private - * @name has - * @memberOf Stack - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ function stackHas(key) { return this.__data__.has(key); } - /** - * Sets the stack `key` to `value`. - * - * @private - * @name set - * @memberOf Stack - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the stack cache instance. - */ function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { @@ -2284,15 +1008,6 @@ UsergridEventable.mixin = function(destObject) { Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; - /*------------------------------------------------------------------------*/ - /** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ function arrayLikeKeys(value, inherited) { var result = isArray(value) || isArguments(value) ? baseTimes(value.length, String) : []; var length = result.length, skipIndexes = !!length; @@ -2303,95 +1018,35 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * A specialized version of `_.sample` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} array The array to sample. - * @returns {*} Returns the random element. - */ function arraySample(array) { var length = array.length; return length ? array[baseRandom(0, length - 1)] : undefined; } - /** - * A specialized version of `_.sampleSize` for arrays. - * - * @private - * @param {Array} array The array to sample. - * @param {number} n The number of elements to sample. - * @returns {Array} Returns the random elements. - */ function arraySampleSize(array, n) { var result = arrayShuffle(array); result.length = baseClamp(n, 0, result.length); return result; } - /** - * A specialized version of `_.shuffle` for arrays. - * - * @private - * @param {Array} array The array to shuffle. - * @returns {Array} Returns the new shuffled array. - */ function arrayShuffle(array) { return shuffleSelf(copyArray(array)); } - /** - * Used by `_.defaults` to customize its `_.assignIn` use. - * - * @private - * @param {*} objValue The destination value. - * @param {*} srcValue The source value. - * @param {string} key The key of the property to assign. - * @param {Object} object The parent object of `objValue`. - * @returns {*} Returns the value to assign. - */ function assignInDefaults(objValue, srcValue, key, object) { if (objValue === undefined || eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key)) { return srcValue; } return objValue; } - /** - * This function is like `assignValue` except that it doesn't assign - * `undefined` values. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ function assignMergeValue(object, key, value) { if (value !== undefined && !eq(object[key], value) || typeof key == "number" && value === undefined && !(key in object)) { baseAssignValue(object, key, value); } } - /** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || value === undefined && !(key in object)) { baseAssignValue(object, key, value); } } - /** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ function assocIndexOf(array, key) { var length = array.length; while (length--) { @@ -2401,44 +1056,15 @@ UsergridEventable.mixin = function(destObject) { } return -1; } - /** - * Aggregates elements of `collection` on `accumulator` with keys transformed - * by `iteratee` and values set by `setter`. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform keys. - * @param {Object} accumulator The initial aggregated object. - * @returns {Function} Returns `accumulator`. - */ function baseAggregator(collection, setter, iteratee, accumulator) { baseEach(collection, function(value, key, collection) { setter(accumulator, value, iteratee(value), collection); }); return accumulator; } - /** - * The base implementation of `_.assign` without support for multiple sources - * or `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ function baseAssign(object, source) { return object && copyObject(source, keys(source), object); } - /** - * The base implementation of `assignValue` and `assignMergeValue` without - * value checks. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ function baseAssignValue(object, key, value) { if (key == "__proto__" && defineProperty) { defineProperty(object, key, { @@ -2451,14 +1077,6 @@ UsergridEventable.mixin = function(destObject) { object[key] = value; } } - /** - * The base implementation of `_.at` without support for individual paths. - * - * @private - * @param {Object} object The object to iterate over. - * @param {string[]} paths The property paths of elements to pick. - * @returns {Array} Returns the picked elements. - */ function baseAt(object, paths) { var index = -1, isNil = object == null, length = paths.length, result = Array(length); while (++index < length) { @@ -2466,15 +1084,6 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * The base implementation of `_.clamp` which doesn't coerce arguments. - * - * @private - * @param {number} number The number to clamp. - * @param {number} [lower] The lower bound. - * @param {number} upper The upper bound. - * @returns {number} Returns the clamped number. - */ function baseClamp(number, lower, upper) { if (number === number) { if (upper !== undefined) { @@ -2486,20 +1095,6 @@ UsergridEventable.mixin = function(destObject) { } return number; } - /** - * The base implementation of `_.clone` and `_.cloneDeep` which tracks - * traversed objects. - * - * @private - * @param {*} value The value to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @param {boolean} [isFull] Specify a clone including symbols. - * @param {Function} [customizer] The function to customize cloning. - * @param {string} [key] The key of `value`. - * @param {Object} [object] The parent object of `value`. - * @param {Object} [stack] Tracks traversed objects and their clone counterparts. - * @returns {*} Returns the cloned value. - */ function baseClone(value, isDeep, isFull, customizer, key, object, stack) { var result; if (customizer) { @@ -2552,27 +1147,12 @@ UsergridEventable.mixin = function(destObject) { }); return result; } - /** - * The base implementation of `_.conforms` which doesn't clone `source`. - * - * @private - * @param {Object} source The object of property predicates to conform to. - * @returns {Function} Returns the new spec function. - */ function baseConforms(source) { var props = keys(source); return function(object) { return baseConformsTo(object, source, props); }; } - /** - * The base implementation of `_.conformsTo` which accepts `props` to check. - * - * @private - * @param {Object} object The object to inspect. - * @param {Object} source The object of property predicates to conform to. - * @returns {boolean} Returns `true` if `object` conforms, else `false`. - */ function baseConformsTo(object, source, props) { var length = props.length; if (object == null) { @@ -2587,27 +1167,9 @@ UsergridEventable.mixin = function(destObject) { } return true; } - /** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} prototype The object to inherit from. - * @returns {Object} Returns the new object. - */ function baseCreate(proto) { return isObject(proto) ? objectCreate(proto) : {}; } - /** - * The base implementation of `_.delay` and `_.defer` which accepts `args` - * to provide to `func`. - * - * @private - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @param {Array} args The arguments to provide to `func`. - * @returns {number|Object} Returns the timer id or timeout object. - */ function baseDelay(func, wait, args) { if (typeof func != "function") { throw new TypeError(FUNC_ERROR_TEXT); @@ -2616,17 +1178,6 @@ UsergridEventable.mixin = function(destObject) { func.apply(undefined, args); }, wait); } - /** - * The base implementation of methods like `_.difference` without support - * for excluding multiple arrays or iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Array} values The values to exclude. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { @@ -2660,33 +1211,8 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * The base implementation of `_.forEach` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - */ var baseEach = createBaseEach(baseForOwn); - /** - * The base implementation of `_.forEachRight` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - */ var baseEachRight = createBaseEach(baseForOwnRight, true); - /** - * The base implementation of `_.every` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false` - */ function baseEvery(collection, predicate) { var result = true; baseEach(collection, function(value, index, collection) { @@ -2695,16 +1221,6 @@ UsergridEventable.mixin = function(destObject) { }); return result; } - /** - * The base implementation of methods like `_.max` and `_.min` which accepts a - * `comparator` to determine the extremum value. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The iteratee invoked per iteration. - * @param {Function} comparator The comparator used to compare values. - * @returns {*} Returns the extremum value. - */ function baseExtremum(array, iteratee, comparator) { var index = -1, length = array.length; while (++index < length) { @@ -2715,16 +1231,6 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * The base implementation of `_.fill` without an iteratee call guard. - * - * @private - * @param {Array} array The array to fill. - * @param {*} value The value to fill `array` with. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns `array`. - */ function baseFill(array, value, start, end) { var length = array.length; start = toInteger(start); @@ -2741,14 +1247,6 @@ UsergridEventable.mixin = function(destObject) { } return array; } - /** - * The base implementation of `_.filter` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ function baseFilter(collection, predicate) { var result = []; baseEach(collection, function(value, index, collection) { @@ -2758,17 +1256,6 @@ UsergridEventable.mixin = function(destObject) { }); return result; } - /** - * The base implementation of `_.flatten` with support for restricting flattening. - * - * @private - * @param {Array} array The array to flatten. - * @param {number} depth The maximum recursion depth. - * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. - * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. - * @param {Array} [result=[]] The initial result value. - * @returns {Array} Returns the new flattened array. - */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = isFlattenable); @@ -2787,73 +1274,19 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * The base implementation of `baseForOwn` which iterates over `object` - * properties returned by `keysFunc` and invokes `iteratee` for each property. - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ var baseFor = createBaseFor(); - /** - * This function is like `baseFor` except that it iterates over properties - * in the opposite order. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ var baseForRight = createBaseFor(true); - /** - * The base implementation of `_.forOwn` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ function baseForOwn(object, iteratee) { return object && baseFor(object, iteratee, keys); } - /** - * The base implementation of `_.forOwnRight` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ function baseForOwnRight(object, iteratee) { return object && baseForRight(object, iteratee, keys); } - /** - * The base implementation of `_.functions` which creates an array of - * `object` function property names filtered from `props`. - * - * @private - * @param {Object} object The object to inspect. - * @param {Array} props The property names to filter. - * @returns {Array} Returns the function names. - */ function baseFunctions(object, props) { return arrayFilter(props, function(key) { return isFunction(object[key]); }); } - /** - * The base implementation of `_.get` without support for default values. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @returns {*} Returns the resolved value. - */ function baseGet(object, path) { path = isKey(path, object) ? [ path ] : castPath(path); var index = 0, length = path.length; @@ -2862,87 +1295,25 @@ UsergridEventable.mixin = function(destObject) { } return index && index == length ? object : undefined; } - /** - * The base implementation of `getAllKeys` and `getAllKeysIn` which uses - * `keysFunc` and `symbolsFunc` to get the enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Function} keysFunc The function to get the keys of `object`. - * @param {Function} symbolsFunc The function to get the symbols of `object`. - * @returns {Array} Returns the array of property names and symbols. - */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } - /** - * The base implementation of `getTag`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ function baseGetTag(value) { return objectToString.call(value); } - /** - * The base implementation of `_.gt` which doesn't coerce arguments. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than `other`, - * else `false`. - */ function baseGt(value, other) { return value > other; } - /** - * The base implementation of `_.has` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ function baseHas(object, key) { return object != null && hasOwnProperty.call(object, key); } - /** - * The base implementation of `_.hasIn` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ function baseHasIn(object, key) { return object != null && key in Object(object); } - /** - * The base implementation of `_.inRange` which doesn't coerce arguments. - * - * @private - * @param {number} number The number to check. - * @param {number} start The start of the range. - * @param {number} end The end of the range. - * @returns {boolean} Returns `true` if `number` is in the range, else `false`. - */ function baseInRange(number, start, end) { return number >= nativeMin(start, end) && number < nativeMax(start, end); } - /** - * The base implementation of methods like `_.intersection`, without support - * for iteratee shorthands, that accepts an array of arrays to inspect. - * - * @private - * @param {Array} arrays The arrays to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of shared values. - */ function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { @@ -2974,33 +1345,12 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * The base implementation of `_.invert` and `_.invertBy` which inverts - * `object` with values transformed by `iteratee` and set by `setter`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform values. - * @param {Object} accumulator The initial inverted object. - * @returns {Function} Returns `accumulator`. - */ function baseInverter(object, setter, iteratee, accumulator) { baseForOwn(object, function(value, key, object) { setter(accumulator, iteratee(value), key, object); }); return accumulator; } - /** - * The base implementation of `_.invoke` without support for individual - * method arguments. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the method to invoke. - * @param {Array} args The arguments to invoke the method with. - * @returns {*} Returns the result of the invoked method. - */ function baseInvoke(object, path, args) { if (!isKey(path, object)) { path = castPath(path); @@ -3010,41 +1360,12 @@ UsergridEventable.mixin = function(destObject) { var func = object == null ? object : object[toKey(path)]; return func == null ? undefined : apply(func, object, args); } - /** - * The base implementation of `_.isArrayBuffer` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. - */ function baseIsArrayBuffer(value) { return isObjectLike(value) && objectToString.call(value) == arrayBufferTag; } - /** - * The base implementation of `_.isDate` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a date object, else `false`. - */ function baseIsDate(value) { return isObjectLike(value) && objectToString.call(value) == dateTag; } - /** - * The base implementation of `_.isEqual` which supports partial comparisons - * and tracks traversed objects. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {Function} [customizer] The function to customize comparisons. - * @param {boolean} [bitmask] The bitmask of comparison flags. - * The bitmask may be composed of the following flags: - * 1 - Unordered comparison - * 2 - Partial comparison - * @param {Object} [stack] Tracks traversed `value` and `other` objects. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - */ function baseIsEqual(value, other, customizer, bitmask, stack) { if (value === other) { return true; @@ -3054,21 +1375,6 @@ UsergridEventable.mixin = function(destObject) { } return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack); } - /** - * A specialized version of `baseIsEqual` for arrays and objects which performs - * deep comparisons and tracks traversed objects enabling objects with circular - * references to be compared. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Function} [customizer] The function to customize comparisons. - * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual` - * for more details. - * @param {Object} [stack] Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = arrayTag, othTag = arrayTag; if (!objIsArr) { @@ -3098,26 +1404,9 @@ UsergridEventable.mixin = function(destObject) { stack || (stack = new Stack()); return equalObjects(object, other, equalFunc, customizer, bitmask, stack); } - /** - * The base implementation of `_.isMap` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a map, else `false`. - */ function baseIsMap(value) { return isObjectLike(value) && getTag(value) == mapTag; } - /** - * The base implementation of `_.isMatch` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Array} matchData The property names, values, and compare flags to match. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { @@ -3149,14 +1438,6 @@ UsergridEventable.mixin = function(destObject) { } return true; } - /** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; @@ -3164,43 +1445,15 @@ UsergridEventable.mixin = function(destObject) { var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } - /** - * The base implementation of `_.isRegExp` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. - */ function baseIsRegExp(value) { return isObject(value) && objectToString.call(value) == regexpTag; } - /** - * The base implementation of `_.isSet` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a set, else `false`. - */ function baseIsSet(value) { return isObjectLike(value) && getTag(value) == setTag; } - /** - * The base implementation of `_.isTypedArray` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objectToString.call(value)]; } - /** - * The base implementation of `_.iteratee`. - * - * @private - * @param {*} [value=_.identity] The value to convert to an iteratee. - * @returns {Function} Returns the iteratee. - */ function baseIteratee(value) { if (typeof value == "function") { return value; @@ -3213,13 +1466,6 @@ UsergridEventable.mixin = function(destObject) { } return property(value); } - /** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); @@ -3232,13 +1478,6 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ function baseKeysIn(object) { if (!isObject(object)) { return nativeKeysIn(object); @@ -3251,26 +1490,9 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * The base implementation of `_.lt` which doesn't coerce arguments. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than `other`, - * else `false`. - */ function baseLt(value, other) { return value < other; } - /** - * The base implementation of `_.map` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value, key, collection) { @@ -3278,13 +1500,6 @@ UsergridEventable.mixin = function(destObject) { }); return result; } - /** - * The base implementation of `_.matches` which doesn't clone `source`. - * - * @private - * @param {Object} source The object of property values to match. - * @returns {Function} Returns the new spec function. - */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { @@ -3294,14 +1509,6 @@ UsergridEventable.mixin = function(destObject) { return object === source || baseIsMatch(object, source, matchData); }; } - /** - * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. - * - * @private - * @param {string} path The path of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ function baseMatchesProperty(path, srcValue) { if (isKey(path) && isStrictComparable(srcValue)) { return matchesStrictComparable(toKey(path), srcValue); @@ -3311,17 +1518,6 @@ UsergridEventable.mixin = function(destObject) { return objValue === undefined && objValue === srcValue ? hasIn(object, path) : baseIsEqual(srcValue, objValue, undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG); }; } - /** - * The base implementation of `_.merge` without support for multiple sources. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {number} srcIndex The index of `source`. - * @param {Function} [customizer] The function to customize merged values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; @@ -3346,21 +1542,6 @@ UsergridEventable.mixin = function(destObject) { } }); } - /** - * A specialized version of `baseMerge` for arrays and objects which performs - * deep merges and tracks traversed objects enabling objects with circular - * references to be merged. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {string} key The key of the value to merge. - * @param {number} srcIndex The index of `source`. - * @param {Function} mergeFunc The function to merge values. - * @param {Function} [customizer] The function to customize assigned values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = object[key], srcValue = source[key], stacked = stack.get(srcValue); if (stacked) { @@ -3400,14 +1581,6 @@ UsergridEventable.mixin = function(destObject) { } assignMergeValue(object, key, newValue); } - /** - * The base implementation of `_.nth` which doesn't coerce arguments. - * - * @private - * @param {Array} array The array to query. - * @param {number} n The index of the element to return. - * @returns {*} Returns the nth element of `array`. - */ function baseNth(array, n) { var length = array.length; if (!length) { @@ -3416,15 +1589,6 @@ UsergridEventable.mixin = function(destObject) { n += n < 0 ? length : 0; return isIndex(n, length) ? array[n] : undefined; } - /** - * The base implementation of `_.orderBy` without param guards. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. - * @param {string[]} orders The sort orders of `iteratees`. - * @returns {Array} Returns the new sorted array. - */ function baseOrderBy(collection, iteratees, orders) { var index = -1; iteratees = arrayMap(iteratees.length ? iteratees : [ identity ], baseUnary(getIteratee())); @@ -3442,30 +1606,12 @@ UsergridEventable.mixin = function(destObject) { return compareMultiple(object, other, orders); }); } - /** - * The base implementation of `_.pick` without support for individual - * property identifiers. - * - * @private - * @param {Object} object The source object. - * @param {string[]} props The property identifiers to pick. - * @returns {Object} Returns the new object. - */ function basePick(object, props) { object = Object(object); return basePickBy(object, props, function(value, key) { return key in object; }); } - /** - * The base implementation of `_.pickBy` without support for iteratee shorthands. - * - * @private - * @param {Object} object The source object. - * @param {string[]} props The property identifiers to pick from. - * @param {Function} predicate The function invoked per property. - * @returns {Object} Returns the new object. - */ function basePickBy(object, props, predicate) { var index = -1, length = props.length, result = {}; while (++index < length) { @@ -3476,29 +1622,11 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * A specialized version of `baseProperty` which supports deep paths. - * - * @private - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. - */ function basePropertyDeep(path) { return function(object) { return baseGet(object, path); }; } - /** - * The base implementation of `_.pullAllBy` without support for iteratee - * shorthands. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns `array`. - */ function basePullAll(array, values, iteratee, comparator) { var indexOf = comparator ? baseIndexOfWith : baseIndexOf, index = -1, length = values.length, seen = array; if (array === values) { @@ -3518,15 +1646,6 @@ UsergridEventable.mixin = function(destObject) { } return array; } - /** - * The base implementation of `_.pullAt` without support for individual - * indexes or capturing the removed elements. - * - * @private - * @param {Array} array The array to modify. - * @param {number[]} indexes The indexes of elements to remove. - * @returns {Array} Returns `array`. - */ function basePullAt(array, indexes) { var length = array ? indexes.length : 0, lastIndex = length - 1; while (length--) { @@ -3547,29 +1666,9 @@ UsergridEventable.mixin = function(destObject) { } return array; } - /** - * The base implementation of `_.random` without support for returning - * floating-point numbers. - * - * @private - * @param {number} lower The lower bound. - * @param {number} upper The upper bound. - * @returns {number} Returns the random number. - */ function baseRandom(lower, upper) { return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); } - /** - * The base implementation of `_.range` and `_.rangeRight` which doesn't - * coerce arguments. - * - * @private - * @param {number} start The start of the range. - * @param {number} end The end of the range. - * @param {number} step The value to increment or decrement by. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Array} Returns the range of numbers. - */ function baseRange(start, end, step, fromRight) { var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); while (length--) { @@ -3578,14 +1677,6 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * The base implementation of `_.repeat` which doesn't coerce arguments. - * - * @private - * @param {string} string The string to repeat. - * @param {number} n The number of times to repeat the string. - * @returns {string} Returns the repeated string. - */ function baseRepeat(string, n) { var result = ""; if (!string || n < 1 || n > MAX_SAFE_INTEGER) { @@ -3602,27 +1693,9 @@ UsergridEventable.mixin = function(destObject) { } while (n); return result; } - /** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ function baseRest(func, start) { return setToString(overRest(func, start, identity), func + ""); } - /** - * The base implementation of `_.set`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. - */ function baseSet(object, path, value, customizer) { if (!isObject(object)) { return object; @@ -3643,26 +1716,10 @@ UsergridEventable.mixin = function(destObject) { } return object; } - /** - * The base implementation of `setData` without support for hot loop shorting. - * - * @private - * @param {Function} func The function to associate metadata with. - * @param {*} data The metadata. - * @returns {Function} Returns `func`. - */ var baseSetData = !metaMap ? identity : function(func, data) { metaMap.set(func, data); return func; }; - /** - * The base implementation of `setToString` without support for hot loop shorting. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ var baseSetToString = !nativeDefineProperty ? identity : function(func, string) { return nativeDefineProperty(func, "toString", { configurable: true, @@ -3671,15 +1728,6 @@ UsergridEventable.mixin = function(destObject) { writable: true }); }; - /** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { @@ -3697,15 +1745,6 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * The base implementation of `_.some` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ function baseSome(collection, predicate) { var result; baseEach(collection, function(value, index, collection) { @@ -3714,18 +1753,6 @@ UsergridEventable.mixin = function(destObject) { }); return !!result; } - /** - * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which - * performs a binary search of `array` to determine the index at which `value` - * should be inserted into `array` in order to maintain its sort order. - * - * @private - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {boolean} [retHighest] Specify returning the highest qualified index. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - */ function baseSortedIndex(array, value, retHighest) { var low = 0, high = array ? array.length : low; if (typeof value == "number" && value === value && high <= HALF_MAX_ARRAY_LENGTH) { @@ -3741,19 +1768,6 @@ UsergridEventable.mixin = function(destObject) { } return baseSortedIndexBy(array, value, identity, retHighest); } - /** - * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` - * which invokes `iteratee` for `value` and each element of `array` to compute - * their sort ranking. The iteratee is invoked with one argument; (value). - * - * @private - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} iteratee The iteratee invoked per element. - * @param {boolean} [retHighest] Specify returning the highest qualified index. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - */ function baseSortedIndexBy(array, value, iteratee, retHighest) { value = iteratee(value); var low = 0, high = array ? array.length : 0, valIsNaN = value !== value, valIsNull = value === null, valIsSymbol = isSymbol(value), valIsUndefined = value === undefined; @@ -3780,15 +1794,6 @@ UsergridEventable.mixin = function(destObject) { } return nativeMin(high, MAX_ARRAY_INDEX); } - /** - * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @returns {Array} Returns the new duplicate free array. - */ function baseSortedUniq(array, iteratee) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { @@ -3800,14 +1805,6 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * The base implementation of `_.toNumber` which doesn't ensure correct - * conversions of binary, hexadecimal, or octal string values. - * - * @private - * @param {*} value The value to process. - * @returns {number} Returns the number. - */ function baseToNumber(value) { if (typeof value == "number") { return value; @@ -3817,14 +1814,6 @@ UsergridEventable.mixin = function(destObject) { } return +value; } - /** - * The base implementation of `_.toString` which doesn't convert nullish - * values to empty strings. - * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ function baseToString(value) { if (typeof value == "string") { return value; @@ -3835,15 +1824,6 @@ UsergridEventable.mixin = function(destObject) { var result = value + ""; return result == "0" && 1 / value == -INFINITY ? "-0" : result; } - /** - * The base implementation of `_.uniqBy` without support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new duplicate free array. - */ function baseUniq(array, iteratee, comparator) { var index = -1, includes = arrayIncludes, length = array.length, isCommon = true, result = [], seen = result; if (comparator) { @@ -3883,59 +1863,20 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * The base implementation of `_.unset`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to unset. - * @returns {boolean} Returns `true` if the property is deleted, else `false`. - */ function baseUnset(object, path) { path = isKey(path, object) ? [ path ] : castPath(path); object = parent(object, path); var key = toKey(last(path)); return !(object != null && hasOwnProperty.call(object, key)) || delete object[key]; } - /** - * The base implementation of `_.update`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to update. - * @param {Function} updater The function to produce the updated value. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. - */ function baseUpdate(object, path, updater, customizer) { return baseSet(object, path, updater(baseGet(object, path)), customizer); } - /** - * The base implementation of methods like `_.dropWhile` and `_.takeWhile` - * without support for iteratee shorthands. - * - * @private - * @param {Array} array The array to query. - * @param {Function} predicate The function invoked per iteration. - * @param {boolean} [isDrop] Specify dropping elements instead of taking them. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Array} Returns the slice of `array`. - */ function baseWhile(array, predicate, isDrop, fromRight) { var length = array.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {} return isDrop ? baseSlice(array, fromRight ? 0 : index, fromRight ? index + 1 : length) : baseSlice(array, fromRight ? index + 1 : 0, fromRight ? length : index); } - /** - * The base implementation of `wrapperValue` which returns the result of - * performing a sequence of actions on the unwrapped `value`, where each - * successive action is supplied the return value of the previous. - * - * @private - * @param {*} value The unwrapped value. - * @param {Array} actions Actions to perform to resolve the unwrapped value. - * @returns {*} Returns the resolved value. - */ function baseWrapperValue(value, actions) { var result = value; if (result instanceof LazyWrapper) { @@ -3945,16 +1886,6 @@ UsergridEventable.mixin = function(destObject) { return action.func.apply(action.thisArg, arrayPush([ result ], action.args)); }, result); } - /** - * The base implementation of methods like `_.xor`, without support for - * iteratee shorthands, that accepts an array of arrays to inspect. - * - * @private - * @param {Array} arrays The arrays to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of values. - */ function baseXor(arrays, iteratee, comparator) { var index = -1, length = arrays.length; while (++index < length) { @@ -3962,15 +1893,6 @@ UsergridEventable.mixin = function(destObject) { } return result && result.length ? baseUniq(result, iteratee, comparator) : []; } - /** - * This base implementation of `_.zipObject` which assigns values using `assignFunc`. - * - * @private - * @param {Array} props The property identifiers. - * @param {Array} values The property values. - * @param {Function} assignFunc The function to assign values. - * @returns {Object} Returns the new object. - */ function baseZipObject(props, values, assignFunc) { var index = -1, length = props.length, valsLength = values.length, result = {}; while (++index < length) { @@ -3979,77 +1901,24 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * Casts `value` to an empty array if it's not an array like object. - * - * @private - * @param {*} value The value to inspect. - * @returns {Array|Object} Returns the cast array-like object. - */ function castArrayLikeObject(value) { return isArrayLikeObject(value) ? value : []; } - /** - * Casts `value` to `identity` if it's not a function. - * - * @private - * @param {*} value The value to inspect. - * @returns {Function} Returns cast function. - */ function castFunction(value) { return typeof value == "function" ? value : identity; } - /** - * Casts `value` to a path array if it's not one. - * - * @private - * @param {*} value The value to inspect. - * @returns {Array} Returns the cast property path array. - */ function castPath(value) { return isArray(value) ? value : stringToPath(value); } - /** - * A `baseRest` alias which can be replaced with `identity` by module - * replacement plugins. - * - * @private - * @type {Function} - * @param {Function} func The function to apply a rest parameter to. - * @returns {Function} Returns the new function. - */ var castRest = baseRest; - /** - * Casts `array` to a slice if it's needed. - * - * @private - * @param {Array} array The array to inspect. - * @param {number} start The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the cast slice. - */ function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return !start && end >= length ? array : baseSlice(array, start, end); } - /** - * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). - * - * @private - * @param {number|Object} id The timer id or timeout object of the timer to clear. - */ var clearTimeout = ctxClearTimeout || function(id) { return root.clearTimeout(id); }; - /** - * Creates a clone of `buffer`. - * - * @private - * @param {Buffer} buffer The buffer to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Buffer} Returns the cloned buffer. - */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); @@ -4058,98 +1927,35 @@ UsergridEventable.mixin = function(destObject) { buffer.copy(result); return result; } - /** - * Creates a clone of `arrayBuffer`. - * - * @private - * @param {ArrayBuffer} arrayBuffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. - */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new Uint8Array(result).set(new Uint8Array(arrayBuffer)); return result; } - /** - * Creates a clone of `dataView`. - * - * @private - * @param {Object} dataView The data view to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned data view. - */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } - /** - * Creates a clone of `map`. - * - * @private - * @param {Object} map The map to clone. - * @param {Function} cloneFunc The function to clone values. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned map. - */ function cloneMap(map, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map); return arrayReduce(array, addMapEntry, new map.constructor()); } - /** - * Creates a clone of `regexp`. - * - * @private - * @param {Object} regexp The regexp to clone. - * @returns {Object} Returns the cloned regexp. - */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } - /** - * Creates a clone of `set`. - * - * @private - * @param {Object} set The set to clone. - * @param {Function} cloneFunc The function to clone values. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned set. - */ function cloneSet(set, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set); return arrayReduce(array, addSetEntry, new set.constructor()); } - /** - * Creates a clone of the `symbol` object. - * - * @private - * @param {Object} symbol The symbol object to clone. - * @returns {Object} Returns the cloned symbol object. - */ function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } - /** - * Creates a clone of `typedArray`. - * - * @private - * @param {Object} typedArray The typed array to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned typed array. - */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } - /** - * Compares values to sort them in ascending order. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {number} Returns the sort order indicator for `value`. - */ function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol(value); @@ -4163,20 +1969,6 @@ UsergridEventable.mixin = function(destObject) { } return 0; } - /** - * Used by `_.orderBy` to compare multiple properties of a value to another - * and stable sort them. - * - * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, - * specify an order of "desc" for descending or "asc" for ascending sort order - * of corresponding values. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {boolean[]|string[]} orders The order to sort by for each property. - * @returns {number} Returns the sort order indicator for `object`. - */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { @@ -4191,17 +1983,6 @@ UsergridEventable.mixin = function(destObject) { } return object.index - other.index; } - /** - * Creates an array that is the composition of partially applied arguments, - * placeholders, and provided arguments into a single array of arguments. - * - * @private - * @param {Array} args The provided arguments. - * @param {Array} partials The arguments to prepend to those provided. - * @param {Array} holders The `partials` placeholder indexes. - * @params {boolean} [isCurried] Specify composing for a curried function. - * @returns {Array} Returns the new array of composed arguments. - */ function composeArgs(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(leftLength + rangeLength), isUncurried = !isCurried; while (++leftIndex < leftLength) { @@ -4217,17 +1998,6 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * This function is like `composeArgs` except that the arguments composition - * is tailored for `_.partialRight`. - * - * @private - * @param {Array} args The provided arguments. - * @param {Array} partials The arguments to append to those provided. - * @param {Array} holders The `partials` placeholder indexes. - * @params {boolean} [isCurried] Specify composing for a curried function. - * @returns {Array} Returns the new array of composed arguments. - */ function composeArgsRight(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(rangeLength + rightLength), isUncurried = !isCurried; while (++argsIndex < rangeLength) { @@ -4244,14 +2014,6 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * Copies the values of `source` to `array`. - * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. - */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); @@ -4260,16 +2022,6 @@ UsergridEventable.mixin = function(destObject) { } return array; } - /** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); @@ -4288,38 +2040,15 @@ UsergridEventable.mixin = function(destObject) { } return object; } - /** - * Copies own symbol properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy symbols from. - * @param {Object} [object={}] The object to copy symbols to. - * @returns {Object} Returns `object`. - */ function copySymbols(source, object) { return copyObject(source, getSymbols(source), object); } - /** - * Creates a function like `_.groupBy`. - * - * @private - * @param {Function} setter The function to set accumulator values. - * @param {Function} [initializer] The accumulator object initializer. - * @returns {Function} Returns the new aggregator function. - */ function createAggregator(setter, initializer) { return function(collection, iteratee) { var func = isArray(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {}; return func(collection, setter, getIteratee(iteratee, 2), accumulator); }; } - /** - * Creates a function like `_.assign`. - * - * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. - */ function createAssigner(assigner) { return baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; @@ -4339,14 +2068,6 @@ UsergridEventable.mixin = function(destObject) { return object; }); } - /** - * Creates a `baseEach` or `baseEachRight` function. - * - * @private - * @param {Function} eachFunc The function to iterate over a collection. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { @@ -4364,13 +2085,6 @@ UsergridEventable.mixin = function(destObject) { return collection; }; } - /** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; @@ -4383,16 +2097,6 @@ UsergridEventable.mixin = function(destObject) { return object; }; } - /** - * Creates a function that wraps `func` to invoke it with the optional `this` - * binding of `thisArg`. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {*} [thisArg] The `this` binding of `func`. - * @returns {Function} Returns the new wrapped function. - */ function createBind(func, bitmask, thisArg) { var isBind = bitmask & BIND_FLAG, Ctor = createCtor(func); function wrapper() { @@ -4401,13 +2105,6 @@ UsergridEventable.mixin = function(destObject) { } return wrapper; } - /** - * Creates a function like `_.lowerFirst`. - * - * @private - * @param {string} methodName The name of the `String` case method to use. - * @returns {Function} Returns the new case function. - */ function createCaseFirst(methodName) { return function(string) { string = toString(string); @@ -4417,26 +2114,11 @@ UsergridEventable.mixin = function(destObject) { return chr[methodName]() + trailing; }; } - /** - * Creates a function like `_.camelCase`. - * - * @private - * @param {Function} callback The function to combine each word. - * @returns {Function} Returns the new compounder function. - */ function createCompounder(callback) { return function(string) { return arrayReduce(words(deburr(string).replace(reApos, "")), callback, ""); }; } - /** - * Creates a function that produces an instance of `Ctor` regardless of - * whether it was invoked as part of a `new` expression or by `call` or `apply`. - * - * @private - * @param {Function} Ctor The constructor to wrap. - * @returns {Function} Returns the new wrapped function. - */ function createCtor(Ctor) { return function() { var args = arguments; @@ -4469,15 +2151,6 @@ UsergridEventable.mixin = function(destObject) { return isObject(result) ? result : thisBinding; }; } - /** - * Creates a function that wraps `func` to enable currying. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {number} arity The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ function createCurry(func, bitmask, arity) { var Ctor = createCtor(func); function wrapper() { @@ -4495,13 +2168,6 @@ UsergridEventable.mixin = function(destObject) { } return wrapper; } - /** - * Creates a `_.find` or `_.findLast` function. - * - * @private - * @param {Function} findIndexFunc The function to find the collection index. - * @returns {Function} Returns the new find function. - */ function createFind(findIndexFunc) { return function(collection, predicate, fromIndex) { var iterable = Object(collection); @@ -4516,13 +2182,6 @@ UsergridEventable.mixin = function(destObject) { return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; }; } - /** - * Creates a `_.flow` or `_.flowRight` function. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new flow function. - */ function createFlow(fromRight) { return flatRest(function(funcs) { var length = funcs.length, index = length, prereq = LodashWrapper.prototype.thru; @@ -4561,25 +2220,6 @@ UsergridEventable.mixin = function(destObject) { }; }); } - /** - * Creates a function that wraps `func` to invoke it with optional `this` - * binding of `thisArg`, partial application, and currying. - * - * @private - * @param {Function|string} func The function or method name to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {*} [thisArg] The `this` binding of `func`. - * @param {Array} [partials] The arguments to prepend to those provided to - * the new function. - * @param {Array} [holders] The `partials` placeholder indexes. - * @param {Array} [partialsRight] The arguments to append to those provided - * to the new function. - * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. - * @param {Array} [argPos] The argument positions of the new function. - * @param {number} [ary] The arity cap of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & ARY_FLAG, isBind = bitmask & BIND_FLAG, isBindKey = bitmask & BIND_KEY_FLAG, isCurried = bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG), isFlip = bitmask & FLIP_FLAG, Ctor = isBindKey ? undefined : createCtor(func); function wrapper() { @@ -4618,27 +2258,11 @@ UsergridEventable.mixin = function(destObject) { } return wrapper; } - /** - * Creates a function like `_.invertBy`. - * - * @private - * @param {Function} setter The function to set accumulator values. - * @param {Function} toIteratee The function to resolve iteratees. - * @returns {Function} Returns the new inverter function. - */ function createInverter(setter, toIteratee) { return function(object, iteratee) { return baseInverter(object, setter, toIteratee(iteratee), {}); }; } - /** - * Creates a function that performs a mathematical operation on two values. - * - * @private - * @param {Function} operator The function to perform the operation. - * @param {number} [defaultValue] The value used for `undefined` arguments. - * @returns {Function} Returns the new mathematical operation function. - */ function createMathOperation(operator, defaultValue) { return function(value, other) { var result; @@ -4664,13 +2288,6 @@ UsergridEventable.mixin = function(destObject) { return result; }; } - /** - * Creates a function like `_.over`. - * - * @private - * @param {Function} arrayFunc The function to iterate over iteratees. - * @returns {Function} Returns the new over function. - */ function createOver(arrayFunc) { return flatRest(function(iteratees) { iteratees = arrayMap(iteratees, baseUnary(getIteratee())); @@ -4682,15 +2299,6 @@ UsergridEventable.mixin = function(destObject) { }); }); } - /** - * Creates the padding for `string` based on `length`. The `chars` string - * is truncated if the number of characters exceeds `length`. - * - * @private - * @param {number} length The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padding for `string`. - */ function createPadding(length, chars) { chars = chars === undefined ? " " : baseToString(chars); var charsLength = chars.length; @@ -4700,18 +2308,6 @@ UsergridEventable.mixin = function(destObject) { var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); return hasUnicode(chars) ? castSlice(stringToArray(result), 0, length).join("") : result.slice(0, length); } - /** - * Creates a function that wraps `func` to invoke it with the `this` binding - * of `thisArg` and `partials` prepended to the arguments it receives. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} partials The arguments to prepend to those provided to - * the new function. - * @returns {Function} Returns the new wrapped function. - */ function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & BIND_FLAG, Ctor = createCtor(func); function wrapper() { @@ -4726,13 +2322,6 @@ UsergridEventable.mixin = function(destObject) { } return wrapper; } - /** - * Creates a `_.range` or `_.rangeRight` function. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new range function. - */ function createRange(fromRight) { return function(start, end, step) { if (step && typeof step != "number" && isIterateeCall(start, end, step)) { @@ -4749,13 +2338,6 @@ UsergridEventable.mixin = function(destObject) { return baseRange(start, end, step, fromRight); }; } - /** - * Creates a function that performs a relational operation on two values. - * - * @private - * @param {Function} operator The function to perform the operation. - * @returns {Function} Returns the new relational operation function. - */ function createRelationalOperation(operator) { return function(value, other) { if (!(typeof value == "string" && typeof other == "string")) { @@ -4765,23 +2347,6 @@ UsergridEventable.mixin = function(destObject) { return operator(value, other); }; } - /** - * Creates a function that wraps `func` to continue currying. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {Function} wrapFunc The function to create the `func` wrapper. - * @param {*} placeholder The placeholder value. - * @param {*} [thisArg] The `this` binding of `func`. - * @param {Array} [partials] The arguments to prepend to those provided to - * the new function. - * @param {Array} [holders] The `partials` placeholder indexes. - * @param {Array} [argPos] The argument positions of the new function. - * @param {number} [ary] The arity cap of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & CURRY_FLAG, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG; @@ -4797,13 +2362,6 @@ UsergridEventable.mixin = function(destObject) { result.placeholder = placeholder; return setWrapToString(result, func, bitmask); } - /** - * Creates a function like `_.round`. - * - * @private - * @param {string} methodName The name of the `Math` method to use when rounding. - * @returns {Function} Returns the new round function. - */ function createRound(methodName) { var func = Math[methodName]; return function(number, precision) { @@ -4817,23 +2375,9 @@ UsergridEventable.mixin = function(destObject) { return func(number); }; } - /** - * Creates a set object of `values`. - * - * @private - * @param {Array} values The values to add to the set. - * @returns {Object} Returns the new set. - */ var createSet = !(Set && 1 / setToArray(new Set([ , -0 ]))[1] == INFINITY) ? noop : function(values) { return new Set(values); }; - /** - * Creates a `_.toPairs` or `_.toPairsIn` function. - * - * @private - * @param {Function} keysFunc The function to get the keys of a given object. - * @returns {Function} Returns the new pairs function. - */ function createToPairs(keysFunc) { return function(object) { var tag = getTag(object); @@ -4846,32 +2390,6 @@ UsergridEventable.mixin = function(destObject) { return baseToPairs(object, keysFunc(object)); }; } - /** - * Creates a function that either curries or invokes `func` with optional - * `this` binding and partially applied arguments. - * - * @private - * @param {Function|string} func The function or method name to wrap. - * @param {number} bitmask The bitmask flags. - * The bitmask may be composed of the following flags: - * 1 - `_.bind` - * 2 - `_.bindKey` - * 4 - `_.curry` or `_.curryRight` of a bound function - * 8 - `_.curry` - * 16 - `_.curryRight` - * 32 - `_.partial` - * 64 - `_.partialRight` - * 128 - `_.rearg` - * 256 - `_.ary` - * 512 - `_.flip` - * @param {*} [thisArg] The `this` binding of `func`. - * @param {Array} [partials] The arguments to be partially applied. - * @param {Array} [holders] The `partials` placeholder indexes. - * @param {Array} [argPos] The argument positions of the new function. - * @param {number} [ary] The arity cap of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & BIND_KEY_FLAG; if (!isBindKey && typeof func != "function") { @@ -4915,20 +2433,6 @@ UsergridEventable.mixin = function(destObject) { var setter = data ? baseSetData : setData; return setWrapToString(setter(result, newData), func, bitmask); } - /** - * A specialized version of `baseIsEqualDeep` for arrays with support for - * partial deep comparisons. - * - * @private - * @param {Array} array The array to compare. - * @param {Array} other The other array to compare. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Function} customizer The function to customize comparisons. - * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` - * for more details. - * @param {Object} stack Tracks traversed `array` and `other` objects. - * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. - */ function equalArrays(array, other, equalFunc, customizer, bitmask, stack) { var isPartial = bitmask & PARTIAL_COMPARE_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { @@ -4971,24 +2475,6 @@ UsergridEventable.mixin = function(destObject) { stack["delete"](other); return result; } - /** - * A specialized version of `baseIsEqualDeep` for comparing objects of - * the same `toStringTag`. - * - * **Note:** This function only supports comparing values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {string} tag The `toStringTag` of the objects to compare. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Function} customizer The function to customize comparisons. - * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` - * for more details. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) { switch (tag) { case dataViewTag: @@ -5042,20 +2528,6 @@ UsergridEventable.mixin = function(destObject) { } return false; } - /** - * A specialized version of `baseIsEqualDeep` for objects with support for - * partial deep comparisons. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Function} customizer The function to customize comparisons. - * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` - * for more details. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ function equalObjects(object, other, equalFunc, customizer, bitmask, stack) { var isPartial = bitmask & PARTIAL_COMPARE_FLAG, objProps = keys(object), objLength = objProps.length, othProps = keys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { @@ -5098,54 +2570,18 @@ UsergridEventable.mixin = function(destObject) { stack["delete"](other); return result; } - /** - * A specialized version of `baseRest` which flattens the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @returns {Function} Returns the new function. - */ function flatRest(func) { return setToString(overRest(func, undefined, flatten), func + ""); } - /** - * Creates an array of own enumerable property names and symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } - /** - * Creates an array of own and inherited enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ function getAllKeysIn(object) { return baseGetAllKeys(object, keysIn, getSymbolsIn); } - /** - * Gets metadata for `func`. - * - * @private - * @param {Function} func The function to query. - * @returns {*} Returns the metadata for `func`. - */ var getData = !metaMap ? noop : function(func) { return metaMap.get(func); }; - /** - * Gets the name of `func`. - * - * @private - * @param {Function} func The function to query. - * @returns {string} Returns the function name. - */ function getFuncName(func) { var result = func.name + "", array = realNames[result], length = hasOwnProperty.call(realNames, result) ? array.length : 0; while (length--) { @@ -5156,52 +2592,19 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * Gets the argument placeholder value for `func`. - * - * @private - * @param {Function} func The function to inspect. - * @returns {*} Returns the placeholder value. - */ function getHolder(func) { var object = hasOwnProperty.call(lodash, "placeholder") ? lodash : func; return object.placeholder; } - /** - * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, - * this function returns the custom method, otherwise it returns `baseIteratee`. - * If arguments are provided, the chosen function is invoked with them and - * its result is returned. - * - * @private - * @param {*} [value] The value to convert to an iteratee. - * @param {number} [arity] The arity of the created iteratee. - * @returns {Function} Returns the chosen function or its result. - */ function getIteratee() { var result = lodash.iteratee || iteratee; result = result === iteratee ? baseIteratee : result; return arguments.length ? result(arguments[0], arguments[1]) : result; } - /** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map; } - /** - * Gets the property names, values, and compare flags of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the match data of `object`. - */ function getMatchData(object) { var result = keys(object), length = result.length; while (length--) { @@ -5210,34 +2613,11 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } - /** - * Creates an array of the own enumerable symbol properties of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray; - /** - * Creates an array of the own and inherited enumerable symbol properties - * of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { var result = []; while (object) { @@ -5246,13 +2626,6 @@ UsergridEventable.mixin = function(destObject) { } return result; }; - /** - * Gets the `toStringTag` of `value`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ var getTag = baseGetTag; if (DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag || Map && getTag(new Map()) != mapTag || Promise && getTag(Promise.resolve()) != promiseTag || Set && getTag(new Set()) != setTag || WeakMap && getTag(new WeakMap()) != weakMapTag) { getTag = function(value) { @@ -5278,16 +2651,6 @@ UsergridEventable.mixin = function(destObject) { return result; }; } - /** - * Gets the view, applying any `transforms` to the `start` and `end` positions. - * - * @private - * @param {number} start The start of the view. - * @param {number} end The end of the view. - * @param {Array} transforms The transformations to apply to the view. - * @returns {Object} Returns an object containing the `start` and `end` - * positions of the view. - */ function getView(start, end, transforms) { var index = -1, length = transforms.length; while (++index < length) { @@ -5315,26 +2678,10 @@ UsergridEventable.mixin = function(destObject) { end: end }; } - /** - * Extracts wrapper details from the `source` body comment. - * - * @private - * @param {string} source The source to inspect. - * @returns {Array} Returns the wrapper details. - */ function getWrapDetails(source) { var match = source.match(reWrapDetails); return match ? match[1].split(reSplitDetails) : []; } - /** - * Checks if `path` exists on `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @param {Function} hasFunc The function to check properties. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - */ function hasPath(object, path, hasFunc) { path = isKey(path, object) ? [ path ] : castPath(path); var index = -1, length = path.length, result = false; @@ -5351,13 +2698,6 @@ UsergridEventable.mixin = function(destObject) { length = object ? object.length : 0; return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object)); } - /** - * Initializes an array clone. - * - * @private - * @param {Array} array The array to clone. - * @returns {Array} Returns the initialized clone. - */ function initCloneArray(array) { var length = array.length, result = array.constructor(length); if (length && typeof array[0] == "string" && hasOwnProperty.call(array, "index")) { @@ -5366,29 +2706,9 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * Initializes an object clone. - * - * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. - */ function initCloneObject(object) { return typeof object.constructor == "function" && !isPrototype(object) ? baseCreate(getPrototype(object)) : {}; } - /** - * Initializes an object clone based on its `toStringTag`. - * - * **Note:** This function only supports cloning values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to clone. - * @param {string} tag The `toStringTag` of the object to clone. - * @param {Function} cloneFunc The function to clone values. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the initialized clone. - */ function initCloneByTag(object, tag, cloneFunc, isDeep) { var Ctor = object.constructor; switch (tag) { @@ -5430,14 +2750,6 @@ UsergridEventable.mixin = function(destObject) { return cloneSymbol(object); } } - /** - * Inserts wrapper `details` in a comment at the top of the `source` body. - * - * @private - * @param {string} source The source to modify. - * @returns {Array} details The details to insert. - * @returns {string} Returns the modified source. - */ function insertWrapDetails(source, details) { var length = details.length; if (!length) { @@ -5448,38 +2760,13 @@ UsergridEventable.mixin = function(destObject) { details = details.join(length > 2 ? ", " : " "); return source.replace(reWrapComment, "{\n/* [wrapped with " + details + "] */\n"); } - /** - * Checks if `value` is a flattenable `arguments` object or array. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. - */ function isFlattenable(value) { return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } - /** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ function isIndex(value, length) { length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (typeof value == "number" || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } - /** - * Checks if the given arguments are from an iteratee call. - * - * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, - * else `false`. - */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; @@ -5490,14 +2777,6 @@ UsergridEventable.mixin = function(destObject) { } return false; } - /** - * Checks if `value` is a property name and not a property path. - * - * @private - * @param {*} value The value to check. - * @param {Object} [object] The object to query keys on. - * @returns {boolean} Returns `true` if `value` is a property name, else `false`. - */ function isKey(value, object) { if (isArray(value)) { return false; @@ -5508,25 +2787,10 @@ UsergridEventable.mixin = function(destObject) { } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object); } - /** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ function isKeyable(value) { var type = typeof value; return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null; } - /** - * Checks if `func` has a lazy counterpart. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` has a lazy counterpart, - * else `false`. - */ function isLaziable(func) { var funcName = getFuncName(func), other = lodash[funcName]; if (typeof other != "function" || !(funcName in LazyWrapper.prototype)) { @@ -5538,55 +2802,17 @@ UsergridEventable.mixin = function(destObject) { var data = getData(other); return !!data && func === data[0]; } - /** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ function isMasked(func) { return !!maskSrcKey && maskSrcKey in func; } - /** - * Checks if `func` is capable of being masked. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `func` is maskable, else `false`. - */ var isMaskable = coreJsData ? isFunction : stubFalse; - /** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ function isPrototype(value) { var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto; return value === proto; } - /** - * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` if suitable for strict - * equality comparisons, else `false`. - */ function isStrictComparable(value) { return value === value && !isObject(value); } - /** - * A specialized version of `matchesProperty` for source values suitable - * for strict equality comparisons, i.e. `===`. - * - * @private - * @param {string} key The key of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { @@ -5595,14 +2821,6 @@ UsergridEventable.mixin = function(destObject) { return object[key] === srcValue && (srcValue !== undefined || key in Object(object)); }; } - /** - * A specialized version of `_.memoize` which clears the memoized function's - * cache when it exceeds `MAX_MEMOIZE_SIZE`. - * - * @private - * @param {Function} func The function to have its output memoized. - * @returns {Function} Returns the new memoized function. - */ function memoizeCapped(func) { var result = memoize(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { @@ -5613,22 +2831,6 @@ UsergridEventable.mixin = function(destObject) { var cache = result.cache; return result; } - /** - * Merges the function metadata of `source` into `data`. - * - * Merging metadata reduces the number of wrappers used to invoke a function. - * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` - * may be applied regardless of execution order. Methods like `_.ary` and - * `_.rearg` modify function arguments, making the order in which they are - * executed important, preventing the merging of metadata. However, we make - * an exception for a safe combined case where curried functions have `_.ary` - * and or `_.rearg` applied. - * - * @private - * @param {Array} data The destination metadata. - * @param {Array} source The source metadata. - * @returns {Array} Returns `data`. - */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (BIND_FLAG | BIND_KEY_FLAG | ARY_FLAG); var isCombo = srcBitmask == ARY_FLAG && bitmask == CURRY_FLAG || srcBitmask == ARY_FLAG && bitmask == REARG_FLAG && data[7].length <= source[8] || srcBitmask == (ARY_FLAG | REARG_FLAG) && source[7].length <= source[8] && bitmask == CURRY_FLAG; @@ -5665,19 +2867,6 @@ UsergridEventable.mixin = function(destObject) { data[1] = newBitmask; return data; } - /** - * Used by `_.defaultsDeep` to customize its `_.merge` use. - * - * @private - * @param {*} objValue The destination value. - * @param {*} srcValue The source value. - * @param {string} key The key of the property to merge. - * @param {Object} object The parent object of `objValue`. - * @param {Object} source The parent object of `srcValue`. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - * @returns {*} Returns the value to assign. - */ function mergeDefaults(objValue, srcValue, key, object, source, stack) { if (isObject(objValue) && isObject(srcValue)) { stack.set(srcValue, objValue); @@ -5686,15 +2875,6 @@ UsergridEventable.mixin = function(destObject) { } return objValue; } - /** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ function nativeKeysIn(object) { var result = []; if (object != null) { @@ -5704,15 +2884,6 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * A specialized version of `baseRest` which transforms the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @param {Function} transform The rest array transform. - * @returns {Function} Returns the new function. - */ function overRest(func, start, transform) { start = nativeMax(start === undefined ? func.length - 1 : start, 0); return function() { @@ -5729,27 +2900,9 @@ UsergridEventable.mixin = function(destObject) { return apply(func, this, otherArgs); }; } - /** - * Gets the parent value at `path` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} path The path to get the parent value of. - * @returns {*} Returns the parent value. - */ function parent(object, path) { return path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); } - /** - * Reorder `array` according to the specified indexes where the element at - * the first index is assigned as the first element, the element at - * the second index is assigned as the second element, and so on. - * - * @private - * @param {Array} array The array to reorder. - * @param {Array} indexes The arranged array indexes. - * @returns {Array} Returns `array`. - */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array); while (length--) { @@ -5758,64 +2911,15 @@ UsergridEventable.mixin = function(destObject) { } return array; } - /** - * Sets metadata for `func`. - * - * **Note:** If this function becomes hot, i.e. is invoked a lot in a short - * period of time, it will trip its breaker and transition to an identity - * function to avoid garbage collection pauses in V8. See - * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) - * for more details. - * - * @private - * @param {Function} func The function to associate metadata with. - * @param {*} data The metadata. - * @returns {Function} Returns `func`. - */ var setData = shortOut(baseSetData); - /** - * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). - * - * @private - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @returns {number|Object} Returns the timer id or timeout object. - */ var setTimeout = ctxSetTimeout || function(func, wait) { return root.setTimeout(func, wait); }; - /** - * Sets the `toString` method of `func` to return `string`. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ var setToString = shortOut(baseSetToString); - /** - * Sets the `toString` method of `wrapper` to mimic the source of `reference` - * with wrapper details in a comment at the top of the source body. - * - * @private - * @param {Function} wrapper The function to modify. - * @param {Function} reference The reference function. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @returns {Function} Returns `wrapper`. - */ function setWrapToString(wrapper, reference, bitmask) { var source = reference + ""; return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); } - /** - * Creates a function that'll short out and invoke `identity` instead - * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` - * milliseconds. - * - * @private - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new shortable function. - */ function shortOut(func) { var count = 0, lastCalled = 0; return function() { @@ -5831,13 +2935,6 @@ UsergridEventable.mixin = function(destObject) { return func.apply(undefined, arguments); }; } - /** - * A specialized version of `arrayShuffle` which mutates `array`. - * - * @private - * @param {Array} array The array to shuffle. - * @returns {Array} Returns `array`. - */ function shuffleSelf(array) { var index = -1, length = array.length, lastIndex = length - 1; while (++index < length) { @@ -5847,13 +2944,6 @@ UsergridEventable.mixin = function(destObject) { } return array; } - /** - * Converts `string` to a property path array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the property path array. - */ var stringToPath = memoizeCapped(function(string) { string = toString(string); var result = []; @@ -5865,13 +2955,6 @@ UsergridEventable.mixin = function(destObject) { }); return result; }); - /** - * Converts `value` to a string key if it's not a string or symbol. - * - * @private - * @param {*} value The value to inspect. - * @returns {string|symbol} Returns the key. - */ function toKey(value) { if (typeof value == "string" || isSymbol(value)) { return value; @@ -5879,13 +2962,6 @@ UsergridEventable.mixin = function(destObject) { var result = value + ""; return result == "0" && 1 / value == -INFINITY ? "-0" : result; } - /** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to process. - * @returns {string} Returns the source code. - */ function toSource(func) { if (func != null) { try { @@ -5897,14 +2973,6 @@ UsergridEventable.mixin = function(destObject) { } return ""; } - /** - * Updates wrapper `details` based on `bitmask` flags. - * - * @private - * @returns {Array} details The details to modify. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @returns {Array} Returns `details`. - */ function updateWrapDetails(details, bitmask) { arrayEach(wrapFlags, function(pair) { var value = "_." + pair[0]; @@ -5914,13 +2982,6 @@ UsergridEventable.mixin = function(destObject) { }); return details.sort(); } - /** - * Creates a clone of `wrapper`. - * - * @private - * @param {Object} wrapper The wrapper to clone. - * @returns {Object} Returns the cloned wrapper. - */ function wrapperClone(wrapper) { if (wrapper instanceof LazyWrapper) { return wrapper.clone(); @@ -5931,28 +2992,6 @@ UsergridEventable.mixin = function(destObject) { result.__values__ = wrapper.__values__; return result; } - /*------------------------------------------------------------------------*/ - /** - * Creates an array of elements split into groups the length of `size`. - * If `array` can't be split evenly, the final chunk will be the remaining - * elements. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to process. - * @param {number} [size=1] The length of each chunk - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the new array of chunks. - * @example - * - * _.chunk(['a', 'b', 'c', 'd'], 2); - * // => [['a', 'b'], ['c', 'd']] - * - * _.chunk(['a', 'b', 'c', 'd'], 3); - * // => [['a', 'b', 'c'], ['d']] - */ function chunk(array, size, guard) { if (guard ? isIterateeCall(array, size, guard) : size === undefined) { size = 1; @@ -5969,21 +3008,6 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * Creates an array with all falsey values removed. The values `false`, `null`, - * `0`, `""`, `undefined`, and `NaN` are falsey. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to compact. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * _.compact([0, 1, false, 2, '', 3]); - * // => [1, 2, 3] - */ function compact(array) { var index = -1, length = array ? array.length : 0, resIndex = 0, result = []; while (++index < length) { @@ -5994,28 +3018,6 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * Creates a new array concatenating `array` with any additional arrays - * and/or values. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to concatenate. - * @param {...*} [values] The values to concatenate. - * @returns {Array} Returns the new concatenated array. - * @example - * - * var array = [1]; - * var other = _.concat(array, 2, [3], [[4]]); - * - * console.log(other); - * // => [1, 2, 3, [4]] - * - * console.log(array); - * // => [1] - */ function concat() { var length = arguments.length; if (!length) { @@ -6027,56 +3029,9 @@ UsergridEventable.mixin = function(destObject) { } return arrayPush(isArray(array) ? copyArray(array) : [ array ], baseFlatten(args, 1)); } - /** - * Creates an array of `array` values not included in the other given arrays - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. The order and references of result values are - * determined by the first array. - * - * **Note:** Unlike `_.pullAll`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @returns {Array} Returns the new array of filtered values. - * @see _.without, _.xor - * @example - * - * _.difference([2, 1], [2, 3]); - * // => [1] - */ var difference = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) : []; }); - /** - * This method is like `_.difference` except that it accepts `iteratee` which - * is invoked for each element of `array` and `values` to generate the criterion - * by which they're compared. The order and references of result values are - * determined by the first array. The iteratee is invoked with one argument: - * (value). - * - * **Note:** Unlike `_.pullAllBy`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); - * // => [1.2] - * - * // The `_.property` iteratee shorthand. - * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); - * // => [{ 'x': 2 }] - */ var differenceBy = baseRest(function(array, values) { var iteratee = last(values); if (isArrayLikeObject(iteratee)) { @@ -6084,29 +3039,6 @@ UsergridEventable.mixin = function(destObject) { } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) : []; }); - /** - * This method is like `_.difference` except that it accepts `comparator` - * which is invoked to compare elements of `array` to `values`. The order and - * references of result values are determined by the first array. The comparator - * is invoked with two arguments: (arrVal, othVal). - * - * **Note:** Unlike `_.pullAllWith`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * - * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); - * // => [{ 'x': 2, 'y': 1 }] - */ var differenceWith = baseRest(function(array, values) { var comparator = last(values); if (isArrayLikeObject(comparator)) { @@ -6114,31 +3046,6 @@ UsergridEventable.mixin = function(destObject) { } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) : []; }); - /** - * Creates a slice of `array` with `n` elements dropped from the beginning. - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to drop. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.drop([1, 2, 3]); - * // => [2, 3] - * - * _.drop([1, 2, 3], 2); - * // => [3] - * - * _.drop([1, 2, 3], 5); - * // => [] - * - * _.drop([1, 2, 3], 0); - * // => [1, 2, 3] - */ function drop(array, n, guard) { var length = array ? array.length : 0; if (!length) { @@ -6147,31 +3054,6 @@ UsergridEventable.mixin = function(destObject) { n = guard || n === undefined ? 1 : toInteger(n); return baseSlice(array, n < 0 ? 0 : n, length); } - /** - * Creates a slice of `array` with `n` elements dropped from the end. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to drop. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.dropRight([1, 2, 3]); - * // => [1, 2] - * - * _.dropRight([1, 2, 3], 2); - * // => [1] - * - * _.dropRight([1, 2, 3], 5); - * // => [] - * - * _.dropRight([1, 2, 3], 0); - * // => [1, 2, 3] - */ function dropRight(array, n, guard) { var length = array ? array.length : 0; if (!length) { @@ -6181,112 +3063,12 @@ UsergridEventable.mixin = function(destObject) { n = length - n; return baseSlice(array, 0, n < 0 ? 0 : n); } - /** - * Creates a slice of `array` excluding elements dropped from the end. - * Elements are dropped until `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * _.dropRightWhile(users, function(o) { return !o.active; }); - * // => objects for ['barney'] - * - * // The `_.matches` iteratee shorthand. - * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); - * // => objects for ['barney', 'fred'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.dropRightWhile(users, ['active', false]); - * // => objects for ['barney'] - * - * // The `_.property` iteratee shorthand. - * _.dropRightWhile(users, 'active'); - * // => objects for ['barney', 'fred', 'pebbles'] - */ function dropRightWhile(array, predicate) { return array && array.length ? baseWhile(array, getIteratee(predicate, 3), true, true) : []; } - /** - * Creates a slice of `array` excluding elements dropped from the beginning. - * Elements are dropped until `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] - * The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.dropWhile(users, function(o) { return !o.active; }); - * // => objects for ['pebbles'] - * - * // The `_.matches` iteratee shorthand. - * _.dropWhile(users, { 'user': 'barney', 'active': false }); - * // => objects for ['fred', 'pebbles'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.dropWhile(users, ['active', false]); - * // => objects for ['pebbles'] - * - * // The `_.property` iteratee shorthand. - * _.dropWhile(users, 'active'); - * // => objects for ['barney', 'fred', 'pebbles'] - */ function dropWhile(array, predicate) { return array && array.length ? baseWhile(array, getIteratee(predicate, 3), true) : []; } - /** - * Fills elements of `array` with `value` from `start` up to, but not - * including, `end`. - * - * **Note:** This method mutates `array`. - * - * @static - * @memberOf _ - * @since 3.2.0 - * @category Array - * @param {Array} array The array to fill. - * @param {*} value The value to fill `array` with. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns `array`. - * @example - * - * var array = [1, 2, 3]; - * - * _.fill(array, 'a'); - * console.log(array); - * // => ['a', 'a', 'a'] - * - * _.fill(Array(3), 2); - * // => [2, 2, 2] - * - * _.fill([4, 6, 8, 10], '*', 1, 3); - * // => [4, '*', '*', 10] - */ function fill(array, value, start, end) { var length = array ? array.length : 0; if (!length) { @@ -6298,42 +3080,6 @@ UsergridEventable.mixin = function(destObject) { } return baseFill(array, value, start, end); } - /** - * This method is like `_.find` except that it returns the index of the first - * element `predicate` returns truthy for instead of the element itself. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [predicate=_.identity] - * The function invoked per iteration. - * @param {number} [fromIndex=0] The index to search from. - * @returns {number} Returns the index of the found element, else `-1`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.findIndex(users, function(o) { return o.user == 'barney'; }); - * // => 0 - * - * // The `_.matches` iteratee shorthand. - * _.findIndex(users, { 'user': 'fred', 'active': false }); - * // => 1 - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findIndex(users, ['active', false]); - * // => 0 - * - * // The `_.property` iteratee shorthand. - * _.findIndex(users, 'active'); - * // => 2 - */ function findIndex(array, predicate, fromIndex) { var length = array ? array.length : 0; if (!length) { @@ -6345,42 +3091,6 @@ UsergridEventable.mixin = function(destObject) { } return baseFindIndex(array, getIteratee(predicate, 3), index); } - /** - * This method is like `_.findIndex` except that it iterates over elements - * of `collection` from right to left. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [predicate=_.identity] - * The function invoked per iteration. - * @param {number} [fromIndex=array.length-1] The index to search from. - * @returns {number} Returns the index of the found element, else `-1`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); - * // => 2 - * - * // The `_.matches` iteratee shorthand. - * _.findLastIndex(users, { 'user': 'barney', 'active': true }); - * // => 0 - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findLastIndex(users, ['active', false]); - * // => 2 - * - * // The `_.property` iteratee shorthand. - * _.findLastIndex(users, 'active'); - * // => 0 - */ function findLastIndex(array, predicate, fromIndex) { var length = array ? array.length : 0; if (!length) { @@ -6393,62 +3103,14 @@ UsergridEventable.mixin = function(destObject) { } return baseFindIndex(array, getIteratee(predicate, 3), index, true); } - /** - * Flattens `array` a single level deep. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to flatten. - * @returns {Array} Returns the new flattened array. - * @example - * - * _.flatten([1, [2, [3, [4]], 5]]); - * // => [1, 2, [3, [4]], 5] - */ function flatten(array) { var length = array ? array.length : 0; return length ? baseFlatten(array, 1) : []; } - /** - * Recursively flattens `array`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to flatten. - * @returns {Array} Returns the new flattened array. - * @example - * - * _.flattenDeep([1, [2, [3, [4]], 5]]); - * // => [1, 2, 3, 4, 5] - */ function flattenDeep(array) { var length = array ? array.length : 0; return length ? baseFlatten(array, INFINITY) : []; } - /** - * Recursively flatten `array` up to `depth` times. - * - * @static - * @memberOf _ - * @since 4.4.0 - * @category Array - * @param {Array} array The array to flatten. - * @param {number} [depth=1] The maximum recursion depth. - * @returns {Array} Returns the new flattened array. - * @example - * - * var array = [1, [2, [3, [4]], 5]]; - * - * _.flattenDepth(array, 1); - * // => [1, 2, [3, [4]], 5] - * - * _.flattenDepth(array, 2); - * // => [1, 2, 3, [4], 5] - */ function flattenDepth(array, depth) { var length = array ? array.length : 0; if (!length) { @@ -6457,21 +3119,6 @@ UsergridEventable.mixin = function(destObject) { depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(array, depth); } - /** - * The inverse of `_.toPairs`; this method returns an object composed - * from key-value `pairs`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} pairs The key-value pairs. - * @returns {Object} Returns the new object. - * @example - * - * _.fromPairs([['a', 1], ['b', 2]]); - * // => { 'a': 1, 'b': 2 } - */ function fromPairs(pairs) { var index = -1, length = pairs ? pairs.length : 0, result = {}; while (++index < length) { @@ -6480,50 +3127,9 @@ UsergridEventable.mixin = function(destObject) { } return result; } - /** - * Gets the first element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @alias first - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the first element of `array`. - * @example - * - * _.head([1, 2, 3]); - * // => 1 - * - * _.head([]); - * // => undefined - */ function head(array) { return array && array.length ? array[0] : undefined; } - /** - * Gets the index at which the first occurrence of `value` is found in `array` - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. If `fromIndex` is negative, it's used as the - * offset from the end of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.indexOf([1, 2, 1, 2], 2); - * // => 1 - * - * // Search from the `fromIndex`. - * _.indexOf([1, 2, 1, 2], 2, 2); - * // => 3 - */ function indexOf(array, value, fromIndex) { var length = array ? array.length : 0; if (!length) { @@ -6535,68 +3141,14 @@ UsergridEventable.mixin = function(destObject) { } return baseIndexOf(array, value, index); } - /** - * Gets all but the last element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.initial([1, 2, 3]); - * // => [1, 2] - */ function initial(array) { var length = array ? array.length : 0; return length ? baseSlice(array, 0, -1) : []; } - /** - * Creates an array of unique values that are included in all given arrays - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. The order and references of result values are - * determined by the first array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of intersecting values. - * @example - * - * _.intersection([2, 1], [2, 3]); - * // => [2] - */ var intersection = baseRest(function(arrays) { var mapped = arrayMap(arrays, castArrayLikeObject); return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped) : []; }); - /** - * This method is like `_.intersection` except that it accepts `iteratee` - * which is invoked for each element of each `arrays` to generate the criterion - * by which they're compared. The order and references of result values are - * determined by the first array. The iteratee is invoked with one argument: - * (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of intersecting values. - * @example - * - * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); - * // => [2.1] - * - * // The `_.property` iteratee shorthand. - * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }] - */ var intersectionBy = baseRest(function(arrays) { var iteratee = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); if (iteratee === last(mapped)) { @@ -6606,27 +3158,6 @@ UsergridEventable.mixin = function(destObject) { } return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped, getIteratee(iteratee, 2)) : []; }); - /** - * This method is like `_.intersection` except that it accepts `comparator` - * which is invoked to compare elements of `arrays`. The order and references - * of result values are determined by the first array. The comparator is - * invoked with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of intersecting values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * - * _.intersectionWith(objects, others, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }] - */ var intersectionWith = baseRest(function(arrays) { var comparator = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); if (comparator === last(mapped)) { @@ -6636,63 +3167,13 @@ UsergridEventable.mixin = function(destObject) { } return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped, undefined, comparator) : []; }); - /** - * Converts all elements in `array` into a string separated by `separator`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to convert. - * @param {string} [separator=','] The element separator. - * @returns {string} Returns the joined string. - * @example - * - * _.join(['a', 'b', 'c'], '~'); - * // => 'a~b~c' - */ function join(array, separator) { return array ? nativeJoin.call(array, separator) : ""; } - /** - * Gets the last element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the last element of `array`. - * @example - * - * _.last([1, 2, 3]); - * // => 3 - */ function last(array) { var length = array ? array.length : 0; return length ? array[length - 1] : undefined; } - /** - * This method is like `_.indexOf` except that it iterates over elements of - * `array` from right to left. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=array.length-1] The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.lastIndexOf([1, 2, 1, 2], 2); - * // => 3 - * - * // Search from the `fromIndex`. - * _.lastIndexOf([1, 2, 1, 2], 2, 2); - * // => 1 - */ function lastIndexOf(array, value, fromIndex) { var length = array ? array.length : 0; if (!length) { @@ -6705,154 +3186,19 @@ UsergridEventable.mixin = function(destObject) { } return value === value ? strictLastIndexOf(array, value, index) : baseFindIndex(array, baseIsNaN, index, true); } - /** - * Gets the element at index `n` of `array`. If `n` is negative, the nth - * element from the end is returned. - * - * @static - * @memberOf _ - * @since 4.11.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=0] The index of the element to return. - * @returns {*} Returns the nth element of `array`. - * @example - * - * var array = ['a', 'b', 'c', 'd']; - * - * _.nth(array, 1); - * // => 'b' - * - * _.nth(array, -2); - * // => 'c'; - */ function nth(array, n) { return array && array.length ? baseNth(array, toInteger(n)) : undefined; } - /** - * Removes all given values from `array` using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` - * to remove elements from an array by predicate. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {...*} [values] The values to remove. - * @returns {Array} Returns `array`. - * @example - * - * var array = ['a', 'b', 'c', 'a', 'b', 'c']; - * - * _.pull(array, 'a', 'c'); - * console.log(array); - * // => ['b', 'b'] - */ var pull = baseRest(pullAll); - /** - * This method is like `_.pull` except that it accepts an array of values to remove. - * - * **Note:** Unlike `_.difference`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @returns {Array} Returns `array`. - * @example - * - * var array = ['a', 'b', 'c', 'a', 'b', 'c']; - * - * _.pullAll(array, ['a', 'c']); - * console.log(array); - * // => ['b', 'b'] - */ function pullAll(array, values) { return array && array.length && values && values.length ? basePullAll(array, values) : array; } - /** - * This method is like `_.pullAll` except that it accepts `iteratee` which is - * invoked for each element of `array` and `values` to generate the criterion - * by which they're compared. The iteratee is invoked with one argument: (value). - * - * **Note:** Unlike `_.differenceBy`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [iteratee=_.identity] - * The iteratee invoked per element. - * @returns {Array} Returns `array`. - * @example - * - * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; - * - * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); - * console.log(array); - * // => [{ 'x': 2 }] - */ function pullAllBy(array, values, iteratee) { return array && array.length && values && values.length ? basePullAll(array, values, getIteratee(iteratee, 2)) : array; } - /** - * This method is like `_.pullAll` except that it accepts `comparator` which - * is invoked to compare elements of `array` to `values`. The comparator is - * invoked with two arguments: (arrVal, othVal). - * - * **Note:** Unlike `_.differenceWith`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 4.6.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns `array`. - * @example - * - * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; - * - * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); - * console.log(array); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] - */ function pullAllWith(array, values, comparator) { return array && array.length && values && values.length ? basePullAll(array, values, undefined, comparator) : array; } - /** - * Removes elements from `array` corresponding to `indexes` and returns an - * array of removed elements. - * - * **Note:** Unlike `_.at`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {...(number|number[])} [indexes] The indexes of elements to remove. - * @returns {Array} Returns the new array of removed elements. - * @example - * - * var array = ['a', 'b', 'c', 'd']; - * var pulled = _.pullAt(array, [1, 3]); - * - * console.log(array); - * // => ['a', 'c'] - * - * console.log(pulled); - * // => ['b', 'd'] - */ var pullAt = flatRest(function(array, indexes) { var length = array ? array.length : 0, result = baseAt(array, indexes); basePullAt(array, arrayMap(indexes, function(index) { @@ -6860,35 +3206,6 @@ UsergridEventable.mixin = function(destObject) { }).sort(compareAscending)); return result; }); - /** - * Removes all elements from `array` that `predicate` returns truthy for - * and returns an array of the removed elements. The predicate is invoked - * with three arguments: (value, index, array). - * - * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` - * to pull elements from an array by value. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Function} [predicate=_.identity] - * The function invoked per iteration. - * @returns {Array} Returns the new array of removed elements. - * @example - * - * var array = [1, 2, 3, 4]; - * var evens = _.remove(array, function(n) { - * return n % 2 == 0; - * }); - * - * console.log(array); - * // => [1, 3] - * - * console.log(evens); - * // => [2, 4] - */ function remove(array, predicate) { var result = []; if (!(array && array.length)) { @@ -6906,48 +3223,9 @@ UsergridEventable.mixin = function(destObject) { basePullAt(array, indexes); return result; } - /** - * Reverses `array` so that the first element becomes the last, the second - * element becomes the second to last, and so on. - * - * **Note:** This method mutates `array` and is based on - * [`Array#reverse`](https://mdn.io/Array/reverse). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to modify. - * @returns {Array} Returns `array`. - * @example - * - * var array = [1, 2, 3]; - * - * _.reverse(array); - * // => [3, 2, 1] - * - * console.log(array); - * // => [3, 2, 1] - */ function reverse(array) { return array ? nativeReverse.call(array) : array; } - /** - * Creates a slice of `array` from `start` up to, but not including, `end`. - * - * **Note:** This method is used instead of - * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are - * returned. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ function slice(array, start, end) { var length = array ? array.length : 0; if (!length) { @@ -6962,71 +3240,12 @@ UsergridEventable.mixin = function(destObject) { } return baseSlice(array, start, end); } - /** - * Uses a binary search to determine the lowest index at which `value` - * should be inserted into `array` in order to maintain its sort order. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * _.sortedIndex([30, 50], 40); - * // => 1 - */ function sortedIndex(array, value) { return baseSortedIndex(array, value); } - /** - * This method is like `_.sortedIndex` except that it accepts `iteratee` - * which is invoked for `value` and each element of `array` to compute their - * sort ranking. The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} [iteratee=_.identity] - * The iteratee invoked per element. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * var objects = [{ 'x': 4 }, { 'x': 5 }]; - * - * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); - * // => 0 - * - * // The `_.property` iteratee shorthand. - * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); - * // => 0 - */ function sortedIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); } - /** - * This method is like `_.indexOf` except that it performs a binary - * search on a sorted `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.sortedIndexOf([4, 5, 5, 5, 6], 5); - * // => 1 - */ function sortedIndexOf(array, value) { var length = array ? array.length : 0; if (length) { @@ -7037,72 +3256,12 @@ UsergridEventable.mixin = function(destObject) { } return -1; } - /** - * This method is like `_.sortedIndex` except that it returns the highest - * index at which `value` should be inserted into `array` in order to - * maintain its sort order. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * _.sortedLastIndex([4, 5, 5, 5, 6], 5); - * // => 4 - */ function sortedLastIndex(array, value) { return baseSortedIndex(array, value, true); } - /** - * This method is like `_.sortedLastIndex` except that it accepts `iteratee` - * which is invoked for `value` and each element of `array` to compute their - * sort ranking. The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} [iteratee=_.identity] - * The iteratee invoked per element. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * var objects = [{ 'x': 4 }, { 'x': 5 }]; - * - * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); - * // => 1 - * - * // The `_.property` iteratee shorthand. - * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); - * // => 1 - */ function sortedLastIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); } - /** - * This method is like `_.lastIndexOf` except that it performs a binary - * search on a sorted `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); - * // => 3 - */ function sortedLastIndexOf(array, value) { var length = array ? array.length : 0; if (length) { @@ -7113,86 +3272,16 @@ UsergridEventable.mixin = function(destObject) { } return -1; } - /** - * This method is like `_.uniq` except that it's designed and optimized - * for sorted arrays. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * _.sortedUniq([1, 1, 2]); - * // => [1, 2] - */ function sortedUniq(array) { return array && array.length ? baseSortedUniq(array) : []; } - /** - * This method is like `_.uniqBy` except that it's designed and optimized - * for sorted arrays. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); - * // => [1.1, 2.3] - */ function sortedUniqBy(array, iteratee) { return array && array.length ? baseSortedUniq(array, getIteratee(iteratee, 2)) : []; } - /** - * Gets all but the first element of `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to query. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.tail([1, 2, 3]); - * // => [2, 3] - */ function tail(array) { var length = array ? array.length : 0; return length ? baseSlice(array, 1, length) : []; } - /** - * Creates a slice of `array` with `n` elements taken from the beginning. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to take. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.take([1, 2, 3]); - * // => [1] - * - * _.take([1, 2, 3], 2); - * // => [1, 2] - * - * _.take([1, 2, 3], 5); - * // => [1, 2, 3] - * - * _.take([1, 2, 3], 0); - * // => [] - */ function take(array, n, guard) { if (!(array && array.length)) { return []; @@ -7200,31 +3289,6 @@ UsergridEventable.mixin = function(destObject) { n = guard || n === undefined ? 1 : toInteger(n); return baseSlice(array, 0, n < 0 ? 0 : n); } - /** - * Creates a slice of `array` with `n` elements taken from the end. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to take. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.takeRight([1, 2, 3]); - * // => [3] - * - * _.takeRight([1, 2, 3], 2); - * // => [2, 3] - * - * _.takeRight([1, 2, 3], 5); - * // => [1, 2, 3] - * - * _.takeRight([1, 2, 3], 0); - * // => [] - */ function takeRight(array, n, guard) { var length = array ? array.length : 0; if (!length) { @@ -7234,127 +3298,15 @@ UsergridEventable.mixin = function(destObject) { n = length - n; return baseSlice(array, n < 0 ? 0 : n, length); } - /** - * Creates a slice of `array` with elements taken from the end. Elements are - * taken until `predicate` returns falsey. The predicate is invoked with - * three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] - * The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * _.takeRightWhile(users, function(o) { return !o.active; }); - * // => objects for ['fred', 'pebbles'] - * - * // The `_.matches` iteratee shorthand. - * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); - * // => objects for ['pebbles'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.takeRightWhile(users, ['active', false]); - * // => objects for ['fred', 'pebbles'] - * - * // The `_.property` iteratee shorthand. - * _.takeRightWhile(users, 'active'); - * // => [] - */ function takeRightWhile(array, predicate) { return array && array.length ? baseWhile(array, getIteratee(predicate, 3), false, true) : []; } - /** - * Creates a slice of `array` with elements taken from the beginning. Elements - * are taken until `predicate` returns falsey. The predicate is invoked with - * three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] - * The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false}, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.takeWhile(users, function(o) { return !o.active; }); - * // => objects for ['barney', 'fred'] - * - * // The `_.matches` iteratee shorthand. - * _.takeWhile(users, { 'user': 'barney', 'active': false }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.takeWhile(users, ['active', false]); - * // => objects for ['barney', 'fred'] - * - * // The `_.property` iteratee shorthand. - * _.takeWhile(users, 'active'); - * // => [] - */ function takeWhile(array, predicate) { return array && array.length ? baseWhile(array, getIteratee(predicate, 3)) : []; } - /** - * Creates an array of unique values, in order, from all given arrays using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of combined values. - * @example - * - * _.union([2], [1, 2]); - * // => [2, 1] - */ var union = baseRest(function(arrays) { return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); }); - /** - * This method is like `_.union` except that it accepts `iteratee` which is - * invoked for each element of each `arrays` to generate the criterion by - * which uniqueness is computed. Result values are chosen from the first - * array in which the value occurs. The iteratee is invoked with one argument: - * (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [iteratee=_.identity] - * The iteratee invoked per element. - * @returns {Array} Returns the new array of combined values. - * @example - * - * _.unionBy([2.1], [1.2, 2.3], Math.floor); - * // => [2.1, 1.2] - * - * // The `_.property` iteratee shorthand. - * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }, { 'x': 2 }] - */ var unionBy = baseRest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { @@ -7362,27 +3314,6 @@ UsergridEventable.mixin = function(destObject) { } return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); }); - /** - * This method is like `_.union` except that it accepts `comparator` which - * is invoked to compare elements of `arrays`. Result values are chosen from - * the first array in which the value occurs. The comparator is invoked - * with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of combined values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * - * _.unionWith(objects, others, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] - */ var unionWith = baseRest(function(arrays) { var comparator = last(arrays); if (isArrayLikeObject(comparator)) { @@ -7390,96 +3321,15 @@ UsergridEventable.mixin = function(destObject) { } return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); }); - /** - * Creates a duplicate-free version of an array, using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons, in which only the first occurrence of each element - * is kept. The order of result values is determined by the order they occur - * in the array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * _.uniq([2, 1, 2]); - * // => [2, 1] - */ function uniq(array) { return array && array.length ? baseUniq(array) : []; } - /** - * This method is like `_.uniq` except that it accepts `iteratee` which is - * invoked for each element in `array` to generate the criterion by which - * uniqueness is computed. The order of result values is determined by the - * order they occur in the array. The iteratee is invoked with one argument: - * (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [iteratee=_.identity] - * The iteratee invoked per element. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * _.uniqBy([2.1, 1.2, 2.3], Math.floor); - * // => [2.1, 1.2] - * - * // The `_.property` iteratee shorthand. - * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }, { 'x': 2 }] - */ function uniqBy(array, iteratee) { return array && array.length ? baseUniq(array, getIteratee(iteratee, 2)) : []; } - /** - * This method is like `_.uniq` except that it accepts `comparator` which - * is invoked to compare elements of `array`. The order of result values is - * determined by the order they occur in the array.The comparator is invoked - * with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * - * _.uniqWith(objects, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] - */ function uniqWith(array, comparator) { return array && array.length ? baseUniq(array, undefined, comparator) : []; } - /** - * This method is like `_.zip` except that it accepts an array of grouped - * elements and creates an array regrouping the elements to their pre-zip - * configuration. - * - * @static - * @memberOf _ - * @since 1.2.0 - * @category Array - * @param {Array} array The array of grouped elements to process. - * @returns {Array} Returns the new array of regrouped elements. - * @example - * - * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); - * // => [['a', 1, true], ['b', 2, false]] - * - * _.unzip(zipped); - * // => [['a', 'b'], [1, 2], [true, false]] - */ function unzip(array) { if (!(array && array.length)) { return []; @@ -7495,27 +3345,6 @@ UsergridEventable.mixin = function(destObject) { return arrayMap(array, baseProperty(index)); }); } - /** - * This method is like `_.unzip` except that it accepts `iteratee` to specify - * how regrouped values should be combined. The iteratee is invoked with the - * elements of each group: (...group). - * - * @static - * @memberOf _ - * @since 3.8.0 - * @category Array - * @param {Array} array The array of grouped elements to process. - * @param {Function} [iteratee=_.identity] The function to combine - * regrouped values. - * @returns {Array} Returns the new array of regrouped elements. - * @example - * - * var zipped = _.zip([1, 2], [10, 20], [100, 200]); - * // => [[1, 10, 100], [2, 20, 200]] - * - * _.unzipWith(zipped, _.add); - * // => [3, 30, 300] - */ function unzipWith(array, iteratee) { if (!(array && array.length)) { return []; @@ -7528,74 +3357,12 @@ UsergridEventable.mixin = function(destObject) { return apply(iteratee, undefined, group); }); } - /** - * Creates an array excluding all given values using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * **Note:** Unlike `_.pull`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...*} [values] The values to exclude. - * @returns {Array} Returns the new array of filtered values. - * @see _.difference, _.xor - * @example - * - * _.without([2, 1, 2, 3], 1, 2); - * // => [3] - */ var without = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, values) : []; }); - /** - * Creates an array of unique values that is the - * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) - * of the given arrays. The order of result values is determined by the order - * they occur in the arrays. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of filtered values. - * @see _.difference, _.without - * @example - * - * _.xor([2, 1], [2, 3]); - * // => [1, 3] - */ var xor = baseRest(function(arrays) { return baseXor(arrayFilter(arrays, isArrayLikeObject)); }); - /** - * This method is like `_.xor` except that it accepts `iteratee` which is - * invoked for each element of each `arrays` to generate the criterion by - * which by which they're compared. The order of result values is determined - * by the order they occur in the arrays. The iteratee is invoked with one - * argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [iteratee=_.identity] - * The iteratee invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); - * // => [1.2, 3.4] - * - * // The `_.property` iteratee shorthand. - * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 2 }] - */ var xorBy = baseRest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { @@ -7603,27 +3370,6 @@ UsergridEventable.mixin = function(destObject) { } return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); }); - /** - * This method is like `_.xor` except that it accepts `comparator` which is - * invoked to compare elements of `arrays`. The order of result values is - * determined by the order they occur in the arrays. The comparator is invoked - * with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * - * _.xorWith(objects, others, _.isEqual); - * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] - */ var xorWith = baseRest(function(arrays) { var comparator = last(arrays); if (isArrayLikeObject(comparator)) { @@ -7631,188 +3377,30 @@ UsergridEventable.mixin = function(destObject) { } return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); }); - /** - * Creates an array of grouped elements, the first of which contains the - * first elements of the given arrays, the second of which contains the - * second elements of the given arrays, and so on. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to process. - * @returns {Array} Returns the new array of grouped elements. - * @example - * - * _.zip(['a', 'b'], [1, 2], [true, false]); - * // => [['a', 1, true], ['b', 2, false]] - */ var zip = baseRest(unzip); - /** - * This method is like `_.fromPairs` except that it accepts two arrays, - * one of property identifiers and one of corresponding values. - * - * @static - * @memberOf _ - * @since 0.4.0 - * @category Array - * @param {Array} [props=[]] The property identifiers. - * @param {Array} [values=[]] The property values. - * @returns {Object} Returns the new object. - * @example - * - * _.zipObject(['a', 'b'], [1, 2]); - * // => { 'a': 1, 'b': 2 } - */ function zipObject(props, values) { return baseZipObject(props || [], values || [], assignValue); } - /** - * This method is like `_.zipObject` except that it supports property paths. - * - * @static - * @memberOf _ - * @since 4.1.0 - * @category Array - * @param {Array} [props=[]] The property identifiers. - * @param {Array} [values=[]] The property values. - * @returns {Object} Returns the new object. - * @example - * - * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); - * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } - */ function zipObjectDeep(props, values) { return baseZipObject(props || [], values || [], baseSet); } - /** - * This method is like `_.zip` except that it accepts `iteratee` to specify - * how grouped values should be combined. The iteratee is invoked with the - * elements of each group: (...group). - * - * @static - * @memberOf _ - * @since 3.8.0 - * @category Array - * @param {...Array} [arrays] The arrays to process. - * @param {Function} [iteratee=_.identity] The function to combine grouped values. - * @returns {Array} Returns the new array of grouped elements. - * @example - * - * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { - * return a + b + c; - * }); - * // => [111, 222] - */ var zipWith = baseRest(function(arrays) { var length = arrays.length, iteratee = length > 1 ? arrays[length - 1] : undefined; iteratee = typeof iteratee == "function" ? (arrays.pop(), iteratee) : undefined; return unzipWith(arrays, iteratee); }); - /*------------------------------------------------------------------------*/ - /** - * Creates a `lodash` wrapper instance that wraps `value` with explicit method - * chain sequences enabled. The result of such sequences must be unwrapped - * with `_#value`. - * - * @static - * @memberOf _ - * @since 1.3.0 - * @category Seq - * @param {*} value The value to wrap. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'pebbles', 'age': 1 } - * ]; - * - * var youngest = _ - * .chain(users) - * .sortBy('age') - * .map(function(o) { - * return o.user + ' is ' + o.age; - * }) - * .head() - * .value(); - * // => 'pebbles is 1' - */ function chain(value) { var result = lodash(value); result.__chain__ = true; return result; } - /** - * This method invokes `interceptor` and returns `value`. The interceptor - * is invoked with one argument; (value). The purpose of this method is to - * "tap into" a method chain sequence in order to modify intermediate results. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Seq - * @param {*} value The value to provide to `interceptor`. - * @param {Function} interceptor The function to invoke. - * @returns {*} Returns `value`. - * @example - * - * _([1, 2, 3]) - * .tap(function(array) { - * // Mutate input array. - * array.pop(); - * }) - * .reverse() - * .value(); - * // => [2, 1] - */ function tap(value, interceptor) { interceptor(value); return value; } - /** - * This method is like `_.tap` except that it returns the result of `interceptor`. - * The purpose of this method is to "pass thru" values replacing intermediate - * results in a method chain sequence. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Seq - * @param {*} value The value to provide to `interceptor`. - * @param {Function} interceptor The function to invoke. - * @returns {*} Returns the result of `interceptor`. - * @example - * - * _(' abc ') - * .chain() - * .trim() - * .thru(function(value) { - * return [value]; - * }) - * .value(); - * // => ['abc'] - */ function thru(value, interceptor) { return interceptor(value); } - /** - * This method is the wrapper version of `_.at`. - * - * @name at - * @memberOf _ - * @since 1.0.0 - * @category Seq - * @param {...(string|string[])} [paths] The property paths of elements to pick. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; - * - * _(object).at(['a[0].b.c', 'a[1]']).value(); - * // => [3, 4] - */ var wrapperAt = flatRest(function(paths) { var length = paths.length, start = length ? paths[0] : 0, value = this.__wrapped__, interceptor = function(object) { return baseAt(object, paths); @@ -7833,87 +3421,12 @@ UsergridEventable.mixin = function(destObject) { return array; }); }); - /** - * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. - * - * @name chain - * @memberOf _ - * @since 0.1.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 } - * ]; - * - * // A sequence without explicit chaining. - * _(users).head(); - * // => { 'user': 'barney', 'age': 36 } - * - * // A sequence with explicit chaining. - * _(users) - * .chain() - * .head() - * .pick('user') - * .value(); - * // => { 'user': 'barney' } - */ function wrapperChain() { return chain(this); } - /** - * Executes the chain sequence and returns the wrapped result. - * - * @name commit - * @memberOf _ - * @since 3.2.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var array = [1, 2]; - * var wrapped = _(array).push(3); - * - * console.log(array); - * // => [1, 2] - * - * wrapped = wrapped.commit(); - * console.log(array); - * // => [1, 2, 3] - * - * wrapped.last(); - * // => 3 - * - * console.log(array); - * // => [1, 2, 3] - */ function wrapperCommit() { return new LodashWrapper(this.value(), this.__chain__); } - /** - * Gets the next value on a wrapped object following the - * [iterator protocol](https://mdn.io/iteration_protocols#iterator). - * - * @name next - * @memberOf _ - * @since 4.0.0 - * @category Seq - * @returns {Object} Returns the next iterator value. - * @example - * - * var wrapped = _([1, 2]); - * - * wrapped.next(); - * // => { 'done': false, 'value': 1 } - * - * wrapped.next(); - * // => { 'done': false, 'value': 2 } - * - * wrapped.next(); - * // => { 'done': true, 'value': undefined } - */ function wrapperNext() { if (this.__values__ === undefined) { this.__values__ = toArray(this.value()); @@ -7924,51 +3437,9 @@ UsergridEventable.mixin = function(destObject) { value: value }; } - /** - * Enables the wrapper to be iterable. - * - * @name Symbol.iterator - * @memberOf _ - * @since 4.0.0 - * @category Seq - * @returns {Object} Returns the wrapper object. - * @example - * - * var wrapped = _([1, 2]); - * - * wrapped[Symbol.iterator]() === wrapped; - * // => true - * - * Array.from(wrapped); - * // => [1, 2] - */ function wrapperToIterator() { return this; } - /** - * Creates a clone of the chain sequence planting `value` as the wrapped value. - * - * @name plant - * @memberOf _ - * @since 3.2.0 - * @category Seq - * @param {*} value The value to plant. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * function square(n) { - * return n * n; - * } - * - * var wrapped = _([1, 2]).map(square); - * var other = wrapped.plant([3, 4]); - * - * other.value(); - * // => [9, 16] - * - * wrapped.value(); - * // => [1, 4] - */ function wrapperPlant(value) { var result, parent = this; while (parent instanceof baseLodash) { @@ -7986,26 +3457,6 @@ UsergridEventable.mixin = function(destObject) { previous.__wrapped__ = value; return result; } - /** - * This method is the wrapper version of `_.reverse`. - * - * **Note:** This method mutates the wrapped array. - * - * @name reverse - * @memberOf _ - * @since 0.1.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var array = [1, 2, 3]; - * - * _(array).reverse().value() - * // => [3, 2, 1] - * - * console.log(array); - * // => [3, 2, 1] - */ function wrapperReverse() { var value = this.__wrapped__; if (value instanceof LazyWrapper) { @@ -8023,47 +3474,9 @@ UsergridEventable.mixin = function(destObject) { } return this.thru(reverse); } - /** - * Executes the chain sequence to resolve the unwrapped value. - * - * @name value - * @memberOf _ - * @since 0.1.0 - * @alias toJSON, valueOf - * @category Seq - * @returns {*} Returns the resolved unwrapped value. - * @example - * - * _([1, 2, 3]).value(); - * // => [1, 2, 3] - */ function wrapperValue() { return baseWrapperValue(this.__wrapped__, this.__actions__); } - /*------------------------------------------------------------------------*/ - /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The corresponding value of - * each key is the number of times the key was returned by `iteratee`. The - * iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] - * The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * _.countBy([6.1, 4.2, 6.3], Math.floor); - * // => { '4': 1, '6': 2 } - * - * // The `_.property` iteratee shorthand. - * _.countBy(['one', 'two', 'three'], 'length'); - * // => { '3': 2, '5': 1 } - */ var countBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { ++result[key]; @@ -8071,48 +3484,6 @@ UsergridEventable.mixin = function(destObject) { baseAssignValue(result, key, 1); } }); - /** - * Checks if `predicate` returns truthy for **all** elements of `collection`. - * Iteration is stopped once `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index|key, collection). - * - * **Note:** This method returns `true` for - * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because - * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of - * elements of empty collections. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] - * The function invoked per iteration. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false`. - * @example - * - * _.every([true, 1, null, 'yes'], Boolean); - * // => false - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; - * - * // The `_.matches` iteratee shorthand. - * _.every(users, { 'user': 'barney', 'active': false }); - * // => false - * - * // The `_.matchesProperty` iteratee shorthand. - * _.every(users, ['active', false]); - * // => true - * - * // The `_.property` iteratee shorthand. - * _.every(users, 'active'); - * // => false - */ function every(collection, predicate, guard) { var func = isArray(collection) ? arrayEvery : baseEvery; if (guard && isIterateeCall(collection, predicate, guard)) { @@ -8120,264 +3491,30 @@ UsergridEventable.mixin = function(destObject) { } return func(collection, getIteratee(predicate, 3)); } - /** - * Iterates over elements of `collection`, returning an array of all elements - * `predicate` returns truthy for. The predicate is invoked with three - * arguments: (value, index|key, collection). - * - * **Note:** Unlike `_.remove`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] - * The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - * @see _.reject - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; - * - * _.filter(users, function(o) { return !o.active; }); - * // => objects for ['fred'] - * - * // The `_.matches` iteratee shorthand. - * _.filter(users, { 'age': 36, 'active': true }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.filter(users, ['active', false]); - * // => objects for ['fred'] - * - * // The `_.property` iteratee shorthand. - * _.filter(users, 'active'); - * // => objects for ['barney'] - */ function filter(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, getIteratee(predicate, 3)); } - /** - * Iterates over elements of `collection`, returning the first element - * `predicate` returns truthy for. The predicate is invoked with three - * arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to inspect. - * @param {Function} [predicate=_.identity] - * The function invoked per iteration. - * @param {number} [fromIndex=0] The index to search from. - * @returns {*} Returns the matched element, else `undefined`. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false }, - * { 'user': 'pebbles', 'age': 1, 'active': true } - * ]; - * - * _.find(users, function(o) { return o.age < 40; }); - * // => object for 'barney' - * - * // The `_.matches` iteratee shorthand. - * _.find(users, { 'age': 1, 'active': true }); - * // => object for 'pebbles' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.find(users, ['active', false]); - * // => object for 'fred' - * - * // The `_.property` iteratee shorthand. - * _.find(users, 'active'); - * // => object for 'barney' - */ var find = createFind(findIndex); - /** - * This method is like `_.find` except that it iterates over elements of - * `collection` from right to left. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Collection - * @param {Array|Object} collection The collection to inspect. - * @param {Function} [predicate=_.identity] - * The function invoked per iteration. - * @param {number} [fromIndex=collection.length-1] The index to search from. - * @returns {*} Returns the matched element, else `undefined`. - * @example - * - * _.findLast([1, 2, 3, 4], function(n) { - * return n % 2 == 1; - * }); - * // => 3 - */ var findLast = createFind(findLastIndex); - /** - * Creates a flattened array of values by running each element in `collection` - * thru `iteratee` and flattening the mapped results. The iteratee is invoked - * with three arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] - * The function invoked per iteration. - * @returns {Array} Returns the new flattened array. - * @example - * - * function duplicate(n) { - * return [n, n]; - * } - * - * _.flatMap([1, 2], duplicate); - * // => [1, 1, 2, 2] - */ function flatMap(collection, iteratee) { return baseFlatten(map(collection, iteratee), 1); } - /** - * This method is like `_.flatMap` except that it recursively flattens the - * mapped results. - * - * @static - * @memberOf _ - * @since 4.7.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] - * The function invoked per iteration. - * @returns {Array} Returns the new flattened array. - * @example - * - * function duplicate(n) { - * return [[[n, n]]]; - * } - * - * _.flatMapDeep([1, 2], duplicate); - * // => [1, 1, 2, 2] - */ function flatMapDeep(collection, iteratee) { return baseFlatten(map(collection, iteratee), INFINITY); } - /** - * This method is like `_.flatMap` except that it recursively flattens the - * mapped results up to `depth` times. - * - * @static - * @memberOf _ - * @since 4.7.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] - * The function invoked per iteration. - * @param {number} [depth=1] The maximum recursion depth. - * @returns {Array} Returns the new flattened array. - * @example - * - * function duplicate(n) { - * return [[[n, n]]]; - * } - * - * _.flatMapDepth([1, 2], duplicate, 2); - * // => [[1, 1], [2, 2]] - */ function flatMapDepth(collection, iteratee, depth) { depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(map(collection, iteratee), depth); } - /** - * Iterates over elements of `collection` and invokes `iteratee` for each element. - * The iteratee is invoked with three arguments: (value, index|key, collection). - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * **Note:** As with other "Collections" methods, objects with a "length" - * property are iterated like arrays. To avoid this behavior use `_.forIn` - * or `_.forOwn` for object iteration. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @alias each - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - * @see _.forEachRight - * @example - * - * _.forEach([1, 2], function(value) { - * console.log(value); - * }); - * // => Logs `1` then `2`. - * - * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a' then 'b' (iteration order is not guaranteed). - */ function forEach(collection, iteratee) { var func = isArray(collection) ? arrayEach : baseEach; return func(collection, getIteratee(iteratee, 3)); } - /** - * This method is like `_.forEach` except that it iterates over elements of - * `collection` from right to left. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @alias eachRight - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - * @see _.forEach - * @example - * - * _.forEachRight([1, 2], function(value) { - * console.log(value); - * }); - * // => Logs `2` then `1`. - */ function forEachRight(collection, iteratee) { var func = isArray(collection) ? arrayEachRight : baseEachRight; return func(collection, getIteratee(iteratee, 3)); } - /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The order of grouped values - * is determined by the order they occur in `collection`. The corresponding - * value of each key is an array of elements responsible for generating the - * key. The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] - * The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * _.groupBy([6.1, 4.2, 6.3], Math.floor); - * // => { '4': [4.2], '6': [6.1, 6.3] } - * - * // The `_.property` iteratee shorthand. - * _.groupBy(['one', 'two', 'three'], 'length'); - * // => { '3': ['one', 'two'], '5': ['three'] } - */ var groupBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { result[key].push(value); @@ -8385,36 +3522,6 @@ UsergridEventable.mixin = function(destObject) { baseAssignValue(result, key, [ value ]); } }); - /** - * Checks if `value` is in `collection`. If `collection` is a string, it's - * checked for a substring of `value`, otherwise - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * is used for equality comparisons. If `fromIndex` is negative, it's used as - * the offset from the end of `collection`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object|string} collection The collection to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. - * @returns {boolean} Returns `true` if `value` is found, else `false`. - * @example - * - * _.includes([1, 2, 3], 1); - * // => true - * - * _.includes([1, 2, 3], 1, 2); - * // => false - * - * _.includes({ 'a': 1, 'b': 2 }, 1); - * // => true - * - * _.includes('abcd', 'bc'); - * // => true - */ function includes(collection, value, fromIndex, guard) { collection = isArrayLike(collection) ? collection : values(collection); fromIndex = fromIndex && !guard ? toInteger(fromIndex) : 0; @@ -8424,29 +3531,6 @@ UsergridEventable.mixin = function(destObject) { } return isString(collection) ? fromIndex <= length && collection.indexOf(value, fromIndex) > -1 : !!length && baseIndexOf(collection, value, fromIndex) > -1; } - /** - * Invokes the method at `path` of each element in `collection`, returning - * an array of the results of each invoked method. Any additional arguments - * are provided to each invoked method. If `path` is a function, it's invoked - * for, and `this` bound to, each element in `collection`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Array|Function|string} path The path of the method to invoke or - * the function invoked per iteration. - * @param {...*} [args] The arguments to invoke each method with. - * @returns {Array} Returns the array of results. - * @example - * - * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); - * // => [[1, 5, 7], [1, 2, 3]] - * - * _.invokeMap([123, 456], String.prototype.split, ''); - * // => [['1', '2', '3'], ['4', '5', '6']] - */ var invokeMap = baseRest(function(collection, path, args) { var index = -1, isFunc = typeof path == "function", isProp = isKey(path), result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value) { @@ -8455,113 +3539,13 @@ UsergridEventable.mixin = function(destObject) { }); return result; }); - /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The corresponding value of - * each key is the last element responsible for generating the key. The - * iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] - * The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * var array = [ - * { 'dir': 'left', 'code': 97 }, - * { 'dir': 'right', 'code': 100 } - * ]; - * - * _.keyBy(array, function(o) { - * return String.fromCharCode(o.code); - * }); - * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } - * - * _.keyBy(array, 'dir'); - * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } - */ var keyBy = createAggregator(function(result, value, key) { baseAssignValue(result, key, value); }); - /** - * Creates an array of values by running each element in `collection` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, index|key, collection). - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. - * - * The guarded methods are: - * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, - * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, - * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, - * `template`, `trim`, `trimEnd`, `trimStart`, and `words` - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - * @example - * - * function square(n) { - * return n * n; - * } - * - * _.map([4, 8], square); - * // => [16, 64] - * - * _.map({ 'a': 4, 'b': 8 }, square); - * // => [16, 64] (iteration order is not guaranteed) - * - * var users = [ - * { 'user': 'barney' }, - * { 'user': 'fred' } - * ]; - * - * // The `_.property` iteratee shorthand. - * _.map(users, 'user'); - * // => ['barney', 'fred'] - */ function map(collection, iteratee) { var func = isArray(collection) ? arrayMap : baseMap; return func(collection, getIteratee(iteratee, 3)); } - /** - * This method is like `_.sortBy` except that it allows specifying the sort - * orders of the iteratees to sort by. If `orders` is unspecified, all values - * are sorted in ascending order. Otherwise, specify an order of "desc" for - * descending or "asc" for ascending sort order of corresponding values. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] - * The iteratees to sort by. - * @param {string[]} [orders] The sort orders of `iteratees`. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. - * @returns {Array} Returns the new sorted array. - * @example - * - * var users = [ - * { 'user': 'fred', 'age': 48 }, - * { 'user': 'barney', 'age': 34 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'barney', 'age': 36 } - * ]; - * - * // Sort by `user` in ascending order and by `age` in descending order. - * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); - * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] - */ function orderBy(collection, iteratees, orders, guard) { if (collection == null) { return []; @@ -8575,189 +3559,26 @@ UsergridEventable.mixin = function(destObject) { } return baseOrderBy(collection, iteratees, orders); } - /** - * Creates an array of elements split into two groups, the first of which - * contains elements `predicate` returns truthy for, the second of which - * contains elements `predicate` returns falsey for. The predicate is - * invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the array of grouped elements. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': true }, - * { 'user': 'pebbles', 'age': 1, 'active': false } - * ]; - * - * _.partition(users, function(o) { return o.active; }); - * // => objects for [['fred'], ['barney', 'pebbles']] - * - * // The `_.matches` iteratee shorthand. - * _.partition(users, { 'age': 1, 'active': false }); - * // => objects for [['pebbles'], ['barney', 'fred']] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.partition(users, ['active', false]); - * // => objects for [['barney', 'pebbles'], ['fred']] - * - * // The `_.property` iteratee shorthand. - * _.partition(users, 'active'); - * // => objects for [['fred'], ['barney', 'pebbles']] - */ var partition = createAggregator(function(result, value, key) { result[key ? 0 : 1].push(value); }, function() { return [ [], [] ]; }); - /** - * Reduces `collection` to a value which is the accumulated result of running - * each element in `collection` thru `iteratee`, where each successive - * invocation is supplied the return value of the previous. If `accumulator` - * is not given, the first element of `collection` is used as the initial - * value. The iteratee is invoked with four arguments: - * (accumulator, value, index|key, collection). - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.reduce`, `_.reduceRight`, and `_.transform`. - * - * The guarded methods are: - * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, - * and `sortBy` - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @returns {*} Returns the accumulated value. - * @see _.reduceRight - * @example - * - * _.reduce([1, 2], function(sum, n) { - * return sum + n; - * }, 0); - * // => 3 - * - * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { - * (result[value] || (result[value] = [])).push(key); - * return result; - * }, {}); - * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) - */ function reduce(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); } - /** - * This method is like `_.reduce` except that it iterates over elements of - * `collection` from right to left. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @returns {*} Returns the accumulated value. - * @see _.reduce - * @example - * - * var array = [[0, 1], [2, 3], [4, 5]]; - * - * _.reduceRight(array, function(flattened, other) { - * return flattened.concat(other); - * }, []); - * // => [4, 5, 2, 3, 0, 1] - */ function reduceRight(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); } - /** - * The opposite of `_.filter`; this method returns the elements of `collection` - * that `predicate` does **not** return truthy for. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - * @see _.filter - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': true } - * ]; - * - * _.reject(users, function(o) { return !o.active; }); - * // => objects for ['fred'] - * - * // The `_.matches` iteratee shorthand. - * _.reject(users, { 'age': 40, 'active': true }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.reject(users, ['active', false]); - * // => objects for ['fred'] - * - * // The `_.property` iteratee shorthand. - * _.reject(users, 'active'); - * // => objects for ['barney'] - */ function reject(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, negate(getIteratee(predicate, 3))); } - /** - * Gets a random element from `collection`. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Collection - * @param {Array|Object} collection The collection to sample. - * @returns {*} Returns the random element. - * @example - * - * _.sample([1, 2, 3, 4]); - * // => 2 - */ function sample(collection) { return arraySample(isArrayLike(collection) ? collection : values(collection)); } - /** - * Gets `n` random elements at unique keys from `collection` up to the - * size of `collection`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to sample. - * @param {number} [n=1] The number of elements to sample. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the random elements. - * @example - * - * _.sampleSize([1, 2, 3], 2); - * // => [3, 1] - * - * _.sampleSize([1, 2, 3], 4); - * // => [2, 3, 1] - */ function sampleSize(collection, n, guard) { if (guard ? isIterateeCall(collection, n, guard) : n === undefined) { n = 1; @@ -8766,45 +3587,9 @@ UsergridEventable.mixin = function(destObject) { } return arraySampleSize(isArrayLike(collection) ? collection : values(collection), n); } - /** - * Creates an array of shuffled values, using a version of the - * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to shuffle. - * @returns {Array} Returns the new shuffled array. - * @example - * - * _.shuffle([1, 2, 3, 4]); - * // => [4, 1, 3, 2] - */ function shuffle(collection) { return shuffleSelf(isArrayLike(collection) ? copyArray(collection) : values(collection)); } - /** - * Gets the size of `collection` by returning its length for array-like - * values or the number of own enumerable string keyed properties for objects. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object|string} collection The collection to inspect. - * @returns {number} Returns the collection size. - * @example - * - * _.size([1, 2, 3]); - * // => 3 - * - * _.size({ 'a': 1, 'b': 2 }); - * // => 2 - * - * _.size('pebbles'); - * // => 7 - */ function size(collection) { if (collection == null) { return 0; @@ -8818,42 +3603,6 @@ UsergridEventable.mixin = function(destObject) { } return baseKeys(collection).length; } - /** - * Checks if `predicate` returns truthy for **any** element of `collection`. - * Iteration is stopped once `predicate` returns truthy. The predicate is - * invoked with three arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - * @example - * - * _.some([null, 0, 'yes', false], Boolean); - * // => true - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false } - * ]; - * - * // The `_.matches` iteratee shorthand. - * _.some(users, { 'user': 'barney', 'active': false }); - * // => false - * - * // The `_.matchesProperty` iteratee shorthand. - * _.some(users, ['active', false]); - * // => true - * - * // The `_.property` iteratee shorthand. - * _.some(users, 'active'); - * // => true - */ function some(collection, predicate, guard) { var func = isArray(collection) ? arraySome : baseSome; if (guard && isIterateeCall(collection, predicate, guard)) { @@ -8861,35 +3610,6 @@ UsergridEventable.mixin = function(destObject) { } return func(collection, getIteratee(predicate, 3)); } - /** - * Creates an array of elements, sorted in ascending order by the results of - * running each element in a collection thru each iteratee. This method - * performs a stable sort, that is, it preserves the original sort order of - * equal elements. The iteratees are invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {...(Function|Function[])} [iteratees=[_.identity]] - * The iteratees to sort by. - * @returns {Array} Returns the new sorted array. - * @example - * - * var users = [ - * { 'user': 'fred', 'age': 48 }, - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'barney', 'age': 34 } - * ]; - * - * _.sortBy(users, [function(o) { return o.user; }]); - * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] - * - * _.sortBy(users, ['user', 'age']); - * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] - */ var sortBy = baseRest(function(collection, iteratees) { if (collection == null) { return []; @@ -8902,51 +3622,9 @@ UsergridEventable.mixin = function(destObject) { } return baseOrderBy(collection, baseFlatten(iteratees, 1), []); }); - /*------------------------------------------------------------------------*/ - /** - * Gets the timestamp of the number of milliseconds that have elapsed since - * the Unix epoch (1 January 1970 00:00:00 UTC). - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Date - * @returns {number} Returns the timestamp. - * @example - * - * _.defer(function(stamp) { - * console.log(_.now() - stamp); - * }, _.now()); - * // => Logs the number of milliseconds it took for the deferred invocation. - */ var now = ctxNow || function() { return root.Date.now(); }; - /*------------------------------------------------------------------------*/ - /** - * The opposite of `_.before`; this method creates a function that invokes - * `func` once it's called `n` or more times. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {number} n The number of calls before `func` is invoked. - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * var saves = ['profile', 'settings']; - * - * var done = _.after(saves.length, function() { - * console.log('done saving!'); - * }); - * - * _.forEach(saves, function(type) { - * asyncSave({ 'type': type, 'complete': done }); - * }); - * // => Logs 'done saving!' after the two async saves have completed. - */ function after(n, func) { if (typeof func != "function") { throw new TypeError(FUNC_ERROR_TEXT); @@ -8958,45 +3636,11 @@ UsergridEventable.mixin = function(destObject) { } }; } - /** - * Creates a function that invokes `func`, with up to `n` arguments, - * ignoring any additional arguments. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} func The function to cap arguments for. - * @param {number} [n=func.length] The arity cap. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the new capped function. - * @example - * - * _.map(['6', '8', '10'], _.ary(parseInt, 1)); - * // => [6, 8, 10] - */ function ary(func, n, guard) { n = guard ? undefined : n; n = func && n == null ? func.length : n; return createWrap(func, ARY_FLAG, undefined, undefined, undefined, undefined, n); } - /** - * Creates a function that invokes `func`, with the `this` binding and arguments - * of the created function, while it's called less than `n` times. Subsequent - * calls to the created function return the result of the last `func` invocation. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {number} n The number of calls at which `func` is no longer invoked. - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * jQuery(element).on('click', _.before(5, addContactToList)); - * // => Allows adding up to 4 contacts to the list. - */ function before(n, func) { var result; if (typeof func != "function") { @@ -9013,41 +3657,6 @@ UsergridEventable.mixin = function(destObject) { return result; }; } - /** - * Creates a function that invokes `func` with the `this` binding of `thisArg` - * and `partials` prepended to the arguments it receives. - * - * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, - * may be used as a placeholder for partially applied arguments. - * - * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" - * property of bound functions. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to bind. - * @param {*} thisArg The `this` binding of `func`. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new bound function. - * @example - * - * function greet(greeting, punctuation) { - * return greeting + ' ' + this.user + punctuation; - * } - * - * var object = { 'user': 'fred' }; - * - * var bound = _.bind(greet, object, 'hi'); - * bound('!'); - * // => 'hi fred!' - * - * // Bound with placeholders. - * var bound = _.bind(greet, object, _, '!'); - * bound('hi'); - * // => 'hi fred!' - */ var bind = baseRest(function(func, thisArg, partials) { var bitmask = BIND_FLAG; if (partials.length) { @@ -9056,51 +3665,6 @@ UsergridEventable.mixin = function(destObject) { } return createWrap(func, bitmask, thisArg, partials, holders); }); - /** - * Creates a function that invokes the method at `object[key]` with `partials` - * prepended to the arguments it receives. - * - * This method differs from `_.bind` by allowing bound functions to reference - * methods that may be redefined or don't yet exist. See - * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) - * for more details. - * - * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. - * - * @static - * @memberOf _ - * @since 0.10.0 - * @category Function - * @param {Object} object The object to invoke the method on. - * @param {string} key The key of the method. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new bound function. - * @example - * - * var object = { - * 'user': 'fred', - * 'greet': function(greeting, punctuation) { - * return greeting + ' ' + this.user + punctuation; - * } - * }; - * - * var bound = _.bindKey(object, 'greet', 'hi'); - * bound('!'); - * // => 'hi fred!' - * - * object.greet = function(greeting, punctuation) { - * return greeting + 'ya ' + this.user + punctuation; - * }; - * - * bound('!'); - * // => 'hiya fred!' - * - * // Bound with placeholders. - * var bound = _.bindKey(object, 'greet', _, '!'); - * bound('hi'); - * // => 'hiya fred!' - */ var bindKey = baseRest(function(object, key, partials) { var bitmask = BIND_FLAG | BIND_KEY_FLAG; if (partials.length) { @@ -9109,151 +3673,18 @@ UsergridEventable.mixin = function(destObject) { } return createWrap(key, bitmask, object, partials, holders); }); - /** - * Creates a function that accepts arguments of `func` and either invokes - * `func` returning its result, if at least `arity` number of arguments have - * been provided, or returns a function that accepts the remaining `func` - * arguments, and so on. The arity of `func` may be specified if `func.length` - * is not sufficient. - * - * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, - * may be used as a placeholder for provided arguments. - * - * **Note:** This method doesn't set the "length" property of curried functions. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Function - * @param {Function} func The function to curry. - * @param {number} [arity=func.length] The arity of `func`. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the new curried function. - * @example - * - * var abc = function(a, b, c) { - * return [a, b, c]; - * }; - * - * var curried = _.curry(abc); - * - * curried(1)(2)(3); - * // => [1, 2, 3] - * - * curried(1, 2)(3); - * // => [1, 2, 3] - * - * curried(1, 2, 3); - * // => [1, 2, 3] - * - * // Curried with placeholders. - * curried(1)(_, 3)(2); - * // => [1, 2, 3] - */ function curry(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curry.placeholder; return result; } - /** - * This method is like `_.curry` except that arguments are applied to `func` - * in the manner of `_.partialRight` instead of `_.partial`. - * - * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for provided arguments. - * - * **Note:** This method doesn't set the "length" property of curried functions. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} func The function to curry. - * @param {number} [arity=func.length] The arity of `func`. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the new curried function. - * @example - * - * var abc = function(a, b, c) { - * return [a, b, c]; - * }; - * - * var curried = _.curryRight(abc); - * - * curried(3)(2)(1); - * // => [1, 2, 3] - * - * curried(2, 3)(1); - * // => [1, 2, 3] - * - * curried(1, 2, 3); - * // => [1, 2, 3] - * - * // Curried with placeholders. - * curried(3)(1, _)(2); - * // => [1, 2, 3] - */ function curryRight(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curryRight.placeholder; return result; } - /** - * Creates a debounced function that delays invoking `func` until after `wait` - * milliseconds have elapsed since the last time the debounced function was - * invoked. The debounced function comes with a `cancel` method to cancel - * delayed `func` invocations and a `flush` method to immediately invoke them. - * Provide `options` to indicate whether `func` should be invoked on the - * leading and/or trailing edge of the `wait` timeout. The `func` is invoked - * with the last arguments provided to the debounced function. Subsequent - * calls to the debounced function return the result of the last `func` - * invocation. - * - * **Note:** If `leading` and `trailing` options are `true`, `func` is - * invoked on the trailing edge of the timeout only if the debounced function - * is invoked more than once during the `wait` timeout. - * - * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred - * until to the next tick, similar to `setTimeout` with a timeout of `0`. - * - * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) - * for details over the differences between `_.debounce` and `_.throttle`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to debounce. - * @param {number} [wait=0] The number of milliseconds to delay. - * @param {Object} [options={}] The options object. - * @param {boolean} [options.leading=false] - * Specify invoking on the leading edge of the timeout. - * @param {number} [options.maxWait] - * The maximum time `func` is allowed to be delayed before it's invoked. - * @param {boolean} [options.trailing=true] - * Specify invoking on the trailing edge of the timeout. - * @returns {Function} Returns the new debounced function. - * @example - * - * // Avoid costly calculations while the window size is in flux. - * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); - * - * // Invoke `sendMail` when clicked, debouncing subsequent calls. - * jQuery(element).on('click', _.debounce(sendMail, 300, { - * 'leading': true, - * 'trailing': false - * })); - * - * // Ensure `batchLog` is invoked once after 1 second of debounced calls. - * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); - * var source = new EventSource('/stream'); - * jQuery(source).on('message', debounced); - * - * // Cancel the trailing debounced invocation. - * jQuery(window).on('popstate', debounced.cancel); - */ function debounce(func, wait, options) { var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; if (typeof func != "function") { @@ -9334,114 +3765,15 @@ UsergridEventable.mixin = function(destObject) { debounced.flush = flush; return debounced; } - /** - * Defers invoking the `func` until the current call stack has cleared. Any - * additional arguments are provided to `func` when it's invoked. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to defer. - * @param {...*} [args] The arguments to invoke `func` with. - * @returns {number} Returns the timer id. - * @example - * - * _.defer(function(text) { - * console.log(text); - * }, 'deferred'); - * // => Logs 'deferred' after one millisecond. - */ var defer = baseRest(function(func, args) { return baseDelay(func, 1, args); }); - /** - * Invokes `func` after `wait` milliseconds. Any additional arguments are - * provided to `func` when it's invoked. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @param {...*} [args] The arguments to invoke `func` with. - * @returns {number} Returns the timer id. - * @example - * - * _.delay(function(text) { - * console.log(text); - * }, 1000, 'later'); - * // => Logs 'later' after one second. - */ var delay = baseRest(function(func, wait, args) { return baseDelay(func, toNumber(wait) || 0, args); }); - /** - * Creates a function that invokes `func` with arguments reversed. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Function - * @param {Function} func The function to flip arguments for. - * @returns {Function} Returns the new flipped function. - * @example - * - * var flipped = _.flip(function() { - * return _.toArray(arguments); - * }); - * - * flipped('a', 'b', 'c', 'd'); - * // => ['d', 'c', 'b', 'a'] - */ function flip(func) { return createWrap(func, FLIP_FLAG); } - /** - * Creates a function that memoizes the result of `func`. If `resolver` is - * provided, it determines the cache key for storing the result based on the - * arguments provided to the memoized function. By default, the first argument - * provided to the memoized function is used as the map cache key. The `func` - * is invoked with the `this` binding of the memoized function. - * - * **Note:** The cache is exposed as the `cache` property on the memoized - * function. Its creation may be customized by replacing the `_.memoize.Cache` - * constructor with one whose instances implement the - * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) - * method interface of `delete`, `get`, `has`, and `set`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to have its output memoized. - * @param {Function} [resolver] The function to resolve the cache key. - * @returns {Function} Returns the new memoized function. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * var other = { 'c': 3, 'd': 4 }; - * - * var values = _.memoize(_.values); - * values(object); - * // => [1, 2] - * - * values(other); - * // => [3, 4] - * - * object.a = 2; - * values(object); - * // => [1, 2] - * - * // Modify the result cache. - * values.cache.set(object, ['a', 'b']); - * values(object); - * // => ['a', 'b'] - * - * // Replace `_.memoize.Cache`. - * _.memoize.Cache = WeakMap; - */ function memoize(func, resolver) { if (typeof func != "function" || resolver && typeof resolver != "function") { throw new TypeError(FUNC_ERROR_TEXT); @@ -9459,26 +3791,6 @@ UsergridEventable.mixin = function(destObject) { return memoized; } memoize.Cache = MapCache; - /** - * Creates a function that negates the result of the predicate `func`. The - * `func` predicate is invoked with the `this` binding and arguments of the - * created function. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} predicate The predicate to negate. - * @returns {Function} Returns the new negated function. - * @example - * - * function isEven(n) { - * return n % 2 == 0; - * } - * - * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); - * // => [1, 3, 5] - */ function negate(predicate) { if (typeof predicate != "function") { throw new TypeError(FUNC_ERROR_TEXT); @@ -9501,58 +3813,9 @@ UsergridEventable.mixin = function(destObject) { return !predicate.apply(this, args); }; } - /** - * Creates a function that is restricted to invoking `func` once. Repeat calls - * to the function return the value of the first invocation. The `func` is - * invoked with the `this` binding and arguments of the created function. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * var initialize = _.once(createApplication); - * initialize(); - * initialize(); - * // => `createApplication` is invoked once - */ function once(func) { return before(2, func); } - /** - * Creates a function that invokes `func` with its arguments transformed. - * - * @static - * @since 4.0.0 - * @memberOf _ - * @category Function - * @param {Function} func The function to wrap. - * @param {...(Function|Function[])} [transforms=[_.identity]] - * The argument transforms. - * @returns {Function} Returns the new function. - * @example - * - * function doubled(n) { - * return n * 2; - * } - * - * function square(n) { - * return n * n; - * } - * - * var func = _.overArgs(function(x, y) { - * return [x, y]; - * }, [square, doubled]); - * - * func(9, 3); - * // => [81, 6] - * - * func(10, 5); - * // => [100, 10] - */ var overArgs = castRest(function(func, transforms) { transforms = transforms.length == 1 && isArray(transforms[0]) ? arrayMap(transforms[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); var funcsLength = transforms.length; @@ -9564,129 +3827,17 @@ UsergridEventable.mixin = function(destObject) { return apply(func, this, args); }); }); - /** - * Creates a function that invokes `func` with `partials` prepended to the - * arguments it receives. This method is like `_.bind` except it does **not** - * alter the `this` binding. - * - * The `_.partial.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. - * - * **Note:** This method doesn't set the "length" property of partially - * applied functions. - * - * @static - * @memberOf _ - * @since 0.2.0 - * @category Function - * @param {Function} func The function to partially apply arguments to. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new partially applied function. - * @example - * - * function greet(greeting, name) { - * return greeting + ' ' + name; - * } - * - * var sayHelloTo = _.partial(greet, 'hello'); - * sayHelloTo('fred'); - * // => 'hello fred' - * - * // Partially applied with placeholders. - * var greetFred = _.partial(greet, _, 'fred'); - * greetFred('hi'); - * // => 'hi fred' - */ var partial = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partial)); return createWrap(func, PARTIAL_FLAG, undefined, partials, holders); }); - /** - * This method is like `_.partial` except that partially applied arguments - * are appended to the arguments it receives. - * - * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. - * - * **Note:** This method doesn't set the "length" property of partially - * applied functions. - * - * @static - * @memberOf _ - * @since 1.0.0 - * @category Function - * @param {Function} func The function to partially apply arguments to. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new partially applied function. - * @example - * - * function greet(greeting, name) { - * return greeting + ' ' + name; - * } - * - * var greetFred = _.partialRight(greet, 'fred'); - * greetFred('hi'); - * // => 'hi fred' - * - * // Partially applied with placeholders. - * var sayHelloTo = _.partialRight(greet, 'hello', _); - * sayHelloTo('fred'); - * // => 'hello fred' - */ var partialRight = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partialRight)); return createWrap(func, PARTIAL_RIGHT_FLAG, undefined, partials, holders); }); - /** - * Creates a function that invokes `func` with arguments arranged according - * to the specified `indexes` where the argument value at the first index is - * provided as the first argument, the argument value at the second index is - * provided as the second argument, and so on. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} func The function to rearrange arguments for. - * @param {...(number|number[])} indexes The arranged argument indexes. - * @returns {Function} Returns the new function. - * @example - * - * var rearged = _.rearg(function(a, b, c) { - * return [a, b, c]; - * }, [2, 0, 1]); - * - * rearged('b', 'c', 'a') - * // => ['a', 'b', 'c'] - */ var rearg = flatRest(function(func, indexes) { return createWrap(func, REARG_FLAG, undefined, undefined, undefined, indexes); }); - /** - * Creates a function that invokes `func` with the `this` binding of the - * created function and arguments from `start` and beyond provided as - * an array. - * - * **Note:** This method is based on the - * [rest parameter](https://mdn.io/rest_parameters). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Function - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - * @example - * - * var say = _.rest(function(what, names) { - * return what + ' ' + _.initial(names).join(', ') + - * (_.size(names) > 1 ? ', & ' : '') + _.last(names); - * }); - * - * say('hello', 'fred', 'barney', 'pebbles'); - * // => 'hello fred, barney, & pebbles' - */ function rest(func, start) { if (typeof func != "function") { throw new TypeError(FUNC_ERROR_TEXT); @@ -9694,40 +3845,6 @@ UsergridEventable.mixin = function(destObject) { start = start === undefined ? start : toInteger(start); return baseRest(func, start); } - /** - * Creates a function that invokes `func` with the `this` binding of the - * create function and an array of arguments much like - * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). - * - * **Note:** This method is based on the - * [spread operator](https://mdn.io/spread_operator). - * - * @static - * @memberOf _ - * @since 3.2.0 - * @category Function - * @param {Function} func The function to spread arguments over. - * @param {number} [start=0] The start position of the spread. - * @returns {Function} Returns the new function. - * @example - * - * var say = _.spread(function(who, what) { - * return who + ' says ' + what; - * }); - * - * say(['fred', 'hello']); - * // => 'fred says hello' - * - * var numbers = Promise.all([ - * Promise.resolve(40), - * Promise.resolve(36) - * ]); - * - * numbers.then(_.spread(function(x, y) { - * return x + y; - * })); - * // => a Promise of 76 - */ function spread(func, start) { if (typeof func != "function") { throw new TypeError(FUNC_ERROR_TEXT); @@ -9741,50 +3858,6 @@ UsergridEventable.mixin = function(destObject) { return apply(func, this, otherArgs); }); } - /** - * Creates a throttled function that only invokes `func` at most once per - * every `wait` milliseconds. The throttled function comes with a `cancel` - * method to cancel delayed `func` invocations and a `flush` method to - * immediately invoke them. Provide `options` to indicate whether `func` - * should be invoked on the leading and/or trailing edge of the `wait` - * timeout. The `func` is invoked with the last arguments provided to the - * throttled function. Subsequent calls to the throttled function return the - * result of the last `func` invocation. - * - * **Note:** If `leading` and `trailing` options are `true`, `func` is - * invoked on the trailing edge of the timeout only if the throttled function - * is invoked more than once during the `wait` timeout. - * - * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred - * until to the next tick, similar to `setTimeout` with a timeout of `0`. - * - * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) - * for details over the differences between `_.throttle` and `_.debounce`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to throttle. - * @param {number} [wait=0] The number of milliseconds to throttle invocations to. - * @param {Object} [options={}] The options object. - * @param {boolean} [options.leading=true] - * Specify invoking on the leading edge of the timeout. - * @param {boolean} [options.trailing=true] - * Specify invoking on the trailing edge of the timeout. - * @returns {Function} Returns the new throttled function. - * @example - * - * // Avoid excessively updating the position while scrolling. - * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); - * - * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. - * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); - * jQuery(element).on('click', throttled); - * - * // Cancel the trailing throttled invocation. - * jQuery(window).on('popstate', throttled.cancel); - */ function throttle(func, wait, options) { var leading = true, trailing = true; if (typeof func != "function") { @@ -9800,84 +3873,13 @@ UsergridEventable.mixin = function(destObject) { trailing: trailing }); } - /** - * Creates a function that accepts up to one argument, ignoring any - * additional arguments. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Function - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - * @example - * - * _.map(['6', '8', '10'], _.unary(parseInt)); - * // => [6, 8, 10] - */ function unary(func) { return ary(func, 1); } - /** - * Creates a function that provides `value` to `wrapper` as its first - * argument. Any additional arguments provided to the function are appended - * to those provided to the `wrapper`. The wrapper is invoked with the `this` - * binding of the created function. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {*} value The value to wrap. - * @param {Function} [wrapper=identity] The wrapper function. - * @returns {Function} Returns the new function. - * @example - * - * var p = _.wrap(_.escape, function(func, text) { - * return '

    ' + func(text) + '

    '; - * }); - * - * p('fred, barney, & pebbles'); - * // => '

    fred, barney, & pebbles

    ' - */ function wrap(value, wrapper) { wrapper = wrapper == null ? identity : wrapper; return partial(wrapper, value); } - /*------------------------------------------------------------------------*/ - /** - * Casts `value` as an array if it's not one. - * - * @static - * @memberOf _ - * @since 4.4.0 - * @category Lang - * @param {*} value The value to inspect. - * @returns {Array} Returns the cast array. - * @example - * - * _.castArray(1); - * // => [1] - * - * _.castArray({ 'a': 1 }); - * // => [{ 'a': 1 }] - * - * _.castArray('abc'); - * // => ['abc'] - * - * _.castArray(null); - * // => [null] - * - * _.castArray(undefined); - * // => [undefined] - * - * _.castArray(); - * // => [] - * - * var array = [1, 2, 3]; - * console.log(_.castArray(array) === array); - * // => true - */ function castArray() { if (!arguments.length) { return []; @@ -9885,461 +3887,47 @@ UsergridEventable.mixin = function(destObject) { var value = arguments[0]; return isArray(value) ? value : [ value ]; } - /** - * Creates a shallow clone of `value`. - * - * **Note:** This method is loosely based on the - * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) - * and supports cloning arrays, array buffers, booleans, date objects, maps, - * numbers, `Object` objects, regexes, sets, strings, symbols, and typed - * arrays. The own enumerable properties of `arguments` objects are cloned - * as plain objects. An empty object is returned for uncloneable values such - * as error objects, functions, DOM nodes, and WeakMaps. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to clone. - * @returns {*} Returns the cloned value. - * @see _.cloneDeep - * @example - * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; - * - * var shallow = _.clone(objects); - * console.log(shallow[0] === objects[0]); - * // => true - */ function clone(value) { return baseClone(value, false, true); } - /** - * This method is like `_.clone` except that it accepts `customizer` which - * is invoked to produce the cloned value. If `customizer` returns `undefined`, - * cloning is handled by the method instead. The `customizer` is invoked with - * up to four arguments; (value [, index|key, object, stack]). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to clone. - * @param {Function} [customizer] The function to customize cloning. - * @returns {*} Returns the cloned value. - * @see _.cloneDeepWith - * @example - * - * function customizer(value) { - * if (_.isElement(value)) { - * return value.cloneNode(false); - * } - * } - * - * var el = _.cloneWith(document.body, customizer); - * - * console.log(el === document.body); - * // => false - * console.log(el.nodeName); - * // => 'BODY' - * console.log(el.childNodes.length); - * // => 0 - */ function cloneWith(value, customizer) { return baseClone(value, false, true, customizer); } - /** - * This method is like `_.clone` except that it recursively clones `value`. - * - * @static - * @memberOf _ - * @since 1.0.0 - * @category Lang - * @param {*} value The value to recursively clone. - * @returns {*} Returns the deep cloned value. - * @see _.clone - * @example - * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; - * - * var deep = _.cloneDeep(objects); - * console.log(deep[0] === objects[0]); - * // => false - */ function cloneDeep(value) { return baseClone(value, true, true); } - /** - * This method is like `_.cloneWith` except that it recursively clones `value`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to recursively clone. - * @param {Function} [customizer] The function to customize cloning. - * @returns {*} Returns the deep cloned value. - * @see _.cloneWith - * @example - * - * function customizer(value) { - * if (_.isElement(value)) { - * return value.cloneNode(true); - * } - * } - * - * var el = _.cloneDeepWith(document.body, customizer); - * - * console.log(el === document.body); - * // => false - * console.log(el.nodeName); - * // => 'BODY' - * console.log(el.childNodes.length); - * // => 20 - */ function cloneDeepWith(value, customizer) { return baseClone(value, true, true, customizer); } - /** - * Checks if `object` conforms to `source` by invoking the predicate - * properties of `source` with the corresponding property values of `object`. - * - * **Note:** This method is equivalent to `_.conforms` when `source` is - * partially applied. - * - * @static - * @memberOf _ - * @since 4.14.0 - * @category Lang - * @param {Object} object The object to inspect. - * @param {Object} source The object of property predicates to conform to. - * @returns {boolean} Returns `true` if `object` conforms, else `false`. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * - * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); - * // => true - * - * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); - * // => false - */ function conformsTo(object, source) { return source == null || baseConformsTo(object, source, keys(source)); } - /** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ function eq(value, other) { return value === other || value !== value && other !== other; } - /** - * Checks if `value` is greater than `other`. - * - * @static - * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than `other`, - * else `false`. - * @see _.lt - * @example - * - * _.gt(3, 1); - * // => true - * - * _.gt(3, 3); - * // => false - * - * _.gt(1, 3); - * // => false - */ var gt = createRelationalOperation(baseGt); - /** - * Checks if `value` is greater than or equal to `other`. - * - * @static - * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than or equal to - * `other`, else `false`. - * @see _.lte - * @example - * - * _.gte(3, 1); - * // => true - * - * _.gte(3, 3); - * // => true - * - * _.gte(1, 3); - * // => false - */ var gte = createRelationalOperation(function(value, other) { return value >= other; }); - /** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ function isArguments(value) { return isArrayLikeObject(value) && hasOwnProperty.call(value, "callee") && (!propertyIsEnumerable.call(value, "callee") || objectToString.call(value) == argsTag); } - /** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ var isArray = Array.isArray; - /** - * Checks if `value` is classified as an `ArrayBuffer` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. - * @example - * - * _.isArrayBuffer(new ArrayBuffer(2)); - * // => true - * - * _.isArrayBuffer(new Array(2)); - * // => false - */ var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; - /** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } - /** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } - /** - * Checks if `value` is classified as a boolean primitive or object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. - * @example - * - * _.isBoolean(false); - * // => true - * - * _.isBoolean(null); - * // => false - */ function isBoolean(value) { return value === true || value === false || isObjectLike(value) && objectToString.call(value) == boolTag; } - /** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ var isBuffer = nativeIsBuffer || stubFalse; - /** - * Checks if `value` is classified as a `Date` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a date object, else `false`. - * @example - * - * _.isDate(new Date); - * // => true - * - * _.isDate('Mon April 23 2012'); - * // => false - */ var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; - /** - * Checks if `value` is likely a DOM element. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. - * @example - * - * _.isElement(document.body); - * // => true - * - * _.isElement(''); - * // => false - */ function isElement(value) { return value != null && value.nodeType === 1 && isObjectLike(value) && !isPlainObject(value); } - /** - * Checks if `value` is an empty object, collection, map, or set. - * - * Objects are considered empty if they have no own enumerable string keyed - * properties. - * - * Array-like values such as `arguments` objects, arrays, buffers, strings, or - * jQuery-like collections are considered empty if they have a `length` of `0`. - * Similarly, maps and sets are considered empty if they have a `size` of `0`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is empty, else `false`. - * @example - * - * _.isEmpty(null); - * // => true - * - * _.isEmpty(true); - * // => true - * - * _.isEmpty(1); - * // => true - * - * _.isEmpty([1, 2, 3]); - * // => false - * - * _.isEmpty({ 'a': 1 }); - * // => false - */ function isEmpty(value) { if (isArrayLike(value) && (isArray(value) || typeof value == "string" || typeof value.splice == "function" || isBuffer(value) || isArguments(value))) { return !value.length; @@ -10358,510 +3946,66 @@ UsergridEventable.mixin = function(destObject) { } return true; } - /** - * Performs a deep comparison between two values to determine if they are - * equivalent. - * - * **Note:** This method supports comparing arrays, array buffers, booleans, - * date objects, error objects, maps, numbers, `Object` objects, regexes, - * sets, strings, symbols, and typed arrays. `Object` objects are compared - * by their own, not inherited, enumerable properties. Functions and DOM - * nodes are **not** supported. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.isEqual(object, other); - * // => true - * - * object === other; - * // => false - */ function isEqual(value, other) { return baseIsEqual(value, other); } - /** - * This method is like `_.isEqual` except that it accepts `customizer` which - * is invoked to compare values. If `customizer` returns `undefined`, comparisons - * are handled by the method instead. The `customizer` is invoked with up to - * six arguments: (objValue, othValue [, index|key, object, other, stack]). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * function isGreeting(value) { - * return /^h(?:i|ello)$/.test(value); - * } - * - * function customizer(objValue, othValue) { - * if (isGreeting(objValue) && isGreeting(othValue)) { - * return true; - * } - * } - * - * var array = ['hello', 'goodbye']; - * var other = ['hi', 'goodbye']; - * - * _.isEqualWith(array, other, customizer); - * // => true - */ function isEqualWith(value, other, customizer) { customizer = typeof customizer == "function" ? customizer : undefined; var result = customizer ? customizer(value, other) : undefined; return result === undefined ? baseIsEqual(value, other, customizer) : !!result; } - /** - * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, - * `SyntaxError`, `TypeError`, or `URIError` object. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an error object, else `false`. - * @example - * - * _.isError(new Error); - * // => true - * - * _.isError(Error); - * // => false - */ function isError(value) { if (!isObjectLike(value)) { return false; } return objectToString.call(value) == errorTag || typeof value.message == "string" && typeof value.name == "string"; } - /** - * Checks if `value` is a finite primitive number. - * - * **Note:** This method is based on - * [`Number.isFinite`](https://mdn.io/Number/isFinite). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. - * @example - * - * _.isFinite(3); - * // => true - * - * _.isFinite(Number.MIN_VALUE); - * // => true - * - * _.isFinite(Infinity); - * // => false - * - * _.isFinite('3'); - * // => false - */ function isFinite(value) { return typeof value == "number" && nativeIsFinite(value); } - /** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ function isFunction(value) { var tag = isObject(value) ? objectToString.call(value) : ""; return tag == funcTag || tag == genTag; } - /** - * Checks if `value` is an integer. - * - * **Note:** This method is based on - * [`Number.isInteger`](https://mdn.io/Number/isInteger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an integer, else `false`. - * @example - * - * _.isInteger(3); - * // => true - * - * _.isInteger(Number.MIN_VALUE); - * // => false - * - * _.isInteger(Infinity); - * // => false - * - * _.isInteger('3'); - * // => false - */ function isInteger(value) { return typeof value == "number" && value == toInteger(value); } - /** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ function isLength(value) { return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } - /** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ function isObject(value) { var type = typeof value; return value != null && (type == "object" || type == "function"); } - /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ function isObjectLike(value) { return value != null && typeof value == "object"; } - /** - * Checks if `value` is classified as a `Map` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a map, else `false`. - * @example - * - * _.isMap(new Map); - * // => true - * - * _.isMap(new WeakMap); - * // => false - */ var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; - /** - * Performs a partial deep comparison between `object` and `source` to - * determine if `object` contains equivalent property values. - * - * **Note:** This method is equivalent to `_.matches` when `source` is - * partially applied. - * - * Partial comparisons will match empty array and empty object `source` - * values against any array or object value, respectively. See `_.isEqual` - * for a list of supported value comparisons. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * - * _.isMatch(object, { 'b': 2 }); - * // => true - * - * _.isMatch(object, { 'b': 1 }); - * // => false - */ function isMatch(object, source) { return object === source || baseIsMatch(object, source, getMatchData(source)); } - /** - * This method is like `_.isMatch` except that it accepts `customizer` which - * is invoked to compare values. If `customizer` returns `undefined`, comparisons - * are handled by the method instead. The `customizer` is invoked with five - * arguments: (objValue, srcValue, index|key, object, source). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - * @example - * - * function isGreeting(value) { - * return /^h(?:i|ello)$/.test(value); - * } - * - * function customizer(objValue, srcValue) { - * if (isGreeting(objValue) && isGreeting(srcValue)) { - * return true; - * } - * } - * - * var object = { 'greeting': 'hello' }; - * var source = { 'greeting': 'hi' }; - * - * _.isMatchWith(object, source, customizer); - * // => true - */ function isMatchWith(object, source, customizer) { customizer = typeof customizer == "function" ? customizer : undefined; return baseIsMatch(object, source, getMatchData(source), customizer); } - /** - * Checks if `value` is `NaN`. - * - * **Note:** This method is based on - * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as - * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for - * `undefined` and other non-number values. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - * @example - * - * _.isNaN(NaN); - * // => true - * - * _.isNaN(new Number(NaN)); - * // => true - * - * isNaN(undefined); - * // => true - * - * _.isNaN(undefined); - * // => false - */ function isNaN(value) { return isNumber(value) && value != +value; } - /** - * Checks if `value` is a pristine native function. - * - * **Note:** This method can't reliably detect native functions in the presence - * of the core-js package because core-js circumvents this kind of detection. - * Despite multiple requests, the core-js maintainer has made it clear: any - * attempt to fix the detection will be obstructed. As a result, we're left - * with little choice but to throw an error. Unfortunately, this also affects - * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), - * which rely on core-js. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - * @example - * - * _.isNative(Array.prototype.push); - * // => true - * - * _.isNative(_); - * // => false - */ function isNative(value) { if (isMaskable(value)) { throw new Error("This method is not supported with core-js. Try https://github.com/es-shims."); } return baseIsNative(value); } - /** - * Checks if `value` is `null`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `null`, else `false`. - * @example - * - * _.isNull(null); - * // => true - * - * _.isNull(void 0); - * // => false - */ function isNull(value) { return value === null; } - /** - * Checks if `value` is `null` or `undefined`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is nullish, else `false`. - * @example - * - * _.isNil(null); - * // => true - * - * _.isNil(void 0); - * // => true - * - * _.isNil(NaN); - * // => false - */ function isNil(value) { return value == null; } - /** - * Checks if `value` is classified as a `Number` primitive or object. - * - * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are - * classified as numbers, use the `_.isFinite` method. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a number, else `false`. - * @example - * - * _.isNumber(3); - * // => true - * - * _.isNumber(Number.MIN_VALUE); - * // => true - * - * _.isNumber(Infinity); - * // => true - * - * _.isNumber('3'); - * // => false - */ function isNumber(value) { return typeof value == "number" || isObjectLike(value) && objectToString.call(value) == numberTag; } - /** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. - * - * @static - * @memberOf _ - * @since 0.8.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - * - * _.isPlainObject(Object.create(null)); - * // => true - */ function isPlainObject(value) { if (!isObjectLike(value) || objectToString.call(value) != objectTag) { return false; @@ -10873,263 +4017,31 @@ UsergridEventable.mixin = function(destObject) { var Ctor = hasOwnProperty.call(proto, "constructor") && proto.constructor; return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; } - /** - * Checks if `value` is classified as a `RegExp` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. - * @example - * - * _.isRegExp(/abc/); - * // => true - * - * _.isRegExp('/abc/'); - * // => false - */ var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; - /** - * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 - * double precision number which isn't the result of a rounded unsafe integer. - * - * **Note:** This method is based on - * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. - * @example - * - * _.isSafeInteger(3); - * // => true - * - * _.isSafeInteger(Number.MIN_VALUE); - * // => false - * - * _.isSafeInteger(Infinity); - * // => false - * - * _.isSafeInteger('3'); - * // => false - */ function isSafeInteger(value) { return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; } - /** - * Checks if `value` is classified as a `Set` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a set, else `false`. - * @example - * - * _.isSet(new Set); - * // => true - * - * _.isSet(new WeakSet); - * // => false - */ var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; - /** - * Checks if `value` is classified as a `String` primitive or object. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a string, else `false`. - * @example - * - * _.isString('abc'); - * // => true - * - * _.isString(1); - * // => false - */ function isString(value) { return typeof value == "string" || !isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag; } - /** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ function isSymbol(value) { return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag; } - /** - * Checks if `value` is classified as a typed array. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true - * - * _.isTypedArray([]); - * // => false - */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; - /** - * Checks if `value` is `undefined`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. - * @example - * - * _.isUndefined(void 0); - * // => true - * - * _.isUndefined(null); - * // => false - */ function isUndefined(value) { return value === undefined; } - /** - * Checks if `value` is classified as a `WeakMap` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. - * @example - * - * _.isWeakMap(new WeakMap); - * // => true - * - * _.isWeakMap(new Map); - * // => false - */ function isWeakMap(value) { return isObjectLike(value) && getTag(value) == weakMapTag; } - /** - * Checks if `value` is classified as a `WeakSet` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. - * @example - * - * _.isWeakSet(new WeakSet); - * // => true - * - * _.isWeakSet(new Set); - * // => false - */ function isWeakSet(value) { return isObjectLike(value) && objectToString.call(value) == weakSetTag; } - /** - * Checks if `value` is less than `other`. - * - * @static - * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than `other`, - * else `false`. - * @see _.gt - * @example - * - * _.lt(1, 3); - * // => true - * - * _.lt(3, 3); - * // => false - * - * _.lt(3, 1); - * // => false - */ var lt = createRelationalOperation(baseLt); - /** - * Checks if `value` is less than or equal to `other`. - * - * @static - * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than or equal to - * `other`, else `false`. - * @see _.gte - * @example - * - * _.lte(1, 3); - * // => true - * - * _.lte(3, 3); - * // => true - * - * _.lte(3, 1); - * // => false - */ var lte = createRelationalOperation(function(value, other) { return value <= other; }); - /** - * Converts `value` to an array. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to convert. - * @returns {Array} Returns the converted array. - * @example - * - * _.toArray({ 'a': 1, 'b': 2 }); - * // => [1, 2] - * - * _.toArray('abc'); - * // => ['a', 'b', 'c'] - * - * _.toArray(1); - * // => [] - * - * _.toArray(null); - * // => [] - */ function toArray(value) { if (!value) { return []; @@ -11143,29 +4055,6 @@ UsergridEventable.mixin = function(destObject) { var tag = getTag(value), func = tag == mapTag ? mapToArray : tag == setTag ? setToArray : values; return func(value); } - /** - * Converts `value` to a finite number. - * - * @static - * @memberOf _ - * @since 4.12.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted number. - * @example - * - * _.toFinite(3.2); - * // => 3.2 - * - * _.toFinite(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toFinite(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toFinite('3.2'); - * // => 3.2 - */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; @@ -11177,89 +4066,13 @@ UsergridEventable.mixin = function(destObject) { } return value === value ? value : 0; } - /** - * Converts `value` to an integer. - * - * **Note:** This method is loosely based on - * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toInteger(3.2); - * // => 3 - * - * _.toInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toInteger(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toInteger('3.2'); - * // => 3 - */ function toInteger(value) { var result = toFinite(value), remainder = result % 1; return result === result ? remainder ? result - remainder : result : 0; } - /** - * Converts `value` to an integer suitable for use as the length of an - * array-like object. - * - * **Note:** This method is based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toLength(3.2); - * // => 3 - * - * _.toLength(Number.MIN_VALUE); - * // => 0 - * - * _.toLength(Infinity); - * // => 4294967295 - * - * _.toLength('3.2'); - * // => 3 - */ function toLength(value) { return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; } - /** - * Converts `value` to a number. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. - * @example - * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toNumber(Infinity); - * // => Infinity - * - * _.toNumber('3.2'); - * // => 3.2 - */ function toNumber(value) { if (typeof value == "number") { return value; @@ -11278,117 +4091,15 @@ UsergridEventable.mixin = function(destObject) { var isBinary = reIsBinary.test(value); return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value; } - /** - * Converts `value` to a plain object flattening inherited enumerable string - * keyed properties of `value` to own properties of the plain object. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {Object} Returns the converted plain object. - * @example - * - * function Foo() { - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.assign({ 'a': 1 }, new Foo); - * // => { 'a': 1, 'b': 2 } - * - * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); - * // => { 'a': 1, 'b': 2, 'c': 3 } - */ function toPlainObject(value) { return copyObject(value, keysIn(value)); } - /** - * Converts `value` to a safe integer. A safe integer can be compared and - * represented correctly. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toSafeInteger(3.2); - * // => 3 - * - * _.toSafeInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toSafeInteger(Infinity); - * // => 9007199254740991 - * - * _.toSafeInteger('3.2'); - * // => 3 - */ function toSafeInteger(value) { return baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); } - /** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {string} Returns the string. - * @example - * - * _.toString(null); - * // => '' - * - * _.toString(-0); - * // => '-0' - * - * _.toString([1, 2, 3]); - * // => '1,2,3' - */ function toString(value) { return value == null ? "" : baseToString(value); } - /*------------------------------------------------------------------------*/ - /** - * Assigns own enumerable string keyed properties of source objects to the - * destination object. Source objects are applied from left to right. - * Subsequent sources overwrite property assignments of previous sources. - * - * **Note:** This method mutates `object` and is loosely based on - * [`Object.assign`](https://mdn.io/Object/assign). - * - * @static - * @memberOf _ - * @since 0.10.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.assignIn - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * function Bar() { - * this.c = 3; - * } - * - * Foo.prototype.b = 2; - * Bar.prototype.d = 4; - * - * _.assign({ 'a': 0 }, new Foo, new Bar); - * // => { 'a': 1, 'c': 3 } - */ var assign = createAssigner(function(object, source) { if (isPrototype(source) || isArrayLike(source)) { copyObject(source, keys(source), object); @@ -11400,590 +4111,65 @@ UsergridEventable.mixin = function(destObject) { } } }); - /** - * This method is like `_.assign` except that it iterates over own and - * inherited source properties. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias extend - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.assign - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * function Bar() { - * this.c = 3; - * } - * - * Foo.prototype.b = 2; - * Bar.prototype.d = 4; - * - * _.assignIn({ 'a': 0 }, new Foo, new Bar); - * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } - */ var assignIn = createAssigner(function(object, source) { copyObject(source, keysIn(source), object); }); - /** - * This method is like `_.assignIn` except that it accepts `customizer` - * which is invoked to produce the assigned values. If `customizer` returns - * `undefined`, assignment is handled by the method instead. The `customizer` - * is invoked with five arguments: (objValue, srcValue, key, object, source). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias extendWith - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @see _.assignWith - * @example - * - * function customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } - * - * var defaults = _.partialRight(_.assignInWith, customizer); - * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keysIn(source), object, customizer); }); - /** - * This method is like `_.assign` except that it accepts `customizer` - * which is invoked to produce the assigned values. If `customizer` returns - * `undefined`, assignment is handled by the method instead. The `customizer` - * is invoked with five arguments: (objValue, srcValue, key, object, source). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @see _.assignInWith - * @example - * - * function customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } - * - * var defaults = _.partialRight(_.assignWith, customizer); - * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ var assignWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keys(source), object, customizer); }); - /** - * Creates an array of values corresponding to `paths` of `object`. - * - * @static - * @memberOf _ - * @since 1.0.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {...(string|string[])} [paths] The property paths of elements to pick. - * @returns {Array} Returns the picked values. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; - * - * _.at(object, ['a[0].b.c', 'a[1]']); - * // => [3, 4] - */ var at = flatRest(baseAt); - /** - * Creates an object that inherits from the `prototype` object. If a - * `properties` object is given, its own enumerable string keyed properties - * are assigned to the created object. - * - * @static - * @memberOf _ - * @since 2.3.0 - * @category Object - * @param {Object} prototype The object to inherit from. - * @param {Object} [properties] The properties to assign to the object. - * @returns {Object} Returns the new object. - * @example - * - * function Shape() { - * this.x = 0; - * this.y = 0; - * } - * - * function Circle() { - * Shape.call(this); - * } - * - * Circle.prototype = _.create(Shape.prototype, { - * 'constructor': Circle - * }); - * - * var circle = new Circle; - * circle instanceof Circle; - * // => true - * - * circle instanceof Shape; - * // => true - */ function create(prototype, properties) { var result = baseCreate(prototype); return properties ? baseAssign(result, properties) : result; } - /** - * Assigns own and inherited enumerable string keyed properties of source - * objects to the destination object for all destination properties that - * resolve to `undefined`. Source objects are applied from left to right. - * Once a property is set, additional values of the same property are ignored. - * - * **Note:** This method mutates `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.defaultsDeep - * @example - * - * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ var defaults = baseRest(function(args) { args.push(undefined, assignInDefaults); return apply(assignInWith, undefined, args); }); - /** - * This method is like `_.defaults` except that it recursively assigns - * default properties. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 3.10.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.defaults - * @example - * - * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); - * // => { 'a': { 'b': 2, 'c': 3 } } - */ var defaultsDeep = baseRest(function(args) { args.push(undefined, mergeDefaults); return apply(mergeWith, undefined, args); }); - /** - * This method is like `_.find` except that it returns the key of the first - * element `predicate` returns truthy for instead of the element itself. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Object - * @param {Object} object The object to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {string|undefined} Returns the key of the matched element, - * else `undefined`. - * @example - * - * var users = { - * 'barney': { 'age': 36, 'active': true }, - * 'fred': { 'age': 40, 'active': false }, - * 'pebbles': { 'age': 1, 'active': true } - * }; - * - * _.findKey(users, function(o) { return o.age < 40; }); - * // => 'barney' (iteration order is not guaranteed) - * - * // The `_.matches` iteratee shorthand. - * _.findKey(users, { 'age': 1, 'active': true }); - * // => 'pebbles' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findKey(users, ['active', false]); - * // => 'fred' - * - * // The `_.property` iteratee shorthand. - * _.findKey(users, 'active'); - * // => 'barney' - */ function findKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); } - /** - * This method is like `_.findKey` except that it iterates over elements of - * a collection in the opposite order. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Object - * @param {Object} object The object to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {string|undefined} Returns the key of the matched element, - * else `undefined`. - * @example - * - * var users = { - * 'barney': { 'age': 36, 'active': true }, - * 'fred': { 'age': 40, 'active': false }, - * 'pebbles': { 'age': 1, 'active': true } - * }; - * - * _.findLastKey(users, function(o) { return o.age < 40; }); - * // => returns 'pebbles' assuming `_.findKey` returns 'barney' - * - * // The `_.matches` iteratee shorthand. - * _.findLastKey(users, { 'age': 36, 'active': true }); - * // => 'barney' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findLastKey(users, ['active', false]); - * // => 'fred' - * - * // The `_.property` iteratee shorthand. - * _.findLastKey(users, 'active'); - * // => 'pebbles' - */ function findLastKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); } - /** - * Iterates over own and inherited enumerable string keyed properties of an - * object and invokes `iteratee` for each property. The iteratee is invoked - * with three arguments: (value, key, object). Iteratee functions may exit - * iteration early by explicitly returning `false`. - * - * @static - * @memberOf _ - * @since 0.3.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forInRight - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forIn(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). - */ function forIn(object, iteratee) { return object == null ? object : baseFor(object, getIteratee(iteratee, 3), keysIn); } - /** - * This method is like `_.forIn` except that it iterates over properties of - * `object` in the opposite order. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forIn - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forInRight(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. - */ function forInRight(object, iteratee) { return object == null ? object : baseForRight(object, getIteratee(iteratee, 3), keysIn); } - /** - * Iterates over own enumerable string keyed properties of an object and - * invokes `iteratee` for each property. The iteratee is invoked with three - * arguments: (value, key, object). Iteratee functions may exit iteration - * early by explicitly returning `false`. - * - * @static - * @memberOf _ - * @since 0.3.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forOwnRight - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forOwn(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a' then 'b' (iteration order is not guaranteed). - */ function forOwn(object, iteratee) { return object && baseForOwn(object, getIteratee(iteratee, 3)); } - /** - * This method is like `_.forOwn` except that it iterates over properties of - * `object` in the opposite order. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forOwn - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forOwnRight(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. - */ function forOwnRight(object, iteratee) { return object && baseForOwnRight(object, getIteratee(iteratee, 3)); } - /** - * Creates an array of function property names from own enumerable properties - * of `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to inspect. - * @returns {Array} Returns the function names. - * @see _.functionsIn - * @example - * - * function Foo() { - * this.a = _.constant('a'); - * this.b = _.constant('b'); - * } - * - * Foo.prototype.c = _.constant('c'); - * - * _.functions(new Foo); - * // => ['a', 'b'] - */ function functions(object) { return object == null ? [] : baseFunctions(object, keys(object)); } - /** - * Creates an array of function property names from own and inherited - * enumerable properties of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to inspect. - * @returns {Array} Returns the function names. - * @see _.functions - * @example - * - * function Foo() { - * this.a = _.constant('a'); - * this.b = _.constant('b'); - * } - * - * Foo.prototype.c = _.constant('c'); - * - * _.functionsIn(new Foo); - * // => ['a', 'b', 'c'] - */ function functionsIn(object) { return object == null ? [] : baseFunctions(object, keysIn(object)); } - /** - * Gets the value at `path` of `object`. If the resolved value is - * `undefined`, the `defaultValue` is returned in its place. - * - * @static - * @memberOf _ - * @since 3.7.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @param {*} [defaultValue] The value returned for `undefined` resolved values. - * @returns {*} Returns the resolved value. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.get(object, 'a[0].b.c'); - * // => 3 - * - * _.get(object, ['a', '0', 'b', 'c']); - * // => 3 - * - * _.get(object, 'a.b.c', 'default'); - * // => 'default' - */ function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, path); return result === undefined ? defaultValue : result; } - /** - * Checks if `path` is a direct property of `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - * @example - * - * var object = { 'a': { 'b': 2 } }; - * var other = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.has(object, 'a'); - * // => true - * - * _.has(object, 'a.b'); - * // => true - * - * _.has(object, ['a', 'b']); - * // => true - * - * _.has(other, 'a'); - * // => false - */ function has(object, path) { return object != null && hasPath(object, path, baseHas); } - /** - * Checks if `path` is a direct or inherited property of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - * @example - * - * var object = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.hasIn(object, 'a'); - * // => true - * - * _.hasIn(object, 'a.b'); - * // => true - * - * _.hasIn(object, ['a', 'b']); - * // => true - * - * _.hasIn(object, 'b'); - * // => false - */ function hasIn(object, path) { return object != null && hasPath(object, path, baseHasIn); } - /** - * Creates an object composed of the inverted keys and values of `object`. - * If `object` contains duplicate values, subsequent values overwrite - * property assignments of previous values. - * - * @static - * @memberOf _ - * @since 0.7.0 - * @category Object - * @param {Object} object The object to invert. - * @returns {Object} Returns the new inverted object. - * @example - * - * var object = { 'a': 1, 'b': 2, 'c': 1 }; - * - * _.invert(object); - * // => { '1': 'c', '2': 'b' } - */ var invert = createInverter(function(result, value, key) { result[value] = key; }, constant(identity)); - /** - * This method is like `_.invert` except that the inverted object is generated - * from the results of running each element of `object` thru `iteratee`. The - * corresponding inverted value of each inverted key is an array of keys - * responsible for generating the inverted value. The iteratee is invoked - * with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.1.0 - * @category Object - * @param {Object} object The object to invert. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Object} Returns the new inverted object. - * @example - * - * var object = { 'a': 1, 'b': 2, 'c': 1 }; - * - * _.invertBy(object); - * // => { '1': ['a', 'c'], '2': ['b'] } - * - * _.invertBy(object, function(value) { - * return 'group' + value; - * }); - * // => { 'group1': ['a', 'c'], 'group2': ['b'] } - */ var invertBy = createInverter(function(result, value, key) { if (hasOwnProperty.call(result, value)) { result[value].push(key); @@ -11991,103 +4177,13 @@ UsergridEventable.mixin = function(destObject) { result[value] = [ key ]; } }, getIteratee); - /** - * Invokes the method at `path` of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the method to invoke. - * @param {...*} [args] The arguments to invoke the method with. - * @returns {*} Returns the result of the invoked method. - * @example - * - * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; - * - * _.invoke(object, 'a[0].b.c.slice', 1, 3); - * // => [2, 3] - */ var invoke = baseRest(baseInvoke); - /** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } - /** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) - */ function keysIn(object) { return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); } - /** - * The opposite of `_.mapValues`; this method creates an object with the - * same values as `object` and keys generated by running each own enumerable - * string keyed property of `object` thru `iteratee`. The iteratee is invoked - * with three arguments: (value, key, object). - * - * @static - * @memberOf _ - * @since 3.8.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapValues - * @example - * - * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { - * return key + value; - * }); - * // => { 'a1': 1, 'b2': 2 } - */ function mapKeys(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); @@ -12096,34 +4192,6 @@ UsergridEventable.mixin = function(destObject) { }); return result; } - /** - * Creates an object with the same keys as `object` and values generated - * by running each own enumerable string keyed property of `object` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, key, object). - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapKeys - * @example - * - * var users = { - * 'fred': { 'user': 'fred', 'age': 40 }, - * 'pebbles': { 'user': 'pebbles', 'age': 1 } - * }; - * - * _.mapValues(users, function(o) { return o.age; }); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - * - * // The `_.property` iteratee shorthand. - * _.mapValues(users, 'age'); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - */ function mapValues(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); @@ -12132,93 +4200,12 @@ UsergridEventable.mixin = function(destObject) { }); return result; } - /** - * This method is like `_.assign` except that it recursively merges own and - * inherited enumerable string keyed properties of source objects into the - * destination object. Source properties that resolve to `undefined` are - * skipped if a destination value exists. Array and plain object properties - * are merged recursively. Other objects and value types are overridden by - * assignment. Source objects are applied from left to right. Subsequent - * sources overwrite property assignments of previous sources. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @example - * - * var object = { - * 'a': [{ 'b': 2 }, { 'd': 4 }] - * }; - * - * var other = { - * 'a': [{ 'c': 3 }, { 'e': 5 }] - * }; - * - * _.merge(object, other); - * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } - */ var merge = createAssigner(function(object, source, srcIndex) { baseMerge(object, source, srcIndex); }); - /** - * This method is like `_.merge` except that it accepts `customizer` which - * is invoked to produce the merged values of the destination and source - * properties. If `customizer` returns `undefined`, merging is handled by the - * method instead. The `customizer` is invoked with six arguments: - * (objValue, srcValue, key, object, source, stack). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} customizer The function to customize assigned values. - * @returns {Object} Returns `object`. - * @example - * - * function customizer(objValue, srcValue) { - * if (_.isArray(objValue)) { - * return objValue.concat(srcValue); - * } - * } - * - * var object = { 'a': [1], 'b': [2] }; - * var other = { 'a': [3], 'b': [4] }; - * - * _.mergeWith(object, other, customizer); - * // => { 'a': [1, 3], 'b': [2, 4] } - */ var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { baseMerge(object, source, srcIndex, customizer); }); - /** - * The opposite of `_.pick`; this method creates an object composed of the - * own and inherited enumerable string keyed properties of `object` that are - * not omitted. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The source object. - * @param {...(string|string[])} [props] The property identifiers to omit. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.omit(object, ['a', 'c']); - * // => { 'b': '2' } - */ var omit = flatRest(function(object, props) { if (object == null) { return {}; @@ -12226,99 +4213,15 @@ UsergridEventable.mixin = function(destObject) { props = arrayMap(props, toKey); return basePick(object, baseDifference(getAllKeysIn(object), props)); }); - /** - * The opposite of `_.pickBy`; this method creates an object composed of - * the own and inherited enumerable string keyed properties of `object` that - * `predicate` doesn't return truthy for. The predicate is invoked with two - * arguments: (value, key). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.omitBy(object, _.isNumber); - * // => { 'b': '2' } - */ function omitBy(object, predicate) { return pickBy(object, negate(getIteratee(predicate))); } - /** - * Creates an object composed of the picked `object` properties. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The source object. - * @param {...(string|string[])} [props] The property identifiers to pick. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.pick(object, ['a', 'c']); - * // => { 'a': 1, 'c': 3 } - */ var pick = flatRest(function(object, props) { return object == null ? {} : basePick(object, arrayMap(props, toKey)); }); - /** - * Creates an object composed of the `object` properties `predicate` returns - * truthy for. The predicate is invoked with two arguments: (value, key). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.pickBy(object, _.isNumber); - * // => { 'a': 1, 'c': 3 } - */ function pickBy(object, predicate) { return object == null ? {} : basePickBy(object, getAllKeysIn(object), getIteratee(predicate)); } - /** - * This method is like `_.get` except that if the resolved value is a - * function it's invoked with the `this` binding of its parent object and - * its result is returned. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to resolve. - * @param {*} [defaultValue] The value returned for `undefined` resolved values. - * @returns {*} Returns the resolved value. - * @example - * - * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; - * - * _.result(object, 'a[0].b.c1'); - * // => 3 - * - * _.result(object, 'a[0].b.c2'); - * // => 4 - * - * _.result(object, 'a[0].b.c3', 'default'); - * // => 'default' - * - * _.result(object, 'a[0].b.c3', _.constant('default')); - * // => 'default' - */ function result(object, path, defaultValue) { path = isKey(path, object) ? [ path ] : castPath(path); var index = -1, length = path.length; @@ -12336,145 +4239,15 @@ UsergridEventable.mixin = function(destObject) { } return object; } - /** - * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, - * it's created. Arrays are created for missing index properties while objects - * are created for all other missing properties. Use `_.setWith` to customize - * `path` creation. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 3.7.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @returns {Object} Returns `object`. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.set(object, 'a[0].b.c', 4); - * console.log(object.a[0].b.c); - * // => 4 - * - * _.set(object, ['x', '0', 'y', 'z'], 5); - * console.log(object.x[0].y.z); - * // => 5 - */ function set(object, path, value) { return object == null ? object : baseSet(object, path, value); } - /** - * This method is like `_.set` except that it accepts `customizer` which is - * invoked to produce the objects of `path`. If `customizer` returns `undefined` - * path creation is handled by the method instead. The `customizer` is invoked - * with three arguments: (nsValue, key, nsObject). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @example - * - * var object = {}; - * - * _.setWith(object, '[0][1]', 'a', Object); - * // => { '0': { '1': 'a' } } - */ function setWith(object, path, value, customizer) { customizer = typeof customizer == "function" ? customizer : undefined; return object == null ? object : baseSet(object, path, value, customizer); } - /** - * Creates an array of own enumerable string keyed-value pairs for `object` - * which can be consumed by `_.fromPairs`. If `object` is a map or set, its - * entries are returned. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias entries - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the key-value pairs. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.toPairs(new Foo); - * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) - */ var toPairs = createToPairs(keys); - /** - * Creates an array of own and inherited enumerable string keyed-value pairs - * for `object` which can be consumed by `_.fromPairs`. If `object` is a map - * or set, its entries are returned. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias entriesIn - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the key-value pairs. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.toPairsIn(new Foo); - * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) - */ var toPairsIn = createToPairs(keysIn); - /** - * An alternative to `_.reduce`; this method transforms `object` to a new - * `accumulator` object which is the result of running each of its own - * enumerable string keyed properties thru `iteratee`, with each invocation - * potentially mutating the `accumulator` object. If `accumulator` is not - * provided, a new object with the same `[[Prototype]]` will be used. The - * iteratee is invoked with four arguments: (accumulator, value, key, object). - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @static - * @memberOf _ - * @since 1.3.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The custom accumulator value. - * @returns {*} Returns the accumulated value. - * @example - * - * _.transform([2, 3, 4], function(result, n) { - * result.push(n *= n); - * return n % 2 == 0; - * }, []); - * // => [4, 9] - * - * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { - * (result[value] || (result[value] = [])).push(key); - * }, {}); - * // => { '1': ['a', 'c'], '2': ['b'] } - */ function transform(object, iteratee, accumulator) { var isArr = isArray(object) || isTypedArray(object); iteratee = getIteratee(iteratee, 4); @@ -12495,170 +4268,22 @@ UsergridEventable.mixin = function(destObject) { }); return accumulator; } - /** - * Removes the property at `path` of `object`. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to unset. - * @returns {boolean} Returns `true` if the property is deleted, else `false`. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 7 } }] }; - * _.unset(object, 'a[0].b.c'); - * // => true - * - * console.log(object); - * // => { 'a': [{ 'b': {} }] }; - * - * _.unset(object, ['a', '0', 'b', 'c']); - * // => true - * - * console.log(object); - * // => { 'a': [{ 'b': {} }] }; - */ function unset(object, path) { return object == null ? true : baseUnset(object, path); } - /** - * This method is like `_.set` except that accepts `updater` to produce the - * value to set. Use `_.updateWith` to customize `path` creation. The `updater` - * is invoked with one argument: (value). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.6.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {Function} updater The function to produce the updated value. - * @returns {Object} Returns `object`. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.update(object, 'a[0].b.c', function(n) { return n * n; }); - * console.log(object.a[0].b.c); - * // => 9 - * - * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); - * console.log(object.x[0].y.z); - * // => 0 - */ function update(object, path, updater) { return object == null ? object : baseUpdate(object, path, castFunction(updater)); } - /** - * This method is like `_.update` except that it accepts `customizer` which is - * invoked to produce the objects of `path`. If `customizer` returns `undefined` - * path creation is handled by the method instead. The `customizer` is invoked - * with three arguments: (nsValue, key, nsObject). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.6.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {Function} updater The function to produce the updated value. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @example - * - * var object = {}; - * - * _.updateWith(object, '[0][1]', _.constant('a'), Object); - * // => { '0': { '1': 'a' } } - */ function updateWith(object, path, updater, customizer) { customizer = typeof customizer == "function" ? customizer : undefined; return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); } - /** - * Creates an array of the own enumerable string keyed property values of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property values. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.values(new Foo); - * // => [1, 2] (iteration order is not guaranteed) - * - * _.values('hi'); - * // => ['h', 'i'] - */ function values(object) { return object ? baseValues(object, keys(object)) : []; } - /** - * Creates an array of the own and inherited enumerable string keyed property - * values of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property values. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.valuesIn(new Foo); - * // => [1, 2, 3] (iteration order is not guaranteed) - */ function valuesIn(object) { return object == null ? [] : baseValues(object, keysIn(object)); } - /*------------------------------------------------------------------------*/ - /** - * Clamps `number` within the inclusive `lower` and `upper` bounds. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Number - * @param {number} number The number to clamp. - * @param {number} [lower] The lower bound. - * @param {number} upper The upper bound. - * @returns {number} Returns the clamped number. - * @example - * - * _.clamp(-10, -5, 5); - * // => -5 - * - * _.clamp(10, -5, 5); - * // => 5 - */ function clamp(number, lower, upper) { if (upper === undefined) { upper = lower; @@ -12674,44 +4299,6 @@ UsergridEventable.mixin = function(destObject) { } return baseClamp(toNumber(number), lower, upper); } - /** - * Checks if `n` is between `start` and up to, but not including, `end`. If - * `end` is not specified, it's set to `start` with `start` then set to `0`. - * If `start` is greater than `end` the params are swapped to support - * negative ranges. - * - * @static - * @memberOf _ - * @since 3.3.0 - * @category Number - * @param {number} number The number to check. - * @param {number} [start=0] The start of the range. - * @param {number} end The end of the range. - * @returns {boolean} Returns `true` if `number` is in the range, else `false`. - * @see _.range, _.rangeRight - * @example - * - * _.inRange(3, 2, 4); - * // => true - * - * _.inRange(4, 8); - * // => true - * - * _.inRange(4, 2); - * // => false - * - * _.inRange(2, 2); - * // => false - * - * _.inRange(1.2, 2); - * // => true - * - * _.inRange(5.2, 4); - * // => false - * - * _.inRange(-3, -2, -6); - * // => true - */ function inRange(number, start, end) { start = toFinite(start); if (end === undefined) { @@ -12723,37 +4310,6 @@ UsergridEventable.mixin = function(destObject) { number = toNumber(number); return baseInRange(number, start, end); } - /** - * Produces a random number between the inclusive `lower` and `upper` bounds. - * If only one argument is provided a number between `0` and the given number - * is returned. If `floating` is `true`, or either `lower` or `upper` are - * floats, a floating-point number is returned instead of an integer. - * - * **Note:** JavaScript follows the IEEE-754 standard for resolving - * floating-point values which can produce unexpected results. - * - * @static - * @memberOf _ - * @since 0.7.0 - * @category Number - * @param {number} [lower=0] The lower bound. - * @param {number} [upper=1] The upper bound. - * @param {boolean} [floating] Specify returning a floating-point number. - * @returns {number} Returns the random number. - * @example - * - * _.random(0, 5); - * // => an integer between 0 and 5 - * - * _.random(5); - * // => also an integer between 0 and 5 - * - * _.random(5, true); - * // => a floating-point number between 0 and 5 - * - * _.random(1.2, 5.2); - * // => a floating-point number between 1.2 and 5.2 - */ function random(lower, upper, floating) { if (floating && typeof floating != "boolean" && isIterateeCall(lower, upper, floating)) { upper = floating = undefined; @@ -12790,94 +4346,17 @@ UsergridEventable.mixin = function(destObject) { } return baseRandom(lower, upper); } - /*------------------------------------------------------------------------*/ - /** - * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the camel cased string. - * @example - * - * _.camelCase('Foo Bar'); - * // => 'fooBar' - * - * _.camelCase('--foo-bar--'); - * // => 'fooBar' - * - * _.camelCase('__FOO_BAR__'); - * // => 'fooBar' - */ var camelCase = createCompounder(function(result, word, index) { word = word.toLowerCase(); return result + (index ? capitalize(word) : word); }); - /** - * Converts the first character of `string` to upper case and the remaining - * to lower case. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to capitalize. - * @returns {string} Returns the capitalized string. - * @example - * - * _.capitalize('FRED'); - * // => 'Fred' - */ function capitalize(string) { return upperFirst(toString(string).toLowerCase()); } - /** - * Deburrs `string` by converting - * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) - * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) - * letters to basic Latin letters and removing - * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to deburr. - * @returns {string} Returns the deburred string. - * @example - * - * _.deburr('déjà vu'); - * // => 'deja vu' - */ function deburr(string) { string = toString(string); return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ""); } - /** - * Checks if `string` ends with the given target string. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to inspect. - * @param {string} [target] The string to search for. - * @param {number} [position=string.length] The position to search up to. - * @returns {boolean} Returns `true` if `string` ends with `target`, - * else `false`. - * @example - * - * _.endsWith('abc', 'c'); - * // => true - * - * _.endsWith('abc', 'b'); - * // => false - * - * _.endsWith('abc', 'b', 2); - * // => true - */ function endsWith(string, target, position) { string = toString(string); target = baseToString(target); @@ -12887,145 +4366,21 @@ UsergridEventable.mixin = function(destObject) { position -= target.length; return position >= 0 && string.slice(position, end) == target; } - /** - * Converts the characters "&", "<", ">", '"', and "'" in `string` to their - * corresponding HTML entities. - * - * **Note:** No other characters are escaped. To escape additional - * characters use a third-party library like [_he_](https://mths.be/he). - * - * Though the ">" character is escaped for symmetry, characters like - * ">" and "/" don't need escaping in HTML and have no special meaning - * unless they're part of a tag or unquoted attribute value. See - * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) - * (under "semi-related fun fact") for more details. - * - * When working with HTML you should always - * [quote attribute values](http://wonko.com/post/html-escaping) to reduce - * XSS vectors. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category String - * @param {string} [string=''] The string to escape. - * @returns {string} Returns the escaped string. - * @example - * - * _.escape('fred, barney, & pebbles'); - * // => 'fred, barney, & pebbles' - */ function escape(string) { string = toString(string); return string && reHasUnescapedHtml.test(string) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string; } - /** - * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", - * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to escape. - * @returns {string} Returns the escaped string. - * @example - * - * _.escapeRegExp('[lodash](https://lodash.com/)'); - * // => '\[lodash\]\(https://lodash\.com/\)' - */ function escapeRegExp(string) { string = toString(string); return string && reHasRegExpChar.test(string) ? string.replace(reRegExpChar, "\\$&") : string; } - /** - * Converts `string` to - * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the kebab cased string. - * @example - * - * _.kebabCase('Foo Bar'); - * // => 'foo-bar' - * - * _.kebabCase('fooBar'); - * // => 'foo-bar' - * - * _.kebabCase('__FOO_BAR__'); - * // => 'foo-bar' - */ var kebabCase = createCompounder(function(result, word, index) { return result + (index ? "-" : "") + word.toLowerCase(); }); - /** - * Converts `string`, as space separated words, to lower case. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the lower cased string. - * @example - * - * _.lowerCase('--Foo-Bar--'); - * // => 'foo bar' - * - * _.lowerCase('fooBar'); - * // => 'foo bar' - * - * _.lowerCase('__FOO_BAR__'); - * // => 'foo bar' - */ var lowerCase = createCompounder(function(result, word, index) { return result + (index ? " " : "") + word.toLowerCase(); }); - /** - * Converts the first character of `string` to lower case. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.lowerFirst('Fred'); - * // => 'fred' - * - * _.lowerFirst('FRED'); - * // => 'fRED' - */ var lowerFirst = createCaseFirst("toLowerCase"); - /** - * Pads `string` on the left and right sides if it's shorter than `length`. - * Padding characters are truncated if they can't be evenly divided by `length`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to pad. - * @param {number} [length=0] The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padded string. - * @example - * - * _.pad('abc', 8); - * // => ' abc ' - * - * _.pad('abc', 8, '_-'); - * // => '_-abc_-_' - * - * _.pad('abc', 3); - * // => 'abc' - */ function pad(string, length, chars) { string = toString(string); length = toInteger(length); @@ -13036,88 +4391,18 @@ UsergridEventable.mixin = function(destObject) { var mid = (length - strLength) / 2; return createPadding(nativeFloor(mid), chars) + string + createPadding(nativeCeil(mid), chars); } - /** - * Pads `string` on the right side if it's shorter than `length`. Padding - * characters are truncated if they exceed `length`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to pad. - * @param {number} [length=0] The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padded string. - * @example - * - * _.padEnd('abc', 6); - * // => 'abc ' - * - * _.padEnd('abc', 6, '_-'); - * // => 'abc_-_' - * - * _.padEnd('abc', 3); - * // => 'abc' - */ function padEnd(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return length && strLength < length ? string + createPadding(length - strLength, chars) : string; } - /** - * Pads `string` on the left side if it's shorter than `length`. Padding - * characters are truncated if they exceed `length`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to pad. - * @param {number} [length=0] The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padded string. - * @example - * - * _.padStart('abc', 6); - * // => ' abc' - * - * _.padStart('abc', 6, '_-'); - * // => '_-_abc' - * - * _.padStart('abc', 3); - * // => 'abc' - */ function padStart(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return length && strLength < length ? createPadding(length - strLength, chars) + string : string; } - /** - * Converts `string` to an integer of the specified radix. If `radix` is - * `undefined` or `0`, a `radix` of `10` is used unless `value` is a - * hexadecimal, in which case a `radix` of `16` is used. - * - * **Note:** This method aligns with the - * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category String - * @param {string} string The string to convert. - * @param {number} [radix=10] The radix to interpret `value` by. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {number} Returns the converted integer. - * @example - * - * _.parseInt('08'); - * // => 8 - * - * _.map(['6', '08', '10'], _.parseInt); - * // => [6, 8, 10] - */ function parseInt(string, radix, guard) { if (guard || radix == null) { radix = 0; @@ -13126,28 +4411,6 @@ UsergridEventable.mixin = function(destObject) { } return nativeParseInt(toString(string), radix || 0); } - /** - * Repeats the given string `n` times. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to repeat. - * @param {number} [n=1] The number of times to repeat the string. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {string} Returns the repeated string. - * @example - * - * _.repeat('*', 3); - * // => '***' - * - * _.repeat('abc', 2); - * // => 'abcabc' - * - * _.repeat('abc', 0); - * // => '' - */ function repeat(string, n, guard) { if (guard ? isIterateeCall(string, n, guard) : n === undefined) { n = 1; @@ -13156,72 +4419,13 @@ UsergridEventable.mixin = function(destObject) { } return baseRepeat(toString(string), n); } - /** - * Replaces matches for `pattern` in `string` with `replacement`. - * - * **Note:** This method is based on - * [`String#replace`](https://mdn.io/String/replace). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to modify. - * @param {RegExp|string} pattern The pattern to replace. - * @param {Function|string} replacement The match replacement. - * @returns {string} Returns the modified string. - * @example - * - * _.replace('Hi Fred', 'Fred', 'Barney'); - * // => 'Hi Barney' - */ function replace() { var args = arguments, string = toString(args[0]); return args.length < 3 ? string : string.replace(args[1], args[2]); } - /** - * Converts `string` to - * [snake case](https://en.wikipedia.org/wiki/Snake_case). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the snake cased string. - * @example - * - * _.snakeCase('Foo Bar'); - * // => 'foo_bar' - * - * _.snakeCase('fooBar'); - * // => 'foo_bar' - * - * _.snakeCase('--FOO-BAR--'); - * // => 'foo_bar' - */ var snakeCase = createCompounder(function(result, word, index) { return result + (index ? "_" : "") + word.toLowerCase(); }); - /** - * Splits `string` by `separator`. - * - * **Note:** This method is based on - * [`String#split`](https://mdn.io/String/split). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to split. - * @param {RegExp|string} separator The separator pattern to split by. - * @param {number} [limit] The length to truncate results to. - * @returns {Array} Returns the string segments. - * @example - * - * _.split('a-b-c', '-', 2); - * // => ['a', 'b'] - */ function split(string, separator, limit) { if (limit && typeof limit != "number" && isIterateeCall(string, separator, limit)) { separator = limit = undefined; @@ -13239,163 +4443,15 @@ UsergridEventable.mixin = function(destObject) { } return string.split(separator, limit); } - /** - * Converts `string` to - * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). - * - * @static - * @memberOf _ - * @since 3.1.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the start cased string. - * @example - * - * _.startCase('--foo-bar--'); - * // => 'Foo Bar' - * - * _.startCase('fooBar'); - * // => 'Foo Bar' - * - * _.startCase('__FOO_BAR__'); - * // => 'FOO BAR' - */ var startCase = createCompounder(function(result, word, index) { return result + (index ? " " : "") + upperFirst(word); }); - /** - * Checks if `string` starts with the given target string. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to inspect. - * @param {string} [target] The string to search for. - * @param {number} [position=0] The position to search from. - * @returns {boolean} Returns `true` if `string` starts with `target`, - * else `false`. - * @example - * - * _.startsWith('abc', 'a'); - * // => true - * - * _.startsWith('abc', 'b'); - * // => false - * - * _.startsWith('abc', 'b', 1); - * // => true - */ function startsWith(string, target, position) { string = toString(string); position = baseClamp(toInteger(position), 0, string.length); target = baseToString(target); return string.slice(position, position + target.length) == target; } - /** - * Creates a compiled template function that can interpolate data properties - * in "interpolate" delimiters, HTML-escape interpolated data properties in - * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data - * properties may be accessed as free variables in the template. If a setting - * object is given, it takes precedence over `_.templateSettings` values. - * - * **Note:** In the development build `_.template` utilizes - * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) - * for easier debugging. - * - * For more information on precompiling templates see - * [lodash's custom builds documentation](https://lodash.com/custom-builds). - * - * For more information on Chrome extension sandboxes see - * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category String - * @param {string} [string=''] The template string. - * @param {Object} [options={}] The options object. - * @param {RegExp} [options.escape=_.templateSettings.escape] - * The HTML "escape" delimiter. - * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] - * The "evaluate" delimiter. - * @param {Object} [options.imports=_.templateSettings.imports] - * An object to import into the template as free variables. - * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] - * The "interpolate" delimiter. - * @param {string} [options.sourceURL='lodash.templateSources[n]'] - * The sourceURL of the compiled template. - * @param {string} [options.variable='obj'] - * The data object variable name. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the compiled template function. - * @example - * - * // Use the "interpolate" delimiter to create a compiled template. - * var compiled = _.template('hello <%= user %>!'); - * compiled({ 'user': 'fred' }); - * // => 'hello fred!' - * - * // Use the HTML "escape" delimiter to escape data property values. - * var compiled = _.template('<%- value %>'); - * compiled({ 'value': ' - - - diff --git a/tests/qunit/tests.js b/tests/qunit/tests.js deleted file mode 100644 index 1d58b00..0000000 --- a/tests/qunit/tests.js +++ /dev/null @@ -1,20 +0,0 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to You under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -test( "hello test", function() { - ok( 1 == "1", "Passed!" ); -}); From 16ca8e9f215ed342c76f1148979129edb44ca2a6 Mon Sep 17 00:00:00 2001 From: Robert Walsh Date: Sun, 9 Oct 2016 22:26:20 -0500 Subject: [PATCH 25/36] Updates. See commit details. Valid examples are all working now. Legacy examples removed. Removed unused files. Moved test random files to correct locations. Base Index.hmtl updated. Bug fix in UsergridQuery when no query is specified but sort is. --- examples/all-calls/app.js | 88 +- examples/dogs/app.js | 321 +++--- examples/dogs/dogs.html | 8 +- examples/facebook/app.js | 129 --- examples/facebook/facebook.html | 73 -- examples/facebook/guide.html | 63 -- examples/persistence/test.html | 54 - examples/persistence/test.js | 130 --- examples/resources/js/json2.js | 486 --------- .../resources/js}/usergrid.validation.js | 0 examples/test/test.html | 54 - examples/test/test.js | 978 ------------------ index.html | 21 +- lib/modules/UsergridQuery.js | 4 +- tests/mocha/test_query.js | 2 +- tests/resources/css/mocha.css | 1 + tests/resources/images/apigee.png | Bin 6010 -> 0 bytes tests/test.html | 54 - tests/test.js | 871 ---------------- usergrid.js | 8 +- usergrid.min.js | 4 +- 21 files changed, 178 insertions(+), 3171 deletions(-) delete mode 100755 examples/facebook/app.js delete mode 100755 examples/facebook/facebook.html delete mode 100755 examples/facebook/guide.html delete mode 100644 examples/persistence/test.html delete mode 100644 examples/persistence/test.js delete mode 100755 examples/resources/js/json2.js rename {extensions => examples/resources/js}/usergrid.validation.js (100%) delete mode 100755 examples/test/test.html delete mode 100755 examples/test/test.js delete mode 100755 tests/resources/images/apigee.png delete mode 100755 tests/test.html delete mode 100755 tests/test.js diff --git a/examples/all-calls/app.js b/examples/all-calls/app.js index 6bf804e..4457691 100755 --- a/examples/all-calls/app.js +++ b/examples/all-calls/app.js @@ -44,14 +44,8 @@ * This file contains the main program logic for All Calls App. */ $(document).ready(function () { - //first set the org / app path (must be orgname / appname or org id / app id - can't mix names and uuids!!) - var client = new Usergrid.Client({ - orgName:'yourorgname', - appName:'yourappname', - logging: true, //optional - turn on logging, off by default - buildCurl: true //optional - turn on curl commands, off by default - }); + var client = new UsergridClient({orgId: "rwalsh", appId: "jssdktestapp", authMode: UsergridAuthMode.NONE}); function hideAllSections(){ $('#get-page').hide(); @@ -133,41 +127,26 @@ $(document).ready(function () { function _get() { var endpoint = $("#get-path").val(); - - var options = { - method:'GET', - endpoint:endpoint - }; - client.request(options, function (err, data) { - //data will contain raw results from API call + client.GET({path:endpoint},function(usergridResponse) { + var err = usergridResponse.error if (err) { - var output = JSON.stringify(data, null, 2); - $("#response").html('
    ERROR: '+output+'
    '); + $("#response").html('
    ERROR: '+JSON.stringify(err,null,2)+'
    '); } else { - var output = JSON.stringify(data, null, 2); - $("#response").html('
    '+output+'
    '); + $("#response").html('
    '+JSON.stringify(usergridResponse.entities,null,2)+'
    '); } - }); + }) } function _post() { var endpoint = $("#post-path").val(); var data = $("#post-data").val(); data = JSON.parse(data); - - var options = { - method:'POST', - endpoint:endpoint, - body:data - }; - client.request(options, function (err, data) { - //data will contain raw results from API call + client.POST({path:endpoint,body:data}, function (usergridResponse) { + var err = usergridResponse.error if (err) { - var output = JSON.stringify(data, null, 2); - $("#response").html('
    ERROR: '+output+'
    '); + $("#response").html('
    ERROR: '+JSON.stringify(err,null,2)+'
    '); } else { - var output = JSON.stringify(data, null, 2); - $("#response").html('
    '+output+'
    '); + $("#response").html('
    '+JSON.stringify(usergridResponse.entities,null,2)+'
    '); } }); } @@ -176,39 +155,24 @@ $(document).ready(function () { var endpoint = $("#put-path").val(); var data = $("#put-data").val(); data = JSON.parse(data); - - var options = { - method:'PUT', - endpoint:endpoint, - body:data - }; - client.request(options, function (err, data) { - //data will contain raw results from API call + client.PUT({path:endpoint,body:data}, function (usergridResponse) { + var err = usergridResponse.error if (err) { - var output = JSON.stringify(data, null, 2); - $("#response").html('
    ERROR: '+output+'
    '); + $("#response").html('
    ERROR: '+JSON.stringify(err,null,2)+'
    '); } else { - var output = JSON.stringify(data, null, 2); - $("#response").html('
    '+output+'
    '); + $("#response").html('
    '+JSON.stringify(usergridResponse.entities,null,2)+'
    '); } }); } function _delete() { var endpoint = $("#delete-path").val(); - - var options = { - method:'DELETE', - endpoint:endpoint - }; - client.request(options, function (err, data) { - //data will contain raw results from API call + client.DELETE({path:endpoint}, function (usergridResponse) { + var err = usergridResponse.error if (err) { - var output = JSON.stringify(data, null, 2); - $("#response").html('
    ERROR: '+output+'
    '); + $("#response").html('
    ERROR: '+JSON.stringify(err,null,2)+'
    '); } else { - var output = JSON.stringify(data, null, 2); - $("#response").html('
    '+output+'
    '); + $("#response").html('
    '+JSON.stringify(usergridResponse.entities,null,2)+'
    '); } }); } @@ -216,21 +180,13 @@ $(document).ready(function () { function _login() { var username = $("#username").val(); var password = $("#password").val(); - - client.login(username, password, function (err, data) { - //at this point, the user has been logged in succesfully and the OAuth token for the user has been stored - //however, in this example, we don't want to use that token for the rest of the API calls, so we will now - //reset it. In your app, you will most likely not want to do this, as you are effectively logging the user - //out. Our calls work because we are going against the Sandbox app, which has no restrictions on permissions. - client.token = null; //delete the user's token by setting it to null + client.authenticateUser({username:username, password:password}, function (auth,user,usergridResponse) { + var err = usergridResponse.error if (err) { - var output = JSON.stringify(data, null, 2); - $("#response").html('
    ERROR: '+output+'
    '); + $("#response").html('
    ERROR: '+JSON.stringify(err,null,2)+'
    '); } else { - var output = JSON.stringify(data, null, 2); - $("#response").html('
    '+output+'
    '); + $("#response").html('
    '+JSON.stringify(usergridResponse.responseJSON,null,2)+'
    '); } }); } - }); \ No newline at end of file diff --git a/examples/dogs/app.js b/examples/dogs/app.js index 930c175..274eed1 100755 --- a/examples/dogs/app.js +++ b/examples/dogs/app.js @@ -1,194 +1,135 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to You under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -/** -* dogs is a sample app that is powered by Usergrid -* This app shows how to use the Usergrid SDK to connect -* to Usergrid, how to add entities, and how to page through -* a result set of entities -* -* Learn more at http://Usergrid.com/docs -* -* Copyright 2012 Apigee Corporation -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -/** -* @file app.js -* @author Rod Simpson (rod@apigee.com) -* -* This file contains the main program logic for Dogs. -*/ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + $(document).ready(function () { - //first set the org / app path (must be orgname / appname or org id / app id - can't mix names and uuids!!) - var client = new Usergrid.Client({ - orgName:'yourorgname', - appName:'dogs', - logging: true, //optional - turn on logging, off by default - buildCurl: true //optional - turn on curl commands, off by default - }); - - //make a new "dogs" Collection - var options = { - type:'dogs', - qs:{ql:'order by created DESC'} - } - - var dogs; - - client.createCollection(options, function (err, response, collection) { - if (err) { - $('#mydoglist').html('could not load dogs'); - } else { - dogs=collection; - //bind the next button to the proper method in the collection object - $('#next-button').bind('click', function() { - $('#message').html(''); - dogs.getNextPage(function(err, data){ - if (err) { - alert('could not get next page of dogs'); - } else { - drawDogs(); - } - }); - }); - - //bind the previous button to the proper method in the collection object - $('#previous-button').bind('click', function() { - $('#message').html(''); - dogs.getPreviousPage(function(err, data){ - if (err) { - alert('could not get previous page of dogs'); - } else { - drawDogs(); - } - }); - }); - - //bind the new button to show the "create new dog" form - $('#new-dog-button').bind('click', function() { - $('#dogs-list').hide(); - $('#new-dog').show(); - }); - - //bind the create new dog button - $('#create-dog').bind('click', function() { - newdog(); - }); - - //bind the create new dog button - $('#cancel-create-dog').bind('click', function() { - $('#new-dog').hide(); - $('#dogs-list').show(); - drawDogs(); - }); - - function drawDogs() { - dogs.fetch(function(err, data) { - if(err) { - alert('there was an error getting the dogs'); + + var client = new UsergridClient({orgId: "rwalsh", appId: "jssdktestapp", authMode: UsergridAuthMode.NONE}), + lastResponse, + lastQueryUsed, + previousCursors = [] + + var message = $('#message'), + nextButton = $('#next-button'), + previousButton = $('#previous-button'), + dogsList = $('#dogs-list'), + myDogList = $('#mydoglist'), + newDog = $('#new-dog'), + newDogButton = $('#new-dog-button'), + createDogButton = $('#create-dog'), + cancelCreateDogButton = $('#cancel-create-dog') + + nextButton.bind('click', function() { + message.html(''); + previousCursors.push(lastQueryUsed._cursor) + lastQueryUsed = new UsergridQuery('dogs').desc('created').cursor(_.get(lastResponse,'responseJSON.cursor')) + lastResponse.loadNextPage(client,function(usergridResponse) { + handleGETDogResponse(usergridResponse) + }) + }); + + previousButton.bind('click', function() { + message.html(''); + var cursor = previousCursors.pop() + if( cursor === '' ) { + previousCursors = '' + cursor = undefined + } + drawDogs(cursor) + }); + + //bind the new button to show the "create new dog" form + newDogButton.bind('click', function() { + dogsList.hide(); + newDog.show(); + }); + + //bind the create new dog button + createDogButton.bind('click', function() { + newdog(); + }); + + //bind the create new dog button + cancelCreateDogButton.bind('click', function() { + newDog.hide(); + dogsList.show(); + drawDogs(); + }); + + function drawDogs(cursor) { + lastQueryUsed = new UsergridQuery('dogs').desc('created') + if( cursor !== undefined && !_.isEmpty(cursor) ) { + lastQueryUsed.cursor(cursor) + } + client.GET(lastQueryUsed,function(usergridResponse) { + handleGETDogResponse(usergridResponse) + }); + } + + function handleGETDogResponse(usergridResponse) { + lastResponse = usergridResponse + if(lastResponse.error) { + alert('there was an error getting the dogs'); } else { - //first empty out all the current dogs in the list - $('#mydoglist').empty(); - //then hide the next / previous buttons - $('#next-button').hide(); - $('#previous-button').hide(); - //iterate through all the items in this "page" of data - //make sure we reset the pointer so we start at the beginning - dogs.resetEntityPointer(); - while(dogs.hasNextEntity()) { - //get a reference to the dog - var dog = dogs.getNextEntity(); - //display the dog in the list - $('#mydoglist').append('
  • '+ dog.get('name') + '
  • '); - } - //if there is more data, display a "next" button - if (dogs.hasNextPage()) { - //show the button - $('#next-button').show(); - } - //if there are previous pages, show a "previous" button - if (dogs.hasPreviousPage()) { - //show the button - $('#previous-button').show(); - } + myDogList.empty(); + nextButton.hide(); + previousButton.hide(); + + _.forEach(lastResponse.entities,function(dog) { + myDogList.append('
  • '+ dog.name + '
  • '); + }) + + if (lastResponse.hasNextPage) { + nextButton.show(); + } + if (previousCursors.length > 0) { + previousButton.show(); + } } - }); - } - - function newdog() { - $('#create-dog').addClass("disabled"); - //get the values from the form - var name = $("#name").val(); - - //make turn off all hints and errors - $("#name-help").hide(); - $("#name-control").removeClass('error'); - - //make sure the input was valid - if (Usergrid.validation.validateName(name, function (){ - $("#name").focus(); - $("#name-help").show(); - $("#name-control").addClass('error'); - $("#name-help").html(Usergrid.validation.getNameAllowedChars()); - $('#create-dog').removeClass("disabled");}) - ) { - - //all is well, so make the new dog - //create a new dog and add it to the collection - var options = { - name:name - } - //just pass the options to the addEntity method - //to the collection and it is saved automatically - dogs.addEntity(options, function(err, dog, data) { - if (err) { - //let the user know there was a problem - alert('Oops! There was an error creating the dog.'); - //enable the button so the form will be ready for next time - $('#create-dog').removeClass("disabled"); - } else { - $('#message').html('New dog created!'); - //the save worked, so hide the new dog form - $('#new-dog').hide(); - //then show the dogs list - $('#dogs-list').show(); - //then call the function to get the list again - drawDogs(); - //finally enable the button so the form will be ready for next time - $('#create-dog').removeClass("disabled"); - } - }); - } - } - drawDogs(); - - } - }); - + } + + function newdog() { + createDogButton.addClass("disabled"); + + var name = $("#name").val(), + nameHelp = $("#name-help"), + nameControl = $("#name-control") + + nameHelp.hide(); + nameControl.removeClass('error'); + + if (Usergrid.validation.validateName(name, function (){ + name.focus(); + nameHelp.show(); + nameControl.addClass('error'); + nameHelp.html(Usergrid.validation.getNameAllowedChars()); + createDogButton.removeClass("disabled");}) + ) { + client.POST({type:'dogs',body:{ name:name }}, function(usergridResponse) { + if (usergridResponse.error) { + alert('Oops! There was an error creating the dog. \n' + JSON.stringify(usergridResponse.error,null,2)); + createDogButton.removeClass("disabled"); + } else { + message.html('New dog created!'); + newDog.hide(); + dogsList.show(); + createDogButton.removeClass("disabled"); + previousCursors = [] + drawDogs(); + } + }) + } + } + + drawDogs(); }); diff --git a/examples/dogs/dogs.html b/examples/dogs/dogs.html index 8f92830..4320012 100755 --- a/examples/dogs/dogs.html +++ b/examples/dogs/dogs.html @@ -5,9 +5,9 @@ The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,7 +24,7 @@ - + @@ -32,7 +32,7 @@ App Services (Usergrid) Javascript SDK

    Dogs

    diff --git a/examples/facebook/app.js b/examples/facebook/app.js deleted file mode 100755 index 35b646d..0000000 --- a/examples/facebook/app.js +++ /dev/null @@ -1,129 +0,0 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to You under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -/** -* dogs is a sample app that is powered by Usergrid -* This app shows how to use the Usergrid SDK to connect -* to Usergrid, how to add entities, and how to page through -* a result set of entities -* -* Learn more at http://Usergrid.com/docs -* -* Copyright 2012 Apigee Corporation -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -/** -* @file app.js -* @author Rod Simpson (rod@apigee.com) -* -* This file contains the main program logic for Facebook Login Example. -*/ -$(document).ready(function () { - //first set the org / app path (must be orgname / appname or org id / app id - can't mix names and uuids!!) - - var client = new Usergrid.Client({ - orgName:'yourorgname', - appName:'sandbox', - logging: true, //optional - turn on logging, off by default - buildCurl: true //optional - turn on curl commands, off by default - }); - - //bind the login button so we can send the user to facebook - $('#login-button').bind('click', function() { - //get the - var apiKey = $("#api-key").val(); - var location = window.location.protocol + '//' + window.location.host; - var path = window.location.pathname; - - var link = "https://www.facebook.com/dialog/oauth?client_id="; - link += apiKey; - link += "&redirect_uri="; - link += location+path - link += "&scope&COMMA_SEPARATED_LIST_OF_PERMISSION_NAMES&response_type=token"; - - //now forward the user to facebook - window.location = link; - }); - //bind the previous button to the proper method in the collection object - $('#logout-button').bind('click', function() { - logout(); - }); - - //load up the facebook api sdk - window.fbAsyncInit = function() { - FB.init({ - appId : '308790195893570', // App ID - channelUrl : '//usergridsdk.dev//examples/channel.html', // Channel File - status : true, // check login status - cookie : true, // enable cookies to allow the server to access the session - xfbml : true // parse XFBML - }); - }; - - function logout() { - FB.logout(function(response) { - client.logoutAppUser(); - var html = "User logged out. \r\n\r\n // Press 'Log in' to log in with Facebook."; - $('#facebook-status').html(html); - }); - } - - function login(facebookAccessToken) { - client.loginFacebook(facebookAccessToken, function(err, response){ - var output = JSON.stringify(response, null, 2); - if (err) { - var html = '
    Oops!  There was an error logging you in. \r\n\r\n';
    -        html += 'Error: \r\n' + output+'
    '; - } else { - var html = '
    Hurray!  You have been logged in. \r\n\r\n';
    -        html += 'Facebook Token: ' + '\r\n' + facebookAccessToken + '\r\n\r\n';
    -        html += 'Facebook Profile data stored in Usergrid: \r\n' + output+'
    '; - } - $('#facebook-status').html(html); - }) - } - - //pull the access token out of the query string - var ql = []; - if (window.location.hash) { - // split up the query string and store in an associative array - var params = window.location.hash.slice(1).split("#"); - var tmp = params[0].split("&"); - for (var i = 0; i < tmp.length; i++) { - var vals = tmp[i].split("="); - ql[vals[0]] = unescape(vals[1]); - } - } - - if (ql['access_token']) { - var facebookAccessToken = ql['access_token'] - //try to log in with facebook - login(facebookAccessToken); - } -}); \ No newline at end of file diff --git a/examples/facebook/facebook.html b/examples/facebook/facebook.html deleted file mode 100755 index 2ea8943..0000000 --- a/examples/facebook/facebook.html +++ /dev/null @@ -1,73 +0,0 @@ - - - - - - Facebook Login Example App for Apigee App Services (Usergrid) - - - - - - - - - -
    - App Services (Usergrid) Javascript SDK -
    - -
    - This sample application will show you how to log into App Services (Usergrid) using Facebook and the Usergrid Javascript SDK. - Enter the API Key that you get from Facebook, then log in. -

    - The Log in button sends the user to the facebook login page. Once the user logs in, they are redirected back to - this page and automatically logged into Usergrid. If the user is already logged into facebook, then they don't need to log in again. -

    - Clicking the log out button calls the logout method of the Facebook JS SDK, and also logs the user out of Usergrid by calling the Usergrid logoutAppUser method. -

    - For a step by step walk-thru on how to get this app running, see this guide. -

    - For more information on App Services, see our docs site, specifically or our Facebook docs page. -

    - For more information on how using the Facebook JS SDK to log users in, see this guide: http://developers.facebook.com/docs/howtos/login/getting-started/ -
    -
    -
    Log in with Facebook
    -
    -
    -
    - - -   - - -   -
    -
    -
    -
    API Response
    -
    - // Press 'Log in' to log in with Facebook. -
    -
    -
    - - diff --git a/examples/facebook/guide.html b/examples/facebook/guide.html deleted file mode 100755 index 725dd9a..0000000 --- a/examples/facebook/guide.html +++ /dev/null @@ -1,63 +0,0 @@ - - - - - - - - - - - -
    - App Services (Usergrid) Javascript SDK -
    -
    - To get the Facebook example working on your development machine, follow these steps: -

    - 1. Sign up -
    Sign up for a Facebook account. -

    - 2. Create a new app -
    Go to https://developers.facebook.com and follow - the prompts to authenticate yourself. Then, go to the Facebook App Dashboard, and create a new app. -

    - 3. Specify your Facebook integration method -
    On the app creation page, make sure you specify that you will use "Website with Facebook Login". - You should see something like this. You should enter the url where - you will host this sample (e.g. http://mywebsite.com/path-to-my-code). If want just to test with our gh-pages repo, - located here: http://apigee.github.com/usergrid-javascript-sdk/, - then enter http://apigee.github.com/usergrid-javascript-sdk in the field instead. -

    - 4. Get your App Id -
    Once your app is created, you can get the app id by going here: https://developers.facebook.com/apps -

    - 5. Download this code (skip this step if you plan to run it on our gh-pages repo) -
    If you haven't done so already, download the Usergrid Javascript SDK: https://github.com/apigee/usergrid-javascript-sdk - and save to a local directory on your hard drive. You will then need to deploy the code to your server. -

    - 6. Run the file -
    Navigate your browser to the location where you uploaded your code, or go to our gh-pages repo - ( http://apigee.github.com/usergrid-javascript-sdk/) and choose "Facebook Login Example". -

    - 7. Log in! -
    Enter your API key, and follow the prompts. -
    - - - diff --git a/examples/persistence/test.html b/examples/persistence/test.html deleted file mode 100644 index 3d7c553..0000000 --- a/examples/persistence/test.html +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - Readme File Tests - - - - - - - - - -
    - App Services (Usergrid) Javascript SDK -
    -
    - This sample application runs tests to demonstrate how to persist collections using the collection.serialize() method. -
    -
    -
    README sample code tests
    -
    -
    -
    - -   -
    -
    -
    -
    Test Output
    -
    -
    // Press Start button to begin
    -
    - - diff --git a/examples/persistence/test.js b/examples/persistence/test.js deleted file mode 100644 index 352323a..0000000 --- a/examples/persistence/test.js +++ /dev/null @@ -1,130 +0,0 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to You under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -$(document).ready(function () { - -//call the runner function to start the process - $('#start-button').bind('click', function() { - $('#start-button').attr("disabled", "disabled"); - $('#test-output').html(''); - runner(0); - }); - - var logSuccess = true; - var successCount = 0; - var logError = true; - var errorCount = 0; - var logNotice = true; - - var client = new Usergrid.Client({ - orgName:'yourorgname', - appName:'sandbox', - logging: true, //optional - turn on logging, off by default - buildCurl: true //optional - turn on curl commands, off by default - }); - - function runner(step, arg, arg2){ - step++; - switch(step) - { - case 1: - notice('-----running step '+step+': create and serialize collection'); - createAndSerialzeCollection(step); - break; - case 2: - notice('-----running step '+step+': de-serialize collection'); - deserializeCollection(step); - break; - default: - notice('-----test complete!-----'); - notice('Success count= ' + successCount); - notice('Error count= ' + errorCount); - notice('-----thank you for playing!-----'); - $('#start-button').removeAttr("disabled"); - } - } - -//logging functions - function success(message){ - successCount++; - if (logSuccess) { - console.log('SUCCESS: ' + message); - var html = $('#test-output').html(); - html += ('SUCCESS: ' + message + '\r\n'); - $('#test-output').html(html); - } - } - - function error(message){ - errorCount++ - if (logError) { - console.log('ERROR: ' + message); - var html = $('#test-output').html(); - html += ('ERROR: ' + message + '\r\n'); - $('#test-output').html(html); - } - } - - function notice(message){ - if (logNotice) { - console.log('NOTICE: ' + message); - var html = $('#test-output').html(); - html += (message + '\r\n'); - $('#test-output').html(html); - } - } - - - function createAndSerialzeCollection(step){ - var options = { - type:'books', - qs:{ql:'order by name'} - } - - client.createCollection(options, function (err, books) { - if (err) { - error('could not make collection'); - } else { - - //collection made, now serialize and store - localStorage.setItem('item', books.serialize()); - - success('new Collection created and data stored'); - - runner(step); - - } - }); - } - - - function deserializeCollection(step){ - var books = client.restoreCollection(localStorage.getItem('item')); - - while(books.hasNextEntity()) { - //get a reference to the book - book = books.getNextEntity(); - var name = book.get('name'); - notice('book is called ' + name); - } - - success('looped through books'); - - runner(step); - } - -}); \ No newline at end of file diff --git a/examples/resources/js/json2.js b/examples/resources/js/json2.js deleted file mode 100755 index c7745df..0000000 --- a/examples/resources/js/json2.js +++ /dev/null @@ -1,486 +0,0 @@ -/* - json2.js - 2012-10-08 - - Public Domain. - - NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. - - See http://www.JSON.org/js.html - - - This code should be minified before deployment. - See http://javascript.crockford.com/jsmin.html - - USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO - NOT CONTROL. - - - This file creates a global JSON object containing two methods: stringify - and parse. - - JSON.stringify(value, replacer, space) - value any JavaScript value, usually an object or array. - - replacer an optional parameter that determines how object - values are stringified for objects. It can be a - function or an array of strings. - - space an optional parameter that specifies the indentation - of nested structures. If it is omitted, the text will - be packed without extra whitespace. If it is a number, - it will specify the number of spaces to indent at each - level. If it is a string (such as '\t' or ' '), - it contains the characters used to indent at each level. - - This method produces a JSON text from a JavaScript value. - - When an object value is found, if the object contains a toJSON - method, its toJSON method will be called and the result will be - stringified. A toJSON method does not serialize: it returns the - value represented by the name/value pair that should be serialized, - or undefined if nothing should be serialized. The toJSON method - will be passed the key associated with the value, and this will be - bound to the value - - For example, this would serialize Dates as ISO strings. - - Date.prototype.toJSON = function (key) { - function f(n) { - // Format integers to have at least two digits. - return n < 10 ? '0' + n : n; - } - - return this.getUTCFullYear() + '-' + - f(this.getUTCMonth() + 1) + '-' + - f(this.getUTCDate()) + 'T' + - f(this.getUTCHours()) + ':' + - f(this.getUTCMinutes()) + ':' + - f(this.getUTCSeconds()) + 'Z'; - }; - - You can provide an optional replacer method. It will be passed the - key and value of each member, with this bound to the containing - object. The value that is returned from your method will be - serialized. If your method returns undefined, then the member will - be excluded from the serialization. - - If the replacer parameter is an array of strings, then it will be - used to select the members to be serialized. It filters the results - such that only members with keys listed in the replacer array are - stringified. - - Values that do not have JSON representations, such as undefined or - functions, will not be serialized. Such values in objects will be - dropped; in arrays they will be replaced with null. You can use - a replacer function to replace those with JSON values. - JSON.stringify(undefined) returns undefined. - - The optional space parameter produces a stringification of the - value that is filled with line breaks and indentation to make it - easier to read. - - If the space parameter is a non-empty string, then that string will - be used for indentation. If the space parameter is a number, then - the indentation will be that many spaces. - - Example: - - text = JSON.stringify(['e', {pluribus: 'unum'}]); - // text is '["e",{"pluribus":"unum"}]' - - - text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); - // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' - - text = JSON.stringify([new Date()], function (key, value) { - return this[key] instanceof Date ? - 'Date(' + this[key] + ')' : value; - }); - // text is '["Date(---current time---)"]' - - - JSON.parse(text, reviver) - This method parses a JSON text to produce an object or array. - It can throw a SyntaxError exception. - - The optional reviver parameter is a function that can filter and - transform the results. It receives each of the keys and values, - and its return value is used instead of the original value. - If it returns what it received, then the structure is not modified. - If it returns undefined then the member is deleted. - - Example: - - // Parse the text. Values that look like ISO date strings will - // be converted to Date objects. - - myData = JSON.parse(text, function (key, value) { - var a; - if (typeof value === 'string') { - a = -/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); - if (a) { - return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], - +a[5], +a[6])); - } - } - return value; - }); - - myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { - var d; - if (typeof value === 'string' && - value.slice(0, 5) === 'Date(' && - value.slice(-1) === ')') { - d = new Date(value.slice(5, -1)); - if (d) { - return d; - } - } - return value; - }); - - - This is a reference implementation. You are free to copy, modify, or - redistribute. -*/ - -/*jslint evil: true, regexp: true */ - -/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, - call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, - getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, - lastIndex, length, parse, prototype, push, replace, slice, stringify, - test, toJSON, toString, valueOf -*/ - - -// Create a JSON object only if one does not already exist. We create the -// methods in a closure to avoid creating global variables. - -if (typeof JSON !== 'object') { - JSON = {}; -} - -(function () { - 'use strict'; - - function f(n) { - // Format integers to have at least two digits. - return n < 10 ? '0' + n : n; - } - - if (typeof Date.prototype.toJSON !== 'function') { - - Date.prototype.toJSON = function (key) { - - return isFinite(this.valueOf()) - ? this.getUTCFullYear() + '-' + - f(this.getUTCMonth() + 1) + '-' + - f(this.getUTCDate()) + 'T' + - f(this.getUTCHours()) + ':' + - f(this.getUTCMinutes()) + ':' + - f(this.getUTCSeconds()) + 'Z' - : null; - }; - - String.prototype.toJSON = - Number.prototype.toJSON = - Boolean.prototype.toJSON = function (key) { - return this.valueOf(); - }; - } - - var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - gap, - indent, - meta = { // table of character substitutions - '\b': '\\b', - '\t': '\\t', - '\n': '\\n', - '\f': '\\f', - '\r': '\\r', - '"' : '\\"', - '\\': '\\\\' - }, - rep; - - - function quote(string) { - -// If the string contains no control characters, no quote characters, and no -// backslash characters, then we can safely slap some quotes around it. -// Otherwise we must also replace the offending characters with safe escape -// sequences. - - escapable.lastIndex = 0; - return escapable.test(string) ? '"' + string.replace(escapable, function (a) { - var c = meta[a]; - return typeof c === 'string' - ? c - : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }) + '"' : '"' + string + '"'; - } - - - function str(key, holder) { - -// Produce a string from holder[key]. - - var i, // The loop counter. - k, // The member key. - v, // The member value. - length, - mind = gap, - partial, - value = holder[key]; - -// If the value has a toJSON method, call it to obtain a replacement value. - - if (value && typeof value === 'object' && - typeof value.toJSON === 'function') { - value = value.toJSON(key); - } - -// If we were called with a replacer function, then call the replacer to -// obtain a replacement value. - - if (typeof rep === 'function') { - value = rep.call(holder, key, value); - } - -// What happens next depends on the value's type. - - switch (typeof value) { - case 'string': - return quote(value); - - case 'number': - -// JSON numbers must be finite. Encode non-finite numbers as null. - - return isFinite(value) ? String(value) : 'null'; - - case 'boolean': - case 'null': - -// If the value is a boolean or null, convert it to a string. Note: -// typeof null does not produce 'null'. The case is included here in -// the remote chance that this gets fixed someday. - - return String(value); - -// If the type is 'object', we might be dealing with an object or an array or -// null. - - case 'object': - -// Due to a specification blunder in ECMAScript, typeof null is 'object', -// so watch out for that case. - - if (!value) { - return 'null'; - } - -// Make an array to hold the partial results of stringifying this object value. - - gap += indent; - partial = []; - -// Is the value an array? - - if (Object.prototype.toString.apply(value) === '[object Array]') { - -// The value is an array. Stringify every element. Use null as a placeholder -// for non-JSON values. - - length = value.length; - for (i = 0; i < length; i += 1) { - partial[i] = str(i, value) || 'null'; - } - -// Join all of the elements together, separated with commas, and wrap them in -// brackets. - - v = partial.length === 0 - ? '[]' - : gap - ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' - : '[' + partial.join(',') + ']'; - gap = mind; - return v; - } - -// If the replacer is an array, use it to select the members to be stringified. - - if (rep && typeof rep === 'object') { - length = rep.length; - for (i = 0; i < length; i += 1) { - if (typeof rep[i] === 'string') { - k = rep[i]; - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } else { - -// Otherwise, iterate through all of the keys in the object. - - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } - -// Join all of the member texts together, separated with commas, -// and wrap them in braces. - - v = partial.length === 0 - ? '{}' - : gap - ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' - : '{' + partial.join(',') + '}'; - gap = mind; - return v; - } - } - -// If the JSON object does not yet have a stringify method, give it one. - - if (typeof JSON.stringify !== 'function') { - JSON.stringify = function (value, replacer, space) { - -// The stringify method takes a value and an optional replacer, and an optional -// space parameter, and returns a JSON text. The replacer can be a function -// that can replace values, or an array of strings that will select the keys. -// A default replacer method can be provided. Use of the space parameter can -// produce text that is more easily readable. - - var i; - gap = ''; - indent = ''; - -// If the space parameter is a number, make an indent string containing that -// many spaces. - - if (typeof space === 'number') { - for (i = 0; i < space; i += 1) { - indent += ' '; - } - -// If the space parameter is a string, it will be used as the indent string. - - } else if (typeof space === 'string') { - indent = space; - } - -// If there is a replacer, it must be a function or an array. -// Otherwise, throw an error. - - rep = replacer; - if (replacer && typeof replacer !== 'function' && - (typeof replacer !== 'object' || - typeof replacer.length !== 'number')) { - throw new Error('JSON.stringify'); - } - -// Make a fake root object containing our value under the key of ''. -// Return the result of stringifying the value. - - return str('', {'': value}); - }; - } - - -// If the JSON object does not yet have a parse method, give it one. - - if (typeof JSON.parse !== 'function') { - JSON.parse = function (text, reviver) { - -// The parse method takes a text and an optional reviver function, and returns -// a JavaScript value if the text is a valid JSON text. - - var j; - - function walk(holder, key) { - -// The walk method is used to recursively walk the resulting structure so -// that modifications can be made. - - var k, v, value = holder[key]; - if (value && typeof value === 'object') { - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = walk(value, k); - if (v !== undefined) { - value[k] = v; - } else { - delete value[k]; - } - } - } - } - return reviver.call(holder, key, value); - } - - -// Parsing happens in four stages. In the first stage, we replace certain -// Unicode characters with escape sequences. JavaScript handles many characters -// incorrectly, either silently deleting them, or treating them as line endings. - - text = String(text); - cx.lastIndex = 0; - if (cx.test(text)) { - text = text.replace(cx, function (a) { - return '\\u' + - ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }); - } - -// In the second stage, we run the text against regular expressions that look -// for non-JSON patterns. We are especially concerned with '()' and 'new' -// because they can cause invocation, and '=' because it can cause mutation. -// But just to be safe, we want to reject all unexpected forms. - -// We split the second stage into 4 regexp operations in order to work around -// crippling inefficiencies in IE's and Safari's regexp engines. First we -// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we -// replace all simple value tokens with ']' characters. Third, we delete all -// open brackets that follow a colon or comma or that begin the text. Finally, -// we look to see that the remaining characters are only whitespace or ']' or -// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. - - if (/^[\],:{}\s]*$/ - .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') - .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') - .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { - -// In the third stage we use the eval function to compile the text into a -// JavaScript structure. The '{' operator is subject to a syntactic ambiguity -// in JavaScript: it can begin a block or an object literal. We wrap the text -// in parens to eliminate the ambiguity. - - j = eval('(' + text + ')'); - -// In the optional fourth stage, we recursively walk the new structure, passing -// each name/value pair to a reviver function for possible transformation. - - return typeof reviver === 'function' - ? walk({'': j}, '') - : j; - } - -// If the text is not JSON parseable, then a SyntaxError is thrown. - - throw new SyntaxError('JSON.parse'); - }; - } -}()); diff --git a/extensions/usergrid.validation.js b/examples/resources/js/usergrid.validation.js similarity index 100% rename from extensions/usergrid.validation.js rename to examples/resources/js/usergrid.validation.js diff --git a/examples/test/test.html b/examples/test/test.html deleted file mode 100755 index e66fcb3..0000000 --- a/examples/test/test.html +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - Readme File Tests - - - - - - - - - -
    - App Services (Usergrid) Javascript SDK -
    -
    - This sample application runs tests on the sample code examples in the readme file. Tests are run against App Services (Usergrid) using the Usergrid Javascript SDK. -
    -
    -
    README sample code tests
    -
    -
    -
    - -   -
    -
    -
    -
    Test Output
    -
    -
    // Press Start button to begin
    -
    - - diff --git a/examples/test/test.js b/examples/test/test.js deleted file mode 100755 index de0f4aa..0000000 --- a/examples/test/test.js +++ /dev/null @@ -1,978 +0,0 @@ -/** -* Test suite for all the examples in the readme -* -* NOTE: No, this test suite doesn't use the traditional format for -* a test suite. This is because the goal is to require as little -* alteration as possible during the copy / paste operation from this test -* suite to the readme file. -* -* @author rod simpson (rod@apigee.com) -*/ - -$(document).ready(function () { - -//call the runner function to start the process -$('#start-button').bind('click', function() { - $('#start-button').attr("disabled", "disabled"); - $('#test-output').html(''); - runner(0); -}); - -var logSuccess = true; -var successCount = 0; -var logError = true; -var errorCount = 0; -var logNotice = true; -var _unique = new Date().getTime(); -var _username = 'marty'+_unique; -var _email = 'marty'+_unique+'@timetravel.com'; -var _password = 'password2'; -var _newpassword = 'password3'; - -var client = new Usergrid.Client({ - orgId:'rwalsh', - appId:'sandbox', - logging: true, //optional - turn on logging, off by default - buildCurl: true //optional - turn on curl commands, off by default -}); - -client.logout(); - -function runner(step, arg, arg2){ - step++; - switch(step) - { - case 1: - notice('-----running step '+step+': DELETE user from DB to prep test'); - clearUser(step); - break; - case 2: - notice('-----running step '+step+': GET test'); - testGET(step); - break; - case 3: - notice('-----running step '+step+': POST test'); - testPOST(step); - break; - case 4: - notice('-----running step '+step+': PUT test'); - testPUT(step); - break; - case 5: - notice('-----running step '+step+': DELETE test'); - testDELETE(step); - break; - case 6: - notice('-----running step '+step+': prepare database - remove all dogs (no real dogs harmed here!!)'); - cleanupAllDogs(step); - break; - case 7: - notice('-----running step '+step+': make a new dog'); - makeNewDog(step); - break; - case 8: - notice('-----running step '+step+': update our dog'); - updateDog(step, arg); - break; - case 9: - notice('-----running step '+step+': refresh our dog'); - refreshDog(step, arg); - break; - case 10: - notice('-----running step '+step+': remove our dog from database (no real dogs harmed here!!)'); - removeDogFromDatabase(step, arg); - break; - case 11: - notice('-----running step '+step+': make lots of dogs!'); - makeSampleData(step, arg); - break; - case 12: - notice('-----running step '+step+': make a dogs collection and show each dog'); - testDogsCollection(step); - break; - case 13: - notice('-----running step '+step+': get the next page of the dogs collection and show each dog'); - getNextDogsPage(step, arg); - break; - case 14: - notice('-----running step '+step+': get the previous page of the dogs collection and show each dog'); - getPreviousDogsPage(step, arg); - break; - case 15: - notice('-----running step '+step+': remove all dogs from the database (no real dogs harmed here!!)'); - cleanupAllDogs(step); - break; - case 16: - notice('-----running step '+step+': prepare database (remove existing user if present)'); - prepareDatabaseForNewUser(step); - break; - case 17: - notice('-----running step '+step+': create a new user'); - createUser(step); - break; - case 18: - notice('-----running step '+step+': update the user'); - updateUser(step, arg); - break; - case 19: - notice('-----running step '+step+': get the existing user'); - getExistingUser(step, arg); - break; - case 20: - notice('-----running step '+step+': refresh the user from the database'); - refreshUser(step, arg); - break; - case 21: - notice('-----running step '+step+': log user in'); - loginUser(step, arg); - break; - case 22: - notice('-----running step '+step+': change users password'); - changeUsersPassword(step, arg); - break; - case 23: - notice('-----running step '+step+': log user out'); - logoutUser(step, arg); - break; - case 24: - notice('-----running step '+step+': relogin user'); - reloginUser(step, arg); - break; - case 25: - notice('-----running step '+step+': logged in user creates dog'); - createDog(step, arg); - break; - case 26: - notice('-----running step '+step+': logged in user likes dog'); - userLikesDog(step, arg, arg2); - break; - case 27: - notice('-----running step '+step+': logged in user removes likes connection to dog'); - removeUserLikesDog(step, arg, arg2); - break; - case 28: - notice('-----running step '+step+': user removes dog'); - removeDog(step, arg, arg2); - break; - case 29: - notice('-----running step '+step+': log the user out'); - logoutUser(step, arg); - break; - case 30: - notice('-----running step '+step+': remove the user from the database'); - destroyUser(step, arg); - break; - case 31: - notice('-----running step '+step+': try to create existing entity'); - createExistingEntity(step, arg); - break; - case 32: - notice('-----running step '+step+': try to create new entity with no name'); - createNewEntityNoName(step, arg); - break; - case 33: - notice('-----running step '+step+': clean up users'); - cleanUpUsers(step, arg); - break; - case 34: - notice('-----running step '+step+': clean up dogs'); - cleanUpDogs(step, arg); - break; - default: - notice('-----test complete!-----'); - notice('Success count= ' + successCount); - notice('Error count= ' + errorCount); - notice('-----thank you for playing!-----'); - $('#start-button').removeAttr("disabled"); - } -} - -//logging functions -function success(message){ - successCount++; - if (logSuccess) { - console.log('SUCCESS: ' + message); - var html = $('#test-output').html(); - html += ('SUCCESS: ' + message + '\r\n'); - $('#test-output').html(html); - } -} - -function error(message){ - errorCount++ - if (logError) { - console.log('ERROR: ' + message); - var html = $('#test-output').html(); - html += ('ERROR: ' + message + '\r\n'); - $('#test-output').html(html); - } -} - -function notice(message){ - if (logNotice) { - console.log('NOTICE: ' + message); - var html = $('#test-output').html(); - html += (message + '\r\n'); - $('#test-output').html(html); - } -} - -//tests -function clearUser(step) { - var options = { - method:'DELETE', - endpoint:'users/fred' - }; - client.request(options, function (err, data) { - //data will contain raw results from API call - success('User cleared from DB'); - runner(step); - }); -} - -function testGET(step) { - var options = { - method:'GET', - endpoint:'users' - }; - client.request(options, function (err, data) { - if (err) { - error('GET failed'); - } else { - //data will contain raw results from API call - success('GET worked'); - runner(step); - } - }); -} - -function testPOST(step) { - var options = { - method:'POST', - endpoint:'users', - body:{ username:'fred', password:'secret' } - }; - client.request(options, function (err, data) { - if (err) { - error('POST failed'); - } else { - //data will contain raw results from API call - success('POST worked'); - runner(step); - } - }); -} - -function testPUT(step) { - var options = { - method:'PUT', - endpoint:'users/fred', - body:{ newkey:'newvalue' } - }; - client.request(options, function (err, data) { - if (err) { - error('PUT failed'); - } else { - //data will contain raw results from API call - success('PUT worked'); - runner(step); - } - }); -} - -function testDELETE(step) { - var options = { - method:'DELETE', - endpoint:'users/fred' - }; - client.request(options, function (err, data) { - if (err) { - error('DELETE failed'); - } else { - //data will contain raw results from API call - success('DELETE worked'); - runner(step); - } - }); -} - -function makeNewDog(step) { - - var options = { - type:'dogs', - name:'Ralph'+_unique - } - - client.createEntity(options, function (err, response, dog) { - if (err) { - error('dog not created'); - } else { - success('dog is created'); - - //once the dog is created, you can set single properties: - dog.set('breed','Dinosaur'); - - //the set function can also take a JSON object: - var data = { - master:'Fred', - state:'hungry' - } - //set is additive, so previously set properties are not overwritten - dog.set(data); - - //finally, call save on the object to save it back to the database - dog.save(function(err){ - if (err){ - error('dog not saved'); - } else { - success('new dog is saved'); - runner(step, dog); - } - }); - } - }); - -} - -function updateDog(step, dog) { - - //change a property in the object - dog.set("state", "fed"); - //and save back to the database - dog.save(function(err){ - if (err){ - error('dog not saved'); - } else { - success('dog is saved'); - runner(step, dog); - } - }); - -} - -function refreshDog(step, dog){ - - //call fetch to refresh the data from the server - dog.fetch(function(err){ - if (err){ - error('dog not refreshed from database'); - } else { - //dog has been refreshed from the database - //will only work if the UUID for the entity is in the dog object - success('dog entity refreshed from database'); - runner(step, dog); - } - }); - -} - -function removeDogFromDatabase(step, dog){ - - //the destroy method will delete the entity from the database - dog.destroy(function(err){ - if (err){ - error('dog not removed from database'); - } else { - success('dog removed from database'); // no real dogs were harmed! - dog = null; //no real dogs were harmed! - runner(step, 1); - } - }); - -} - -function makeSampleData(step, i) { - notice('making dog '+i); - - var options = { - type:'dogs', - name:'dog'+_unique+i, - index:i - } - - client.createEntity(options, function (err, dog) { - if (err) { - error('dog ' + i + ' not created'); - } else { - if (i >= 30) { - //data made, ready to go - success('all dogs made'); - runner(step); - } else { - success('dog ' + i + ' made'); - //keep making dogs - makeSampleData(step, ++i); - } - } - }); -} - -function testDogsCollection(step) { - - var options = { - type:'dogs', - qs:{ql:'order by index'} - } - - client.createCollection(options, function (err, response, dogs) { - if (err) { - error('could not make collection'); - } else { - - success('new Collection created'); - - //we got the dogs, now display the Entities: - while(dogs.hasNextEntity()) { - //get a reference to the dog - dog = dogs.getNextEntity(); - var name = dog.get('name'); - notice('dog is called ' + name); - } - - success('looped through dogs'); - - //create a new dog and add it to the collection - var options = { - name:'extra-dog', - fur:'shedding' - } - //just pass the options to the addEntity method - //to the collection and it is saved automatically - dogs.addEntity(options, function(err, dog, data) { - if (err) { - error('extra dog not saved or added to collection'); - } else { - success('extra dog saved and added to collection'); - runner(step, dogs); - } - }); - } - }); - -} - -function getNextDogsPage(step, dogs) { - - if (dogs.hasNextPage()) { - //there is a next page, so get it from the server - dogs.getNextPage(function(err){ - if (err) { - error('could not get next page of dogs'); - } else { - success('got next page of dogs'); - //we got the next page of data, so do something with it: - var i = 11; - while(dogs.hasNextEntity()) { - //get a reference to the dog - var dog = dogs.getNextEntity(); - var index = dog.get('index'); - if(i !== index) { - error('wrong dog loaded: wanted' + i + ', got ' + index); - } - notice('got dog ' + i); - i++ - } - success('looped through dogs') - runner(step, dogs); - } - }); - } else { - getPreviousDogsPage(dogs); - } - -} - -function getPreviousDogsPage(step, dogs) { - - if (dogs.hasPreviousPage()) { - //there is a previous page, so get it from the server - dogs.getPreviousPage(function(err){ - if(err) { - error('could not get previous page of dogs'); - } else { - success('got next page of dogs'); - //we got the previous page of data, so do something with it: - var i = 1; - while(dogs.hasNextEntity()) { - //get a reference to the dog - var dog = dogs.getNextEntity(); - var index = dog.get('index'); - if(i !== index) { - error('wrong dog loaded: wanted' + i + ', got ' + index); - } - notice('got dog ' + i); - i++ - } - success('looped through dogs'); - runner(step); - } - }); - } else { - getAllDogs(); - } -} - -function cleanupAllDogs(step){ - - var options = { - type:'dogs', - qs:{limit:50} //limit statement set to 50 - } - - client.createCollection(options, function (err, response, dogs) { - if (err) { - error('could not get all dogs'); - } else { - success('got at most 50 dogs'); - //we got 50 dogs, now display the Entities: - while(dogs.hasNextEntity()) { - //get a reference to the dog - var dog = dogs.getNextEntity(); - var name = dog.get('name'); - notice('dog is called ' + name); - } - dogs.resetEntityPointer(); - //do doggy cleanup - while(dogs.hasNextEntity()) { - //get a reference to the dog - var dog = dogs.getNextEntity(); - var dogname = dog.get('name'); - notice('removing dog ' + dogname + ' from database'); - dog.destroy(function(err, data) { - if (err) { - error('dog not removed'); - } else { - success('dog removed'); - } - }); - } - - //no need to wait around for dogs to be removed, so go on to next test - runner(step); - } - }); -} - - -function prepareDatabaseForNewUser(step) { - var options = { - method:'DELETE', - endpoint:'users/', - qs:{ql:"select * where username ='marty*'"} - }; - client.request(options, function (err, data) { - if (err) { - notice('database ready - no user to delete'); - runner(step); - } else { - //data will contain raw results from API call - success('database ready - user deleted worked'); - runner(step); - } - }); -} - -function createUser(step) { - client.signup(_username, _password, _email, 'Marty McFly', - function (err, response, marty) { - if (err){ - error('user not created'); - runner(step, marty); - } else { - success('user created'); - runner(step, marty); - } - } - ); -} - -function updateUser(step, marty) { - - //add properties cumulatively - marty.set('state', 'California'); - marty.set("girlfriend","Jennifer"); - marty.save(function(err){ - if (err){ - error('user not updated'); - } else { - success('user updated'); - runner(step, marty); - } - }); - -} - -function getExistingUser(step, marty) { - - var options = { - type:'users', - username:_username - } - client.getEntity(options, function(err, response, existingUser){ - if (err){ - error('existing user not retrieved'); - } else { - success('existing user was retrieved'); - - var username = existingUser.get('username'); - if (username === _username){ - success('got existing user username'); - } else { - error('could not get existing user username'); - } - runner(step, marty); - } - }); - -} - - -function refreshUser(step, marty) { - - marty.fetch(function(err){ - if (err){ - error('not refreshed'); - } else { - success('user refreshed'); - runner(step, marty); - } - }); - -} - -function loginUser(step, marty) { - username = _username; - password = _password; - client.login(username, password, - function (err, response, user) { - if (err) { - error('could not log user in'); - } else { - success('user has been logged in'); - - //the login call will return an OAuth token, which is saved - //in the client. Any calls made now will use the token. - //once a user has logged in, their user object is stored - //in the client and you can access it this way: - var token = client.token; - - //Then make calls against the API. For example, you can - //get the user entity this way: - client.getLoggedInUser(function(err, data, user) { - console.error(err, data, user); - if(err) { - error('could not get logged in user'); - } else { - success('got logged in user'); - - //you can then get info from the user entity object: - var username = user.get('username'); - notice('logged in user was: ' + username); - - runner(step, user); - } - }); - - } - } - ); -} - -function changeUsersPassword(step, marty) { - - marty.set('oldpassword', _password); - marty.set('password', _newpassword); - marty.set('newpassword', _newpassword); - marty.changePassword(function(err, response){ - if (err){ - error('user password not updated'); - } else { - success('user password updated'); - runner(step, marty); - } - }); - -} - -function logoutUser(step, marty) { - - //to log the user out, call the logout() method - client.logout(); - - //verify the logout worked - if (client.isLoggedIn()) { - error('logout failed'); - } else { - success('user has been logged out'); - } - - runner(step, marty); -} - -function reloginUser(step, marty) { - - username = _username - password = _newpassword; - client.login(username, password, - function (err, response, marty) { - if (err) { - error('could not relog user in'); - } else { - success('user has been re-logged in'); - runner(step, marty); - } - } - ); -} - - - -//TODO: currently, this code assumes permissions have been set to support user actions. need to add code to show how to add new role and permission programatically -// -//first create a new permission on the default role: -//POST "https://api.usergrid.com/yourorgname/yourappname/roles/default/permissions" -d '{"permission":"get,post,put,delete:/dogs/**"}' -//then after user actions, delete the permission on the default role: -//DELETE "https://api.usergrid.com/yourorgname/yourappname/roles/default/permissions?permission=get%2Cpost%2Cput%2Cdelete%3A%2Fdogs%2F**" - - -function createDog(step, marty) { - - var options = { - type:'dogs', - name:'einstein', - breed:'mutt' - } - - client.createEntity(options, function (err, response, dog) { - if (err) { - error('POST new dog by logged in user failed'); - } else { - success('POST new dog by logged in user succeeded'); - runner(step, marty, dog); - } - }); - -} - -function userLikesDog(step, marty, dog) { - - marty.connect('likes', dog, function (err, response, data) { - if (err) { - error('connection not created'); - runner(step, marty); - } else { - - //call succeeded, so pull the connections back down - marty.getConnections('likes', function (err, response, data) { - if (err) { - error('could not get connections'); - } else { - //verify that connection exists - if (marty.likes.einstein) { - success('connection exists'); - } else { - error('connection does not exist'); - } - - runner(step, marty, dog); - } - }); - } - }); - -} - -function removeUserLikesDog(step, marty, dog) { - - marty.disconnect('likes', dog, function (err, data) { - if (err) { - error('connection not deleted'); - runner(step, marty); - } else { - - //call succeeded, so pull the connections back down - marty.getConnections('likes', function (err, data) { - if (err) { - error('error getting connections'); - } else { - //verify that connection exists - if (marty.likes.einstein) { - error('connection still exists'); - } else { - success('connection deleted'); - } - - runner(step, marty, dog); - } - }); - } - }); - -} - -function removeDog(step, marty, dog) { - - //now delete the dog from the database - dog.destroy(function(err, data) { - if (err) { - error('dog not removed'); - } else { - success('dog removed'); - } - }); - runner(step, marty); -} - -function destroyUser(step, marty) { - - marty.destroy(function(err){ - if (err){ - error('user not deleted from database'); - } else { - success('user deleted from database'); - marty = null; //blow away the local object - runner(step); - } - }); - -} - -function createExistingEntity(step, marty) { - - var options = { - type:'dogs', - name:'einstein' - } - - client.createEntity(options, function (err, response, dog) { - if (err) { - error('Create new entity to use for existing entity failed'); - } else { - success('Create new entity to use for existing entity succeeded'); - - var uuid = dog.get('uuid'); - //now create new entity, but use same entity name of einstein. This means that - //the original einstein entity now exists. Thus, the new einstein entity should - //be the same as the original + any data differences from the options var: - - options = { - type:'dogs', - name:'einstein', - breed:'mutt' - } - client.createEntity(options, function (err, response, newdog) { - if (err) { - success('Create new entity to use for existing entity failed'); - } else { - error('Create new entity to use for existing entity succeeded'); - } - dog.destroy(function(err){ - if (err){ - error('existing entity not deleted from database'); - } else { - success('existing entity deleted from database'); - dog = null; //blow away the local object - newdog = null; //blow away the local object - runner(step); - } - }); - }); - } - }); - -} - -function createNewEntityNoName(step, marty) { - - var options = { - type:"something", - othervalue:"something else" - } - - client.createEntity(options, function (err, response, entity) { - if (err) { - error('Create new entity with no name failed'); - } else { - success('Create new entity with no name succeeded'); - - entity.destroy(); - runner(step); - } - }); - -} - -function cleanUpUsers(step){ - - var options = { - type:'users', - qs:{limit:50} //limit statement set to 50 - } - - client.createCollection(options, function (err, response, users) { - if (err) { - error('could not get all users'); - } else { - success('got users'); - //do doggy cleanup - while(users.hasNextEntity()) { - //get a reference to the dog - var user = users.getNextEntity(); - var username = user.get('name'); - notice('removing dog ' + username + ' from database'); - user.destroy(function(err, data) { - if (err) { - error('user not removed'); - } else { - success('user removed'); - } - }); - } - - runner(step); - } - }); - -} - -function cleanUpDogs(step){ - - var options = { - type:'dogs', - qs:{limit:50} //limit statement set to 50 - } - - client.createCollection(options, function (err, response, dogs) { - if (err) { - error('could not get all dogs'); - } else { - success('got at most 50 dogs'); - //we got 50 dogs, now display the Entities: - while(dogs.hasNextEntity()) { - //get a reference to the dog - var dog = dogs.getNextEntity(); - var name = dog.get('name'); - notice('dog is called ' + name); - } - dogs.resetEntityPointer(); - //do doggy cleanup - while(dogs.hasNextEntity()) { - //get a reference to the dog - var dog = dogs.getNextEntity(); - var dogname = dog.get('name'); - notice('removing dog ' + dogname + ' from database'); - dog.destroy(function(err, data) { - if (err) { - error('dog not removed'); - } else { - success('dog removed'); - } - }); - } - - //no need to wait around for dogs to be removed, so go on to next test - runner(step); - } - }); - } -}); diff --git a/index.html b/index.html index 309d90b..627f879 100755 --- a/index.html +++ b/index.html @@ -35,7 +35,7 @@

    Javascript SDK


    Read me

    View the read me file for the SDK: - https://github.com/usergrid/usergrid/blob/master/sdks/html5-javascript/README.md. + https://github.com/apache/usergrid-javascript/README.md.

    API documentation

    @@ -44,26 +44,23 @@

    API documentation



    -

    Example Apps:

    +

    Tests:


    - All Calls example app + Mocha Tests
    - This app shows the basic method for making all call types against the API. It also shows how to log in an app user. + This is a test script that runs all of the Mocha test cases written for the Javascript SDK.

    - Dogs example app +

    Examples:


    - This app shows you how to use the Entity and Collection objects + User Example
    + This example shows the basic methods for making all REST calls against the API for creating, editing and logging in a new UsergridUser.
    - Facebook Login Example
    - This app shows you how to use Facebook to log into Usergrid. + Dogs Example
    -
    - Tests for examples in readme file -
    - This is a test script that runs all the sample code shown in the readme file. See the samples in action! + This example shows you how to POST UsergridEntity objects and page through responses.
    diff --git a/lib/modules/UsergridQuery.js b/lib/modules/UsergridQuery.js index 1c5411f..ada0e57 100644 --- a/lib/modules/UsergridQuery.js +++ b/lib/modules/UsergridQuery.js @@ -116,7 +116,9 @@ var UsergridQuery = function(type) { if (queryString !== undefined) { return queryString } else { - return 'select *' + ((query.length > 0 || sort !== undefined) ? ' where ' + (query || '') + (sort || '') : '') + var qL = 'select * ' + ((query.length > 0) ? 'where ' + (query || '') : '') + qL += (sort !== undefined) ? sort : '' + return qL } } }) diff --git a/tests/mocha/test_query.js b/tests/mocha/test_query.js index c7487bb..b919869 100644 --- a/tests/mocha/test_query.js +++ b/tests/mocha/test_query.js @@ -49,7 +49,7 @@ describe('UsergridQuery', function() { describe('_ql', function() { it('should be an select all if query or sort are empty or underfined', function() { var query = new UsergridQuery('cats') - query.should.have.property('_ql').equal("select *") + query.should.have.property('_ql').equal("select * ") }) it('should support complex builder pattern syntax (chained constructor methods)', function() { diff --git a/tests/resources/css/mocha.css b/tests/resources/css/mocha.css index 42b9798..dfa7138 100644 --- a/tests/resources/css/mocha.css +++ b/tests/resources/css/mocha.css @@ -1,3 +1,4 @@ + @charset "utf-8"; body { diff --git a/tests/resources/images/apigee.png b/tests/resources/images/apigee.png deleted file mode 100755 index c0d0f8481222ffab07dc439e90cd4d7760426ea7..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6010 zcmV-=7lr7FP)4Tx07wn3mUmPWSsTXhOnRdwR4Ji`UZqP3J)nSe5S5SwLW?mZfQX&N6<7-* zQmn`-MZr}mvKB-X+ag%NzCjihbzLmjQ28dX#692n_P_7u%*-#(ednF`zBBin2LN&% zTPVzgl>o>Rh(!^BKJ>Ww1Ul{kAOadt09wGB&B+!r!^7u;e;w}!0VJEeX(h|`uVMdt zLYd3U<^TYNBh$&;Y)%%!Cy=9*BNT}NKzSp&QLb1hV=lrp5mF$+c`{C&;ZhkV&+xwK zn5YO}BnHWYC$rh2Q~*d_h)&Ppq#}7pQiN><+%y3IWMt*Qlf!2txyiB`EVHtf$+!Sv z)8v2TN&N@2*~#*pY<8-gXV!w;i9FaZEnAq$UNQaW|9Q&Flpy_@9=gbxoShLFf?R1x z&+<5I|HxV9^H{QXHmwWAJ`uB=CT2y=GG7uDJ_W_3=sFVg#& zoca8y*jeWC{QPHGv@Aj%pPdsa*Yo+lp|dgR>|j~1r)y)25c->WnSt`>3dP~_It7`b z^0lOh0^~8g?C2Ot?anmdY2?naB>{S<+bojZK_IJ%>4FIYr09v~_5>d{~y=d75 zgX~mAq?4LJ7Z?IlV1-oX1l)l)@CU&l3`Bu=umq``53-Qjb3p-E2Z}%m*a~)lYOog^ z0QKMqI0o9mDR2&41Xn>nxDD+?pp(!!=rS|_-GzpsG3X8S8Aicmm>Ca?|c z0yE(dI0{}2r^3tOe7F$a3|GRn@L{+OJ_lcgZ^Kgf1w4TQC=yByrH`^gxuASeVWLyBxdWrgk#-gccI@${Djt)XcqdDm1=+)>_bTzsj-G=T# z-$W0i$I;&~6pS{;0^^2ZVd5~Um|RQ|rUG*i(~7x(xs4gcyvJg(YFGx=85@L+$EIUf zVoR~Ru`Spx>;QHIJAuRDG;tO<4_p|IjT7UFa8X-^tWZ3zcwO7>$-(u6Wq*-kl3IZL@zxl#GD@-r2jiiwK93Rk62<$%h0l@Th6YDo2^ za;O`qb<_*gQ5u%Ups{G_v=Z78S|4p(RYi5KYK&^0YK`h?RjC?E%|wl*mZ`Qy?U>r2 z+Glkgb*4H`eUo~#`VI9D8gn$fHFz4u8Z8>PH9l+7HT^X+G`DHCYd+LMYnf{;)XLS` zqjf>+>kV2A9vTu2 zT?|tU%MH5?$Bp!i78n&6H5uJACK$UI^Nn{J_ZojNVVK04Y&2;%dB)ISuo(G_CdLC( zim8|Ba?@JVTV_}@7qbkr-Ddsfu(_i--@L~Bx&>_EWRYgE+hV{HW9e!su&lKlvLahC zt#YiItcI=Ctmj*=w{Ew7Wn*NMV6)Ap*XEn8qiv>bo$Y-)6}w=&^>&?hZ|u$OIrcU7 zw;U)A0S;>%IviflwV2DByJzklN2=oj$BmBNj$fUeokUK}PGinS&PmR@oQGU!F5xbv zE|**}u0F17Tu-@va&vMMyB%};%iYR7!@be{**wNP-n_bbBOV4GY>)jOQct>PlIK28 zsh7SN+pE^=vA3Z&*ZZLNQ>Ga+oq3q~%E#76MY1)=R>AdD5ZJ?vpPBYb)IuM4pY!xz>pd=g<7Q4rA^NsU|@*%%@mld|@f``cgqVbb2@{L_7wuRy zn&_BVlsLGUu{dw>4T_ z@L5S&Cj}~k3_;H_-DP>p280&EBB6A-+wvXD$3-EcgV|8_;_MDF4KXg)B&L!dB*QtL zIW;*Sb7OLk=PBn2@~*8gU$JS$)BJ$^pI4$+a#nU1=ohRj7+%F(wSP6VI(c>X8pAb( zYev@wuB~53T$i!#xAnH`%htc!5WAtXP^WNh;m8kxKQt976p4z4Ho9-z`y=|tv>*F6 zIc%!h^sSg%e5J&;q@v_YDW~+xPj)|5{xr2YWpm#ar!9N7Vz&ym4sP?>R$r!EmR~lq zeZls&a(a1j`MVuUcU-QRTd{X1ai?Ubv~qrBN0m|4)~YYn{Oa2^J~b`7w0CXV^@C^*d0*PTJNpCox7C`|Rvf?{$T{$&E~c*cXP2KF4r(1NIr#OE;E=RF zqQ0lWxuKy^yKzes+$3olJDhm9|A^m_j%KUo{Vi%OB}c(g$ggYEaX`CahK!G zCyY<*YNfUow?SX6kJI z*@-S;*UNLM=SI4hcHciAcm7t-!k)ehAr~%P47hl{m)U#vlEl(!+{J+K*~~H~YOs>Lfiq>^FSvapdFsBb<>Je`Nph zWwh`K8lfedH;27JZ^mSwdnQK zo6@(MZx6kj`>uN;eB#mjtoM^2ia%<8tpDWlsrPg2=ckjoUvOV4znXpR{1)=@15kx917Ye~0A$t;v1YJ?gZw}g*~m_Du%8Bqtc6&UuBoXvQvl$S0QlNBH8oi| zHTAUu@jCASI2$_Svt`j}5prVCyzM=&^uJjvQ~o*r13S6&?3l9ORA>e5 zTYGd9RT{rDlQhk%NlMdq($bbf0p-m~VR;l55LgkE1z%_7$nsc3LEZJR>h3D%@N@z7 zh#bXLeCvS~p`t|vq(@*u7LWpc)23>uYeQ9YUD7JZ_b@^OoV%2gkQH#A)WbD{JPV zb~CcJ>eesGa9jJ((_5z6|GC(Ukq;vwfk-0KUV#dY5CvDnDy(T5BX9R1fFLqOXqXQn zkcH+&QlMc_A~b#@gZ;LmfZiIVNgcnLn>%YEB}wqL8p`+X$f`T%A*lL0XV~Rxt?q(W zf60M~x`L@~iJH{r%B-5xHleg>D_WR2d=&0zuRQdz;^YApa$g%%*qWRtuP-ZT_+OlVh+>Rd#j57K zahh3+lv%mhI%>M&Ll2xaUdrp^RG?go;ZpisY zL`L*a6nikyIB8M#b8n!8MBXpyI z1^L1iLQNj80t7Z(t5`O5h)oBy4O7I9Bl7V@pl(0&o#g46Y(SNZ)Y-2cjxQL4F(yb7 z-ohO<)|fuqHQ12s*+nQ`sP2{7KHQNsmLyXv${8hek10jqHZY$F`f?)2@ z=Wbd*KPU5<9eC0`94^oS7`A{;PytDw)zt9NsDXAvH6hFUN{?g;M!lom_WSe%pQ}=& z&fHTf88{e}7(Nd%)L~ZaHVFKyTb~|Uyc0%x+mdIKS8qh!Uc%)O>iF?{`%`n$Xl{Ho zr4CNpeGDa~@hxIixT@V+y`m^jcbJ|)C8sonIkIBU@LS`3F5?xvxsm3f6pD_#un z4Yl~xSNQU2Sf8*Kq@#bU`1?Cfn#mUyBuw3Y5GST^#@$``Vky3GBCx8FCgkq^wne18 z9)z24`T=6qQ#+AB$oX*CO&cDwOqH6a%Ji>4e-p>-E1$lqYQbR3L_x#MWb@ab@bZfB zMNR1ie3d86`FDxNOy#StWBXfXrC6tk^(&?^3y;v!K?nzLcn6U%j{^3%{k^TW#Y4Q$ z%yF-ncx~|r)Wzio@zjO7?9m`%p1Bld`m>h4x^}MCy=t=O@oC2SS*YS1XIrKet=q}b zkv;kfG1lbAkDkK$!npF;CF*b9O{85(v@`9qExJ7$Z`KTt+q8U2zPUP)!djPEuxY99 z+GS2&Af#q23Dd=tAa3?Uh~Q=@Z~2epKOabSni2`G=IV+1RWpz$WbfCcy^~DOVU1YM z9E*GFZ%V=kYl(OgY;$j>?Pv8uJv5En-tJ&~XlHLw;dp-o%PQ z6WO~+mJkrmAKfw_D==4^n^ozW#|5aN(;ANDq^+UF<^wnzKI_7047e8VV)88TQKXo8vE{6!%2vT4-M2z$a} zC5(eSu5eC-^=2K(%%+hQ7?&1fWTK2zU!xd1JK#HmA-HFc9N&fokQsURo$>M{g_>DQ zfeb{ke|5pi-?88!`r@JBW#)h}lVHiggu!N_yksx;XCYQo7Z`)jPWpG;7Hqz zdG+VI=TJtr$I@4bQTS2)=uKn;WZ3#h8G! z0_mRT0Kx1^6dH(LwX;p;vLV{XWg(F`q4s>1?n1CI&{j&^Bu~w@)KNimK$y(+)$pNu zy+jY3t7p9pRh$e(WpDYkX5hGXny~l?cY6h-Ny{FRJ)I8riJb&cB<~0 z!O8o4uHwD0q7GIkyE-p@{3g$l7u{DeYb7jZZ9bw#mZsQVOi1MXTOe@hLAs5bqbO~@ zcl|pCk;+Lk$inBWPah_D`)p2eU2bumdG=#+z|AwzOc-JUA(qI21EY_-6NK*GT3 z;k)h*;X@LH)Fw?pVkv`5x4h-d(YUoU43un8Nh6ZT8D^)geO|g%D9QS~8p*lEKf{Mi z<#G^;q~QH7@ULupX4s(}`uR_0tb3WAKN;gLCsB79TTO%}A7$ilfWqU%0pI!s4f6Et zFRGD99N<@7z(zd*ZOa=0n@pC^xO-$cYPuE>yD8P@C`Kr&?5O#`+aX?*NnC>fz83Ghw)@2mTg;Zd}~7paJ&#rTTg#i{mA&N+Oxoe ziMOEa$dy&Ik;%Y|gb+51Y1i}8?JHqyhVXA%>4!wY+V8@sL6xn3cwNGX39x7Nwwo*V zY|XlIyaQ9R)tjUlS+#q&53Kls+;Wgl6qna7NNlRYa~{nooX%`>ZEY1FzMgpI%izPz zdWA;4@p;qbra7 ztO}>u{Qxbn#CNPoAfp6AwbKGNSzj;`VVi5F#H#%@NU3HaHmseOd7&iO4$v@hvEj$6 zguM-`x-o)_IW8qI94r6ggZX|)6u~V6AjBkd@%X}9U;@53DnF|dEDX9lzPb^!QjeI_ zM@;DbONPmd+vRFFs&-+bN|qtm`~{Ji!YSI!^u^L(BP$2;-kkl^(X*w2O-99pqb4`ZwkbecIjWZHF(bO%uSzQpO5IUVuDZv{S-i8+_3jw z8aM*(o%!B0r8lw>e9hjNySXgWWmw+(3t-_VBYMJtsqXM6Arl>ZB*g#(2N!&Szqt6} zOXdC@z5INdhAx0KoqxV4bl!q@M}WJ2W0TMPmjue0hb_Nn0E(xMB7`D1 z`5-#mQTdOZCrhMG>+O*q{B31UIb#3UBY;L!s9!ZvM5PC}z0nxNQU63Sh+_~(9f7Dj oh(&P>;;17KbqBF1jylBu2PR0M>f)=ll>h($07*qoM6N<$g4-{>H~;_u diff --git a/tests/test.html b/tests/test.html deleted file mode 100755 index 66391d2..0000000 --- a/tests/test.html +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - Readme File Tests - - - - - - - - - -
    - App Services (Usergrid) Javascript SDK -
    -
    - This sample application runs tests on the sample code examples in the readme file. Tests are run against App Services (Usergrid) using the Usergrid Javascript SDK. -
    -
    -
    README sample code tests
    -
    -
    -
    - -   -
    -
    -
    -
    Test Output
    -
    -
    // Press Start button to begin
    -
    - - diff --git a/tests/test.js b/tests/test.js deleted file mode 100755 index 6a9e5b8..0000000 --- a/tests/test.js +++ /dev/null @@ -1,871 +0,0 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to You under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -/** -* Test suite for all the examples in the readme -* -* NOTE: No, this test suite doesn't use the traditional format for -* a test suite. This is because the goal is to require as little -* alteration as possible during the copy / paste operation from this test -* suite to the readme file. -* -* @author rod simpson (rod@apigee.com) -*/ - -$(document).ready(function () { - -//call the runner function to start the process -$('#start-button').bind('click', function() { - $('#start-button').attr("disabled", "disabled"); - $('#test-output').html(''); - runner(0); -}); - -var logSuccess = true; -var successCount = 0; -var logError = true; -var errorCount = 0; -var logNotice = true; -var _username = 'marty2'; -var _email = 'marty2@timetravel.com'; -var _password = 'password2'; -var _newpassword = 'password3'; - -var client = new Usergrid.Client({ - orgId:'rwalsh', - appId:'sandbox', - logging: true, //optional - turn on logging, off by default - buildCurl: true //optional - turn on curl commands, off by default -}); - -client.logout(); - -function runner(step, arg, arg2){ - step++; - switch(step) - { - case 1: - notice('-----running step '+step+': DELETE user from DB to prep test'); - clearUser(step); - break; - case 2: - notice('-----running step '+step+': GET test'); - testGET(step); - break; - case 3: - notice('-----running step '+step+': POST test'); - testPOST(step); - break; - case 4: - notice('-----running step '+step+': PUT test'); - testPUT(step); - break; - case 5: - notice('-----running step '+step+': DELETE test'); - testDELETE(step); - break; - case 6: - notice('-----running step '+step+': prepare database - remove all dogs (no real dogs harmed here!!)'); - cleanupAllDogs(step); - break; - case 7: - notice('-----running step '+step+': make a new dog'); - makeNewDog(step); - break; - case 8: - notice('-----running step '+step+': update our dog'); - updateDog(step, arg); - break; - case 9: - notice('-----running step '+step+': refresh our dog'); - refreshDog(step, arg); - break; - case 10: - notice('-----running step '+step+': remove our dog from database (no real dogs harmed here!!)'); - removeDogFromDatabase(step, arg); - break; - case 11: - notice('-----running step '+step+': make lots of dogs!'); - makeSampleData(step, arg); - break; - case 12: - notice('-----running step '+step+': make a dogs collection and show each dog'); - testDogsCollection(step); - break; - case 13: - notice('-----running step '+step+': get the next page of the dogs collection and show each dog'); - getNextDogsPage(step, arg); - break; - case 14: - notice('-----running step '+step+': get the previous page of the dogs collection and show each dog'); - getPreviousDogsPage(step, arg); - break; - case 15: - notice('-----running step '+step+': remove all dogs from the database (no real dogs harmed here!!)'); - cleanupAllDogs(step); - break; - case 16: - notice('-----running step '+step+': prepare database (remove existing user if present)'); - prepareDatabaseForNewUser(step); - break; - case 17: - notice('-----running step '+step+': create a new user'); - createUser(step); - break; - case 18: - notice('-----running step '+step+': update the user'); - updateUser(step, arg); - break; - case 19: - notice('-----running step '+step+': get the existing user'); - getExistingUser(step, arg); - break; - case 20: - notice('-----running step '+step+': refresh the user from the database'); - refreshUser(step, arg); - break; - case 21: - notice('-----running step '+step+': log user in'); - loginUser(step, arg); - break; - case 22: - notice('-----running step '+step+': change users password'); - changeUsersPassword(step, arg); - break; - case 23: - notice('-----running step '+step+': log user out'); - logoutUser(step, arg); - break; - case 24: - notice('-----running step '+step+': relogin user'); - reloginUser(step, arg); - break; - case 25: - notice('-----running step '+step+': logged in user creates dog'); - createDog(step, arg); - break; - case 26: - notice('-----running step '+step+': logged in user likes dog'); - userLikesDog(step, arg, arg2); - break; - case 27: - notice('-----running step '+step+': logged in user removes likes connection to dog'); - removeUserLikesDog(step, arg, arg2); - break; - case 28: - notice('-----running step '+step+': user removes dog'); - removeDog(step, arg, arg2); - break; - case 29: - notice('-----running step '+step+': log the user out'); - logoutUser(step, arg); - break; - case 30: - notice('-----running step '+step+': remove the user from the database'); - destroyUser(step, arg); - break; - case 31: - notice('-----running step '+step+': try to create new entity with no name'); - createNewEntityNoName(step, arg); - break; - default: - notice('-----test complete!-----'); - notice('Success count= ' + successCount); - notice('Error count= ' + errorCount); - notice('-----thank you for playing!-----'); - $('#start-button').removeAttr("disabled"); - } -} - -//logging functions -function success(message){ - successCount++; - if (logSuccess) { - console.log('SUCCESS: ' + message); - var html = $('#test-output').html(); - html += ('SUCCESS: ' + message + '\r\n'); - $('#test-output').html(html); - } -} - -function error(message){ - errorCount++ - if (logError) { - console.log('ERROR: ' + message); - var html = $('#test-output').html(); - html += ('ERROR: ' + message + '\r\n'); - $('#test-output').html(html); - } -} - -function notice(message){ - if (logNotice) { - console.log('NOTICE: ' + message); - var html = $('#test-output').html(); - html += (message + '\r\n'); - $('#test-output').html(html); - } -} - -//tests -function clearUser(step) { - var options = { - method:'DELETE', - endpoint:'users/fred' - }; - client.request(options, function (err, data) { - //data will contain raw results from API call - success('User cleared from DB'); - runner(step); - }); -} - -function testGET(step) { - var options = { - method:'GET', - endpoint:'users' - }; - client.request(options, function (err, data) { - if (err) { - error('GET failed'); - } else { - //data will contain raw results from API call - success('GET worked'); - runner(step); - } - }); -} - -function testPOST(step) { - var options = { - method:'POST', - endpoint:'users', - body:{ username:'fred', password:'secret' } - }; - client.request(options, function (err, data) { - if (err) { - error('POST failed'); - } else { - //data will contain raw results from API call - success('POST worked'); - runner(step); - } - }); -} - -function testPUT(step) { - var options = { - method:'PUT', - endpoint:'users/fred', - body:{ newkey:'newvalue' } - }; - client.request(options, function (err, data) { - if (err) { - error('PUT failed'); - } else { - //data will contain raw results from API call - success('PUT worked'); - runner(step); - } - }); -} - -function testDELETE(step) { - var options = { - method:'DELETE', - endpoint:'users/fred' - }; - client.request(options, function (err, data) { - if (err) { - error('DELETE failed'); - } else { - //data will contain raw results from API call - success('DELETE worked'); - runner(step); - } - }); -} - -function makeNewDog(step) { - - var options = { - type:'dogs', - name:'Rocky' - } - - client.createEntity(options, function (err, response, dog) { - if (err) { - error('dog not created'); - } else { - success('dog is created'); - - //once the dog is created, you can set single properties: - dog.set('breed','Dinosaur'); - - //the set function can also take a JSON object: - var data = { - master:'Fred', - state:'hungry' - } - //set is additive, so previously set properties are not overwritten - dog.set(data); - - //finally, call save on the object to save it back to the database - dog.save(function(err){ - if (err){ - error('dog not saved'); - runner(step, dog); - } else { - success('new dog is saved'); - runner(step, dog); - } - }); - } - }); - -} - -function updateDog(step, dog) { - - //change a property in the object - dog.set("state", "fed"); - //and save back to the database - dog.save(function(err){ - if (err){ - error('dog not saved'); - } else { - success('dog is saved'); - runner(step, dog); - } - }); - -} - -function refreshDog(step, dog){ - - //call fetch to refresh the data from the server - dog.fetch(function(err){ - if (err){ - error('dog not refreshed from database'); - } else { - //dog has been refreshed from the database - //will only work if the UUID for the entity is in the dog object - success('dog entity refreshed from database'); - runner(step, dog); - } - }); - -} - -function removeDogFromDatabase(step, dog){ - - //the destroy method will delete the entity from the database - dog.destroy(function(err){ - if (err){ - error('dog not removed from database'); - } else { - success('dog removed from database'); // no real dogs were harmed! - dog = null; //no real dogs were harmed! - runner(step, 1); - } - }); - -} - -function makeSampleData(step, i) { - notice('making dog '+i); - - var options = { - type:'dogs', - name:'dog'+i, - index:i - } - - client.createEntity(options, function (err, dog) { - if (err) { - error('dog ' + i + ' not created'); - } else { - if (i >= 30) { - //data made, ready to go - success('all dogs made'); - runner(step); - } else { - success('dog ' + i + ' made'); - //keep making dogs - makeSampleData(step, ++i); - } - } - }); -} - -function testDogsCollection(step) { - - var options = { - type:'dogs', - qs:{ql:'order by index'} - } - - client.createCollection(options, function (err, data, dogs) { - if (err) { - error('could not make collection'); - } else { - - success('new Collection created'); - - //we got the dogs, now display the Entities: - while(dogs.hasNextEntity()) { - //get a reference to the dog - dog = dogs.getNextEntity(); - var name = dog.get('name'); - notice('dog is called ' + name); - } - - success('looped through dogs'); - - //create a new dog and add it to the collection - var options = { - name:'extra-dog', - fur:'shedding' - } - //just pass the options to the addEntity method - //to the collection and it is saved automatically - dogs.addEntity(options, function(err, dog, data) { - if (err) { - error('extra dog not saved or added to collection'); - } else { - success('extra dog saved and added to collection'); - runner(step, dogs); - } - }); - } - }); - -} - -function getNextDogsPage(step, dogs) { - - if (dogs.hasNextPage()) { - //there is a next page, so get it from the server - dogs.getNextPage(function(err){ - if (err) { - error('could not get next page of dogs'); - } else { - success('got next page of dogs'); - //we got the next page of data, so do something with it: - var i = 11; - while(dogs.hasNextEntity()) { - //get a reference to the dog - var dog = dogs.getNextEntity(); - var index = dog.get('index'); - if(i !== index) { - error('wrong dog loaded: wanted' + i + ', got ' + index); - } - notice('got dog ' + i); - i++ - } - success('looped through dogs') - runner(step, dogs); - } - }); - } else { - getPreviousDogsPage(dogs); - } - -} - -function getPreviousDogsPage(step, dogs) { - - if (dogs.hasPreviousPage()) { - //there is a previous page, so get it from the server - dogs.getPreviousPage(function(err){ - if(err) { - error('could not get previous page of dogs'); - } else { - success('got next page of dogs'); - //we got the previous page of data, so do something with it: - var i = 1; - while(dogs.hasNextEntity()) { - //get a reference to the dog - var dog = dogs.getNextEntity(); - var index = dog.get('index'); - if(i !== index) { - error('wrong dog loaded: wanted' + i + ', got ' + index); - } - notice('got dog ' + i); - i++ - } - success('looped through dogs'); - runner(step); - } - }); - } else { - getAllDogs(); - } -} - -function cleanupAllDogs(step){ - - var options = { - type:'dogs', - qs:{limit:50} //limit statement set to 50 - } - - client.createCollection(options, function (err, response, dogs) { - if (err) { - error('could not get all dogs'); - } else { - success('got at most 50 dogs'); - //we got 50 dogs, now display the Entities: - - do { - while(dogs.hasNextEntity()) { - //get a reference to the dog - var dog = dogs.getNextEntity(); - var name = dog.get('name'); - notice('dog is called ' + name); - } - success('Poop'); - dogs.resetEntityPointer(); - //do doggy cleanup - - while(dogs.hasNextEntity()) { - //get a reference to the dog - var dog = dogs.getNextEntity(); - var dogname = dog.get('name'); - notice('removing dog ' + dogname + ' from database'); - dog.destroy(function(err, data) { - if (err) { - error('dog not removed'); - } else { - success('dog removed'); - } - }); - } - if( !dogs.hasNextPage() ) { - break; - } else { - dogs.getNextPage(function(err,data) {}); - } - } while(true) - - - //no need to wait around for dogs to be removed, so go on to next test - } - runner(step); - }); -} - - -function prepareDatabaseForNewUser(step) { - var options = { - method:'DELETE', - endpoint:'users/'+_username - }; - client.request(options, function (err, data) { - if (err) { - notice('database ready - no user to delete'); - runner(step); - } else { - //data will contain raw results from API call - success('database ready - user deleted worked'); - runner(step); - } - }); -} - - -function createUser(step) { - client.signup(_username, _password, _email, 'Marty McFly', - function (err, response, marty) { - if (err){ - error('user not created'); - runner(step, marty); - } else { - success('user created'); - runner(step, marty); - } - } - ); -} - -function updateUser(step, marty) { - - //add properties cumulatively - marty.set('state', 'California'); - marty.set("girlfriend","Jennifer"); - marty.save(function(err){ - if (err){ - error('user not updated'); - } else { - success('user updated'); - runner(step, marty); - } - }); - -} - -function getExistingUser(step, marty) { - - var options = { - type:'users', - username:_username - } - client.getEntity(options, function(err, response, existingUser){ - if (err){ - error('existing user not retrieved'); - } else { - success('existing user was retrieved'); - - var username = existingUser.get('username'); - if (username === _username){ - success('got existing user username'); - } else { - error('could not get existing user username'); - } - runner(step, marty); - } - }); - -} - - -function refreshUser(step, marty) { - - marty.fetch(function(err){ - if (err){ - error('not refreshed'); - } else { - success('user refreshed'); - runner(step, marty); - } - }); - -} - -function loginUser(step, marty) { - username = _username; - password = _password; - client.login(username, password, - function (err) { - if (err) { - error('could not log user in'); - } else { - success('user has been logged in'); - - //the login call will return an OAuth token, which is saved - //in the client. Any calls made now will use the token. - //once a user has logged in, their user object is stored - //in the client and you can access it this way: - var token = client.token; - - //Then make calls against the API. For example, you can - //get the user entity this way: - client.getLoggedInUser(function(err, data, user) { - if(err) { - error('could not get logged in user'); - } else { - success('got logged in user'); - - //you can then get info from the user entity object: - var username = user.get('username'); - notice('logged in user was: ' + username); - - runner(step, user); - } - }); - - } - } - ); -} - -function changeUsersPassword(step, marty) { - marty.changePassword(_password, _newpassword, function(err){ - if (err){ - error('user password not updated'); - } else { - success('user password updated'); - runner(step, marty); - } - }); - -} - -function logoutUser(step, marty) { - - //to log the user out, call the logout() method - client.logout(); - - //verify the logout worked - if (client.isLoggedIn()) { - error('logout failed'); - } else { - success('user has been logged out'); - } - - runner(step, marty); -} - -function reloginUser(step, marty) { - - username = _username - password = _newpassword; - client.login(_username, _newpassword, - function (err) { - if (err) { - error('could not relog user in'); - } else { - success('user has been re-logged in'); - runner(step, marty); - } - } - ); -} - - - -//TODO: currently, this code assumes permissions have been set to support user actions. need to add code to show how to add new role and permission programatically -// -//first create a new permission on the default role: -//POST "https://api.usergrid.com/yourorgname/yourappname/roles/default/permissions" -d '{"permission":"get,post,put,delete:/dogs/**"}' -//then after user actions, delete the permission on the default role: -//DELETE "https://api.usergrid.com/yourorgname/yourappname/roles/default/permissions?permission=get%2Cpost%2Cput%2Cdelete%3A%2Fdogs%2F**" - - -function createDog(step, marty) { - - var options = { - type:'dogs', - name:'einstein', - breed:'mutt' - } - - client.createEntity(options, function (err, response, dog) { - if (err) { - error('POST new dog by logged in user failed'); - } else { - success('POST new dog by logged in user succeeded'); - runner(step, marty, dog); - } - }); - -} - -function userLikesDog(step, marty, dog) { - - marty.connect('likes', dog, function (err, response, data) { - if (err) { - error('connection not created'); - runner(step, marty); - } else { - - //call succeeded, so pull the connections back down - marty.getConnections('likes', function (err, data) { - if (err) { - error('could not get connections'); - } else { - //verify that connection exists - if (marty.likes.einstein) { - success('connection exists'); - } else { - error('connection does not exist'); - } - - runner(step, marty, dog); - } - }); - } - }); - -} - -function removeUserLikesDog(step, marty, dog) { - - marty.disconnect('likes', dog, function (err, response, data) { - if (err) { - error('connection not deleted'); - runner(step, marty); - } else { - - //call succeeded, so pull the connections back down - marty.getConnections('likes', function (err, response, data) { - if (err) { - error('error getting connections'); - } else { - //verify that connection exists - if (marty.likes.einstein) { - error('connection still exists'); - } else { - success('connection deleted'); - } - - runner(step, marty, dog); - } - }); - } - }); - -} - -function removeDog(step, marty, dog) { - - //now delete the dog from the database - dog.destroy(function(err, data) { - if (err) { - error('dog not removed'); - } else { - success('dog removed'); - } - }); - runner(step, marty); -} - -function destroyUser(step, marty) { - - marty.destroy(function (err) { - if (err) { - error('user not deleted from database'); - } else { - success('user deleted from database'); - marty = null; //blow away the local object - runner(step); - } - }); - -} - -function createNewEntityNoName(step, marty) { - - var options = { - type:"something", - othervalue:"something else" - } - - client.createEntity(options, function (err, response, entity) { - if (err) { - error('Create new entity with no name failed'); - } else { - success('Create new entity with no name succeeded'); - - entity.destroy(); - runner(step); - } - }); - -} - -}); \ No newline at end of file diff --git a/usergrid.js b/usergrid.js index f28d2fc..46bad91 100644 --- a/usergrid.js +++ b/usergrid.js @@ -17,7 +17,7 @@ *under the License. * * - * usergrid@0.11.0 2016-10-09 + * usergrid@2.0.0 2016-10-09 */ (function(global) { var name = "Promise", overwrittenName = global[name], exports; @@ -6018,7 +6018,9 @@ var UsergridQuery = function(type) { if (queryString !== undefined) { return queryString; } else { - return "select *" + (query.length > 0 || sort !== undefined ? " where " + (query || "") + (sort || "") : ""); + var qL = "select * " + (query.length > 0 ? "where " + (query || "") : ""); + qL += sort !== undefined ? sort : ""; + return qL; } } }); @@ -6554,7 +6556,7 @@ UsergridResponse.prototype = { var client = UsergridHelpers.validateAndRetrieveClient(args); var type = _.last(_.get(self, "responseJSON.path").split("/")); var limit = _.first(_.get(this, "responseJSON.params.limit")); - var query = new UsergridQuery(type).cursor(this.responseJSON.cursor).limit(limit); + var query = new UsergridQuery(type).fromString(_.get(self,'responseJSON.params.ql.0')).cursor(this.responseJSON.cursor).limit(limit); return client.GET(query, callback); } }; diff --git a/usergrid.min.js b/usergrid.min.js index 7a516f9..1d0bac7 100644 --- a/usergrid.min.js +++ b/usergrid.min.js @@ -17,11 +17,11 @@ *under the License. * * - * usergrid@0.11.0 2016-10-09 + * usergrid@2.0.0 2016-10-09 */ "use strict";!function(global){function Promise(){this.complete=!1,this.result=null,this.callbacks=[]}var name="Promise",overwrittenName=global[name];return Promise.prototype.then=function(callback,context){var f=function(){return callback.apply(context,arguments)};this.complete?f(this.result):this.callbacks.push(f)},Promise.prototype.done=function(result){if(this.complete=!0,this.result=result,this.callbacks){for(var i=0;ii;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,result){var p=new Promise;return null===promises||0===promises.length?p.done(result):promises[0](result).then(function(res){promises.splice(0,1),promises?Promise.chain(promises,res).then(function(r){p.done(r)}):p.done(res)}),p},global[name]=Promise,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Promise},global[name]}(this),function(){function addMapEntry(map,pair){return map.set(pair[0],pair[1]),map}function addSetEntry(set,value){return set.add(value),set}function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}function arrayAggregator(array,setter,iteratee,accumulator){for(var index=-1,length=array?array.length:0;++index-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1;);return index}function charsEndIndex(strSymbols,chrSymbols){for(var index=strSymbols.length;index--&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1;);return index}function countHolders(array,placeholder){for(var length=array.length,result=0;length--;)array[length]===placeholder&&++result;return result}function escapeStringChar(chr){return"\\"+stringEscapes[chr]}function getValue(object,key){return null==object?undefined:object[key]}function hasUnicode(string){return reHasUnicode.test(string)}function hasUnicodeWord(string){return reHasUnicodeWord.test(string)}function iteratorToArray(iterator){for(var data,result=[];!(data=iterator.next()).done;)result.push(data.value);return result}function mapToArray(map){var index=-1,result=Array(map.size);return map.forEach(function(value,key){result[++index]=[key,value]}),result}function overArg(func,transform){return function(arg){return func(transform(arg))}}function replaceHolders(array,placeholder){for(var index=-1,length=array.length,resIndex=0,result=[];++indexdir,arrLength=isArr?array.length:0,view=getView(0,arrLength,this.__views__),start=view.start,end=view.end,length=end-start,index=isRight?end:start-1,iteratees=this.__iteratees__,iterLength=iteratees.length,resIndex=0,takeCount=nativeMin(length,this.__takeCount__);if(!isArr||LARGE_ARRAY_SIZE>arrLength||arrLength==length&&takeCount==length)return baseWrapperValue(array,this.__actions__);var result=[];outer:for(;length--&&takeCount>resIndex;){index+=dir;for(var iterIndex=-1,value=array[index];++iterIndexindex)return!1;var lastIndex=data.length-1;return index==lastIndex?data.pop():splice.call(data,index,1),--this.size,!0}function listCacheGet(key){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?undefined:data[index][1]}function listCacheHas(key){return assocIndexOf(this.__data__,key)>-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?(++this.size,data.push([key,value])):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index=number?number:upper),lower!==undefined&&(number=number>=lower?number:lower)),number}function baseClone(value,isDeep,isFull,customizer,key,object,stack){var result;if(customizer&&(result=object?customizer(value,key,object,stack):customizer(value)),result!==undefined)return result;if(!isObject(value))return value;var isArr=isArray(value);if(isArr){if(result=initCloneArray(value),!isDeep)return copyArray(value,result)}else{var tag=getTag(value),isFunc=tag==funcTag||tag==genTag;if(isBuffer(value))return cloneBuffer(value,isDeep);if(tag==objectTag||tag==argsTag||isFunc&&!object){if(result=initCloneObject(isFunc?{}:value),!isDeep)return copySymbols(value,baseAssign(result,value))}else{if(!cloneableTags[tag])return object?value:{};result=initCloneByTag(value,tag,baseClone,isDeep)}}stack||(stack=new Stack);var stacked=stack.get(value);if(stacked)return stacked;if(stack.set(value,result),!isArr)var props=isFull?getAllKeys(value):keys(value);return arrayEach(props||value,function(subValue,key){props&&(key=subValue,subValue=value[key]),assignValue(result,key,baseClone(subValue,isDeep,isFull,customizer,key,value,stack))}),result}function baseConforms(source){var props=keys(source);return function(object){return baseConformsTo(object,source,props)}}function baseConformsTo(object,source,props){var length=props.length;if(null==object)return!length;for(object=Object(object);length--;){var key=props[length],predicate=source[key],value=object[key];if(value===undefined&&!(key in object)||!predicate(value))return!1}return!0}function baseCreate(proto){return isObject(proto)?objectCreate(proto):{}}function baseDelay(func,wait,args){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return setTimeout(function(){func.apply(undefined,args)},wait)}function baseDifference(array,values,iteratee,comparator){var index=-1,includes=arrayIncludes,isCommon=!0,length=array.length,result=[],valuesLength=values.length;if(!length)return result;iteratee&&(values=arrayMap(values,baseUnary(iteratee))),comparator?(includes=arrayIncludesWith,isCommon=!1):values.length>=LARGE_ARRAY_SIZE&&(includes=cacheHas,isCommon=!1,values=new SetCache(values));outer:for(;++indexstart&&(start=-start>length?0:length+start),end=end===undefined||end>length?length:toInteger(end),0>end&&(end+=length),end=start>end?0:toLength(end);end>start;)array[start++]=value;return array}function baseFilter(collection,predicate){var result=[];return baseEach(collection,function(value,index,collection){predicate(value,index,collection)&&result.push(value)}),result}function baseFlatten(array,depth,predicate,isStrict,result){var index=-1,length=array.length;for(predicate||(predicate=isFlattenable),result||(result=[]);++index0&&predicate(value)?depth>1?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}function baseForOwn(object,iteratee){return object&&baseFor(object,iteratee,keys)}function baseForOwnRight(object,iteratee){return object&&baseForRight(object,iteratee,keys)}function baseFunctions(object,props){return arrayFilter(props,function(key){return isFunction(object[key])})}function baseGet(object,path){path=isKey(path,object)?[path]:castPath(path);for(var index=0,length=path.length;null!=object&&length>index;)object=object[toKey(path[index++])];return index&&index==length?object:undefined}function baseGetAllKeys(object,keysFunc,symbolsFunc){var result=keysFunc(object);return isArray(object)?result:arrayPush(result,symbolsFunc(object))}function baseGetTag(value){return objectToString.call(value)}function baseGt(value,other){return value>other}function baseHas(object,key){return null!=object&&hasOwnProperty.call(object,key)}function baseHasIn(object,key){return null!=object&&key in Object(object)}function baseInRange(number,start,end){return number>=nativeMin(start,end)&&number=120&&array.length>=120)?new SetCache(othIndex&&array):undefined}array=arrays[0];var index=-1,seen=caches[0];outer:for(;++indexvalue}function baseMap(collection,iteratee){var index=-1,result=isArrayLike(collection)?Array(collection.length):[];return baseEach(collection,function(value,key,collection){result[++index]=iteratee(value,key,collection)}),result}function baseMatches(source){var matchData=getMatchData(source);return 1==matchData.length&&matchData[0][2]?matchesStrictComparable(matchData[0][0],matchData[0][1]):function(object){return object===source||baseIsMatch(object,source,matchData)}}function baseMatchesProperty(path,srcValue){return isKey(path)&&isStrictComparable(srcValue)?matchesStrictComparable(toKey(path),srcValue):function(object){var objValue=get(object,path);return objValue===undefined&&objValue===srcValue?hasIn(object,path):baseIsEqual(srcValue,objValue,undefined,UNORDERED_COMPARE_FLAG|PARTIAL_COMPARE_FLAG)}}function baseMerge(object,source,srcIndex,customizer,stack){if(object!==source){if(!isArray(source)&&!isTypedArray(source))var props=baseKeysIn(source);arrayEach(props||source,function(srcValue,key){if(props&&(key=srcValue,srcValue=source[key]),isObject(srcValue))stack||(stack=new Stack),baseMergeDeep(object,source,key,srcIndex,baseMerge,customizer,stack);else{var newValue=customizer?customizer(object[key],srcValue,key+"",object,source,stack):undefined;newValue===undefined&&(newValue=srcValue),assignMergeValue(object,key,newValue)}})}}function baseMergeDeep(object,source,key,srcIndex,mergeFunc,customizer,stack){var objValue=object[key],srcValue=source[key],stacked=stack.get(srcValue);if(stacked)return void assignMergeValue(object,key,stacked);var newValue=customizer?customizer(objValue,srcValue,key+"",object,source,stack):undefined,isCommon=newValue===undefined;isCommon&&(newValue=srcValue,isArray(srcValue)||isTypedArray(srcValue)?isArray(objValue)?newValue=objValue:isArrayLikeObject(objValue)?newValue=copyArray(objValue):(isCommon=!1,newValue=baseClone(srcValue,!0)):isPlainObject(srcValue)||isArguments(srcValue)?isArguments(objValue)?newValue=toPlainObject(objValue):!isObject(objValue)||srcIndex&&isFunction(objValue)?(isCommon=!1,newValue=baseClone(srcValue,!0)):newValue=objValue:isCommon=!1),isCommon&&(stack.set(srcValue,newValue),mergeFunc(newValue,srcValue,srcIndex,customizer,stack),stack["delete"](srcValue)),assignMergeValue(object,key,newValue)}function baseNth(array,n){var length=array.length;if(length)return n+=0>n?length:0,isIndex(n,length)?array[n]:undefined}function baseOrderBy(collection,iteratees,orders){var index=-1;iteratees=arrayMap(iteratees.length?iteratees:[identity],baseUnary(getIteratee()));var result=baseMap(collection,function(value,key,collection){var criteria=arrayMap(iteratees,function(iteratee){return iteratee(value)});return{criteria:criteria,index:++index,value:value}});return baseSortBy(result,function(object,other){return compareMultiple(object,other,orders)})}function basePick(object,props){return object=Object(object),basePickBy(object,props,function(value,key){return key in object})}function basePickBy(object,props,predicate){for(var index=-1,length=props.length,result={};++index-1;)seen!==array&&splice.call(seen,fromIndex,1),splice.call(array,fromIndex,1);return array}function basePullAt(array,indexes){for(var length=array?indexes.length:0,lastIndex=length-1;length--;){var index=indexes[length];if(length==lastIndex||index!==previous){var previous=index;if(isIndex(index))splice.call(array,index,1);else if(isKey(index,array))delete array[toKey(index)];else{var path=castPath(index),object=parent(array,path);null!=object&&delete object[toKey(last(path))]}}}return array}function baseRandom(lower,upper){return lower+nativeFloor(nativeRandom()*(upper-lower+1))}function baseRange(start,end,step,fromRight){for(var index=-1,length=nativeMax(nativeCeil((end-start)/(step||1)),0),result=Array(length);length--;)result[fromRight?length:++index]=start,start+=step;return result}function baseRepeat(string,n){var result="";if(!string||1>n||n>MAX_SAFE_INTEGER)return result;do n%2&&(result+=string),n=nativeFloor(n/2),n&&(string+=string);while(n);return result}function baseRest(func,start){return setToString(overRest(func,start,identity),func+"")}function baseSet(object,path,value,customizer){if(!isObject(object))return object;path=isKey(path,object)?[path]:castPath(path);for(var index=-1,length=path.length,lastIndex=length-1,nested=object;null!=nested&&++indexstart&&(start=-start>length?0:length+start),end=end>length?length:end,0>end&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index=high){for(;high>low;){var mid=low+high>>>1,computed=array[mid];null!==computed&&!isSymbol(computed)&&(retHighest?value>=computed:value>computed)?low=mid+1:high=mid}return high}return baseSortedIndexBy(array,value,identity,retHighest)}function baseSortedIndexBy(array,value,iteratee,retHighest){value=iteratee(value);for(var low=0,high=array?array.length:0,valIsNaN=value!==value,valIsNull=null===value,valIsSymbol=isSymbol(value),valIsUndefined=value===undefined;high>low;){var mid=nativeFloor((low+high)/2),computed=iteratee(array[mid]),othIsDefined=computed!==undefined,othIsNull=null===computed,othIsReflexive=computed===computed,othIsSymbol=isSymbol(computed);if(valIsNaN)var setLow=retHighest||othIsReflexive;else setLow=valIsUndefined?othIsReflexive&&(retHighest||othIsDefined):valIsNull?othIsReflexive&&othIsDefined&&(retHighest||!othIsNull):valIsSymbol?othIsReflexive&&othIsDefined&&!othIsNull&&(retHighest||!othIsSymbol):othIsNull||othIsSymbol?!1:retHighest?value>=computed:value>computed; setLow?low=mid+1:high=mid}return nativeMin(high,MAX_ARRAY_INDEX)}function baseSortedUniq(array,iteratee){for(var index=-1,length=array.length,resIndex=0,result=[];++index=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++indexindex?values[index]:undefined;assignFunc(result,props[index],value)}return result}function castArrayLikeObject(value){return isArrayLikeObject(value)?value:[]}function castFunction(value){return"function"==typeof value?value:identity}function castPath(value){return isArray(value)?value:stringToPath(value)}function castSlice(array,start,end){var length=array.length;return end=end===undefined?length:end,!start&&end>=length?array:baseSlice(array,start,end)}function cloneBuffer(buffer,isDeep){if(isDeep)return buffer.slice();var result=new buffer.constructor(buffer.length);return buffer.copy(result),result}function cloneArrayBuffer(arrayBuffer){var result=new arrayBuffer.constructor(arrayBuffer.byteLength);return new Uint8Array(result).set(new Uint8Array(arrayBuffer)),result}function cloneDataView(dataView,isDeep){var buffer=isDeep?cloneArrayBuffer(dataView.buffer):dataView.buffer;return new dataView.constructor(buffer,dataView.byteOffset,dataView.byteLength)}function cloneMap(map,isDeep,cloneFunc){var array=isDeep?cloneFunc(mapToArray(map),!0):mapToArray(map);return arrayReduce(array,addMapEntry,new map.constructor)}function cloneRegExp(regexp){var result=new regexp.constructor(regexp.source,reFlags.exec(regexp));return result.lastIndex=regexp.lastIndex,result}function cloneSet(set,isDeep,cloneFunc){var array=isDeep?cloneFunc(setToArray(set),!0):setToArray(set);return arrayReduce(array,addSetEntry,new set.constructor)}function cloneSymbol(symbol){return symbolValueOf?Object(symbolValueOf.call(symbol)):{}}function cloneTypedArray(typedArray,isDeep){var buffer=isDeep?cloneArrayBuffer(typedArray.buffer):typedArray.buffer;return new typedArray.constructor(buffer,typedArray.byteOffset,typedArray.length)}function compareAscending(value,other){if(value!==other){var valIsDefined=value!==undefined,valIsNull=null===value,valIsReflexive=value===value,valIsSymbol=isSymbol(value),othIsDefined=other!==undefined,othIsNull=null===other,othIsReflexive=other===other,othIsSymbol=isSymbol(other);if(!othIsNull&&!othIsSymbol&&!valIsSymbol&&value>other||valIsSymbol&&othIsDefined&&othIsReflexive&&!othIsNull&&!othIsSymbol||valIsNull&&othIsDefined&&othIsReflexive||!valIsDefined&&othIsReflexive||!valIsReflexive)return 1;if(!valIsNull&&!valIsSymbol&&!othIsSymbol&&other>value||othIsSymbol&&valIsDefined&&valIsReflexive&&!valIsNull&&!valIsSymbol||othIsNull&&valIsDefined&&valIsReflexive||!othIsDefined&&valIsReflexive||!othIsReflexive)return-1}return 0}function compareMultiple(object,other,orders){for(var index=-1,objCriteria=object.criteria,othCriteria=other.criteria,length=objCriteria.length,ordersLength=orders.length;++index=ordersLength)return result;var order=orders[index];return result*("desc"==order?-1:1)}}return object.index-other.index}function composeArgs(args,partials,holders,isCurried){for(var argsIndex=-1,argsLength=args.length,holdersLength=holders.length,leftIndex=-1,leftLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(leftLength+rangeLength),isUncurried=!isCurried;++leftIndexargsIndex)&&(result[holders[argsIndex]]=args[argsIndex]);for(;rangeLength--;)result[leftIndex++]=args[argsIndex++];return result}function composeArgsRight(args,partials,holders,isCurried){for(var argsIndex=-1,argsLength=args.length,holdersIndex=-1,holdersLength=holders.length,rightIndex=-1,rightLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(rangeLength+rightLength),isUncurried=!isCurried;++argsIndexargsIndex)&&(result[offset+holders[holdersIndex]]=args[argsIndex++]);return result}function copyArray(source,array){var index=-1,length=source.length;for(array||(array=Array(length));++index1?sources[length-1]:undefined,guard=length>2?sources[2]:undefined;for(customizer=assigner.length>3&&"function"==typeof customizer?(length--,customizer):undefined,guard&&isIterateeCall(sources[0],sources[1],guard)&&(customizer=3>length?undefined:customizer,length=1),object=Object(object);++indexlength&&args[0]!==placeholder&&args[length-1]!==placeholder?[]:replaceHolders(args,placeholder);if(length-=holders.length,arity>length)return createRecurry(func,bitmask,createHybrid,wrapper.placeholder,undefined,args,holders,undefined,undefined,arity-length);var fn=this&&this!==root&&this instanceof wrapper?Ctor:func;return apply(fn,this,args)}var Ctor=createCtor(func);return wrapper}function createFind(findIndexFunc){return function(collection,predicate,fromIndex){var iterable=Object(collection);if(!isArrayLike(collection)){var iteratee=getIteratee(predicate,3);collection=keys(collection),predicate=function(key){return iteratee(iterable[key],key,iterable)}}var index=findIndexFunc(collection,predicate,fromIndex);return index>-1?iterable[iteratee?collection[index]:index]:undefined}}function createFlow(fromRight){return flatRest(function(funcs){var length=funcs.length,index=length,prereq=LodashWrapper.prototype.thru;for(fromRight&&funcs.reverse();index--;){var func=funcs[index];if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);if(prereq&&!wrapper&&"wrapper"==getFuncName(func))var wrapper=new LodashWrapper([],!0)}for(index=wrapper?index:length;++index=LARGE_ARRAY_SIZE)return wrapper.plant(value).value();for(var index=0,result=length?funcs[index].apply(this,args):value;++indexlength){var newHolders=replaceHolders(args,placeholder);return createRecurry(func,bitmask,createHybrid,wrapper.placeholder,thisArg,args,newHolders,argPos,ary,arity-length)}var thisBinding=isBind?thisArg:this,fn=isBindKey?thisBinding[func]:func;return length=args.length,argPos?args=reorder(args,argPos):isFlip&&length>1&&args.reverse(),isAry&&length>ary&&(args.length=ary),this&&this!==root&&this instanceof wrapper&&(fn=Ctor||createCtor(fn)),fn.apply(thisBinding,args)}var isAry=bitmask&ARY_FLAG,isBind=bitmask&BIND_FLAG,isBindKey=bitmask&BIND_KEY_FLAG,isCurried=bitmask&(CURRY_FLAG|CURRY_RIGHT_FLAG),isFlip=bitmask&FLIP_FLAG,Ctor=isBindKey?undefined:createCtor(func);return wrapper}function createInverter(setter,toIteratee){return function(object,iteratee){return baseInverter(object,setter,toIteratee(iteratee),{})}}function createMathOperation(operator,defaultValue){return function(value,other){var result;if(value===undefined&&other===undefined)return defaultValue;if(value!==undefined&&(result=value),other!==undefined){if(result===undefined)return other;"string"==typeof value||"string"==typeof other?(value=baseToString(value),other=baseToString(other)):(value=baseToNumber(value),other=baseToNumber(other)),result=operator(value,other)}return result}}function createOver(arrayFunc){return flatRest(function(iteratees){return iteratees=arrayMap(iteratees,baseUnary(getIteratee())),baseRest(function(args){var thisArg=this;return arrayFunc(iteratees,function(iteratee){return apply(iteratee,thisArg,args)})})})}function createPadding(length,chars){chars=chars===undefined?" ":baseToString(chars);var charsLength=chars.length;if(2>charsLength)return charsLength?baseRepeat(chars,length):chars;var result=baseRepeat(chars,nativeCeil(length/stringSize(chars)));return hasUnicode(chars)?castSlice(stringToArray(result),0,length).join(""):result.slice(0,length)}function createPartial(func,bitmask,thisArg,partials){function wrapper(){for(var argsIndex=-1,argsLength=arguments.length,leftIndex=-1,leftLength=partials.length,args=Array(leftLength+argsLength),fn=this&&this!==root&&this instanceof wrapper?Ctor:func;++leftIndexstart?1:-1:toFinite(step),baseRange(start,end,step,fromRight)}}function createRelationalOperation(operator){return function(value,other){return("string"!=typeof value||"string"!=typeof other)&&(value=toNumber(value),other=toNumber(other)),operator(value,other)}}function createRecurry(func,bitmask,wrapFunc,placeholder,thisArg,partials,holders,argPos,ary,arity){var isCurry=bitmask&CURRY_FLAG,newHolders=isCurry?holders:undefined,newHoldersRight=isCurry?undefined:holders,newPartials=isCurry?partials:undefined,newPartialsRight=isCurry?undefined:partials;bitmask|=isCurry?PARTIAL_FLAG:PARTIAL_RIGHT_FLAG,bitmask&=~(isCurry?PARTIAL_RIGHT_FLAG:PARTIAL_FLAG),bitmask&CURRY_BOUND_FLAG||(bitmask&=~(BIND_FLAG|BIND_KEY_FLAG));var newData=[func,bitmask,thisArg,newPartials,newHolders,newPartialsRight,newHoldersRight,argPos,ary,arity],result=wrapFunc.apply(undefined,newData);return isLaziable(func)&&setData(result,newData),result.placeholder=placeholder,setWrapToString(result,func,bitmask)}function createRound(methodName){var func=Math[methodName];return function(number,precision){if(number=toNumber(number),precision=nativeMin(toInteger(precision),292)){var pair=(toString(number)+"e").split("e"),value=func(pair[0]+"e"+(+pair[1]+precision));return pair=(toString(value)+"e").split("e"),+(pair[0]+"e"+(+pair[1]-precision))}return func(number)}}function createToPairs(keysFunc){return function(object){var tag=getTag(object);return tag==mapTag?mapToArray(object):tag==setTag?setToPairs(object):baseToPairs(object,keysFunc(object))}}function createWrap(func,bitmask,thisArg,partials,holders,argPos,ary,arity){var isBindKey=bitmask&BIND_KEY_FLAG;if(!isBindKey&&"function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);var length=partials?partials.length:0;if(length||(bitmask&=~(PARTIAL_FLAG|PARTIAL_RIGHT_FLAG),partials=holders=undefined),ary=ary===undefined?ary:nativeMax(toInteger(ary),0),arity=arity===undefined?arity:toInteger(arity),length-=holders?holders.length:0,bitmask&PARTIAL_RIGHT_FLAG){var partialsRight=partials,holdersRight=holders;partials=holders=undefined}var data=isBindKey?undefined:getData(func),newData=[func,bitmask,thisArg,partials,holders,partialsRight,holdersRight,argPos,ary,arity];if(data&&mergeData(newData,data),func=newData[0],bitmask=newData[1],thisArg=newData[2],partials=newData[3],holders=newData[4],arity=newData[9]=null==newData[9]?isBindKey?0:func.length:nativeMax(newData[9]-length,0),!arity&&bitmask&(CURRY_FLAG|CURRY_RIGHT_FLAG)&&(bitmask&=~(CURRY_FLAG|CURRY_RIGHT_FLAG)),bitmask&&bitmask!=BIND_FLAG)result=bitmask==CURRY_FLAG||bitmask==CURRY_RIGHT_FLAG?createCurry(func,bitmask,arity):bitmask!=PARTIAL_FLAG&&bitmask!=(BIND_FLAG|PARTIAL_FLAG)||holders.length?createHybrid.apply(undefined,newData):createPartial(func,bitmask,thisArg,partials);else var result=createBind(func,bitmask,thisArg);var setter=data?baseSetData:setData;return setWrapToString(setter(result,newData),func,bitmask)}function equalArrays(array,other,equalFunc,customizer,bitmask,stack){var isPartial=bitmask&PARTIAL_COMPARE_FLAG,arrLength=array.length,othLength=other.length;if(arrLength!=othLength&&!(isPartial&&othLength>arrLength))return!1;var stacked=stack.get(array);if(stacked&&stack.get(other))return stacked==other;var index=-1,result=!0,seen=bitmask&UNORDERED_COMPARE_FLAG?new SetCache:undefined;for(stack.set(array,other),stack.set(other,array);++index1?"& ":"")+details[lastIndex],details=details.join(length>2?", ":" "),source.replace(reWrapComment,"{\n/* [wrapped with "+details+"] */\n")}function isFlattenable(value){return isArray(value)||isArguments(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol])}function isIndex(value,length){return length=null==length?MAX_SAFE_INTEGER:length,!!length&&("number"==typeof value||reIsUint.test(value))&&value>-1&&value%1==0&&length>value}function isIterateeCall(value,index,object){if(!isObject(object))return!1;var type=typeof index;return("number"==type?isArrayLike(object)&&isIndex(index,object.length):"string"==type&&index in object)?eq(object[index],value):!1}function isKey(value,object){if(isArray(value))return!1;var type=typeof value;return"number"==type||"symbol"==type||"boolean"==type||null==value||isSymbol(value)?!0:reIsPlainProp.test(value)||!reIsDeepProp.test(value)||null!=object&&value in Object(object)}function isKeyable(value){var type=typeof value;return"string"==type||"number"==type||"symbol"==type||"boolean"==type?"__proto__"!==value:null===value}function isLaziable(func){var funcName=getFuncName(func),other=lodash[funcName];if("function"!=typeof other||!(funcName in LazyWrapper.prototype))return!1;if(func===other)return!0;var data=getData(other);return!!data&&func===data[0]}function isMasked(func){return!!maskSrcKey&&maskSrcKey in func}function isPrototype(value){var Ctor=value&&value.constructor,proto="function"==typeof Ctor&&Ctor.prototype||objectProto;return value===proto}function isStrictComparable(value){return value===value&&!isObject(value)}function matchesStrictComparable(key,srcValue){return function(object){return null==object?!1:object[key]===srcValue&&(srcValue!==undefined||key in Object(object))}}function memoizeCapped(func){var result=memoize(func,function(key){return cache.size===MAX_MEMOIZE_SIZE&&cache.clear(),key}),cache=result.cache;return result}function mergeData(data,source){var bitmask=data[1],srcBitmask=source[1],newBitmask=bitmask|srcBitmask,isCommon=(BIND_FLAG|BIND_KEY_FLAG|ARY_FLAG)>newBitmask,isCombo=srcBitmask==ARY_FLAG&&bitmask==CURRY_FLAG||srcBitmask==ARY_FLAG&&bitmask==REARG_FLAG&&data[7].length<=source[8]||srcBitmask==(ARY_FLAG|REARG_FLAG)&&source[7].length<=source[8]&&bitmask==CURRY_FLAG;if(!isCommon&&!isCombo)return data;srcBitmask&BIND_FLAG&&(data[2]=source[2],newBitmask|=bitmask&BIND_FLAG?0:CURRY_BOUND_FLAG);var value=source[3];if(value){var partials=data[3];data[3]=partials?composeArgs(partials,value,source[4]):value,data[4]=partials?replaceHolders(data[3],PLACEHOLDER):source[4]}return value=source[5],value&&(partials=data[5],data[5]=partials?composeArgsRight(partials,value,source[6]):value,data[6]=partials?replaceHolders(data[5],PLACEHOLDER):source[6]),value=source[7],value&&(data[7]=value),srcBitmask&ARY_FLAG&&(data[8]=null==data[8]?source[8]:nativeMin(data[8],source[8])),null==data[9]&&(data[9]=source[9]),data[0]=source[0],data[1]=newBitmask,data}function mergeDefaults(objValue,srcValue,key,object,source,stack){return isObject(objValue)&&isObject(srcValue)&&(stack.set(srcValue,objValue),baseMerge(objValue,srcValue,undefined,mergeDefaults,stack),stack["delete"](srcValue)),objValue}function nativeKeysIn(object){var result=[];if(null!=object)for(var key in Object(object))result.push(key);return result}function overRest(func,start,transform){return start=nativeMax(start===undefined?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index0){if(++count>=HOT_COUNT)return arguments[0]}else count=0;return func.apply(undefined,arguments)}}function shuffleSelf(array){for(var index=-1,length=array.length,lastIndex=length-1;++indexsize)return[];for(var index=0,resIndex=0,result=Array(nativeCeil(length/size));length>index;)result[resIndex++]=baseSlice(array,index,index+=size);return result}function compact(array){for(var index=-1,length=array?array.length:0,resIndex=0,result=[];++indexn?0:n,length)):[]}function dropRight(array,n,guard){var length=array?array.length:0;return length?(n=guard||n===undefined?1:toInteger(n),n=length-n,baseSlice(array,0,0>n?0:n)):[]}function dropRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!0,!0):[]}function dropWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!0):[]}function fill(array,value,start,end){var length=array?array.length:0;return length?(start&&"number"!=typeof start&&isIterateeCall(array,value,start)&&(start=0,end=length),baseFill(array,value,start,end)):[]}function findIndex(array,predicate,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=null==fromIndex?0:toInteger(fromIndex);return 0>index&&(index=nativeMax(length+index,0)), baseFindIndex(array,getIteratee(predicate,3),index)}function findLastIndex(array,predicate,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=length-1;return fromIndex!==undefined&&(index=toInteger(fromIndex),index=0>fromIndex?nativeMax(length+index,0):nativeMin(index,length-1)),baseFindIndex(array,getIteratee(predicate,3),index,!0)}function flatten(array){var length=array?array.length:0;return length?baseFlatten(array,1):[]}function flattenDeep(array){var length=array?array.length:0;return length?baseFlatten(array,INFINITY):[]}function flattenDepth(array,depth){var length=array?array.length:0;return length?(depth=depth===undefined?1:toInteger(depth),baseFlatten(array,depth)):[]}function fromPairs(pairs){for(var index=-1,length=pairs?pairs.length:0,result={};++indexindex&&(index=nativeMax(length+index,0)),baseIndexOf(array,value,index)}function initial(array){var length=array?array.length:0;return length?baseSlice(array,0,-1):[]}function join(array,separator){return array?nativeJoin.call(array,separator):""}function last(array){var length=array?array.length:0;return length?array[length-1]:undefined}function lastIndexOf(array,value,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=length;return fromIndex!==undefined&&(index=toInteger(fromIndex),index=0>index?nativeMax(length+index,0):nativeMin(index,length-1)),value===value?strictLastIndexOf(array,value,index):baseFindIndex(array,baseIsNaN,index,!0)}function nth(array,n){return array&&array.length?baseNth(array,toInteger(n)):undefined}function pullAll(array,values){return array&&array.length&&values&&values.length?basePullAll(array,values):array}function pullAllBy(array,values,iteratee){return array&&array.length&&values&&values.length?basePullAll(array,values,getIteratee(iteratee,2)):array}function pullAllWith(array,values,comparator){return array&&array.length&&values&&values.length?basePullAll(array,values,undefined,comparator):array}function remove(array,predicate){var result=[];if(!array||!array.length)return result;var index=-1,indexes=[],length=array.length;for(predicate=getIteratee(predicate,3);++indexindex&&eq(array[index],value))return index}return-1}function sortedLastIndex(array,value){return baseSortedIndex(array,value,!0)}function sortedLastIndexBy(array,value,iteratee){return baseSortedIndexBy(array,value,getIteratee(iteratee,2),!0)}function sortedLastIndexOf(array,value){var length=array?array.length:0;if(length){var index=baseSortedIndex(array,value,!0)-1;if(eq(array[index],value))return index}return-1}function sortedUniq(array){return array&&array.length?baseSortedUniq(array):[]}function sortedUniqBy(array,iteratee){return array&&array.length?baseSortedUniq(array,getIteratee(iteratee,2)):[]}function tail(array){var length=array?array.length:0;return length?baseSlice(array,1,length):[]}function take(array,n,guard){return array&&array.length?(n=guard||n===undefined?1:toInteger(n),baseSlice(array,0,0>n?0:n)):[]}function takeRight(array,n,guard){var length=array?array.length:0;return length?(n=guard||n===undefined?1:toInteger(n),n=length-n,baseSlice(array,0>n?0:n,length)):[]}function takeRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!1,!0):[]}function takeWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3)):[]}function uniq(array){return array&&array.length?baseUniq(array):[]}function uniqBy(array,iteratee){return array&&array.length?baseUniq(array,getIteratee(iteratee,2)):[]}function uniqWith(array,comparator){return array&&array.length?baseUniq(array,undefined,comparator):[]}function unzip(array){if(!array||!array.length)return[];var length=0;return array=arrayFilter(array,function(group){return isArrayLikeObject(group)?(length=nativeMax(group.length,length),!0):void 0}),baseTimes(length,function(index){return arrayMap(array,baseProperty(index))})}function unzipWith(array,iteratee){if(!array||!array.length)return[];var result=unzip(array);return null==iteratee?result:arrayMap(result,function(group){return apply(iteratee,undefined,group)})}function zipObject(props,values){return baseZipObject(props||[],values||[],assignValue)}function zipObjectDeep(props,values){return baseZipObject(props||[],values||[],baseSet)}function chain(value){var result=lodash(value);return result.__chain__=!0,result}function tap(value,interceptor){return interceptor(value),value}function thru(value,interceptor){return interceptor(value)}function wrapperChain(){return chain(this)}function wrapperCommit(){return new LodashWrapper(this.value(),this.__chain__)}function wrapperNext(){this.__values__===undefined&&(this.__values__=toArray(this.value()));var done=this.__index__>=this.__values__.length,value=done?undefined:this.__values__[this.__index__++];return{done:done,value:value}}function wrapperToIterator(){return this}function wrapperPlant(value){for(var result,parent=this;parent instanceof baseLodash;){var clone=wrapperClone(parent);clone.__index__=0,clone.__values__=undefined,result?previous.__wrapped__=clone:result=clone;var previous=clone;parent=parent.__wrapped__}return previous.__wrapped__=value,result}function wrapperReverse(){var value=this.__wrapped__;if(value instanceof LazyWrapper){var wrapped=value;return this.__actions__.length&&(wrapped=new LazyWrapper(this)),wrapped=wrapped.reverse(),wrapped.__actions__.push({func:thru,args:[reverse],thisArg:undefined}),new LodashWrapper(wrapped,this.__chain__)}return this.thru(reverse)}function wrapperValue(){return baseWrapperValue(this.__wrapped__,this.__actions__)}function every(collection,predicate,guard){var func=isArray(collection)?arrayEvery:baseEvery;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=undefined),func(collection,getIteratee(predicate,3))}function filter(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,getIteratee(predicate,3))}function flatMap(collection,iteratee){return baseFlatten(map(collection,iteratee),1)}function flatMapDeep(collection,iteratee){return baseFlatten(map(collection,iteratee),INFINITY)}function flatMapDepth(collection,iteratee,depth){return depth=depth===undefined?1:toInteger(depth),baseFlatten(map(collection,iteratee),depth)}function forEach(collection,iteratee){var func=isArray(collection)?arrayEach:baseEach;return func(collection,getIteratee(iteratee,3))}function forEachRight(collection,iteratee){var func=isArray(collection)?arrayEachRight:baseEachRight;return func(collection,getIteratee(iteratee,3))}function includes(collection,value,fromIndex,guard){collection=isArrayLike(collection)?collection:values(collection),fromIndex=fromIndex&&!guard?toInteger(fromIndex):0;var length=collection.length;return 0>fromIndex&&(fromIndex=nativeMax(length+fromIndex,0)),isString(collection)?length>=fromIndex&&collection.indexOf(value,fromIndex)>-1:!!length&&baseIndexOf(collection,value,fromIndex)>-1}function map(collection,iteratee){var func=isArray(collection)?arrayMap:baseMap;return func(collection,getIteratee(iteratee,3))}function orderBy(collection,iteratees,orders,guard){return null==collection?[]:(isArray(iteratees)||(iteratees=null==iteratees?[]:[iteratees]),orders=guard?undefined:orders,isArray(orders)||(orders=null==orders?[]:[orders]),baseOrderBy(collection,iteratees,orders))}function reduce(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduce:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEach)}function reduceRight(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduceRight:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEachRight)}function reject(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,negate(getIteratee(predicate,3)))}function sample(collection){return arraySample(isArrayLike(collection)?collection:values(collection))}function sampleSize(collection,n,guard){return n=(guard?isIterateeCall(collection,n,guard):n===undefined)?1:toInteger(n),arraySampleSize(isArrayLike(collection)?collection:values(collection),n)}function shuffle(collection){return shuffleSelf(isArrayLike(collection)?copyArray(collection):values(collection))}function size(collection){if(null==collection)return 0;if(isArrayLike(collection))return isString(collection)?stringSize(collection):collection.length;var tag=getTag(collection);return tag==mapTag||tag==setTag?collection.size:baseKeys(collection).length}function some(collection,predicate,guard){var func=isArray(collection)?arraySome:baseSome;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=undefined),func(collection,getIteratee(predicate,3))}function after(n,func){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return n=toInteger(n),function(){return--n<1?func.apply(this,arguments):void 0}}function ary(func,n,guard){return n=guard?undefined:n,n=func&&null==n?func.length:n,createWrap(func,ARY_FLAG,undefined,undefined,undefined,undefined,n)}function before(n,func){var result;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return n=toInteger(n),function(){return--n>0&&(result=func.apply(this,arguments)),1>=n&&(func=undefined),result}}function curry(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,CURRY_FLAG,undefined,undefined,undefined,undefined,undefined,arity);return result.placeholder=curry.placeholder,result}function curryRight(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,CURRY_RIGHT_FLAG,undefined,undefined,undefined,undefined,undefined,arity);return result.placeholder=curryRight.placeholder,result}function debounce(func,wait,options){function invokeFunc(time){var args=lastArgs,thisArg=lastThis;return lastArgs=lastThis=undefined,lastInvokeTime=time,result=func.apply(thisArg,args)}function leadingEdge(time){return lastInvokeTime=time,timerId=setTimeout(timerExpired,wait),leading?invokeFunc(time):result}function remainingWait(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime,result=wait-timeSinceLastCall;return maxing?nativeMin(result,maxWait-timeSinceLastInvoke):result}function shouldInvoke(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime;return lastCallTime===undefined||timeSinceLastCall>=wait||0>timeSinceLastCall||maxing&&timeSinceLastInvoke>=maxWait}function timerExpired(){var time=now();return shouldInvoke(time)?trailingEdge(time):void(timerId=setTimeout(timerExpired,remainingWait(time)))}function trailingEdge(time){return timerId=undefined,trailing&&lastArgs?invokeFunc(time):(lastArgs=lastThis=undefined,result)}function cancel(){timerId!==undefined&&clearTimeout(timerId),lastInvokeTime=0,lastArgs=lastCallTime=lastThis=timerId=undefined}function flush(){return timerId===undefined?result:trailingEdge(now())}function debounced(){var time=now(),isInvoking=shouldInvoke(time);if(lastArgs=arguments,lastThis=this,lastCallTime=time,isInvoking){if(timerId===undefined)return leadingEdge(lastCallTime);if(maxing)return timerId=setTimeout(timerExpired,wait),invokeFunc(lastCallTime)}return timerId===undefined&&(timerId=setTimeout(timerExpired,wait)),result}var lastArgs,lastThis,maxWait,result,timerId,lastCallTime,lastInvokeTime=0,leading=!1,maxing=!1,trailing=!0;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return wait=toNumber(wait)||0,isObject(options)&&(leading=!!options.leading,maxing="maxWait"in options,maxWait=maxing?nativeMax(toNumber(options.maxWait)||0,wait):maxWait,trailing="trailing"in options?!!options.trailing:trailing),debounced.cancel=cancel,debounced.flush=flush,debounced}function flip(func){return createWrap(func,FLIP_FLAG)}function memoize(func,resolver){if("function"!=typeof func||resolver&&"function"!=typeof resolver)throw new TypeError(FUNC_ERROR_TEXT);var memoized=function(){var args=arguments,key=resolver?resolver.apply(this,args):args[0],cache=memoized.cache;if(cache.has(key))return cache.get(key);var result=func.apply(this,args);return memoized.cache=cache.set(key,result)||cache,result};return memoized.cache=new(memoize.Cache||MapCache),memoized}function negate(predicate){if("function"!=typeof predicate)throw new TypeError(FUNC_ERROR_TEXT);return function(){var args=arguments;switch(args.length){case 0:return!predicate.call(this);case 1:return!predicate.call(this,args[0]);case 2:return!predicate.call(this,args[0],args[1]);case 3:return!predicate.call(this,args[0],args[1],args[2])}return!predicate.apply(this,args)}}function once(func){return before(2,func)}function rest(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=start===undefined?start:toInteger(start),baseRest(func,start)}function spread(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=start===undefined?0:nativeMax(toInteger(start),0),baseRest(function(args){var array=args[start],otherArgs=castSlice(args,0,start);return array&&arrayPush(otherArgs,array),apply(func,this,otherArgs)})}function throttle(func,wait,options){var leading=!0,trailing=!0;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return isObject(options)&&(leading="leading"in options?!!options.leading:leading,trailing="trailing"in options?!!options.trailing:trailing),debounce(func,wait,{leading:leading,maxWait:wait,trailing:trailing})}function unary(func){return ary(func,1)}function wrap(value,wrapper){return wrapper=null==wrapper?identity:wrapper,partial(wrapper,value)}function castArray(){if(!arguments.length)return[];var value=arguments[0];return isArray(value)?value:[value]}function clone(value){return baseClone(value,!1,!0)}function cloneWith(value,customizer){return baseClone(value,!1,!0,customizer)}function cloneDeep(value){return baseClone(value,!0,!0)}function cloneDeepWith(value,customizer){return baseClone(value,!0,!0,customizer)}function conformsTo(object,source){return null==source||baseConformsTo(object,source,keys(source))}function eq(value,other){return value===other||value!==value&&other!==other}function isArguments(value){return isArrayLikeObject(value)&&hasOwnProperty.call(value,"callee")&&(!propertyIsEnumerable.call(value,"callee")||objectToString.call(value)==argsTag)}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value)}function isBoolean(value){return value===!0||value===!1||isObjectLike(value)&&objectToString.call(value)==boolTag}function isElement(value){return null!=value&&1===value.nodeType&&isObjectLike(value)&&!isPlainObject(value)}function isEmpty(value){if(isArrayLike(value)&&(isArray(value)||"string"==typeof value||"function"==typeof value.splice||isBuffer(value)||isArguments(value)))return!value.length;var tag=getTag(value);if(tag==mapTag||tag==setTag)return!value.size;if(isPrototype(value))return!nativeKeys(value).length;for(var key in value)if(hasOwnProperty.call(value,key))return!1;return!0}function isEqual(value,other){return baseIsEqual(value,other)}function isEqualWith(value,other,customizer){customizer="function"==typeof customizer?customizer:undefined;var result=customizer?customizer(value,other):undefined;return result===undefined?baseIsEqual(value,other,customizer):!!result}function isError(value){return isObjectLike(value)?objectToString.call(value)==errorTag||"string"==typeof value.message&&"string"==typeof value.name:!1}function isFinite(value){return"number"==typeof value&&nativeIsFinite(value)}function isFunction(value){var tag=isObject(value)?objectToString.call(value):"";return tag==funcTag||tag==genTag}function isInteger(value){return"number"==typeof value&&value==toInteger(value)}function isLength(value){return"number"==typeof value&&value>-1&&value%1==0&&MAX_SAFE_INTEGER>=value}function isObject(value){var type=typeof value;return null!=value&&("object"==type||"function"==type)}function isObjectLike(value){return null!=value&&"object"==typeof value}function isMatch(object,source){return object===source||baseIsMatch(object,source,getMatchData(source))}function isMatchWith(object,source,customizer){return customizer="function"==typeof customizer?customizer:undefined,baseIsMatch(object,source,getMatchData(source),customizer)}function isNaN(value){return isNumber(value)&&value!=+value}function isNative(value){if(isMaskable(value))throw new Error("This method is not supported with core-js. Try https://github.com/es-shims.");return baseIsNative(value)}function isNull(value){return null===value}function isNil(value){return null==value}function isNumber(value){return"number"==typeof value||isObjectLike(value)&&objectToString.call(value)==numberTag}function isPlainObject(value){if(!isObjectLike(value)||objectToString.call(value)!=objectTag)return!1;var proto=getPrototype(value);if(null===proto)return!0;var Ctor=hasOwnProperty.call(proto,"constructor")&&proto.constructor;return"function"==typeof Ctor&&Ctor instanceof Ctor&&funcToString.call(Ctor)==objectCtorString}function isSafeInteger(value){return isInteger(value)&&value>=-MAX_SAFE_INTEGER&&MAX_SAFE_INTEGER>=value}function isString(value){return"string"==typeof value||!isArray(value)&&isObjectLike(value)&&objectToString.call(value)==stringTag}function isSymbol(value){return"symbol"==typeof value||isObjectLike(value)&&objectToString.call(value)==symbolTag}function isUndefined(value){return value===undefined}function isWeakMap(value){return isObjectLike(value)&&getTag(value)==weakMapTag}function isWeakSet(value){return isObjectLike(value)&&objectToString.call(value)==weakSetTag}function toArray(value){if(!value)return[];if(isArrayLike(value))return isString(value)?stringToArray(value):copyArray(value);if(iteratorSymbol&&value[iteratorSymbol])return iteratorToArray(value[iteratorSymbol]());var tag=getTag(value),func=tag==mapTag?mapToArray:tag==setTag?setToArray:values;return func(value)}function toFinite(value){if(!value)return 0===value?value:0;if(value=toNumber(value),value===INFINITY||value===-INFINITY){var sign=0>value?-1:1;return sign*MAX_INTEGER}return value===value?value:0}function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0}function toLength(value){return value?baseClamp(toInteger(value),0,MAX_ARRAY_LENGTH):0}function toNumber(value){if("number"==typeof value)return value;if(isSymbol(value))return NAN;if(isObject(value)){var other="function"==typeof value.valueOf?value.valueOf():value;value=isObject(other)?other+"":other}if("string"!=typeof value)return 0===value?value:+value;value=value.replace(reTrim,"");var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value}function toPlainObject(value){return copyObject(value,keysIn(value))}function toSafeInteger(value){return baseClamp(toInteger(value),-MAX_SAFE_INTEGER,MAX_SAFE_INTEGER)}function toString(value){return null==value?"":baseToString(value)}function create(prototype,properties){var result=baseCreate(prototype);return properties?baseAssign(result,properties):result}function findKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwn)}function findLastKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwnRight)}function forIn(object,iteratee){return null==object?object:baseFor(object,getIteratee(iteratee,3),keysIn)}function forInRight(object,iteratee){return null==object?object:baseForRight(object,getIteratee(iteratee,3),keysIn)}function forOwn(object,iteratee){return object&&baseForOwn(object,getIteratee(iteratee,3))}function forOwnRight(object,iteratee){return object&&baseForOwnRight(object,getIteratee(iteratee,3))}function functions(object){return null==object?[]:baseFunctions(object,keys(object))}function functionsIn(object){return null==object?[]:baseFunctions(object,keysIn(object))}function get(object,path,defaultValue){var result=null==object?undefined:baseGet(object,path);return result===undefined?defaultValue:result}function has(object,path){return null!=object&&hasPath(object,path,baseHas)}function hasIn(object,path){return null!=object&&hasPath(object,path,baseHasIn)}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function keysIn(object){return isArrayLike(object)?arrayLikeKeys(object,!0):baseKeysIn(object)}function mapKeys(object,iteratee){var result={};return iteratee=getIteratee(iteratee,3),baseForOwn(object,function(value,key,object){baseAssignValue(result,iteratee(value,key,object),value)}),result}function mapValues(object,iteratee){var result={};return iteratee=getIteratee(iteratee,3),baseForOwn(object,function(value,key,object){baseAssignValue(result,key,iteratee(value,key,object))}),result}function omitBy(object,predicate){return pickBy(object,negate(getIteratee(predicate)))}function pickBy(object,predicate){return null==object?{}:basePickBy(object,getAllKeysIn(object),getIteratee(predicate))}function result(object,path,defaultValue){path=isKey(path,object)?[path]:castPath(path);var index=-1,length=path.length;for(length||(object=undefined,length=1);++indexupper){var temp=lower;lower=upper,upper=temp}if(floating||lower%1||upper%1){var rand=nativeRandom();return nativeMin(lower+rand*(upper-lower+freeParseFloat("1e-"+((rand+"").length-1))),upper)}return baseRandom(lower,upper)}function capitalize(string){return upperFirst(toString(string).toLowerCase())}function deburr(string){return string=toString(string),string&&string.replace(reLatin,deburrLetter).replace(reComboMark,"")}function endsWith(string,target,position){string=toString(string),target=baseToString(target);var length=string.length;position=position===undefined?length:baseClamp(toInteger(position),0,length);var end=position;return position-=target.length,position>=0&&string.slice(position,end)==target}function escape(string){return string=toString(string),string&&reHasUnescapedHtml.test(string)?string.replace(reUnescapedHtml,escapeHtmlChar):string}function escapeRegExp(string){return string=toString(string),string&&reHasRegExpChar.test(string)?string.replace(reRegExpChar,"\\$&"):string}function pad(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;if(!length||strLength>=length)return string;var mid=(length-strLength)/2;return createPadding(nativeFloor(mid),chars)+string+createPadding(nativeCeil(mid),chars)}function padEnd(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;return length&&length>strLength?string+createPadding(length-strLength,chars):string}function padStart(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;return length&&length>strLength?createPadding(length-strLength,chars)+string:string}function parseInt(string,radix,guard){return guard||null==radix?radix=0:radix&&(radix=+radix),nativeParseInt(toString(string),radix||0)}function repeat(string,n,guard){return n=(guard?isIterateeCall(string,n,guard):n===undefined)?1:toInteger(n),baseRepeat(toString(string),n)}function replace(){var args=arguments,string=toString(args[0]);return args.length<3?string:string.replace(args[1],args[2])}function split(string,separator,limit){return limit&&"number"!=typeof limit&&isIterateeCall(string,separator,limit)&&(separator=limit=undefined),(limit=limit===undefined?MAX_ARRAY_LENGTH:limit>>>0)?(string=toString(string),string&&("string"==typeof separator||null!=separator&&!isRegExp(separator))&&(separator=baseToString(separator),!separator&&hasUnicode(string))?castSlice(stringToArray(string),0,limit):string.split(separator,limit)):[]}function startsWith(string,target,position){return string=toString(string),position=baseClamp(toInteger(position),0,string.length),target=baseToString(target),string.slice(position,position+target.length)==target}function template(string,options,guard){var settings=lodash.templateSettings;guard&&isIterateeCall(string,options,guard)&&(options=undefined),string=toString(string),options=assignInWith({},options,settings,assignInDefaults);var isEscaping,isEvaluating,imports=assignInWith({},options.imports,settings.imports,assignInDefaults),importsKeys=keys(imports),importsValues=baseValues(imports,importsKeys),index=0,interpolate=options.interpolate||reNoMatch,source="__p += '",reDelimiters=RegExp((options.escape||reNoMatch).source+"|"+interpolate.source+"|"+(interpolate===reInterpolate?reEsTemplate:reNoMatch).source+"|"+(options.evaluate||reNoMatch).source+"|$","g"),sourceURL="//# sourceURL="+("sourceURL"in options?options.sourceURL:"lodash.templateSources["+ ++templateCounter+"]")+"\n";string.replace(reDelimiters,function(match,escapeValue,interpolateValue,esTemplateValue,evaluateValue,offset){return interpolateValue||(interpolateValue=esTemplateValue),source+=string.slice(index,offset).replace(reUnescapedString,escapeStringChar),escapeValue&&(isEscaping=!0,source+="' +\n__e("+escapeValue+") +\n'"),evaluateValue&&(isEvaluating=!0,source+="';\n"+evaluateValue+";\n__p += '"),interpolateValue&&(source+="' +\n((__t = ("+interpolateValue+")) == null ? '' : __t) +\n'"),index=offset+match.length,match}),source+="';\n";var variable=options.variable;variable||(source="with (obj) {\n"+source+"\n}\n"),source=(isEvaluating?source.replace(reEmptyStringLeading,""):source).replace(reEmptyStringMiddle,"$1").replace(reEmptyStringTrailing,"$1;"),source="function("+(variable||"obj")+") {\n"+(variable?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(isEscaping?", __e = _.escape":"")+(isEvaluating?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+source+"return __p\n}";var result=attempt(function(){return Function(importsKeys,sourceURL+"return "+source).apply(undefined,importsValues)});if(result.source=source,isError(result))throw result;return result}function toLower(value){return toString(value).toLowerCase()}function toUpper(value){return toString(value).toUpperCase()}function trim(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrim,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),chrSymbols=stringToArray(chars),start=charsStartIndex(strSymbols,chrSymbols),end=charsEndIndex(strSymbols,chrSymbols)+1;return castSlice(strSymbols,start,end).join("")}function trimEnd(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrimEnd,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),end=charsEndIndex(strSymbols,stringToArray(chars))+1;return castSlice(strSymbols,0,end).join("")}function trimStart(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrimStart,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),start=charsStartIndex(strSymbols,stringToArray(chars));return castSlice(strSymbols,start).join("")}function truncate(string,options){var length=DEFAULT_TRUNC_LENGTH,omission=DEFAULT_TRUNC_OMISSION;if(isObject(options)){var separator="separator"in options?options.separator:separator;length="length"in options?toInteger(options.length):length,omission="omission"in options?baseToString(options.omission):omission}string=toString(string);var strLength=string.length;if(hasUnicode(string)){var strSymbols=stringToArray(string);strLength=strSymbols.length}if(length>=strLength)return string;var end=length-stringSize(omission);if(1>end)return omission;var result=strSymbols?castSlice(strSymbols,0,end).join(""):string.slice(0,end);if(separator===undefined)return result+omission;if(strSymbols&&(end+=result.length-end),isRegExp(separator)){if(string.slice(end).search(separator)){var match,substring=result;for(separator.global||(separator=RegExp(separator.source,toString(reFlags.exec(separator))+"g")),separator.lastIndex=0;match=separator.exec(substring);)var newEnd=match.index;result=result.slice(0,newEnd===undefined?end:newEnd)}}else if(string.indexOf(baseToString(separator),end)!=end){var index=result.lastIndexOf(separator);index>-1&&(result=result.slice(0,index))}return result+omission}function unescape(string){return string=toString(string),string&&reHasEscapedHtml.test(string)?string.replace(reEscapedHtml,unescapeHtmlChar):string}function words(string,pattern,guard){ return string=toString(string),pattern=guard?undefined:pattern,pattern===undefined?hasUnicodeWord(string)?unicodeWords(string):asciiWords(string):string.match(pattern)||[]}function cond(pairs){var length=pairs?pairs.length:0,toIteratee=getIteratee();return pairs=length?arrayMap(pairs,function(pair){if("function"!=typeof pair[1])throw new TypeError(FUNC_ERROR_TEXT);return[toIteratee(pair[0]),pair[1]]}):[],baseRest(function(args){for(var index=-1;++indexn||n>MAX_SAFE_INTEGER)return[];var index=MAX_ARRAY_LENGTH,length=nativeMin(n,MAX_ARRAY_LENGTH);iteratee=getIteratee(iteratee),n-=MAX_ARRAY_LENGTH;for(var result=baseTimes(length,iteratee);++index1?arrays[length-1]:undefined;return iteratee="function"==typeof iteratee?(arrays.pop(),iteratee):undefined,unzipWith(arrays,iteratee)}),wrapperAt=flatRest(function(paths){var length=paths.length,start=length?paths[0]:0,value=this.__wrapped__,interceptor=function(object){return baseAt(object,paths)};return!(length>1||this.__actions__.length)&&value instanceof LazyWrapper&&isIndex(start)?(value=value.slice(start,+start+(length?1:0)),value.__actions__.push({func:thru,args:[interceptor],thisArg:undefined}),new LodashWrapper(value,this.__chain__).thru(function(array){return length&&!array.length&&array.push(undefined),array})):this.thru(interceptor)}),countBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?++result[key]:baseAssignValue(result,key,1)}),find=createFind(findIndex),findLast=createFind(findLastIndex),groupBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?result[key].push(value):baseAssignValue(result,key,[value])}),invokeMap=baseRest(function(collection,path,args){var index=-1,isFunc="function"==typeof path,isProp=isKey(path),result=isArrayLike(collection)?Array(collection.length):[];return baseEach(collection,function(value){var func=isFunc?path:isProp&&null!=value?value[path]:undefined;result[++index]=func?apply(func,value,args):baseInvoke(value,path,args)}),result}),keyBy=createAggregator(function(result,value,key){baseAssignValue(result,key,value)}),partition=createAggregator(function(result,value,key){result[key?0:1].push(value)},function(){return[[],[]]}),sortBy=baseRest(function(collection,iteratees){if(null==collection)return[];var length=iteratees.length;return length>1&&isIterateeCall(collection,iteratees[0],iteratees[1])?iteratees=[]:length>2&&isIterateeCall(iteratees[0],iteratees[1],iteratees[2])&&(iteratees=[iteratees[0]]),baseOrderBy(collection,baseFlatten(iteratees,1),[])}),now=ctxNow||function(){return root.Date.now()},bind=baseRest(function(func,thisArg,partials){var bitmask=BIND_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bind));bitmask|=PARTIAL_FLAG}return createWrap(func,bitmask,thisArg,partials,holders)}),bindKey=baseRest(function(object,key,partials){var bitmask=BIND_FLAG|BIND_KEY_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bindKey));bitmask|=PARTIAL_FLAG}return createWrap(key,bitmask,object,partials,holders)}),defer=baseRest(function(func,args){return baseDelay(func,1,args)}),delay=baseRest(function(func,wait,args){return baseDelay(func,toNumber(wait)||0,args)});memoize.Cache=MapCache;var overArgs=castRest(function(func,transforms){transforms=1==transforms.length&&isArray(transforms[0])?arrayMap(transforms[0],baseUnary(getIteratee())):arrayMap(baseFlatten(transforms,1),baseUnary(getIteratee()));var funcsLength=transforms.length;return baseRest(function(args){for(var index=-1,length=nativeMin(args.length,funcsLength);++index=other}),isArray=Array.isArray,isArrayBuffer=nodeIsArrayBuffer?baseUnary(nodeIsArrayBuffer):baseIsArrayBuffer,isBuffer=nativeIsBuffer||stubFalse,isDate=nodeIsDate?baseUnary(nodeIsDate):baseIsDate,isMap=nodeIsMap?baseUnary(nodeIsMap):baseIsMap,isRegExp=nodeIsRegExp?baseUnary(nodeIsRegExp):baseIsRegExp,isSet=nodeIsSet?baseUnary(nodeIsSet):baseIsSet,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray,lt=createRelationalOperation(baseLt),lte=createRelationalOperation(function(value,other){return other>=value}),assign=createAssigner(function(object,source){if(isPrototype(source)||isArrayLike(source))return void copyObject(source,keys(source),object);for(var key in source)hasOwnProperty.call(source,key)&&assignValue(object,key,source[key])}),assignIn=createAssigner(function(object,source){copyObject(source,keysIn(source),object)}),assignInWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keysIn(source),object,customizer)}),assignWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keys(source),object,customizer)}),at=flatRest(baseAt),defaults=baseRest(function(args){return args.push(undefined,assignInDefaults),apply(assignInWith,undefined,args)}),defaultsDeep=baseRest(function(args){return args.push(undefined,mergeDefaults),apply(mergeWith,undefined,args)}),invert=createInverter(function(result,value,key){result[value]=key},constant(identity)),invertBy=createInverter(function(result,value,key){hasOwnProperty.call(result,value)?result[value].push(key):result[value]=[key]},getIteratee),invoke=baseRest(baseInvoke),merge=createAssigner(function(object,source,srcIndex){baseMerge(object,source,srcIndex)}),mergeWith=createAssigner(function(object,source,srcIndex,customizer){baseMerge(object,source,srcIndex,customizer)}),omit=flatRest(function(object,props){return null==object?{}:(props=arrayMap(props,toKey),basePick(object,baseDifference(getAllKeysIn(object),props)))}),pick=flatRest(function(object,props){return null==object?{}:basePick(object,arrayMap(props,toKey))}),toPairs=createToPairs(keys),toPairsIn=createToPairs(keysIn),camelCase=createCompounder(function(result,word,index){return word=word.toLowerCase(),result+(index?capitalize(word):word)}),kebabCase=createCompounder(function(result,word,index){return result+(index?"-":"")+word.toLowerCase()}),lowerCase=createCompounder(function(result,word,index){return result+(index?" ":"")+word.toLowerCase()}),lowerFirst=createCaseFirst("toLowerCase"),snakeCase=createCompounder(function(result,word,index){return result+(index?"_":"")+word.toLowerCase()}),startCase=createCompounder(function(result,word,index){return result+(index?" ":"")+upperFirst(word)}),upperCase=createCompounder(function(result,word,index){return result+(index?" ":"")+word.toUpperCase()}),upperFirst=createCaseFirst("toUpperCase"),attempt=baseRest(function(func,args){try{return apply(func,undefined,args)}catch(e){return isError(e)?e:new Error(e)}}),bindAll=flatRest(function(object,methodNames){return arrayEach(methodNames,function(key){key=toKey(key),baseAssignValue(object,key,bind(object[key],object))}),object}),flow=createFlow(),flowRight=createFlow(!0),method=baseRest(function(path,args){return function(object){return baseInvoke(object,path,args)}}),methodOf=baseRest(function(object,args){return function(path){return baseInvoke(object,path,args)}}),over=createOver(arrayMap),overEvery=createOver(arrayEvery),overSome=createOver(arraySome),range=createRange(),rangeRight=createRange(!0),add=createMathOperation(function(augend,addend){return augend+addend},0),ceil=createRound("ceil"),divide=createMathOperation(function(dividend,divisor){return dividend/divisor},1),floor=createRound("floor"),multiply=createMathOperation(function(multiplier,multiplicand){return multiplier*multiplicand},1),round=createRound("round"),subtract=createMathOperation(function(minuend,subtrahend){return minuend-subtrahend},0);return lodash.after=after,lodash.ary=ary,lodash.assign=assign,lodash.assignIn=assignIn,lodash.assignInWith=assignInWith,lodash.assignWith=assignWith,lodash.at=at,lodash.before=before,lodash.bind=bind,lodash.bindAll=bindAll,lodash.bindKey=bindKey,lodash.castArray=castArray,lodash.chain=chain,lodash.chunk=chunk,lodash.compact=compact,lodash.concat=concat,lodash.cond=cond,lodash.conforms=conforms,lodash.constant=constant,lodash.countBy=countBy,lodash.create=create,lodash.curry=curry,lodash.curryRight=curryRight,lodash.debounce=debounce,lodash.defaults=defaults,lodash.defaultsDeep=defaultsDeep,lodash.defer=defer,lodash.delay=delay,lodash.difference=difference,lodash.differenceBy=differenceBy,lodash.differenceWith=differenceWith,lodash.drop=drop,lodash.dropRight=dropRight,lodash.dropRightWhile=dropRightWhile,lodash.dropWhile=dropWhile,lodash.fill=fill,lodash.filter=filter,lodash.flatMap=flatMap,lodash.flatMapDeep=flatMapDeep,lodash.flatMapDepth=flatMapDepth,lodash.flatten=flatten,lodash.flattenDeep=flattenDeep,lodash.flattenDepth=flattenDepth,lodash.flip=flip,lodash.flow=flow,lodash.flowRight=flowRight,lodash.fromPairs=fromPairs,lodash.functions=functions,lodash.functionsIn=functionsIn,lodash.groupBy=groupBy,lodash.initial=initial,lodash.intersection=intersection,lodash.intersectionBy=intersectionBy,lodash.intersectionWith=intersectionWith,lodash.invert=invert,lodash.invertBy=invertBy,lodash.invokeMap=invokeMap,lodash.iteratee=iteratee,lodash.keyBy=keyBy,lodash.keys=keys,lodash.keysIn=keysIn,lodash.map=map,lodash.mapKeys=mapKeys,lodash.mapValues=mapValues,lodash.matches=matches,lodash.matchesProperty=matchesProperty,lodash.memoize=memoize,lodash.merge=merge,lodash.mergeWith=mergeWith,lodash.method=method,lodash.methodOf=methodOf,lodash.mixin=mixin,lodash.negate=negate,lodash.nthArg=nthArg,lodash.omit=omit,lodash.omitBy=omitBy,lodash.once=once,lodash.orderBy=orderBy,lodash.over=over,lodash.overArgs=overArgs,lodash.overEvery=overEvery,lodash.overSome=overSome,lodash.partial=partial,lodash.partialRight=partialRight,lodash.partition=partition,lodash.pick=pick,lodash.pickBy=pickBy,lodash.property=property,lodash.propertyOf=propertyOf,lodash.pull=pull,lodash.pullAll=pullAll,lodash.pullAllBy=pullAllBy,lodash.pullAllWith=pullAllWith,lodash.pullAt=pullAt,lodash.range=range,lodash.rangeRight=rangeRight,lodash.rearg=rearg,lodash.reject=reject,lodash.remove=remove,lodash.rest=rest,lodash.reverse=reverse,lodash.sampleSize=sampleSize,lodash.set=set,lodash.setWith=setWith,lodash.shuffle=shuffle,lodash.slice=slice,lodash.sortBy=sortBy,lodash.sortedUniq=sortedUniq,lodash.sortedUniqBy=sortedUniqBy,lodash.split=split,lodash.spread=spread,lodash.tail=tail,lodash.take=take,lodash.takeRight=takeRight,lodash.takeRightWhile=takeRightWhile,lodash.takeWhile=takeWhile,lodash.tap=tap,lodash.throttle=throttle,lodash.thru=thru,lodash.toArray=toArray,lodash.toPairs=toPairs,lodash.toPairsIn=toPairsIn,lodash.toPath=toPath,lodash.toPlainObject=toPlainObject,lodash.transform=transform,lodash.unary=unary,lodash.union=union,lodash.unionBy=unionBy,lodash.unionWith=unionWith,lodash.uniq=uniq,lodash.uniqBy=uniqBy,lodash.uniqWith=uniqWith,lodash.unset=unset,lodash.unzip=unzip,lodash.unzipWith=unzipWith,lodash.update=update,lodash.updateWith=updateWith,lodash.values=values,lodash.valuesIn=valuesIn,lodash.without=without,lodash.words=words,lodash.wrap=wrap,lodash.xor=xor,lodash.xorBy=xorBy,lodash.xorWith=xorWith,lodash.zip=zip,lodash.zipObject=zipObject,lodash.zipObjectDeep=zipObjectDeep,lodash.zipWith=zipWith,lodash.entries=toPairs,lodash.entriesIn=toPairsIn,lodash.extend=assignIn,lodash.extendWith=assignInWith,mixin(lodash,lodash),lodash.add=add,lodash.attempt=attempt,lodash.camelCase=camelCase,lodash.capitalize=capitalize,lodash.ceil=ceil,lodash.clamp=clamp,lodash.clone=clone,lodash.cloneDeep=cloneDeep,lodash.cloneDeepWith=cloneDeepWith,lodash.cloneWith=cloneWith,lodash.conformsTo=conformsTo,lodash.deburr=deburr,lodash.defaultTo=defaultTo,lodash.divide=divide,lodash.endsWith=endsWith,lodash.eq=eq,lodash.escape=escape,lodash.escapeRegExp=escapeRegExp,lodash.every=every,lodash.find=find,lodash.findIndex=findIndex,lodash.findKey=findKey,lodash.findLast=findLast,lodash.findLastIndex=findLastIndex,lodash.findLastKey=findLastKey,lodash.floor=floor,lodash.forEach=forEach,lodash.forEachRight=forEachRight,lodash.forIn=forIn,lodash.forInRight=forInRight,lodash.forOwn=forOwn,lodash.forOwnRight=forOwnRight,lodash.get=get,lodash.gt=gt,lodash.gte=gte,lodash.has=has,lodash.hasIn=hasIn,lodash.head=head,lodash.identity=identity,lodash.includes=includes,lodash.indexOf=indexOf,lodash.inRange=inRange,lodash.invoke=invoke,lodash.isArguments=isArguments,lodash.isArray=isArray,lodash.isArrayBuffer=isArrayBuffer,lodash.isArrayLike=isArrayLike,lodash.isArrayLikeObject=isArrayLikeObject,lodash.isBoolean=isBoolean,lodash.isBuffer=isBuffer,lodash.isDate=isDate,lodash.isElement=isElement,lodash.isEmpty=isEmpty,lodash.isEqual=isEqual,lodash.isEqualWith=isEqualWith,lodash.isError=isError,lodash.isFinite=isFinite,lodash.isFunction=isFunction,lodash.isInteger=isInteger,lodash.isLength=isLength,lodash.isMap=isMap,lodash.isMatch=isMatch,lodash.isMatchWith=isMatchWith,lodash.isNaN=isNaN,lodash.isNative=isNative,lodash.isNil=isNil,lodash.isNull=isNull,lodash.isNumber=isNumber,lodash.isObject=isObject,lodash.isObjectLike=isObjectLike,lodash.isPlainObject=isPlainObject,lodash.isRegExp=isRegExp,lodash.isSafeInteger=isSafeInteger,lodash.isSet=isSet,lodash.isString=isString,lodash.isSymbol=isSymbol,lodash.isTypedArray=isTypedArray,lodash.isUndefined=isUndefined,lodash.isWeakMap=isWeakMap,lodash.isWeakSet=isWeakSet,lodash.join=join,lodash.kebabCase=kebabCase,lodash.last=last,lodash.lastIndexOf=lastIndexOf,lodash.lowerCase=lowerCase,lodash.lowerFirst=lowerFirst,lodash.lt=lt,lodash.lte=lte,lodash.max=max,lodash.maxBy=maxBy,lodash.mean=mean,lodash.meanBy=meanBy,lodash.min=min,lodash.minBy=minBy,lodash.stubArray=stubArray,lodash.stubFalse=stubFalse,lodash.stubObject=stubObject,lodash.stubString=stubString,lodash.stubTrue=stubTrue,lodash.multiply=multiply,lodash.nth=nth,lodash.noConflict=noConflict,lodash.noop=noop,lodash.now=now,lodash.pad=pad,lodash.padEnd=padEnd,lodash.padStart=padStart,lodash.parseInt=parseInt,lodash.random=random,lodash.reduce=reduce,lodash.reduceRight=reduceRight,lodash.repeat=repeat,lodash.replace=replace,lodash.result=result,lodash.round=round,lodash.runInContext=runInContext,lodash.sample=sample,lodash.size=size,lodash.snakeCase=snakeCase,lodash.some=some,lodash.sortedIndex=sortedIndex,lodash.sortedIndexBy=sortedIndexBy,lodash.sortedIndexOf=sortedIndexOf,lodash.sortedLastIndex=sortedLastIndex,lodash.sortedLastIndexBy=sortedLastIndexBy,lodash.sortedLastIndexOf=sortedLastIndexOf,lodash.startCase=startCase,lodash.startsWith=startsWith,lodash.subtract=subtract,lodash.sum=sum,lodash.sumBy=sumBy,lodash.template=template,lodash.times=times,lodash.toFinite=toFinite,lodash.toInteger=toInteger,lodash.toLength=toLength,lodash.toLower=toLower,lodash.toNumber=toNumber,lodash.toSafeInteger=toSafeInteger,lodash.toString=toString,lodash.toUpper=toUpper,lodash.trim=trim,lodash.trimEnd=trimEnd,lodash.trimStart=trimStart,lodash.truncate=truncate,lodash.unescape=unescape,lodash.uniqueId=uniqueId,lodash.upperCase=upperCase,lodash.upperFirst=upperFirst,lodash.each=forEach,lodash.eachRight=forEachRight,lodash.first=head,mixin(lodash,function(){var source={};return baseForOwn(lodash,function(func,methodName){hasOwnProperty.call(lodash.prototype,methodName)||(source[methodName]=func)}),source}(),{chain:!1}),lodash.VERSION=VERSION,arrayEach(["bind","bindKey","curry","curryRight","partial","partialRight"],function(methodName){lodash[methodName].placeholder=lodash}),arrayEach(["drop","take"],function(methodName,index){LazyWrapper.prototype[methodName]=function(n){var filtered=this.__filtered__;if(filtered&&!index)return new LazyWrapper(this);n=n===undefined?1:nativeMax(toInteger(n),0);var result=this.clone();return filtered?result.__takeCount__=nativeMin(n,result.__takeCount__):result.__views__.push({size:nativeMin(n,MAX_ARRAY_LENGTH),type:methodName+(result.__dir__<0?"Right":"")}),result},LazyWrapper.prototype[methodName+"Right"]=function(n){return this.reverse()[methodName](n).reverse()}}),arrayEach(["filter","map","takeWhile"],function(methodName,index){var type=index+1,isFilter=type==LAZY_FILTER_FLAG||type==LAZY_WHILE_FLAG;LazyWrapper.prototype[methodName]=function(iteratee){var result=this.clone();return result.__iteratees__.push({iteratee:getIteratee(iteratee,3),type:type}),result.__filtered__=result.__filtered__||isFilter,result}}),arrayEach(["head","last"],function(methodName,index){var takeName="take"+(index?"Right":"");LazyWrapper.prototype[methodName]=function(){return this[takeName](1).value()[0]}}),arrayEach(["initial","tail"],function(methodName,index){var dropName="drop"+(index?"":"Right");LazyWrapper.prototype[methodName]=function(){return this.__filtered__?new LazyWrapper(this):this[dropName](1)}}),LazyWrapper.prototype.compact=function(){return this.filter(identity)},LazyWrapper.prototype.find=function(predicate){return this.filter(predicate).head()},LazyWrapper.prototype.findLast=function(predicate){return this.reverse().find(predicate)},LazyWrapper.prototype.invokeMap=baseRest(function(path,args){return"function"==typeof path?new LazyWrapper(this):this.map(function(value){return baseInvoke(value,path,args)})}),LazyWrapper.prototype.reject=function(predicate){return this.filter(negate(getIteratee(predicate)))},LazyWrapper.prototype.slice=function(start,end){start=toInteger(start);var result=this;return result.__filtered__&&(start>0||0>end)?new LazyWrapper(result):(0>start?result=result.takeRight(-start):start&&(result=result.drop(start)),end!==undefined&&(end=toInteger(end),result=0>end?result.dropRight(-end):result.take(end-start)),result)},LazyWrapper.prototype.takeRightWhile=function(predicate){return this.reverse().takeWhile(predicate).reverse()},LazyWrapper.prototype.toArray=function(){return this.take(MAX_ARRAY_LENGTH)},baseForOwn(LazyWrapper.prototype,function(func,methodName){var checkIteratee=/^(?:filter|find|map|reject)|While$/.test(methodName),isTaker=/^(?:head|last)$/.test(methodName),lodashFunc=lodash[isTaker?"take"+("last"==methodName?"Right":""):methodName],retUnwrapped=isTaker||/^find/.test(methodName);lodashFunc&&(lodash.prototype[methodName]=function(){var value=this.__wrapped__,args=isTaker?[1]:arguments,isLazy=value instanceof LazyWrapper,iteratee=args[0],useLazy=isLazy||isArray(value),interceptor=function(value){var result=lodashFunc.apply(lodash,arrayPush([value],args));return isTaker&&chainAll?result[0]:result};useLazy&&checkIteratee&&"function"==typeof iteratee&&1!=iteratee.length&&(isLazy=useLazy=!1);var chainAll=this.__chain__,isHybrid=!!this.__actions__.length,isUnwrapped=retUnwrapped&&!chainAll,onlyLazy=isLazy&&!isHybrid;if(!retUnwrapped&&useLazy){value=onlyLazy?value:new LazyWrapper(this);var result=func.apply(value,args);return result.__actions__.push({func:thru,args:[interceptor],thisArg:undefined}),new LodashWrapper(result,chainAll)}return isUnwrapped&&onlyLazy?func.apply(this,args):(result=this.thru(interceptor),isUnwrapped?isTaker?result.value()[0]:result.value():result)})}),arrayEach(["pop","push","shift","sort","splice","unshift"],function(methodName){var func=arrayProto[methodName],chainName=/^(?:push|sort|unshift)$/.test(methodName)?"tap":"thru",retUnwrapped=/^(?:pop|shift)$/.test(methodName);lodash.prototype[methodName]=function(){var args=arguments;if(retUnwrapped&&!this.__chain__){var value=this.value();return func.apply(isArray(value)?value:[],args)}return this[chainName](function(value){return func.apply(isArray(value)?value:[],args)})}}),baseForOwn(LazyWrapper.prototype,function(func,methodName){var lodashFunc=lodash[methodName];if(lodashFunc){var key=lodashFunc.name+"",names=realNames[key]||(realNames[key]=[]);names.push({name:methodName,func:lodashFunc})}}),realNames[createHybrid(undefined,BIND_KEY_FLAG).name]=[{name:"wrapper",func:undefined}],LazyWrapper.prototype.clone=lazyClone,LazyWrapper.prototype.reverse=lazyReverse,LazyWrapper.prototype.value=lazyValue,lodash.prototype.at=wrapperAt,lodash.prototype.chain=wrapperChain,lodash.prototype.commit=wrapperCommit,lodash.prototype.next=wrapperNext,lodash.prototype.plant=wrapperPlant,lodash.prototype.reverse=wrapperReverse,lodash.prototype.toJSON=lodash.prototype.valueOf=lodash.prototype.value=wrapperValue, -lodash.prototype.first=lodash.prototype.head,iteratorSymbol&&(lodash.prototype[iteratorSymbol]=wrapperToIterator),lodash}var undefined,VERSION="4.16.0",LARGE_ARRAY_SIZE=200,FUNC_ERROR_TEXT="Expected a function",HASH_UNDEFINED="__lodash_hash_undefined__",MAX_MEMOIZE_SIZE=500,PLACEHOLDER="__lodash_placeholder__",BIND_FLAG=1,BIND_KEY_FLAG=2,CURRY_BOUND_FLAG=4,CURRY_FLAG=8,CURRY_RIGHT_FLAG=16,PARTIAL_FLAG=32,PARTIAL_RIGHT_FLAG=64,ARY_FLAG=128,REARG_FLAG=256,FLIP_FLAG=512,UNORDERED_COMPARE_FLAG=1,PARTIAL_COMPARE_FLAG=2,DEFAULT_TRUNC_LENGTH=30,DEFAULT_TRUNC_OMISSION="...",HOT_COUNT=500,HOT_SPAN=16,LAZY_FILTER_FLAG=1,LAZY_MAP_FLAG=2,LAZY_WHILE_FLAG=3,INFINITY=1/0,MAX_SAFE_INTEGER=9007199254740991,MAX_INTEGER=1.7976931348623157e308,NAN=NaN,MAX_ARRAY_LENGTH=4294967295,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH-1,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH>>>1,wrapFlags=[["ary",ARY_FLAG],["bind",BIND_FLAG],["bindKey",BIND_KEY_FLAG],["curry",CURRY_FLAG],["curryRight",CURRY_RIGHT_FLAG],["flip",FLIP_FLAG],["partial",PARTIAL_FLAG],["partialRight",PARTIAL_RIGHT_FLAG],["rearg",REARG_FLAG]],argsTag="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",genTag="[object GeneratorFunction]",mapTag="[object Map]",numberTag="[object Number]",objectTag="[object Object]",promiseTag="[object Promise]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]",weakMapTag="[object WeakMap]",weakSetTag="[object WeakSet]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]",reEmptyStringLeading=/\b__p \+= '';/g,reEmptyStringMiddle=/\b(__p \+=) '' \+/g,reEmptyStringTrailing=/(__e\(.*?\)|\b__t\)) \+\n'';/g,reEscapedHtml=/&(?:amp|lt|gt|quot|#39|#96);/g,reUnescapedHtml=/[&<>"'`]/g,reHasEscapedHtml=RegExp(reEscapedHtml.source),reHasUnescapedHtml=RegExp(reUnescapedHtml.source),reEscape=/<%-([\s\S]+?)%>/g,reEvaluate=/<%([\s\S]+?)%>/g,reInterpolate=/<%=([\s\S]+?)%>/g,reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/,reLeadingDot=/^\./,rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reHasRegExpChar=RegExp(reRegExpChar.source),reTrim=/^\s+|\s+$/g,reTrimStart=/^\s+/,reTrimEnd=/\s+$/,reWrapComment=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,reWrapDetails=/\{\n\/\* \[wrapped with (.+)\] \*/,reSplitDetails=/,? & /,reAsciiWord=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,reEscapeChar=/\\(\\)?/g,reEsTemplate=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,reFlags=/\w*$/,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsHostCtor=/^\[object .+?Constructor\]$/,reIsOctal=/^0o[0-7]+$/i,reIsUint=/^(?:0|[1-9]\d*)$/,reLatin=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,reNoMatch=/($^)/,reUnescapedString=/['\n\r\u2028\u2029\\]/g,rsAstralRange="\\ud800-\\udfff",rsComboMarksRange="\\u0300-\\u036f\\ufe20-\\ufe23",rsComboSymbolsRange="\\u20d0-\\u20f0",rsDingbatRange="\\u2700-\\u27bf",rsLowerRange="a-z\\xdf-\\xf6\\xf8-\\xff",rsMathOpRange="\\xac\\xb1\\xd7\\xf7",rsNonCharRange="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",rsPunctuationRange="\\u2000-\\u206f",rsSpaceRange=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",rsUpperRange="A-Z\\xc0-\\xd6\\xd8-\\xde",rsVarRange="\\ufe0e\\ufe0f",rsBreakRange=rsMathOpRange+rsNonCharRange+rsPunctuationRange+rsSpaceRange,rsApos="['’]",rsAstral="["+rsAstralRange+"]",rsBreak="["+rsBreakRange+"]",rsCombo="["+rsComboMarksRange+rsComboSymbolsRange+"]",rsDigits="\\d+",rsDingbat="["+rsDingbatRange+"]",rsLower="["+rsLowerRange+"]",rsMisc="[^"+rsAstralRange+rsBreakRange+rsDigits+rsDingbatRange+rsLowerRange+rsUpperRange+"]",rsFitz="\\ud83c[\\udffb-\\udfff]",rsModifier="(?:"+rsCombo+"|"+rsFitz+")",rsNonAstral="[^"+rsAstralRange+"]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",rsUpper="["+rsUpperRange+"]",rsZWJ="\\u200d",rsLowerMisc="(?:"+rsLower+"|"+rsMisc+")",rsUpperMisc="(?:"+rsUpper+"|"+rsMisc+")",rsOptLowerContr="(?:"+rsApos+"(?:d|ll|m|re|s|t|ve))?",rsOptUpperContr="(?:"+rsApos+"(?:D|LL|M|RE|S|T|VE))?",reOptMod=rsModifier+"?",rsOptVar="["+rsVarRange+"]?",rsOptJoin="(?:"+rsZWJ+"(?:"+[rsNonAstral,rsRegional,rsSurrPair].join("|")+")"+rsOptVar+reOptMod+")*",rsSeq=rsOptVar+reOptMod+rsOptJoin,rsEmoji="(?:"+[rsDingbat,rsRegional,rsSurrPair].join("|")+")"+rsSeq,rsSymbol="(?:"+[rsNonAstral+rsCombo+"?",rsCombo,rsRegional,rsSurrPair,rsAstral].join("|")+")",reApos=RegExp(rsApos,"g"),reComboMark=RegExp(rsCombo,"g"),reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g"),reUnicodeWord=RegExp([rsUpper+"?"+rsLower+"+"+rsOptLowerContr+"(?="+[rsBreak,rsUpper,"$"].join("|")+")",rsUpperMisc+"+"+rsOptUpperContr+"(?="+[rsBreak,rsUpper+rsLowerMisc,"$"].join("|")+")",rsUpper+"?"+rsLowerMisc+"+"+rsOptLowerContr,rsUpper+"+"+rsOptUpperContr,rsDigits,rsEmoji].join("|"),"g"),reHasUnicode=RegExp("["+rsZWJ+rsAstralRange+rsComboMarksRange+rsComboSymbolsRange+rsVarRange+"]"),reHasUnicodeWord=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,contextProps=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],templateCounter=-1,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[dataViewTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[mapTag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[setTag]=cloneableTags[stringTag]=cloneableTags[symbolTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=!0,cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[weakMapTag]=!1;var deburredLetters={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"},htmlEscapes={"&":"&","<":"<",">":">",'"':""","'":"'"},htmlUnescapes={"&":"&","<":"<",">":">",""":'"',"'":"'"},stringEscapes={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},freeParseFloat=parseFloat,freeParseInt=parseInt,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,freeProcess=moduleExports&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding("util")}catch(e){}}(),nodeIsArrayBuffer=nodeUtil&&nodeUtil.isArrayBuffer,nodeIsDate=nodeUtil&&nodeUtil.isDate,nodeIsMap=nodeUtil&&nodeUtil.isMap,nodeIsRegExp=nodeUtil&&nodeUtil.isRegExp,nodeIsSet=nodeUtil&&nodeUtil.isSet,nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,asciiSize=baseProperty("length"),deburrLetter=basePropertyOf(deburredLetters),escapeHtmlChar=basePropertyOf(htmlEscapes),unescapeHtmlChar=basePropertyOf(htmlUnescapes),_=runInContext();"function"==typeof define&&"object"==typeof define.amd&&define.amd?(root._=_,define(function(){return _})):freeModule?((freeModule.exports=_)._=_,freeExports._=_):root._=_}.call(this);var UsergridAuthMode=Object.freeze({NONE:"none",USER:"user",APP:"app"}),UsergridDirection=Object.freeze({IN:"connecting",OUT:"connections"}),UsergridHttpMethod=Object.freeze({GET:"GET",PUT:"PUT",POST:"POST",DELETE:"DELETE"}),UsergridQueryOperator=Object.freeze({EQUAL:"=",GREATER_THAN:">",GREATER_THAN_EQUAL_TO:">=",LESS_THAN:"<",LESS_THAN_EQUAL_TO:"<="}),UsergridQuerySortOrder=Object.freeze({ASC:"asc",DESC:"desc"});!function(global){function UsergridHelpers(){}var name="UsergridHelpers",overwrittenName=global[name];UsergridHelpers.validateAndRetrieveClient=function(args){var client=void 0;if(args instanceof UsergridClient)client=args;else if(args[0]instanceof UsergridClient)client=args[0];else if(_.get(args,"client"))client=args.client;else{if(!Usergrid.isInitialized)throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument");client=Usergrid}return client},UsergridHelpers.inherits=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})},UsergridHelpers.flattenArgs=function(args){return _.flattenDeep(Array.prototype.slice.call(args))},UsergridHelpers.callback=function(){var args=_.flattenDeep(Array.prototype.slice.call(arguments)).reverse(),emptyFunc=function(){};return _.first(_.flattenDeep([args,_.get(args,"0.callback"),emptyFunc]).filter(_.isFunction))},UsergridHelpers.doCallback=function(callback,params,context){var returnValue;return _.isFunction(callback)&&(params||(params=[]),context||(context=this),params.push(context),returnValue=callback.apply(context,params)),returnValue},UsergridHelpers.authForRequests=function(client){var authForRequests=void 0;return _.get(client,"tempAuth.isValid")?(authForRequests=client.tempAuth,client.tempAuth=void 0):_.get(client,"currentUser.auth.isValid")&&client.authMode===UsergridAuthMode.USER?authForRequests=client.currentUser.auth:_.get(client,"appAuth.isValid")&&client.authMode===UsergridAuthMode.APP&&(authForRequests=client.appAuth),authForRequests},UsergridHelpers.userLoginBody=function(options){var body={grant_type:"password",password:options.password};return options.tokenTtl&&(body.ttl=options.tokenTtl),body[options.username?"username":"email"]=options.username?options.username:options.email,body},UsergridHelpers.appLoginBody=function(options){var body={grant_type:"client_credentials",client_id:options.clientId,client_secret:options.clientSecret};return options.tokenTtl&&(body.ttl=options.tokenTtl),body},UsergridHelpers.calculateExpiry=function(expires_in){return Date.now()+1e3*(expires_in?expires_in-5:0)};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;return UsergridHelpers.isUUID=function(uuid){return uuid?uuidValueRegex.test(uuid):!1},UsergridHelpers.useQuotesIfRequired=function(value){return _.isFinite(value)||UsergridHelpers.isUUID(value)||_.isBoolean(value)||_.isObject(value)&&!_.isFunction(value)||_.isArray(value)?value:"'"+value+"'"},UsergridHelpers.setReadOnly=function(obj,key){return _.isArray(key)?key.forEach(function(k){UsergridHelpers.setReadOnly(obj,k)}):_.isPlainObject(obj[key])?Object.freeze(obj[key]):_.isPlainObject(obj)&&void 0===key?Object.freeze(obj):_.has(obj,key)?Object.defineProperty(obj,key,{writable:!1}):obj},UsergridHelpers.setWritable=function(obj,key){return _.isArray(key)?key.forEach(function(k){UsergridHelpers.setWritable(obj,k)}):_.isPlainObject(obj[key])?_.clone(obj[key]):_.isPlainObject(obj)&&void 0===key?_.clone(obj):_.has(obj,key)?Object.defineProperty(obj,key,{writable:!0}):obj},UsergridHelpers.assignPrefabOptions=function(args){return _.isObject(args[0])&&!_.isFunction(args[0])&&_.has(args,"method")&&_.assign(this,args[0]),this},UsergridHelpers.normalize=function(str){return str=str.replace(/:\//g,"://"),str=str.replace(/([^:\s])\/+/g,"$1/"),str=str.replace(/\/(\?|&|#[^!])/g,"$1"),str=str.replace(/(\?.+)\?/g,"$1&")},UsergridHelpers.urljoin=function(){var input=arguments,options={};"object"==typeof arguments[0]&&(input=arguments[0],options=arguments[1]||{});var joined=[].slice.call(input,0).join("/");return UsergridHelpers.normalize(joined,options)},UsergridHelpers.parseResponseHeaders=function(headerStr){var headers={};if(!headerStr)return headers;for(var headerPairs=headerStr.split("\r\n"),i=0;i0){var key=headerPair.substring(0,index);headers[key]=headerPair.substring(index+2)}}return headers},UsergridHelpers.uri=function(client,method,options){var path="";path=options instanceof UsergridEntity?options.type:options instanceof UsergridQuery?options._type:_.isString(options)?options:_.isArray(options)?_.get(options,"0.type")||_.get(options,"0.path"):options.path||options.type||_.get(options,"entity.type")||_.get(options,"query._type")||_.get(options,"body.type")||_.get(options,"body.path");var uuidOrName="";return method!==UsergridHttpMethod.POST&&(uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,_.get(options,"entity.uuid"),_.get(options,"entity.name"),_.get(options,"body.uuid"),_.get(options,"body.name"),""].filter(_.isString))),UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,path,uuidOrName)},UsergridHelpers.body=function(options){var rawBody=void 0;options instanceof UsergridEntity?rawBody=options:(rawBody=options.body||options.entity||options.entities,void 0===rawBody&&_.isArray(options)&&options[0]instanceof UsergridEntity&&(rawBody=options));var returnBody=rawBody;return rawBody instanceof UsergridEntity?returnBody=rawBody.jsonValue():rawBody instanceof Array&&rawBody[0]instanceof UsergridEntity&&(returnBody=_.map(rawBody,function(entity){return entity.jsonValue()})),returnBody},UsergridHelpers.updateEntityFromRemote=function(entity,usergridResponse){UsergridHelpers.setWritable(entity,["uuid","name","type","created"]),_.assign(entity,usergridResponse.entity),UsergridHelpers.setReadOnly(entity,["uuid","name","type","created"])},UsergridHelpers.headers=function(client,options){var headers={"User-Agent":"usergrid-js/v"+UsergridSDKVersion};_.assign(headers,options.headers);var authForRequests=UsergridHelpers.authForRequests(client);return authForRequests&&_.assign(headers,{authorization:"Bearer "+authForRequests.token}),headers},UsergridHelpers.encode=function(data){var result="";if("string"==typeof data)result=data;else{var encode=encodeURIComponent;_.forOwn(data,function(value,key){result+="&"+encode(key)+"="+encode(value)})}return result},UsergridHelpers.buildConnectionRequest=function(client,method,args){var options={client:client,method:method,entity:{},to:{}};if(UsergridHelpers.assignPrefabOptions.call(options,args),_.isObject(options.from)&&(options.to=options.from),_.isObject(args[0])&&_.has(args[0],"entity")&&_.has(args[0],"to")&&(_.assign(options.entity,args[0].entity),options.relationship=_.get(args,"0.relationship"),_.assign(options.to,args[0].to)),_.isObject(args[0])&&!_.isFunction(args[0])&&_.isString(args[1])&&(_.assign(options.entity,args[0]),options.relationship=_.first([options.relationship,args[1]].filter(_.isString))),_.isObject(args[2])&&!_.isFunction(args[2])&&_.assign(options.to,args[2]),options.entity.uuidOrName=_.first([options.entity.uuidOrName,options.entity.uuid,options.entity.name,args[1]].filter(_.isString)),options.entity.type||(options.entity.type=_.first([options.entity.type,args[0]].filter(_.isString))),options.relationship=_.first([options.relationship,args[2]].filter(_.isString)),_.isString(args[3])&&!UsergridHelpers.isUUID(args[3])&&_.isString(args[4])?options.to.type=args[3]:_.isString(args[2])&&!UsergridHelpers.isUUID(args[2])&&_.isString(args[3])&&_.isObject(args[0])&&!_.isFunction(args[0])&&(options.to.type=args[2]),options.to.uuidOrName=_.first([options.to.uuidOrName,options.to.uuid,options.to.name,args[4],args[3],args[2]].filter(function(property){return _.isString(options.to.type)&&_.isString(property)||UsergridHelpers.isUUID(property)})),!_.isString(options.entity.uuidOrName))throw new Error('source entity "uuidOrName" is required when connecting or disconnecting entities');if(!_.isString(options.to.uuidOrName))throw new Error('target entity "uuidOrName" is required when connecting or disconnecting entities');if(!_.isString(options.to.type)&&!UsergridHelpers.isUUID(options.to.uuidOrName))throw new Error('target "type" (collection name) parameter is required connecting or disconnecting entities by name');return options.uri=UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,_.isString(options.entity.type)?options.entity.type:"",_.isString(options.entity.uuidOrName)?options.entity.uuidOrName:"",options.relationship,_.isString(options.to.type)?options.to.type:"",_.isString(options.to.uuidOrName)?options.to.uuidOrName:""),new UsergridRequest(options)},UsergridHelpers.buildGetConnectionRequest=function(client,args){var options={client:client,method:"GET"};if(UsergridHelpers.assignPrefabOptions.call(options,args),_.isObject(args[1])&&!_.isFunction(args[1])&&_.assign(options,args[1]),options.direction=_.first([options.direction,args[0]].filter(function(property){return property===UsergridDirection.IN||property===UsergridDirection.OUT})),options.relationship=_.first([options.relationship,args[3],args[2]].filter(_.isString)),options.uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,args[2]].filter(_.isString)),options.type=_.first([options.type,args[1]].filter(_.isString)),!_.isString(options.type))throw new Error('"type" (collection name) parameter is required when retrieving connections');if(!_.isString(options.uuidOrName))throw new Error('target entity "uuidOrName" is required when retrieving connections');return options.uri=UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,_.isString(options.type)?options.type:"",_.isString(options.uuidOrName)?options.uuidOrName:"",options.direction,options.relationship),new UsergridRequest(options)},global[name]=UsergridHelpers,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),UsergridHelpers},global[name]}(this);var defaultOptions={baseUrl:"https://api.usergrid.com",authMode:UsergridAuthMode.USER},UsergridClient=function(options){var __appAuth,self=this;if(self.tempAuth=void 0,self.isSharedInstance=!1,2===arguments.length&&(self.orgId=arguments[0],self.appId=arguments[1]),_.defaults(self,options,defaultOptions),!self.orgId||!self.appId)throw new Error('"orgId" and "appId" parameters are required when instantiating UsergridClient');return Object.defineProperty(self,"clientId",{enumerable:!1}),Object.defineProperty(self,"clientSecret",{enumerable:!1}),Object.defineProperty(self,"appAuth",{get:function(){return __appAuth},set:function(options){options instanceof UsergridAppAuth?__appAuth=options:"undefined"!=typeof options&&(__appAuth=new UsergridAppAuth(options))}}),self.clientId&&self.clientSecret&&self.setAppAuth(self.clientId,self.clientSecret),self};UsergridClient.prototype={GET:function(options,callback){var self=this;return self.performRequest(new UsergridRequest({client:self,method:UsergridHttpMethod.GET,uri:UsergridHelpers.uri(self,UsergridHttpMethod.GET,options),query:options instanceof UsergridQuery?options:options.query,queryParams:options.queryParams,body:UsergridHelpers.body(options)}),callback)},PUT:function(options,callback){var self=this;return self.performRequest(new UsergridRequest({client:self,method:UsergridHttpMethod.PUT,uri:UsergridHelpers.uri(self,UsergridHttpMethod.PUT,options),query:options instanceof UsergridQuery?options:options.query,queryParams:options.queryParams,body:UsergridHelpers.body(options)}),callback)},POST:function(options,callback){var self=this;return self.performRequest(new UsergridRequest({client:self,method:UsergridHttpMethod.POST,uri:UsergridHelpers.uri(self,UsergridHttpMethod.POST,options),query:options instanceof UsergridQuery?options:options.query,queryParams:options.queryParams,body:UsergridHelpers.body(options)}),callback)},DELETE:function(options,callback){var self=this;return self.performRequest(new UsergridRequest({client:self,method:UsergridHttpMethod.DELETE,uri:UsergridHelpers.uri(self,UsergridHttpMethod.DELETE,options),query:options instanceof UsergridQuery?options:options.query,queryParams:options.queryParams,body:UsergridHelpers.body(options)}),callback)},connect:function(){var self=this;return self.performRequest(UsergridHelpers.buildConnectionRequest(self,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments)),UsergridHelpers.callback(arguments))},disconnect:function(){var self=this;return self.performRequest(UsergridHelpers.buildConnectionRequest(self,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments)),UsergridHelpers.callback(arguments))},getConnections:function(){var self=this;return self.performRequest(UsergridHelpers.buildGetConnectionRequest(self,UsergridHelpers.flattenArgs(arguments)),UsergridHelpers.callback(arguments))},setAppAuth:function(){this.appAuth=new UsergridAppAuth(UsergridHelpers.flattenArgs(arguments))},authenticateApp:function(options){var self=this,callback=UsergridHelpers.callback(UsergridHelpers.flattenArgs(arguments)),auth=_.first([options,self.appAuth,new UsergridAppAuth(options),new UsergridAppAuth(self.clientId,self.clientSecret)].filter(function(p){return p instanceof UsergridAppAuth}));if(!(auth instanceof UsergridAppAuth))throw new Error("App auth context was not defined when attempting to call .authenticateApp()");if(!auth.clientId||!auth.clientSecret)throw new Error("authenticateApp() failed because clientId or clientSecret are missing");var authCallback=function(usergridResponse){if(usergridResponse.ok){self.appAuth||(self.appAuth=auth),self.appAuth.token=_.get(usergridResponse.responseJSON,"access_token");var expiresIn=_.get(usergridResponse.responseJSON,"expires_in");self.appAuth.expiry=UsergridHelpers.calculateExpiry(expiresIn),self.appAuth.tokenTtl=expiresIn}callback(usergridResponse)};return self.performRequest(new UsergridRequest({client:self,method:UsergridHttpMethod.POST,uri:UsergridHelpers.uri(self,UsergridHttpMethod.POST,{path:"token"}),body:UsergridHelpers.appLoginBody(auth)}),authCallback)},authenticateUser:function(options){var self=this,args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args),setAsCurrentUser=void 0!==_.last(args.filter(_.isBoolean))?_.last(args.filter(_.isBoolean)):!0,currentUser=new UsergridUser(options);currentUser.login(self,function(auth,user,usergridResponse){usergridResponse.ok&&setAsCurrentUser&&(self.currentUser=currentUser),callback(auth,user,usergridResponse)})},usingAuth:function(auth){return _.isString(auth)?this.tempAuth=new UsergridAuth(auth):auth instanceof UsergridAuth?this.tempAuth=auth:this.tempAuth=void 0,this},downloadAsset:function(entity,callback){var self=this,uploadRequest=new UsergridRequest({client:self,method:UsergridHttpMethod.GET,uri:UsergridHelpers.uri(self,UsergridHttpMethod.GET,entity)});return self.performAssetDownloadRequest(uploadRequest,entity,callback)},uploadAsset:function(entity,asset,callback){var self=this,method=UsergridHttpMethod.PUT,uploadRequest=new UsergridRequest({client:self,method:method,uri:UsergridHelpers.uri(self,method,entity),asset:asset});return self.performAssetUploadRequest(uploadRequest,entity,callback)},performRequest:function(usergridRequest,callback){var self=this,requestPromise=function(){var promise=new Promise,xmlHttpRequest=new XMLHttpRequest;return xmlHttpRequest.open(usergridRequest.method.toString(),usergridRequest.uri),_.forOwn(usergridRequest.headers,function(value,key){xmlHttpRequest.setRequestHeader(key,value)}),xmlHttpRequest.open=function(){void 0!==usergridRequest.body&&(xmlHttpRequest.setRequestHeader("Content-Type","application/json"),xmlHttpRequest.setRequestHeader("Accept","application/json"))},xmlHttpRequest.onreadystatechange=function(){this.readyState===XMLHttpRequest.DONE&&promise.done(xmlHttpRequest)},xmlHttpRequest.send(UsergridHelpers.encode(usergridRequest.body)),promise}.bind(self),responsePromise=function(xmlRequest){var promise=new Promise,usergridResponse=new UsergridResponse(xmlRequest);return promise.done(usergridResponse),promise}.bind(self),onCompletePromise=function(response){var promise=new Promise;response.request=usergridRequest,promise.done(response),UsergridHelpers.doCallback(callback,[response])}.bind(self);return Promise.chain([requestPromise,responsePromise]).then(onCompletePromise),usergridRequest},performAssetDownloadRequest:function(usergridRequest,entity,callback){var req=new XMLHttpRequest;return req.open("GET",usergridRequest.uri,!0),req.setRequestHeader("Accept",_.get(entity,"file-metadata.content-type")),req.responseType="blob",req.onload=function(){entity.asset=new UsergridAsset(req.response),UsergridHelpers.doCallback(callback,[entity.asset,null,entity])},req.send(null),usergridRequest},performAssetUploadRequest:function(usergridRequest,entity,callback){var asset=usergridRequest.asset,xmlHttpRequest=new XMLHttpRequest;xmlHttpRequest.open(usergridRequest.method,usergridRequest.uri,!0),xmlHttpRequest.onload=function(){var response=new UsergridResponse(xmlHttpRequest);UsergridHelpers.updateEntityFromRemote(entity,response),UsergridHelpers.doCallback(callback,[asset,response,entity])};var formData=new FormData;return formData.append("file",asset.data),xmlHttpRequest.send(formData),usergridRequest}};var UsergridSDKVersion="2.0.0",UsergridClientSharedInstance=function(){var self=this;return self.isInitialized=!1,self.isSharedInstance=!0,self};UsergridHelpers.inherits(UsergridClientSharedInstance,UsergridClient);var Usergrid=new UsergridClientSharedInstance;Usergrid.initSharedInstance=function(options){return Usergrid.isInitialized?console.log("Usergrid shared instance is already initialized"):(_.assign(Usergrid,new UsergridClient(options)),Usergrid.isInitialized=!0,Usergrid.isSharedInstance=!0),Usergrid},Usergrid.init=Usergrid.initSharedInstance;var UsergridQuery=function(type){var queryString,sort,self=this,query="",__nextIsNot=!1;return self._type=type,_.assign(self,{type:function(value){return self._type=value,self},collection:function(value){return self._type=value,self},limit:function(value){return self._limit=value,self},cursor:function(value){return self._cursor=value,self},eq:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.EQUAL+" "+UsergridHelpers.useQuotesIfRequired(value)),self},equal:this.eq,gt:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.GREATER_THAN+" "+UsergridHelpers.useQuotesIfRequired(value)),self},greaterThan:this.gt,gte:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.GREATER_THAN_EQUAL_TO+" "+UsergridHelpers.useQuotesIfRequired(value)),self},greaterThanOrEqual:this.gte,lt:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.LESS_THAN+" "+UsergridHelpers.useQuotesIfRequired(value)),self},lessThan:this.lt,lte:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.LESS_THAN_EQUAL_TO+" "+UsergridHelpers.useQuotesIfRequired(value)),self},lessThanOrEqual:this.lte,contains:function(key,value){return query=self.andJoin(key+" contains "+UsergridHelpers.useQuotesIfRequired(value)),self},locationWithin:function(distanceInMeters,lat,lng){return query=self.andJoin("location within "+distanceInMeters+" of "+lat+", "+lng),self},asc:function(key){return self.sort(key,UsergridQuerySortOrder.ASC),self},desc:function(key){return self.sort(key,UsergridQuerySortOrder.DESC),self},sort:function(key,order){return sort=key&&order?" order by "+key+" "+order:"",self},fromString:function(string){return queryString=string,self},andJoin:function(append){return __nextIsNot&&(append="not "+append,__nextIsNot=!1),append?0===query.length?append:_.endsWith(query,"and")||_.endsWith(query,"or")?query+" "+append:query+" and "+append:query},orJoin:function(){return query.length>0&&!_.endsWith(query,"or")?query+" or":query}}),Object.defineProperty(self,"_ql",{get:function(){return void 0!==queryString?queryString:"select *"+(query.length>0||void 0!==sort?" where "+(query||"")+(sort||""):"")}}),Object.defineProperty(self,"encodedStringValue",{get:function(){var self=this,limit=self._limit,cursor=self._cursor,requirementsString=self._ql,encodedStringValue=void 0;if(void 0!==limit&&(encodedStringValue="limit"+UsergridQueryOperator.EQUAL+limit),!_.isEmpty(cursor)){var cursorString="cursor"+UsergridQueryOperator.EQUAL+cursor;_.isEmpty(encodedStringValue)?encodedStringValue=cursorString:encodedStringValue+="&"+cursorString}if(!_.isEmpty(requirementsString)){var qLString="ql="+encodeURIComponent(requirementsString);_.isEmpty(encodedStringValue)?encodedStringValue=qLString:encodedStringValue+="&"+qLString}return _.isEmpty(encodedStringValue)||(encodedStringValue="?"+encodedStringValue),_.isEmpty(encodedStringValue)?void 0:encodedStringValue}}),Object.defineProperty(self,"and",{get:function(){return query=self.andJoin(""),self}}),Object.defineProperty(self,"or",{get:function(){return query=self.orJoin(),self}}),Object.defineProperty(self,"not",{get:function(){return __nextIsNot=!0,self}}),self},UsergridRequest=function(options){var self=this,client=UsergridHelpers.validateAndRetrieveClient(options);if(!_.isString(options.type)&&!_.isString(options.path)&&!_.isString(options.uri))throw new Error('one of "type" (collection name), "path", or "uri" parameters are required when initializing a UsergridRequest');if(!_.includes(["GET","PUT","POST","DELETE"],options.method))throw new Error('"method" parameter is required when initializing a UsergridRequest');self.method=options.method,self.uri=options.uri||UsergridHelpers.uri(client,options), +lodash.prototype.first=lodash.prototype.head,iteratorSymbol&&(lodash.prototype[iteratorSymbol]=wrapperToIterator),lodash}var undefined,VERSION="4.16.0",LARGE_ARRAY_SIZE=200,FUNC_ERROR_TEXT="Expected a function",HASH_UNDEFINED="__lodash_hash_undefined__",MAX_MEMOIZE_SIZE=500,PLACEHOLDER="__lodash_placeholder__",BIND_FLAG=1,BIND_KEY_FLAG=2,CURRY_BOUND_FLAG=4,CURRY_FLAG=8,CURRY_RIGHT_FLAG=16,PARTIAL_FLAG=32,PARTIAL_RIGHT_FLAG=64,ARY_FLAG=128,REARG_FLAG=256,FLIP_FLAG=512,UNORDERED_COMPARE_FLAG=1,PARTIAL_COMPARE_FLAG=2,DEFAULT_TRUNC_LENGTH=30,DEFAULT_TRUNC_OMISSION="...",HOT_COUNT=500,HOT_SPAN=16,LAZY_FILTER_FLAG=1,LAZY_MAP_FLAG=2,LAZY_WHILE_FLAG=3,INFINITY=1/0,MAX_SAFE_INTEGER=9007199254740991,MAX_INTEGER=1.7976931348623157e308,NAN=NaN,MAX_ARRAY_LENGTH=4294967295,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH-1,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH>>>1,wrapFlags=[["ary",ARY_FLAG],["bind",BIND_FLAG],["bindKey",BIND_KEY_FLAG],["curry",CURRY_FLAG],["curryRight",CURRY_RIGHT_FLAG],["flip",FLIP_FLAG],["partial",PARTIAL_FLAG],["partialRight",PARTIAL_RIGHT_FLAG],["rearg",REARG_FLAG]],argsTag="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",genTag="[object GeneratorFunction]",mapTag="[object Map]",numberTag="[object Number]",objectTag="[object Object]",promiseTag="[object Promise]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]",weakMapTag="[object WeakMap]",weakSetTag="[object WeakSet]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]",reEmptyStringLeading=/\b__p \+= '';/g,reEmptyStringMiddle=/\b(__p \+=) '' \+/g,reEmptyStringTrailing=/(__e\(.*?\)|\b__t\)) \+\n'';/g,reEscapedHtml=/&(?:amp|lt|gt|quot|#39|#96);/g,reUnescapedHtml=/[&<>"'`]/g,reHasEscapedHtml=RegExp(reEscapedHtml.source),reHasUnescapedHtml=RegExp(reUnescapedHtml.source),reEscape=/<%-([\s\S]+?)%>/g,reEvaluate=/<%([\s\S]+?)%>/g,reInterpolate=/<%=([\s\S]+?)%>/g,reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/,reLeadingDot=/^\./,rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reHasRegExpChar=RegExp(reRegExpChar.source),reTrim=/^\s+|\s+$/g,reTrimStart=/^\s+/,reTrimEnd=/\s+$/,reWrapComment=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,reWrapDetails=/\{\n\/\* \[wrapped with (.+)\] \*/,reSplitDetails=/,? & /,reAsciiWord=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,reEscapeChar=/\\(\\)?/g,reEsTemplate=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,reFlags=/\w*$/,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsHostCtor=/^\[object .+?Constructor\]$/,reIsOctal=/^0o[0-7]+$/i,reIsUint=/^(?:0|[1-9]\d*)$/,reLatin=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,reNoMatch=/($^)/,reUnescapedString=/['\n\r\u2028\u2029\\]/g,rsAstralRange="\\ud800-\\udfff",rsComboMarksRange="\\u0300-\\u036f\\ufe20-\\ufe23",rsComboSymbolsRange="\\u20d0-\\u20f0",rsDingbatRange="\\u2700-\\u27bf",rsLowerRange="a-z\\xdf-\\xf6\\xf8-\\xff",rsMathOpRange="\\xac\\xb1\\xd7\\xf7",rsNonCharRange="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",rsPunctuationRange="\\u2000-\\u206f",rsSpaceRange=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",rsUpperRange="A-Z\\xc0-\\xd6\\xd8-\\xde",rsVarRange="\\ufe0e\\ufe0f",rsBreakRange=rsMathOpRange+rsNonCharRange+rsPunctuationRange+rsSpaceRange,rsApos="['’]",rsAstral="["+rsAstralRange+"]",rsBreak="["+rsBreakRange+"]",rsCombo="["+rsComboMarksRange+rsComboSymbolsRange+"]",rsDigits="\\d+",rsDingbat="["+rsDingbatRange+"]",rsLower="["+rsLowerRange+"]",rsMisc="[^"+rsAstralRange+rsBreakRange+rsDigits+rsDingbatRange+rsLowerRange+rsUpperRange+"]",rsFitz="\\ud83c[\\udffb-\\udfff]",rsModifier="(?:"+rsCombo+"|"+rsFitz+")",rsNonAstral="[^"+rsAstralRange+"]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",rsUpper="["+rsUpperRange+"]",rsZWJ="\\u200d",rsLowerMisc="(?:"+rsLower+"|"+rsMisc+")",rsUpperMisc="(?:"+rsUpper+"|"+rsMisc+")",rsOptLowerContr="(?:"+rsApos+"(?:d|ll|m|re|s|t|ve))?",rsOptUpperContr="(?:"+rsApos+"(?:D|LL|M|RE|S|T|VE))?",reOptMod=rsModifier+"?",rsOptVar="["+rsVarRange+"]?",rsOptJoin="(?:"+rsZWJ+"(?:"+[rsNonAstral,rsRegional,rsSurrPair].join("|")+")"+rsOptVar+reOptMod+")*",rsSeq=rsOptVar+reOptMod+rsOptJoin,rsEmoji="(?:"+[rsDingbat,rsRegional,rsSurrPair].join("|")+")"+rsSeq,rsSymbol="(?:"+[rsNonAstral+rsCombo+"?",rsCombo,rsRegional,rsSurrPair,rsAstral].join("|")+")",reApos=RegExp(rsApos,"g"),reComboMark=RegExp(rsCombo,"g"),reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g"),reUnicodeWord=RegExp([rsUpper+"?"+rsLower+"+"+rsOptLowerContr+"(?="+[rsBreak,rsUpper,"$"].join("|")+")",rsUpperMisc+"+"+rsOptUpperContr+"(?="+[rsBreak,rsUpper+rsLowerMisc,"$"].join("|")+")",rsUpper+"?"+rsLowerMisc+"+"+rsOptLowerContr,rsUpper+"+"+rsOptUpperContr,rsDigits,rsEmoji].join("|"),"g"),reHasUnicode=RegExp("["+rsZWJ+rsAstralRange+rsComboMarksRange+rsComboSymbolsRange+rsVarRange+"]"),reHasUnicodeWord=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,contextProps=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],templateCounter=-1,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[dataViewTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[mapTag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[setTag]=cloneableTags[stringTag]=cloneableTags[symbolTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=!0,cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[weakMapTag]=!1;var deburredLetters={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"},htmlEscapes={"&":"&","<":"<",">":">",'"':""","'":"'"},htmlUnescapes={"&":"&","<":"<",">":">",""":'"',"'":"'"},stringEscapes={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},freeParseFloat=parseFloat,freeParseInt=parseInt,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,freeProcess=moduleExports&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding("util")}catch(e){}}(),nodeIsArrayBuffer=nodeUtil&&nodeUtil.isArrayBuffer,nodeIsDate=nodeUtil&&nodeUtil.isDate,nodeIsMap=nodeUtil&&nodeUtil.isMap,nodeIsRegExp=nodeUtil&&nodeUtil.isRegExp,nodeIsSet=nodeUtil&&nodeUtil.isSet,nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,asciiSize=baseProperty("length"),deburrLetter=basePropertyOf(deburredLetters),escapeHtmlChar=basePropertyOf(htmlEscapes),unescapeHtmlChar=basePropertyOf(htmlUnescapes),_=runInContext();"function"==typeof define&&"object"==typeof define.amd&&define.amd?(root._=_,define(function(){return _})):freeModule?((freeModule.exports=_)._=_,freeExports._=_):root._=_}.call(this);var UsergridAuthMode=Object.freeze({NONE:"none",USER:"user",APP:"app"}),UsergridDirection=Object.freeze({IN:"connecting",OUT:"connections"}),UsergridHttpMethod=Object.freeze({GET:"GET",PUT:"PUT",POST:"POST",DELETE:"DELETE"}),UsergridQueryOperator=Object.freeze({EQUAL:"=",GREATER_THAN:">",GREATER_THAN_EQUAL_TO:">=",LESS_THAN:"<",LESS_THAN_EQUAL_TO:"<="}),UsergridQuerySortOrder=Object.freeze({ASC:"asc",DESC:"desc"});!function(global){function UsergridHelpers(){}var name="UsergridHelpers",overwrittenName=global[name];UsergridHelpers.validateAndRetrieveClient=function(args){var client=void 0;if(args instanceof UsergridClient)client=args;else if(args[0]instanceof UsergridClient)client=args[0];else if(_.get(args,"client"))client=args.client;else{if(!Usergrid.isInitialized)throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument");client=Usergrid}return client},UsergridHelpers.inherits=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})},UsergridHelpers.flattenArgs=function(args){return _.flattenDeep(Array.prototype.slice.call(args))},UsergridHelpers.callback=function(){var args=_.flattenDeep(Array.prototype.slice.call(arguments)).reverse(),emptyFunc=function(){};return _.first(_.flattenDeep([args,_.get(args,"0.callback"),emptyFunc]).filter(_.isFunction))},UsergridHelpers.doCallback=function(callback,params,context){var returnValue;return _.isFunction(callback)&&(params||(params=[]),context||(context=this),params.push(context),returnValue=callback.apply(context,params)),returnValue},UsergridHelpers.authForRequests=function(client){var authForRequests=void 0;return _.get(client,"tempAuth.isValid")?(authForRequests=client.tempAuth,client.tempAuth=void 0):_.get(client,"currentUser.auth.isValid")&&client.authMode===UsergridAuthMode.USER?authForRequests=client.currentUser.auth:_.get(client,"appAuth.isValid")&&client.authMode===UsergridAuthMode.APP&&(authForRequests=client.appAuth),authForRequests},UsergridHelpers.userLoginBody=function(options){var body={grant_type:"password",password:options.password};return options.tokenTtl&&(body.ttl=options.tokenTtl),body[options.username?"username":"email"]=options.username?options.username:options.email,body},UsergridHelpers.appLoginBody=function(options){var body={grant_type:"client_credentials",client_id:options.clientId,client_secret:options.clientSecret};return options.tokenTtl&&(body.ttl=options.tokenTtl),body},UsergridHelpers.calculateExpiry=function(expires_in){return Date.now()+1e3*(expires_in?expires_in-5:0)};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;return UsergridHelpers.isUUID=function(uuid){return uuid?uuidValueRegex.test(uuid):!1},UsergridHelpers.useQuotesIfRequired=function(value){return _.isFinite(value)||UsergridHelpers.isUUID(value)||_.isBoolean(value)||_.isObject(value)&&!_.isFunction(value)||_.isArray(value)?value:"'"+value+"'"},UsergridHelpers.setReadOnly=function(obj,key){return _.isArray(key)?key.forEach(function(k){UsergridHelpers.setReadOnly(obj,k)}):_.isPlainObject(obj[key])?Object.freeze(obj[key]):_.isPlainObject(obj)&&void 0===key?Object.freeze(obj):_.has(obj,key)?Object.defineProperty(obj,key,{writable:!1}):obj},UsergridHelpers.setWritable=function(obj,key){return _.isArray(key)?key.forEach(function(k){UsergridHelpers.setWritable(obj,k)}):_.isPlainObject(obj[key])?_.clone(obj[key]):_.isPlainObject(obj)&&void 0===key?_.clone(obj):_.has(obj,key)?Object.defineProperty(obj,key,{writable:!0}):obj},UsergridHelpers.assignPrefabOptions=function(args){return _.isObject(args[0])&&!_.isFunction(args[0])&&_.has(args,"method")&&_.assign(this,args[0]),this},UsergridHelpers.normalize=function(str){return str=str.replace(/:\//g,"://"),str=str.replace(/([^:\s])\/+/g,"$1/"),str=str.replace(/\/(\?|&|#[^!])/g,"$1"),str=str.replace(/(\?.+)\?/g,"$1&")},UsergridHelpers.urljoin=function(){var input=arguments,options={};"object"==typeof arguments[0]&&(input=arguments[0],options=arguments[1]||{});var joined=[].slice.call(input,0).join("/");return UsergridHelpers.normalize(joined,options)},UsergridHelpers.parseResponseHeaders=function(headerStr){var headers={};if(!headerStr)return headers;for(var headerPairs=headerStr.split("\r\n"),i=0;i0){var key=headerPair.substring(0,index);headers[key]=headerPair.substring(index+2)}}return headers},UsergridHelpers.uri=function(client,method,options){var path="";path=options instanceof UsergridEntity?options.type:options instanceof UsergridQuery?options._type:_.isString(options)?options:_.isArray(options)?_.get(options,"0.type")||_.get(options,"0.path"):options.path||options.type||_.get(options,"entity.type")||_.get(options,"query._type")||_.get(options,"body.type")||_.get(options,"body.path");var uuidOrName="";return method!==UsergridHttpMethod.POST&&(uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,_.get(options,"entity.uuid"),_.get(options,"entity.name"),_.get(options,"body.uuid"),_.get(options,"body.name"),""].filter(_.isString))),UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,path,uuidOrName)},UsergridHelpers.body=function(options){var rawBody=void 0;options instanceof UsergridEntity?rawBody=options:(rawBody=options.body||options.entity||options.entities,void 0===rawBody&&_.isArray(options)&&options[0]instanceof UsergridEntity&&(rawBody=options));var returnBody=rawBody;return rawBody instanceof UsergridEntity?returnBody=rawBody.jsonValue():rawBody instanceof Array&&rawBody[0]instanceof UsergridEntity&&(returnBody=_.map(rawBody,function(entity){return entity.jsonValue()})),returnBody},UsergridHelpers.updateEntityFromRemote=function(entity,usergridResponse){UsergridHelpers.setWritable(entity,["uuid","name","type","created"]),_.assign(entity,usergridResponse.entity),UsergridHelpers.setReadOnly(entity,["uuid","name","type","created"])},UsergridHelpers.headers=function(client,options){var headers={"User-Agent":"usergrid-js/v"+UsergridSDKVersion};_.assign(headers,options.headers);var authForRequests=UsergridHelpers.authForRequests(client);return authForRequests&&_.assign(headers,{authorization:"Bearer "+authForRequests.token}),headers},UsergridHelpers.encode=function(data){var result="";if("string"==typeof data)result=data;else{var encode=encodeURIComponent;_.forOwn(data,function(value,key){result+="&"+encode(key)+"="+encode(value)})}return result},UsergridHelpers.buildConnectionRequest=function(client,method,args){var options={client:client,method:method,entity:{},to:{}};if(UsergridHelpers.assignPrefabOptions.call(options,args),_.isObject(options.from)&&(options.to=options.from),_.isObject(args[0])&&_.has(args[0],"entity")&&_.has(args[0],"to")&&(_.assign(options.entity,args[0].entity),options.relationship=_.get(args,"0.relationship"),_.assign(options.to,args[0].to)),_.isObject(args[0])&&!_.isFunction(args[0])&&_.isString(args[1])&&(_.assign(options.entity,args[0]),options.relationship=_.first([options.relationship,args[1]].filter(_.isString))),_.isObject(args[2])&&!_.isFunction(args[2])&&_.assign(options.to,args[2]),options.entity.uuidOrName=_.first([options.entity.uuidOrName,options.entity.uuid,options.entity.name,args[1]].filter(_.isString)),options.entity.type||(options.entity.type=_.first([options.entity.type,args[0]].filter(_.isString))),options.relationship=_.first([options.relationship,args[2]].filter(_.isString)),_.isString(args[3])&&!UsergridHelpers.isUUID(args[3])&&_.isString(args[4])?options.to.type=args[3]:_.isString(args[2])&&!UsergridHelpers.isUUID(args[2])&&_.isString(args[3])&&_.isObject(args[0])&&!_.isFunction(args[0])&&(options.to.type=args[2]),options.to.uuidOrName=_.first([options.to.uuidOrName,options.to.uuid,options.to.name,args[4],args[3],args[2]].filter(function(property){return _.isString(options.to.type)&&_.isString(property)||UsergridHelpers.isUUID(property)})),!_.isString(options.entity.uuidOrName))throw new Error('source entity "uuidOrName" is required when connecting or disconnecting entities');if(!_.isString(options.to.uuidOrName))throw new Error('target entity "uuidOrName" is required when connecting or disconnecting entities');if(!_.isString(options.to.type)&&!UsergridHelpers.isUUID(options.to.uuidOrName))throw new Error('target "type" (collection name) parameter is required connecting or disconnecting entities by name');return options.uri=UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,_.isString(options.entity.type)?options.entity.type:"",_.isString(options.entity.uuidOrName)?options.entity.uuidOrName:"",options.relationship,_.isString(options.to.type)?options.to.type:"",_.isString(options.to.uuidOrName)?options.to.uuidOrName:""),new UsergridRequest(options)},UsergridHelpers.buildGetConnectionRequest=function(client,args){var options={client:client,method:"GET"};if(UsergridHelpers.assignPrefabOptions.call(options,args),_.isObject(args[1])&&!_.isFunction(args[1])&&_.assign(options,args[1]),options.direction=_.first([options.direction,args[0]].filter(function(property){return property===UsergridDirection.IN||property===UsergridDirection.OUT})),options.relationship=_.first([options.relationship,args[3],args[2]].filter(_.isString)),options.uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,args[2]].filter(_.isString)),options.type=_.first([options.type,args[1]].filter(_.isString)),!_.isString(options.type))throw new Error('"type" (collection name) parameter is required when retrieving connections');if(!_.isString(options.uuidOrName))throw new Error('target entity "uuidOrName" is required when retrieving connections');return options.uri=UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,_.isString(options.type)?options.type:"",_.isString(options.uuidOrName)?options.uuidOrName:"",options.direction,options.relationship),new UsergridRequest(options)},global[name]=UsergridHelpers,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),UsergridHelpers},global[name]}(this);var defaultOptions={baseUrl:"https://api.usergrid.com",authMode:UsergridAuthMode.USER},UsergridClient=function(options){var __appAuth,self=this;if(self.tempAuth=void 0,self.isSharedInstance=!1,2===arguments.length&&(self.orgId=arguments[0],self.appId=arguments[1]),_.defaults(self,options,defaultOptions),!self.orgId||!self.appId)throw new Error('"orgId" and "appId" parameters are required when instantiating UsergridClient');return Object.defineProperty(self,"clientId",{enumerable:!1}),Object.defineProperty(self,"clientSecret",{enumerable:!1}),Object.defineProperty(self,"appAuth",{get:function(){return __appAuth},set:function(options){options instanceof UsergridAppAuth?__appAuth=options:"undefined"!=typeof options&&(__appAuth=new UsergridAppAuth(options))}}),self.clientId&&self.clientSecret&&self.setAppAuth(self.clientId,self.clientSecret),self};UsergridClient.prototype={GET:function(options,callback){var self=this;return self.performRequest(new UsergridRequest({client:self,method:UsergridHttpMethod.GET,uri:UsergridHelpers.uri(self,UsergridHttpMethod.GET,options),query:options instanceof UsergridQuery?options:options.query,queryParams:options.queryParams,body:UsergridHelpers.body(options)}),callback)},PUT:function(options,callback){var self=this;return self.performRequest(new UsergridRequest({client:self,method:UsergridHttpMethod.PUT,uri:UsergridHelpers.uri(self,UsergridHttpMethod.PUT,options),query:options instanceof UsergridQuery?options:options.query,queryParams:options.queryParams,body:UsergridHelpers.body(options)}),callback)},POST:function(options,callback){var self=this;return self.performRequest(new UsergridRequest({client:self,method:UsergridHttpMethod.POST,uri:UsergridHelpers.uri(self,UsergridHttpMethod.POST,options),query:options instanceof UsergridQuery?options:options.query,queryParams:options.queryParams,body:UsergridHelpers.body(options)}),callback)},DELETE:function(options,callback){var self=this;return self.performRequest(new UsergridRequest({client:self,method:UsergridHttpMethod.DELETE,uri:UsergridHelpers.uri(self,UsergridHttpMethod.DELETE,options),query:options instanceof UsergridQuery?options:options.query,queryParams:options.queryParams,body:UsergridHelpers.body(options)}),callback)},connect:function(){var self=this;return self.performRequest(UsergridHelpers.buildConnectionRequest(self,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments)),UsergridHelpers.callback(arguments))},disconnect:function(){var self=this;return self.performRequest(UsergridHelpers.buildConnectionRequest(self,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments)),UsergridHelpers.callback(arguments))},getConnections:function(){var self=this;return self.performRequest(UsergridHelpers.buildGetConnectionRequest(self,UsergridHelpers.flattenArgs(arguments)),UsergridHelpers.callback(arguments))},setAppAuth:function(){this.appAuth=new UsergridAppAuth(UsergridHelpers.flattenArgs(arguments))},authenticateApp:function(options){var self=this,callback=UsergridHelpers.callback(UsergridHelpers.flattenArgs(arguments)),auth=_.first([options,self.appAuth,new UsergridAppAuth(options),new UsergridAppAuth(self.clientId,self.clientSecret)].filter(function(p){return p instanceof UsergridAppAuth}));if(!(auth instanceof UsergridAppAuth))throw new Error("App auth context was not defined when attempting to call .authenticateApp()");if(!auth.clientId||!auth.clientSecret)throw new Error("authenticateApp() failed because clientId or clientSecret are missing");var authCallback=function(usergridResponse){if(usergridResponse.ok){self.appAuth||(self.appAuth=auth),self.appAuth.token=_.get(usergridResponse.responseJSON,"access_token");var expiresIn=_.get(usergridResponse.responseJSON,"expires_in");self.appAuth.expiry=UsergridHelpers.calculateExpiry(expiresIn),self.appAuth.tokenTtl=expiresIn}callback(usergridResponse)};return self.performRequest(new UsergridRequest({client:self,method:UsergridHttpMethod.POST,uri:UsergridHelpers.uri(self,UsergridHttpMethod.POST,{path:"token"}),body:UsergridHelpers.appLoginBody(auth)}),authCallback)},authenticateUser:function(options){var self=this,args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args),setAsCurrentUser=void 0!==_.last(args.filter(_.isBoolean))?_.last(args.filter(_.isBoolean)):!0,currentUser=new UsergridUser(options);currentUser.login(self,function(auth,user,usergridResponse){usergridResponse.ok&&setAsCurrentUser&&(self.currentUser=currentUser),callback(auth,user,usergridResponse)})},usingAuth:function(auth){return _.isString(auth)?this.tempAuth=new UsergridAuth(auth):auth instanceof UsergridAuth?this.tempAuth=auth:this.tempAuth=void 0,this},downloadAsset:function(entity,callback){var self=this,uploadRequest=new UsergridRequest({client:self,method:UsergridHttpMethod.GET,uri:UsergridHelpers.uri(self,UsergridHttpMethod.GET,entity)});return self.performAssetDownloadRequest(uploadRequest,entity,callback)},uploadAsset:function(entity,asset,callback){var self=this,method=UsergridHttpMethod.PUT,uploadRequest=new UsergridRequest({client:self,method:method,uri:UsergridHelpers.uri(self,method,entity),asset:asset});return self.performAssetUploadRequest(uploadRequest,entity,callback)},performRequest:function(usergridRequest,callback){var self=this,requestPromise=function(){var promise=new Promise,xmlHttpRequest=new XMLHttpRequest;return xmlHttpRequest.open(usergridRequest.method.toString(),usergridRequest.uri),_.forOwn(usergridRequest.headers,function(value,key){xmlHttpRequest.setRequestHeader(key,value)}),xmlHttpRequest.open=function(){void 0!==usergridRequest.body&&(xmlHttpRequest.setRequestHeader("Content-Type","application/json"),xmlHttpRequest.setRequestHeader("Accept","application/json"))},xmlHttpRequest.onreadystatechange=function(){this.readyState===XMLHttpRequest.DONE&&promise.done(xmlHttpRequest)},xmlHttpRequest.send(UsergridHelpers.encode(usergridRequest.body)),promise}.bind(self),responsePromise=function(xmlRequest){var promise=new Promise,usergridResponse=new UsergridResponse(xmlRequest);return promise.done(usergridResponse),promise}.bind(self),onCompletePromise=function(response){var promise=new Promise;response.request=usergridRequest,promise.done(response),UsergridHelpers.doCallback(callback,[response])}.bind(self);return Promise.chain([requestPromise,responsePromise]).then(onCompletePromise),usergridRequest},performAssetDownloadRequest:function(usergridRequest,entity,callback){var req=new XMLHttpRequest;return req.open("GET",usergridRequest.uri,!0),req.setRequestHeader("Accept",_.get(entity,"file-metadata.content-type")),req.responseType="blob",req.onload=function(){entity.asset=new UsergridAsset(req.response),UsergridHelpers.doCallback(callback,[entity.asset,null,entity])},req.send(null),usergridRequest},performAssetUploadRequest:function(usergridRequest,entity,callback){var asset=usergridRequest.asset,xmlHttpRequest=new XMLHttpRequest;xmlHttpRequest.open(usergridRequest.method,usergridRequest.uri,!0),xmlHttpRequest.onload=function(){var response=new UsergridResponse(xmlHttpRequest);UsergridHelpers.updateEntityFromRemote(entity,response),UsergridHelpers.doCallback(callback,[asset,response,entity])};var formData=new FormData;return formData.append("file",asset.data),xmlHttpRequest.send(formData),usergridRequest}};var UsergridSDKVersion="2.0.0",UsergridClientSharedInstance=function(){var self=this;return self.isInitialized=!1,self.isSharedInstance=!0,self};UsergridHelpers.inherits(UsergridClientSharedInstance,UsergridClient);var Usergrid=new UsergridClientSharedInstance;Usergrid.initSharedInstance=function(options){return Usergrid.isInitialized?console.log("Usergrid shared instance is already initialized"):(_.assign(Usergrid,new UsergridClient(options)),Usergrid.isInitialized=!0,Usergrid.isSharedInstance=!0),Usergrid},Usergrid.init=Usergrid.initSharedInstance;var UsergridQuery=function(type){var queryString,sort,self=this,query="",__nextIsNot=!1;return self._type=type,_.assign(self,{type:function(value){return self._type=value,self},collection:function(value){return self._type=value,self},limit:function(value){return self._limit=value,self},cursor:function(value){return self._cursor=value,self},eq:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.EQUAL+" "+UsergridHelpers.useQuotesIfRequired(value)),self},equal:this.eq,gt:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.GREATER_THAN+" "+UsergridHelpers.useQuotesIfRequired(value)),self},greaterThan:this.gt,gte:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.GREATER_THAN_EQUAL_TO+" "+UsergridHelpers.useQuotesIfRequired(value)),self},greaterThanOrEqual:this.gte,lt:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.LESS_THAN+" "+UsergridHelpers.useQuotesIfRequired(value)),self},lessThan:this.lt,lte:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.LESS_THAN_EQUAL_TO+" "+UsergridHelpers.useQuotesIfRequired(value)),self},lessThanOrEqual:this.lte,contains:function(key,value){return query=self.andJoin(key+" contains "+UsergridHelpers.useQuotesIfRequired(value)),self},locationWithin:function(distanceInMeters,lat,lng){return query=self.andJoin("location within "+distanceInMeters+" of "+lat+", "+lng),self},asc:function(key){return self.sort(key,UsergridQuerySortOrder.ASC),self},desc:function(key){return self.sort(key,UsergridQuerySortOrder.DESC),self},sort:function(key,order){return sort=key&&order?" order by "+key+" "+order:"",self},fromString:function(string){return queryString=string,self},andJoin:function(append){return __nextIsNot&&(append="not "+append,__nextIsNot=!1),append?0===query.length?append:_.endsWith(query,"and")||_.endsWith(query,"or")?query+" "+append:query+" and "+append:query},orJoin:function(){return query.length>0&&!_.endsWith(query,"or")?query+" or":query}}),Object.defineProperty(self,"_ql",{get:function(){if(void 0!==queryString)return queryString;var qL="select * "+(query.length>0?"where "+(query||""):"");return qL+=void 0!==sort?sort:""}}),Object.defineProperty(self,"encodedStringValue",{get:function(){var self=this,limit=self._limit,cursor=self._cursor,requirementsString=self._ql,encodedStringValue=void 0;if(void 0!==limit&&(encodedStringValue="limit"+UsergridQueryOperator.EQUAL+limit),!_.isEmpty(cursor)){var cursorString="cursor"+UsergridQueryOperator.EQUAL+cursor;_.isEmpty(encodedStringValue)?encodedStringValue=cursorString:encodedStringValue+="&"+cursorString}if(!_.isEmpty(requirementsString)){var qLString="ql="+encodeURIComponent(requirementsString);_.isEmpty(encodedStringValue)?encodedStringValue=qLString:encodedStringValue+="&"+qLString}return _.isEmpty(encodedStringValue)||(encodedStringValue="?"+encodedStringValue),_.isEmpty(encodedStringValue)?void 0:encodedStringValue}}),Object.defineProperty(self,"and",{get:function(){return query=self.andJoin(""),self}}),Object.defineProperty(self,"or",{get:function(){return query=self.orJoin(),self}}),Object.defineProperty(self,"not",{get:function(){return __nextIsNot=!0,self}}),self},UsergridRequest=function(options){var self=this,client=UsergridHelpers.validateAndRetrieveClient(options);if(!_.isString(options.type)&&!_.isString(options.path)&&!_.isString(options.uri))throw new Error('one of "type" (collection name), "path", or "uri" parameters are required when initializing a UsergridRequest');if(!_.includes(["GET","PUT","POST","DELETE"],options.method))throw new Error('"method" parameter is required when initializing a UsergridRequest');self.method=options.method,self.uri=options.uri||UsergridHelpers.uri(client,options), self.headers=UsergridHelpers.headers(client,options),self.body=options.body||void 0,self.asset=options.asset||void 0,self.query=options.query,void 0!==self.query&&(self.uri+=UsergridHelpers.normalize(self.query.encodedStringValue,{})),self.queryParams=options.queryParams,void 0!==self.queryParams&&(_.forOwn(self.queryParams,function(value,key){self.uri+="?"+encodeURIComponent(key)+"="+encodeURIComponent(value)}),self.uri=UsergridHelpers.normalize(self.uri,{}));try{_.isPlainObject(self.body)&&(self.body=JSON.stringify(self.body)),_.isArray(self.body)&&(self.body=JSON.stringify(self.body))}catch(exception){}return self},UsergridAuth=function(token,expiry){var self=this;self.token=token,self.expiry=expiry||0;var usingToken=token?!0:!1;return Object.defineProperty(self,"hasToken",{get:function(){return void 0!==self.token},configurable:!0}),Object.defineProperty(self,"isExpired",{get:function(){return usingToken?!1:Date.now()>=self.expiry},configurable:!0}),Object.defineProperty(self,"isValid",{get:function(){return!self.isExpired&&self.hasToken},configurable:!0}),Object.defineProperty(self,"tokenTtl",{configurable:!0,writable:!0}),_.assign(self,{destroy:function(){self.token=void 0,self.expiry=0,self.tokenTtl=void 0}}),self},UsergridAppAuth=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments);return _.isPlainObject(args[0])?(self.clientId=args[0].clientId,self.clientSecret=args[0].clientSecret,self.tokenTtl=args[0].tokenTtl):(self.clientId=args[0],self.clientSecret=args[1],self.tokenTtl=args[2]),UsergridAuth.call(self),_.assign(self,UsergridAuth),self};UsergridHelpers.inherits(UsergridAppAuth,UsergridAuth);var UsergridUserAuth=function(options){var self=this,args=_.flattenDeep(UsergridHelpers.flattenArgs(arguments));return _.isPlainObject(args[0])&&(options=args[0]),self.username=options.username||args[0],self.email=options.email,(options.password||args[1])&&(self.password=options.password||args[1]),self.tokenTtl=options.tokenTtl||args[2],UsergridAuth.call(self),_.assign(self,UsergridAuth),self};UsergridHelpers.inherits(UsergridUserAuth,UsergridAuth);var UsergridEntity=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments);if(0===args.length)throw new Error("A UsergridEntity object cannot be initialized without passing one or more arguments");if(self.asset=void 0,_.isPlainObject(args[0])?_.assign(self,args[0]):(self.type||(self.type=_.isString(args[0])?args[0]:void 0),self.name||(self.name=_.isString(args[1])?args[1]:void 0)),!_.isString(self.type))throw new Error('"type" (or "collection") parameter is required when initializing a UsergridEntity object');return Object.defineProperty(self,"isUser",{get:function(){return"user"===self.type.toLowerCase()}}),Object.defineProperty(self,"hasAsset",{get:function(){return _.has(self,"file-metadata")}}),UsergridHelpers.setReadOnly(self,["uuid","name","type","created"]),self};UsergridEntity.prototype={jsonValue:function(){var jsonValue={};return _.forOwn(this,function(value,key){jsonValue[key]=value}),jsonValue},putProperty:function(key,value){this[key]=value},putProperties:function(obj){_.assign(this,obj)},removeProperty:function(key){this.removeProperties([key])},removeProperties:function(keys){var self=this;keys.forEach(function(key){delete self[key]})},insert:function(key,value,idx){_.isArray(this[key])||(this[key]=this[key]?[this[key]]:[]),this[key].splice.apply(this[key],[idx,0].concat(value))},append:function(key,value){this.insert(key,value,Number.MAX_VALUE)},prepend:function(key,value){this.insert(key,value,0)},pop:function(key){_.isArray(this[key])&&this[key].pop()},shift:function(key){_.isArray(this[key])&&this[key].shift()},reload:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.GET(this,function(usergridResponse){UsergridHelpers.updateEntityFromRemote(this,usergridResponse),callback(usergridResponse)}.bind(this))},save:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args),uuid=this.uuid;void 0===uuid?client.POST(this,function(usergridResponse){UsergridHelpers.updateEntityFromRemote(this,usergridResponse),callback(usergridResponse,this)}.bind(this)):client.PUT(this,function(usergridResponse){UsergridHelpers.updateEntityFromRemote(this,usergridResponse),callback(usergridResponse,this)}.bind(this))},remove:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.DELETE(this,function(usergridResponse){callback(usergridResponse,this)}.bind(this))},attachAsset:function(asset){this.asset=asset},uploadAsset:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.uploadAsset(this,this.asset,function(asset,usergridResponse){UsergridHelpers.updateEntityFromRemote(this,usergridResponse),this.asset=asset,callback(asset,usergridResponse,this)}.bind(this))},downloadAsset:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.downloadAsset(this,callback)},connect:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args[0]=this,client.connect.apply(client,args)},disconnect:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args[0]=this,client.disconnect.apply(client,args)},getConnections:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args.shift(),args.splice(1,0,this),client.getConnections.apply(client,args)}};var UsergridUser=function(obj){if(!_.has(obj,"email")&&!_.has(obj,"username"))throw new Error('"email" or "username" property is required when initializing a UsergridUser object');var self=this;return _.assign(self,obj,UsergridEntity),UsergridEntity.call(self,"user"),UsergridHelpers.setWritable(self,"name"),self};UsergridUser.CheckAvailable=function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);args[0]instanceof UsergridClient&&args.shift();var checkQuery,callback=UsergridHelpers.callback(args);if(args[0].username&&args[0].email)checkQuery=new UsergridQuery("users").eq("username",args[0].username).or.eq("email",args[0].email);else if(args[0].username)checkQuery=new UsergridQuery("users").eq("username",args[0].username);else{if(!args[0].email)throw new Error("'username' or 'email' property is required when checking for available users");checkQuery=new UsergridQuery("users").eq("email",args[0].email)}client.GET(checkQuery,function(usergridResponse){callback(usergridResponse,usergridResponse.entities.length>0)})},UsergridHelpers.inherits(UsergridUser,UsergridEntity),UsergridUser.prototype.uniqueId=function(){var self=this;return _.first([self.uuid,self.username,self.email].filter(_.isString))},UsergridUser.prototype.create=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.POST(self,function(usergridResponse){delete self.password,_.assign(self,usergridResponse.user),callback(usergridResponse)}.bind(self))},UsergridUser.prototype.login=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args),client=UsergridHelpers.validateAndRetrieveClient(args);client.POST({path:"token",body:UsergridHelpers.userLoginBody(self)},function(usergridResponse){if(delete self.password,usergridResponse.ok){var responseJSON=usergridResponse.responseJSON;self.auth=new UsergridUserAuth(self),self.auth.token=_.get(responseJSON,"access_token");var expiresIn=_.get(responseJSON,"expires_in");self.auth.expiry=UsergridHelpers.calculateExpiry(expiresIn),self.auth.tokenTtl=expiresIn}callback(self.auth,self,usergridResponse)})},UsergridUser.prototype.logout=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args);if(!self.auth||!self.auth.isValid){var response=new UsergridResponse;return response.error=new UsergridResponseError({error:"no_valid_token",description:"this user does not have a valid token"}),callback(response)}var revokeAll=_.first(args.filter(_.isBoolean))||!1,revokeTokenPath=["users",self.uniqueId(),"revoketoken"+(revokeAll?"s":"")].join("/"),queryParams=void 0;revokeAll||(queryParams={token:self.auth.token});var client=UsergridHelpers.validateAndRetrieveClient(args);return client.PUT({path:revokeTokenPath,queryParams:queryParams},function(usergridResponse){self.auth.destroy(),callback(usergridResponse)})},UsergridUser.prototype.logoutAllSessions=function(){var args=UsergridHelpers.flattenArgs(arguments);return args=_.concat([UsergridHelpers.validateAndRetrieveClient(args),!0],args),this.logout.apply(this,args)},UsergridUser.prototype.resetPassword=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args),client=UsergridHelpers.validateAndRetrieveClient(args);args[0]instanceof UsergridClient&&args.shift();var body={oldpassword:_.isPlainObject(args[0])?args[0].oldPassword:_.isString(args[0])?args[0]:void 0,newpassword:_.isPlainObject(args[0])?args[0].newPassword:_.isString(args[1])?args[1]:void 0};if(!body.oldpassword||!body.newpassword)throw new Error('"oldPassword" and "newPassword" properties are required when resetting a user password');return client.PUT({path:["users",self.uniqueId(),"password"].join("/"),body:body},function(usergridResponse){callback(usergridResponse)})};var UsergridResponseError=function(responseErrorObject){var self=this;if(_.has(responseErrorObject,"error")!==!1)return self.name=responseErrorObject.error,self.description=responseErrorObject.error_description||responseErrorObject.description,self.exception=responseErrorObject.exception,self},UsergridResponse=function(request){var self=this;if(self.ok=!1,request){self.statusCode=parseInt(request.status),self.headers=UsergridHelpers.parseResponseHeaders(request.getAllResponseHeaders());try{var responseText=request.responseText,responseJSON=JSON.parse(responseText)}catch(e){responseJSON={}}if(self.statusCode<400){if(self.ok=!0,_.assign(self,{responseJSON:_.cloneDeep(responseJSON)}),_.has(responseJSON,"entities")){var entities=_.map(responseJSON.entities,function(en){var entity=new UsergridEntity(en);return entity.isUser&&(entity=new UsergridUser(entity)),entity});_.assign(self,{entities:entities}),delete self.responseJSON.entities,self.first=_.first(entities)||void 0,self.entity=self.first,self.last=_.last(entities)||void 0,"/users"===_.get(self,"responseJSON.path")&&(self.user=self.first,self.users=self.entities),Object.defineProperty(self,"hasNextPage",{get:function(){return _.has(self,"responseJSON.cursor")}}),UsergridHelpers.setReadOnly(self.responseJSON)}}else self.error=new UsergridResponseError(responseJSON)}return self};UsergridResponse.prototype={loadNextPage:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args);self.responseJSON.cursor||callback();var client=UsergridHelpers.validateAndRetrieveClient(args),type=_.last(_.get(self,"responseJSON.path").split("/")),limit=_.first(_.get(this,"responseJSON.params.limit")),query=new UsergridQuery(type).cursor(this.responseJSON.cursor).limit(limit);return client.GET(query,callback)}};var UsergridAssetDefaultFileName="file",UsergridAsset=function(fileOrBlob){if(!fileOrBlob instanceof File||!fileOrBlob instanceof Blob)throw new Error("UsergridAsset must be initialized with a 'File' or 'Blob'");var self=this;return self.data=fileOrBlob,self.filename=fileOrBlob.name||UsergridAssetDefaultFileName,self.contentLength=fileOrBlob.size,self.contentType=fileOrBlob.type,self}; \ No newline at end of file From b702fdfb44feb87b45e459970b93cccef37dea5a Mon Sep 17 00:00:00 2001 From: Robert Walsh Date: Wed, 12 Oct 2016 19:22:49 -0500 Subject: [PATCH 26/36] Major updates. --- examples/all-calls/app.js | 8 +- examples/dogs/app.js | 2 +- lib/Usergrid.js | 32 +- lib/modules/UsergridAsset.js | 20 +- lib/modules/UsergridAuth.js | 86 +-- lib/modules/UsergridClient.js | 266 +++----- lib/modules/UsergridEntity.js | 190 +++--- lib/modules/UsergridQuery.js | 168 ++--- lib/modules/UsergridRequest.js | 91 ++- lib/modules/UsergridResponse.js | 136 ++-- lib/modules/UsergridUser.js | 185 ++--- lib/modules/util/UsergridHelpers.js | 256 ++++--- tests/mocha/index.html | 20 +- tests/mocha/test_asset.js | 159 +++-- tests/mocha/test_client_auth.js | 527 ++++++++------- tests/mocha/test_client_connections.js | 352 +++++----- tests/mocha/test_client_rest.js | 712 ++++++++++---------- tests/mocha/test_entity.js | 890 +++++++++++++------------ tests/mocha/test_helpers.js | 60 +- tests/mocha/test_response.js | 243 +++---- tests/mocha/test_response_error.js | 46 +- tests/mocha/test_user.js | 365 +++++----- tests/mocha/test_usergrid_init.js | 25 +- usergrid.js | 725 +++++++++++--------- usergrid.min.js | 6 +- 25 files changed, 2962 insertions(+), 2608 deletions(-) diff --git a/examples/all-calls/app.js b/examples/all-calls/app.js index 4457691..194b4f0 100755 --- a/examples/all-calls/app.js +++ b/examples/all-calls/app.js @@ -127,7 +127,7 @@ $(document).ready(function () { function _get() { var endpoint = $("#get-path").val(); - client.GET({path:endpoint},function(usergridResponse) { + client.GET(endpoint, function(usergridResponse) { var err = usergridResponse.error if (err) { $("#response").html('
    ERROR: '+JSON.stringify(err,null,2)+'
    '); @@ -141,7 +141,7 @@ $(document).ready(function () { var endpoint = $("#post-path").val(); var data = $("#post-data").val(); data = JSON.parse(data); - client.POST({path:endpoint,body:data}, function (usergridResponse) { + client.POST(endpoint, data, function (usergridResponse) { var err = usergridResponse.error if (err) { $("#response").html('
    ERROR: '+JSON.stringify(err,null,2)+'
    '); @@ -155,7 +155,7 @@ $(document).ready(function () { var endpoint = $("#put-path").val(); var data = $("#put-data").val(); data = JSON.parse(data); - client.PUT({path:endpoint,body:data}, function (usergridResponse) { + client.PUT(endpoint, data, function (usergridResponse) { var err = usergridResponse.error if (err) { $("#response").html('
    ERROR: '+JSON.stringify(err,null,2)+'
    '); @@ -167,7 +167,7 @@ $(document).ready(function () { function _delete() { var endpoint = $("#delete-path").val(); - client.DELETE({path:endpoint}, function (usergridResponse) { + client.DELETE(endpoint, function (usergridResponse) { var err = usergridResponse.error if (err) { $("#response").html('
    ERROR: '+JSON.stringify(err,null,2)+'
    '); diff --git a/examples/dogs/app.js b/examples/dogs/app.js index 274eed1..ed68063 100755 --- a/examples/dogs/app.js +++ b/examples/dogs/app.js @@ -115,7 +115,7 @@ $(document).ready(function () { nameHelp.html(Usergrid.validation.getNameAllowedChars()); createDogButton.removeClass("disabled");}) ) { - client.POST({type:'dogs',body:{ name:name }}, function(usergridResponse) { + client.POST('dogs',{ name:name }, function(usergridResponse) { if (usergridResponse.error) { alert('Oops! There was an error creating the dog. \n' + JSON.stringify(usergridResponse.error,null,2)); createDogButton.removeClass("disabled"); diff --git a/lib/Usergrid.js b/lib/Usergrid.js index 3c7e09d..885f337 100644 --- a/lib/Usergrid.js +++ b/lib/Usergrid.js @@ -17,27 +17,27 @@ * under the License. */ -'use strict' +'use strict'; -var UsergridSDKVersion = '2.0.0' +var UsergridSDKVersion = '2.0.0'; var UsergridClientSharedInstance = function() { - var self = this - self.isInitialized = false - self.isSharedInstance = true - return self -} -UsergridHelpers.inherits(UsergridClientSharedInstance, UsergridClient) + var self = this; + self.isInitialized = false; + self.isSharedInstance = true; + return self; +}; +UsergridHelpers.inherits(UsergridClientSharedInstance, UsergridClient); -var Usergrid = new UsergridClientSharedInstance() +var Usergrid = new UsergridClientSharedInstance(); Usergrid.initSharedInstance = function(options) { if (Usergrid.isInitialized) { - console.log('Usergrid shared instance is already initialized') + console.log('Usergrid shared instance is already initialized'); } else { - _.assign(Usergrid, new UsergridClient(options)) - Usergrid.isInitialized = true - Usergrid.isSharedInstance = true + _.assign(Usergrid, new UsergridClient(options)); + Usergrid.isInitialized = true; + Usergrid.isSharedInstance = true; } - return Usergrid -} -Usergrid.init = Usergrid.initSharedInstance + return Usergrid; +}; +Usergrid.init = Usergrid.initSharedInstance; diff --git a/lib/modules/UsergridAsset.js b/lib/modules/UsergridAsset.js index 5aefc67..25715cd 100644 --- a/lib/modules/UsergridAsset.js +++ b/lib/modules/UsergridAsset.js @@ -12,18 +12,18 @@ limitations under the License. */ -'use strict' +'use strict'; -var UsergridAssetDefaultFileName = 'file' +var UsergridAssetDefaultFileName = 'file'; var UsergridAsset = function(fileOrBlob) { if( !fileOrBlob instanceof File || !fileOrBlob instanceof Blob ) { - throw new Error("UsergridAsset must be initialized with a 'File' or 'Blob'") + throw new Error("UsergridAsset must be initialized with a 'File' or 'Blob'"); } - var self = this - self.data = fileOrBlob - self.filename = fileOrBlob.name || UsergridAssetDefaultFileName - self.contentLength = fileOrBlob.size - self.contentType = fileOrBlob.type - return self -} \ No newline at end of file + var self = this; + self.data = fileOrBlob; + self.filename = fileOrBlob.name || UsergridAssetDefaultFileName; + self.contentLength = fileOrBlob.size; + self.contentType = fileOrBlob.type; + return self; +}; \ No newline at end of file diff --git a/lib/modules/UsergridAuth.js b/lib/modules/UsergridAuth.js index 8e7652c..2f80671 100644 --- a/lib/modules/UsergridAuth.js +++ b/lib/modules/UsergridAuth.js @@ -12,85 +12,85 @@ limitations under the License. */ -'use strict' +'use strict'; var UsergridAuth = function(token, expiry) { - var self = this + var self = this; - self.token = token - self.expiry = expiry || 0 + self.token = token; + self.expiry = expiry || 0; - var usingToken = (token) ? true : false + var usingToken = (token) ? true : false; Object.defineProperty(self, "hasToken", { get: function() { - return self.token !== undefined + return self.token !== undefined; }, configurable: true - }) + }); Object.defineProperty(self, "isExpired", { get: function() { - return (usingToken) ? false : (Date.now() >= self.expiry) + return (usingToken) ? false : (Date.now() >= self.expiry); }, configurable: true - }) + }); Object.defineProperty(self, "isValid", { get: function() { - return (!self.isExpired && self.hasToken) + return (!self.isExpired && self.hasToken); }, configurable: true - }) + }); Object.defineProperty(self, 'tokenTtl', { configurable: true, writable: true - }) + }); _.assign(self, { destroy: function() { - self.token = undefined - self.expiry = 0 - self.tokenTtl = undefined + self.token = undefined; + self.expiry = 0; + self.tokenTtl = undefined; } - }) + }); - return self -} + return self; +}; var UsergridAppAuth = function() { - var self = this - var args = UsergridHelpers.flattenArgs(arguments) + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); if (_.isPlainObject(args[0])) { - self.clientId = args[0].clientId - self.clientSecret = args[0].clientSecret - self.tokenTtl = args[0].tokenTtl + self.clientId = args[0].clientId; + self.clientSecret = args[0].clientSecret; + self.tokenTtl = args[0].tokenTtl; } else { - self.clientId = args[0] - self.clientSecret = args[1] - self.tokenTtl = args[2] + self.clientId = args[0]; + self.clientSecret = args[1]; + self.tokenTtl = args[2]; } - UsergridAuth.call(self) - _.assign(self, UsergridAuth) - return self -} -UsergridHelpers.inherits(UsergridAppAuth,UsergridAuth) + UsergridAuth.call(self); + _.assign(self, UsergridAuth); + return self; +}; +UsergridHelpers.inherits(UsergridAppAuth,UsergridAuth); var UsergridUserAuth = function(options) { - var self = this - var args = _.flattenDeep(UsergridHelpers.flattenArgs(arguments)) + var self = this; + var args = _.flattenDeep(UsergridHelpers.flattenArgs(arguments)); if (_.isPlainObject(args[0])) { - options = args[0] + options = args[0]; } - self.username = options.username || args[0] - self.email = options.email + self.username = options.username || args[0]; + self.email = options.email; if (options.password || args[1]) { - self.password = options.password || args[1] + self.password = options.password || args[1]; } - self.tokenTtl = options.tokenTtl || args[2] - UsergridAuth.call(self) - _.assign(self, UsergridAuth) - return self -} -UsergridHelpers.inherits(UsergridUserAuth,UsergridAuth) \ No newline at end of file + self.tokenTtl = options.tokenTtl || args[2]; + UsergridAuth.call(self); + _.assign(self, UsergridAuth); + return self; +}; +UsergridHelpers.inherits(UsergridUserAuth,UsergridAuth); \ No newline at end of file diff --git a/lib/modules/UsergridClient.js b/lib/modules/UsergridClient.js index fe1ea1e..870d8d2 100644 --- a/lib/modules/UsergridClient.js +++ b/lib/modules/UsergridClient.js @@ -12,12 +12,12 @@ limitations under the License. */ -'use strict' +'use strict'; -var defaultOptions = { +var UsergridClientDefaultOptions = { baseUrl: 'https://api.usergrid.com', authMode: UsergridAuthMode.USER -} +}; var UsergridClient = function(options) { var self = this; @@ -31,228 +31,162 @@ var UsergridClient = function(options) { self.appId = arguments[1]; } - _.defaults(self, options, defaultOptions); + _.defaults(self, options, UsergridClientDefaultOptions); if (!self.orgId || !self.appId) { - throw new Error('"orgId" and "appId" parameters are required when instantiating UsergridClient') + throw new Error('"orgId" and "appId" parameters are required when instantiating UsergridClient'); } Object.defineProperty(self, 'clientId', { enumerable: false - }) + }); Object.defineProperty(self, 'clientSecret', { enumerable: false - }) + }); Object.defineProperty(self, 'appAuth', { get: function() { - return __appAuth + return __appAuth; }, set: function(options) { if (options instanceof UsergridAppAuth) { - __appAuth = options + __appAuth = options; } else if (typeof options !== "undefined") { - __appAuth = new UsergridAppAuth(options) + __appAuth = new UsergridAppAuth(options); } } - }) + }); // if client ID and secret are defined on initialization, initialize appAuth if (self.clientId && self.clientSecret) { - self.setAppAuth(self.clientId, self.clientSecret) + self.setAppAuth(self.clientId, self.clientSecret); } - return self -} + return self; +}; UsergridClient.prototype = { - GET: function(options,callback) { - var self = this; - return self.performRequest(new UsergridRequest({ client:self, - method:UsergridHttpMethod.GET, - uri:UsergridHelpers.uri(self,UsergridHttpMethod.GET,options), - query:(options instanceof UsergridQuery ? options : options.query), - queryParams:options.queryParams, - body:UsergridHelpers.body(options) }), callback) + sendRequest: function(usergridRequest) { + return usergridRequest.sendRequest(); }, - PUT: function(options,callback) { - var self = this; - return self.performRequest(new UsergridRequest({ client:self, - method:UsergridHttpMethod.PUT, - uri:UsergridHelpers.uri(self,UsergridHttpMethod.PUT,options), - query:(options instanceof UsergridQuery ? options : options.query), - queryParams:options.queryParams, - body:UsergridHelpers.body(options) }), callback) + GET: function() { + var usergridRequest = UsergridHelpers.buildReqest(this,UsergridHttpMethod.GET,UsergridHelpers.flattenArgs(arguments)); + return this.sendRequest(usergridRequest); }, - POST: function(options,callback) { - var self = this; - return self.performRequest(new UsergridRequest({client:self, - method:UsergridHttpMethod.POST, - uri:UsergridHelpers.uri(self,UsergridHttpMethod.POST,options), - query:(options instanceof UsergridQuery ? options : options.query), - queryParams:options.queryParams, - body:UsergridHelpers.body(options)}), callback) + PUT: function() { + var usergridRequest = UsergridHelpers.buildReqest(this,UsergridHttpMethod.PUT,UsergridHelpers.flattenArgs(arguments)); + return this.sendRequest(usergridRequest); }, - DELETE: function(options,callback) { - var self = this; - return self.performRequest(new UsergridRequest({client:self, - method:UsergridHttpMethod.DELETE, - uri:UsergridHelpers.uri(self,UsergridHttpMethod.DELETE,options), - query:(options instanceof UsergridQuery ? options : options.query), - queryParams:options.queryParams, - body:UsergridHelpers.body(options)}), callback) + POST: function() { + var usergridRequest = UsergridHelpers.buildReqest(this,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments)); + return this.sendRequest(usergridRequest); + }, + DELETE: function() { + var usergridRequest = UsergridHelpers.buildReqest(this,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments)); + return this.sendRequest(usergridRequest); }, connect: function() { - var self = this; - return self.performRequest(UsergridHelpers.buildConnectionRequest(self,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments)), UsergridHelpers.callback(arguments)) + var usergridRequest = UsergridHelpers.buildConnectionRequest(this,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments)); + return this.sendRequest(usergridRequest); }, disconnect: function() { - var self = this; - return self.performRequest(UsergridHelpers.buildConnectionRequest(self,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments)), UsergridHelpers.callback(arguments)) + var usergridRequest = UsergridHelpers.buildConnectionRequest(this,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments)); + return this.sendRequest(usergridRequest); }, getConnections: function() { - var self = this - return self.performRequest(UsergridHelpers.buildGetConnectionRequest(self,UsergridHelpers.flattenArgs(arguments)), UsergridHelpers.callback(arguments)) + var usergridRequest = UsergridHelpers.buildGetConnectionRequest(this,UsergridHelpers.flattenArgs(arguments)); + return this.sendRequest(usergridRequest); + }, + usingAuth: function(auth) { + var self = this; + if( _.isString(auth) ) { self.tempAuth = new UsergridAuth(auth); } + else if( auth instanceof UsergridAuth ) { self.tempAuth = auth; } + else { self.tempAuth = undefined; } + return self; }, setAppAuth: function() { - this.appAuth = new UsergridAppAuth(UsergridHelpers.flattenArgs(arguments)) + this.appAuth = new UsergridAppAuth(UsergridHelpers.flattenArgs(arguments)); }, authenticateApp: function(options) { - var self = this - var callback = UsergridHelpers.callback(UsergridHelpers.flattenArgs(arguments)) + var self = this; + var authenticateAppCallback = UsergridHelpers.callback(UsergridHelpers.flattenArgs(arguments)); var auth = _.first([options, self.appAuth, new UsergridAppAuth(options), new UsergridAppAuth(self.clientId, self.clientSecret)].filter(function(p) { - return p instanceof UsergridAppAuth - })) + return p instanceof UsergridAppAuth; + })); if (!(auth instanceof UsergridAppAuth)) { - throw new Error('App auth context was not defined when attempting to call .authenticateApp()') + throw new Error('App auth context was not defined when attempting to call .authenticateApp()'); } else if (!auth.clientId || !auth.clientSecret) { - throw new Error('authenticateApp() failed because clientId or clientSecret are missing') + throw new Error('authenticateApp() failed because clientId or clientSecret are missing'); } - var authCallback = function(usergridResponse) { + var callback = function(usergridResponse) { if (usergridResponse.ok) { if (!self.appAuth) { - self.appAuth = auth + self.appAuth = auth; } - self.appAuth.token = _.get(usergridResponse.responseJSON,'access_token') - var expiresIn = _.get(usergridResponse.responseJSON,'expires_in') - self.appAuth.expiry = UsergridHelpers.calculateExpiry(expiresIn) - self.appAuth.tokenTtl = expiresIn + self.appAuth.token = _.get(usergridResponse.responseJSON,'access_token'); + var expiresIn = _.get(usergridResponse.responseJSON,'expires_in'); + self.appAuth.expiry = UsergridHelpers.calculateExpiry(expiresIn); + self.appAuth.tokenTtl = expiresIn; } - callback(usergridResponse) + authenticateAppCallback(usergridResponse); }; - return self.performRequest(new UsergridRequest({client: self, - method:UsergridHttpMethod.POST, - uri:UsergridHelpers.uri(self,UsergridHttpMethod.POST,{path:'token'}), - body: UsergridHelpers.appLoginBody(auth)}), authCallback) + var usergridRequest = UsergridHelpers.buildAppAuthRequest(self,auth,callback); + return self.sendRequest(usergridRequest); }, authenticateUser: function(options) { - var self = this - var args = UsergridHelpers.flattenArgs(arguments) - var callback = UsergridHelpers.callback(args) - var setAsCurrentUser = (_.last(args.filter(_.isBoolean))) !== undefined ? _.last(args.filter(_.isBoolean)) : true - var currentUser = new UsergridUser(options) - currentUser.login(self, function(auth, user, usergridResponse) { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var callback = UsergridHelpers.callback(args); + var setAsCurrentUser = (_.last(args.filter(_.isBoolean))) !== undefined ? _.last(args.filter(_.isBoolean)) : true; + + var userToAuthenticate = new UsergridUser(options); + userToAuthenticate.login(self, function(auth, user, usergridResponse) { if (usergridResponse.ok && setAsCurrentUser) { - self.currentUser = currentUser + self.currentUser = userToAuthenticate; } - callback(auth,user,usergridResponse) + callback(auth,user,usergridResponse); }) }, - usingAuth: function(auth) { - if( _.isString(auth) ) { - this.tempAuth = new UsergridAuth(auth) - } else if( auth instanceof UsergridAuth ) { - this.tempAuth = auth - } else { - this.tempAuth = undefined + downloadAsset: function() { + var self = this; + var usergridRequest = UsergridHelpers.buildReqest(self,UsergridHttpMethod.GET,UsergridHelpers.flattenArgs(arguments)); + var assetContentType = _.get(usergridRequest,'entity.file-metadata.content-type'); + if( assetContentType !== undefined ) { + _.assign(usergridRequest.headers,{"Accept":assetContentType}); } - return this - }, - downloadAsset: function(entity,callback) { - var self = this - var uploadRequest = new UsergridRequest({client:self, method:UsergridHttpMethod.GET, uri:UsergridHelpers.uri(self,UsergridHttpMethod.GET,entity)}) - return self.performAssetDownloadRequest(uploadRequest,entity,callback) - }, - uploadAsset: function(entity,asset,callback) { - var self = this - var method = UsergridHttpMethod.PUT - var uploadRequest = new UsergridRequest({client:self, method:method, uri:UsergridHelpers.uri(self,method,entity), asset:asset}) - return self.performAssetUploadRequest(uploadRequest,entity,callback) + var realDownloadAssetCallback = usergridRequest.callback; + usergridRequest.callback = function (usergridResponse) { + var entity = usergridRequest.entity; + entity.asset = usergridResponse.asset; + realDownloadAssetCallback(entity.asset,usergridResponse,entity); + }; + return self.sendRequest(usergridRequest); }, - performRequest: function(usergridRequest,callback) { + uploadAsset: function() { var self = this; - - var requestPromise = function() { - var promise = new Promise(); - - var xmlHttpRequest = new XMLHttpRequest(); - xmlHttpRequest.open(usergridRequest.method.toString(),usergridRequest.uri) - _.forOwn(usergridRequest.headers, function(value,key) { - xmlHttpRequest.setRequestHeader(key, value) - }); - xmlHttpRequest.open = function() { - if (usergridRequest.body !== undefined) { - xmlHttpRequest.setRequestHeader("Content-Type", "application/json"); - xmlHttpRequest.setRequestHeader("Accept", "application/json"); - } - }; - xmlHttpRequest.onreadystatechange = function() { - if( this.readyState === XMLHttpRequest.DONE ) { - promise.done(xmlHttpRequest); - } - }; - xmlHttpRequest.send(UsergridHelpers.encode(usergridRequest.body)) - return promise - }.bind(self); - - var responsePromise = function(xmlRequest) { - var promise = new Promise(); - var usergridResponse = new UsergridResponse(xmlRequest); - promise.done(usergridResponse) - return promise - }.bind(self); - - var onCompletePromise = function(response) { - var promise = new Promise(); - response.request = usergridRequest - promise.done(response); - UsergridHelpers.doCallback(callback, [response]); - }.bind(self); - - /* and a promise to chain them all together */ - Promise.chain([requestPromise, responsePromise]).then(onCompletePromise); - return usergridRequest; - }, - performAssetDownloadRequest: function(usergridRequest,entity,callback) { - var req = new XMLHttpRequest(); - req.open('GET', usergridRequest.uri, true); - req.setRequestHeader('Accept',_.get(entity,'file-metadata.content-type')) - req.responseType = 'blob'; - req.onload = function () { - entity.asset = new UsergridAsset(req.response) - UsergridHelpers.doCallback(callback, [ entity.asset, null , entity ]); + var usergridRequest = UsergridHelpers.buildReqest(self,UsergridHttpMethod.PUT,UsergridHelpers.flattenArgs(arguments)); + if (usergridRequest.asset === undefined) { + throw new Error('An UsergridAsset was not defined when attempting to call .uploadAsset()'); } - req.send(null); - return usergridRequest - }, - performAssetUploadRequest: function(usergridRequest,entity,callback) { - var asset = usergridRequest.asset - var xmlHttpRequest = new XMLHttpRequest(); - xmlHttpRequest.open(usergridRequest.method, usergridRequest.uri, true); - xmlHttpRequest.onload = function() { - var response = new UsergridResponse(xmlHttpRequest) - UsergridHelpers.updateEntityFromRemote(entity, response) - UsergridHelpers.doCallback(callback, [ asset, response, entity ]); + var realUploadAssetCallback = usergridRequest.callback; + usergridRequest.callback = function (usergridResponse) { + var requestEntity = usergridRequest.entity; + var responseEntity = usergridResponse.entity; + var requestAsset = usergridRequest.asset; + + if( usergridResponse.ok && responseEntity !== undefined ) { + UsergridHelpers.updateEntityFromRemote(requestEntity,usergridResponse); + requestEntity.asset = requestAsset; + if( responseEntity ) { + responseEntity.asset = requestAsset; + } + } + realUploadAssetCallback(requestAsset,usergridResponse,requestEntity); }; - - var formData = new FormData(); - formData.append('file',asset.data) - xmlHttpRequest.send(formData) - - return usergridRequest + return self.sendRequest(usergridRequest); } -} \ No newline at end of file +}; \ No newline at end of file diff --git a/lib/modules/UsergridEntity.js b/lib/modules/UsergridEntity.js index f71e89d..1a3f7eb 100644 --- a/lib/modules/UsergridEntity.js +++ b/lib/modules/UsergridEntity.js @@ -15,165 +15,195 @@ 'use strict'; var UsergridEntity = function() { - var self = this - var args = UsergridHelpers.flattenArgs(arguments) + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); if (args.length === 0) { - throw new Error('A UsergridEntity object cannot be initialized without passing one or more arguments') + throw new Error('A UsergridEntity object cannot be initialized without passing one or more arguments'); } self.asset = undefined; if (_.isPlainObject(args[0])) { - _.assign(self, args[0]) + _.assign(self, args[0]); } else { if( !self.type ) { - self.type = _.isString(args[0]) ? args[0] : undefined + self.type = _.isString(args[0]) ? args[0] : undefined; } if( !self.name ) { - self.name = _.isString(args[1]) ? args[1] : undefined + self.name = _.isString(args[1]) ? args[1] : undefined; } } if (!_.isString(self.type)) { - throw new Error('"type" (or "collection") parameter is required when initializing a UsergridEntity object') + throw new Error('"type" (or "collection") parameter is required when initializing a UsergridEntity object'); } Object.defineProperty(self, 'isUser', { get: function() { - return (self.type.toLowerCase() === 'user') + return (self.type.toLowerCase() === 'user'); } - }) + }); Object.defineProperty(self, 'hasAsset', { get: function() { - return _.has(self, 'file-metadata') + return _.has(self, 'file-metadata'); } - }) + }); - UsergridHelpers.setReadOnly(self, ['uuid', 'name', 'type', 'created']) + UsergridHelpers.setReadOnly(self, ['uuid', 'name', 'type', 'created']); - return self -} + return self; +}; UsergridEntity.prototype = { jsonValue: function() { var jsonValue = {}; _.forOwn(this, function(value,key) { - jsonValue[key] = value + jsonValue[key] = value; }); - return jsonValue + return jsonValue; }, putProperty: function(key, value) { - this[key] = value + this[key] = value; }, putProperties: function(obj) { - _.assign(this, obj) + _.assign(this, obj); }, removeProperty: function(key) { - this.removeProperties([key]) + this.removeProperties([key]); }, removeProperties: function(keys) { - var self = this + var self = this; keys.forEach(function(key) { - delete self[key] - }) + delete self[key]; + }); }, insert: function(key, value, idx) { if (!_.isArray(this[key])) { - this[key] = this[key] ? [this[key]] : [] + this[key] = this[key] ? [this[key]] : []; } - this[key].splice.apply(this[key], [idx, 0].concat(value)) + this[key].splice.apply(this[key], [idx, 0].concat(value)); }, append: function(key, value) { - this.insert(key, value, Number.MAX_VALUE) + this.insert(key, value, Number.MAX_VALUE); }, prepend: function(key, value) { - this.insert(key, value, 0) + this.insert(key, value, 0); }, pop: function(key) { if (_.isArray(this[key])) { - this[key].pop() + this[key].pop(); } }, shift: function(key) { if (_.isArray(this[key])) { - this[key].shift() + this[key].shift(); } }, reload: function() { - var args = UsergridHelpers.flattenArgs(arguments) - var client = UsergridHelpers.validateAndRetrieveClient(args) - var callback = UsergridHelpers.callback(args) + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); - client.GET(this, function(usergridResponse) { - UsergridHelpers.updateEntityFromRemote(this, usergridResponse) - callback(usergridResponse) - }.bind(this)) + client.GET(self, function(usergridResponse) { + UsergridHelpers.updateEntityFromRemote(self, usergridResponse); + callback(usergridResponse,self); + }.bind(self)); }, save: function() { - var args = UsergridHelpers.flattenArgs(arguments) - var client = UsergridHelpers.validateAndRetrieveClient(args) - var callback = UsergridHelpers.callback(args) + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + var currentAsset = self.asset; - var uuid = this.uuid + var uuid = self.uuid; if( uuid === undefined ) { - client.POST(this,function(usergridResponse) { - UsergridHelpers.updateEntityFromRemote(this, usergridResponse) - callback(usergridResponse, this) - }.bind(this)) + client.POST(self,function(usergridResponse) { + UsergridHelpers.updateEntityFromRemote(self, usergridResponse); + if( self.hasAsset ) { + self.asset = currentAsset; + } + callback(usergridResponse,self); + }.bind(self)); } else { - client.PUT(this, function(usergridResponse) { - UsergridHelpers.updateEntityFromRemote(this, usergridResponse) - callback(usergridResponse, this) - }.bind(this)) + client.PUT(self, function(usergridResponse) { + UsergridHelpers.updateEntityFromRemote(self, usergridResponse); + if( self.hasAsset ) { + self.asset = currentAsset; + } + callback(usergridResponse,self); + }.bind(self)); } }, remove: function() { - var args = UsergridHelpers.flattenArgs(arguments) - var client = UsergridHelpers.validateAndRetrieveClient(args) - var callback = UsergridHelpers.callback(args) + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); - client.DELETE(this, function(usergridResponse) { - callback(usergridResponse, this) - }.bind(this)) + client.DELETE(self, function(usergridResponse) { + callback(usergridResponse,self); + }.bind(self)); }, attachAsset: function(asset) { - this.asset = asset + this.asset = asset; }, uploadAsset: function() { - var args = UsergridHelpers.flattenArgs(arguments) - var client = UsergridHelpers.validateAndRetrieveClient(args) - var callback = UsergridHelpers.callback(args) - client.uploadAsset(this,this.asset,function(asset, usergridResponse) { - UsergridHelpers.updateEntityFromRemote(this,usergridResponse) - this.asset = asset - callback(asset,usergridResponse,this) - }.bind(this)) + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + + if( _.has(self,'asset.contentType') ) { + client.uploadAsset(self,callback); + } else { + var response = new UsergridResponse(); + response.error = new UsergridResponseError({ + error: 'asset_not_found', + description: 'The specified entity does not have a valid asset attached' + }); + callback(null,response,self); + } }, downloadAsset: function() { - var args = UsergridHelpers.flattenArgs(arguments) - var client = UsergridHelpers.validateAndRetrieveClient(args) - var callback = UsergridHelpers.callback(args) - client.downloadAsset(this,callback) + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + + if( _.has(self,'asset.contentType') ) { + client.downloadAsset(self,callback); + } else { + var response = new UsergridResponse(); + response.error = new UsergridResponseError({ + error: 'asset_not_found', + description: 'The specified entity does not have a valid asset attached' + }); + callback(null,response,self); + } }, connect: function() { - var args = UsergridHelpers.flattenArgs(arguments) - var client = UsergridHelpers.validateAndRetrieveClient(args) - args[0] = this - return client.connect.apply(client, args) + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + args[0] = this; + return client.connect.apply(client, args); }, disconnect: function() { - var args = UsergridHelpers.flattenArgs(arguments) - var client = UsergridHelpers.validateAndRetrieveClient(args) - args[0] = this - return client.disconnect.apply(client, args) + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + args[0] = this; + return client.disconnect.apply(client, args); }, getConnections: function() { - var args = UsergridHelpers.flattenArgs(arguments) - var client = UsergridHelpers.validateAndRetrieveClient(args) - args.shift() - args.splice(1, 0, this) - return client.getConnections.apply(client, args) + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + args.shift(); + args.splice(1, 0, this); + return client.getConnections.apply(client, args); } -} +}; diff --git a/lib/modules/UsergridQuery.js b/lib/modules/UsergridQuery.js index ada0e57..f5473ae 100644 --- a/lib/modules/UsergridQuery.js +++ b/lib/modules/UsergridQuery.js @@ -12,172 +12,190 @@ limitations under the License. */ -'use strict' +'use strict'; var UsergridQuery = function(type) { - var self = this + var self = this; var query = '', queryString, sort, - __nextIsNot = false + urlTerms = {}, + __nextIsNot = false; - self._type = type + self._type = type; // builder pattern _.assign(self, { type: function(value) { - self._type = value - return self + self._type = value; + return self; }, collection: function(value) { - self._type = value - return self + self._type = value; + return self; }, limit: function(value) { - self._limit = value - return self + self._limit = value; + return self; }, cursor: function(value) { - self._cursor = value - return self + self._cursor = value; + return self; }, eq: function(key, value) { - query = self.andJoin(key + ' ' + UsergridQueryOperator.EQUAL + ' ' + UsergridHelpers.useQuotesIfRequired(value)) - return self + query = self.andJoin(key + ' ' + UsergridQueryOperator.EQUAL + ' ' + UsergridHelpers.useQuotesIfRequired(value)); + return self; }, equal: this.eq, gt: function(key, value) { - query = self.andJoin(key + ' ' + UsergridQueryOperator.GREATER_THAN + ' ' + UsergridHelpers.useQuotesIfRequired(value)) - return self + query = self.andJoin(key + ' ' + UsergridQueryOperator.GREATER_THAN + ' ' + UsergridHelpers.useQuotesIfRequired(value)); + return self; }, greaterThan: this.gt, gte: function(key, value) { - query = self.andJoin(key + ' ' + UsergridQueryOperator.GREATER_THAN_EQUAL_TO + ' ' + UsergridHelpers.useQuotesIfRequired(value)) - return self + query = self.andJoin(key + ' ' + UsergridQueryOperator.GREATER_THAN_EQUAL_TO + ' ' + UsergridHelpers.useQuotesIfRequired(value)); + return self; }, greaterThanOrEqual: this.gte, lt: function(key, value) { - query = self.andJoin(key + ' ' + UsergridQueryOperator.LESS_THAN + ' ' + UsergridHelpers.useQuotesIfRequired(value)) - return self + query = self.andJoin(key + ' ' + UsergridQueryOperator.LESS_THAN + ' ' + UsergridHelpers.useQuotesIfRequired(value)); + return self; }, lessThan: this.lt, lte: function(key, value) { - query = self.andJoin(key + ' ' + UsergridQueryOperator.LESS_THAN_EQUAL_TO + ' ' + UsergridHelpers.useQuotesIfRequired(value)) - return self + query = self.andJoin(key + ' ' + UsergridQueryOperator.LESS_THAN_EQUAL_TO + ' ' + UsergridHelpers.useQuotesIfRequired(value)); + return self; }, lessThanOrEqual: this.lte, contains: function(key, value) { - query = self.andJoin(key + ' contains ' + UsergridHelpers.useQuotesIfRequired(value)) - return self + query = self.andJoin(key + ' contains ' + UsergridHelpers.useQuotesIfRequired(value)); + return self; }, locationWithin: function(distanceInMeters, lat, lng) { - query = self.andJoin('location within ' + distanceInMeters + ' of ' + lat + ', ' + lng) - return self + query = self.andJoin('location within ' + distanceInMeters + ' of ' + lat + ', ' + lng); + return self; }, asc: function(key) { - self.sort(key, UsergridQuerySortOrder.ASC) - return self + self.sort(key, UsergridQuerySortOrder.ASC); + return self; }, desc: function(key) { - self.sort(key, UsergridQuerySortOrder.DESC) - return self + self.sort(key, UsergridQuerySortOrder.DESC); + return self; }, sort: function(key, order) { - sort = (key && order) ? (' order by ' + key + ' ' + order) : '' - return self + sort = (key && order) ? (' order by ' + key + ' ' + order) : ''; + return self; }, fromString: function(string) { - queryString = string - return self + queryString = string; + return self; + }, + urlTerm: function(key,value) { + if( key === 'ql' ) { + self.fromString(); + } else { + urlTerms[key] = value; + } + return self; }, andJoin: function(append) { if (__nextIsNot) { - append = 'not ' + append - __nextIsNot = false + append = 'not ' + append; + __nextIsNot = false; } if (!append) { - return query + return query; } else if (query.length === 0) { - return append + return append; } else { - return (_.endsWith(query, 'and') || _.endsWith(query, 'or')) ? (query + ' ' + append) : (query + ' and ' + append) + return (_.endsWith(query, 'and') || _.endsWith(query, 'or')) ? (query + ' ' + append) : (query + ' and ' + append); } }, orJoin: function() { - return (query.length > 0 && !_.endsWith(query, 'or')) ? (query + ' or') : query + return (query.length > 0 && !_.endsWith(query, 'or')) ? (query + ' or') : query; } - }) + }); // public accessors Object.defineProperty(self, '_ql', { get: function() { + var ql = 'select * '; if (queryString !== undefined) { - return queryString + ql = queryString; } else { - var qL = 'select * ' + ((query.length > 0) ? 'where ' + (query || '') : '') - qL += (sort !== undefined) ? sort : '' - return qL + ql += ((query.length > 0) ? 'where ' + (query || '') : ''); + ql += ((sort !== undefined) ? sort : ''); } + return ql; } - }) + }); Object.defineProperty(self, 'encodedStringValue', { get: function() { - var self = this - var limit = self._limit - var cursor = self._cursor - var requirementsString = self._ql - var encodedStringValue = undefined; + var self = this; + var limit = self._limit; + var cursor = self._cursor; + var requirementsString = self._ql; + var returnString = undefined; if( limit !== undefined ) { - encodedStringValue = 'limit' + UsergridQueryOperator.EQUAL + limit + returnString = 'limit' + UsergridQueryOperator.EQUAL + limit; } if( !_.isEmpty(cursor) ) { - var cursorString = 'cursor' + UsergridQueryOperator.EQUAL + cursor - if( _.isEmpty(encodedStringValue) ) { - encodedStringValue = cursorString + var cursorString = 'cursor' + UsergridQueryOperator.EQUAL + cursor; + if( _.isEmpty(returnString) ) { + returnString = cursorString; } else { - encodedStringValue += '&' + cursorString + returnString += '&' + cursorString; } } + _.forEach(urlTerms,function(value,key) { + var encodedURLTermString = encodeURIComponent(key) + UsergridQueryOperator.EQUAL + encodeURIComponent(value); + if( _.isEmpty(returnString) ) { + returnString = encodedURLTermString; + } else { + returnString += '&' + encodedURLTermString; + } + }); if( !_.isEmpty(requirementsString) ) { - var qLString = 'ql=' + encodeURIComponent(requirementsString) - if( _.isEmpty(encodedStringValue) ) { - encodedStringValue = qLString + var qLString = 'ql=' + encodeURIComponent(requirementsString); + if( _.isEmpty(returnString) ) { + returnString = qLString; } else { - encodedStringValue += '&' + qLString + returnString += '&' + qLString; } } - if( !_.isEmpty(encodedStringValue) ) { - encodedStringValue = '?' + encodedStringValue + if( !_.isEmpty(returnString) ) { + returnString = '?' + returnString; } - return !_.isEmpty(encodedStringValue) ? encodedStringValue : undefined + return !_.isEmpty(returnString) ? returnString : undefined; } - }) + }); Object.defineProperty(self, 'and', { get: function() { - query = self.andJoin('') - return self + query = self.andJoin(''); + return self; } - }) + }); Object.defineProperty(self, 'or', { get: function() { - query = self.orJoin() - return self + query = self.orJoin(); + return self; } - }) + }); Object.defineProperty(self, 'not', { get: function() { - __nextIsNot = true - return self + __nextIsNot = true; + return self; } - }) + }); - return self -} + return self; +}; diff --git a/lib/modules/UsergridRequest.js b/lib/modules/UsergridRequest.js index 25641a1..bf451cc 100644 --- a/lib/modules/UsergridRequest.js +++ b/lib/modules/UsergridRequest.js @@ -12,7 +12,9 @@ limitations under the License. */ -'use strict' +'use strict'; + +var UsergridRequestDefaultHeaders = Object.freeze({"Content-Type":"application/json","Accept":"application/json"}); var UsergridRequest = function(options) { var self = this; @@ -26,33 +28,82 @@ var UsergridRequest = function(options) { throw new Error('"method" parameter is required when initializing a UsergridRequest') } - self.method = options.method + self.method = options.method; + self.callback = options.callback; self.uri = options.uri || UsergridHelpers.uri(client, options); - self.headers = UsergridHelpers.headers(client, options) - self.body = options.body || undefined - self.asset = options.asset || undefined + self.entity = options.entity; + self.body = options.body || undefined; + self.asset = options.asset || undefined; + self.query = options.query; + self.queryParams = options.queryParams || options.qs; + + var defaultHeadersToUse = self.asset === undefined ? UsergridRequestDefaultHeaders : {}; + self.headers = UsergridHelpers.headers(client, options, defaultHeadersToUse); - self.query = options.query if( self.query !== undefined ) { - self.uri += UsergridHelpers.normalize(self.query.encodedStringValue, {}) + self.uri += UsergridHelpers.normalize(self.query.encodedStringValue, {}); } - self.queryParams = options.queryParams if( self.queryParams !== undefined ) { _.forOwn(self.queryParams, function(value,key){ - self.uri += '?' + encodeURIComponent(key) + '=' + encodeURIComponent(value) - }) - self.uri = UsergridHelpers.normalize(self.uri,{}) + self.uri += '?' + encodeURIComponent(key) + '=' + encodeURIComponent(value); + }); + self.uri = UsergridHelpers.normalize(self.uri,{}); } - try{ - if( _.isPlainObject(self.body) ) { - self.body = JSON.stringify(self.body) - } - if( _.isArray(self.body) ) { - self.body = JSON.stringify(self.body) + if( self.asset !== undefined ) { + self.body = new FormData(); + self.body.append("file", self.asset.data); + } else { + try{ + if( _.isPlainObject(self.body) ) { + self.body = JSON.stringify(self.body); + } else if( _.isArray(self.body) ) { + self.body = JSON.stringify(self.body); + } + } catch( exception ) { } + } + + return self; +}; + +UsergridRequest.prototype.sendRequest = function() { + var self = this; + + var requestPromise = function() { + var promise = new Promise(); + + var xmlHttpRequest = new XMLHttpRequest(); + xmlHttpRequest.open(self.method, self.uri,true); + xmlHttpRequest.onload = function() { promise.done(xmlHttpRequest); }; + + // Add any request headers + _.forOwn(self.headers, function(value,key) { + xmlHttpRequest.setRequestHeader(key, value); + }); + + // If we are getting something that is not JSON we must be getting an asset so set the responseType to 'blob'. + if ( self.method === UsergridHttpMethod.GET && _.get(self.headers, "Accept") !== "application/json") { + xmlHttpRequest.responseType = "blob"; } - } catch( exception ) { } - return self -} \ No newline at end of file + xmlHttpRequest.send(self.body); + return promise; + }.bind(self); + + var responsePromise = function(xmlRequest) { + var promise = new Promise(); + var usergridResponse = new UsergridResponse(xmlRequest,self); + promise.done(usergridResponse); + return promise; + }.bind(self); + + var onCompletePromise = function(response) { + var promise = new Promise(); + promise.done(response); + self.callback(response); + }.bind(self); + + Promise.chain([requestPromise, responsePromise]).then(onCompletePromise); + return self; +}; \ No newline at end of file diff --git a/lib/modules/UsergridResponse.js b/lib/modules/UsergridResponse.js index 87e9af4..df067e5 100644 --- a/lib/modules/UsergridResponse.js +++ b/lib/modules/UsergridResponse.js @@ -12,87 +12,97 @@ limitations under the License. */ -'use strict' +'use strict'; var UsergridResponseError = function(responseErrorObject) { - var self = this + var self = this; if (_.has(responseErrorObject,'error') === false) { - return + return; } - self.name = responseErrorObject.error - self.description = responseErrorObject.error_description || responseErrorObject.description - self.exception = responseErrorObject.exception - return self -} + self.name = responseErrorObject.error; + self.description = _.get(responseErrorObject,'error_description') || responseErrorObject.description; + self.exception = responseErrorObject.exception; + return self; +}; -var UsergridResponse = function(request) { - var self = this - self.ok = false +var UsergridResponse = function(xmlRequest,usergridRequest) { + var self = this; + self.ok = false; + self.request = usergridRequest; - if( request ) { - self.statusCode = parseInt(request.status) - self.headers = UsergridHelpers.parseResponseHeaders(request.getAllResponseHeaders()) - try { - var responseText = request.responseText - var responseJSON = JSON.parse(responseText); - } catch (e) { - responseJSON = {} - } + if( xmlRequest ) { + self.statusCode = parseInt(xmlRequest.status); + self.ok = (self.statusCode < 400); + self.headers = UsergridHelpers.parseResponseHeaders(xmlRequest.getAllResponseHeaders()); - if (self.statusCode < 400) { - self.ok = true - _.assign(self, { - responseJSON: _.cloneDeep(responseJSON) - }) - if (_.has(responseJSON, 'entities')) { - var entities = _.map(responseJSON.entities,function(en) { - var entity = new UsergridEntity(en) - if (entity.isUser) { - entity = new UsergridUser(entity) - } - return entity - }) - _.assign(self, { - entities: entities - }) - delete self.responseJSON.entities + var responseContentType = _.get(self.headers,'content-type'); + if( responseContentType === 'application/json' ) { + try { + var responseText = xmlRequest.responseText; + var responseJSON = JSON.parse(responseText); + } catch (e) { + responseJSON = {}; + } + if (self.ok) { + if( responseJSON !== undefined ) { + _.assign(self, { + responseJSON: _.cloneDeep(responseJSON) + }); + if (_.has(responseJSON, 'entities')) { + var entities = _.map(responseJSON.entities,function(en) { + var entity = new UsergridEntity(en); + if (entity.isUser) { + entity = new UsergridUser(entity); + } + return entity; + }); + _.assign(self, { + entities: entities + }); + delete self.responseJSON.entities; - self.first = _.first(entities) || undefined - self.entity = self.first - self.last = _.last(entities) || undefined + self.first = _.first(entities) || undefined; + self.entity = self.first; + self.last = _.last(entities) || undefined; - if (_.get(self, 'responseJSON.path') === '/users') { - self.user = self.first - self.users = self.entities - } + if (_.get(self, 'responseJSON.path') === '/users') { + self.user = self.first; + self.users = self.entities; + } - Object.defineProperty(self, 'hasNextPage', { - get: function () { - return _.has(self, 'responseJSON.cursor') - } - }) + Object.defineProperty(self, 'hasNextPage', { + get: function () { + return _.has(self, 'responseJSON.cursor'); + } + }); - UsergridHelpers.setReadOnly(self.responseJSON) + UsergridHelpers.setReadOnly(self.responseJSON); + } + } + } else { + self.error = new UsergridResponseError(responseJSON); } } else { - self.error = new UsergridResponseError(responseJSON) + self.asset = new UsergridAsset(xmlRequest.response); } } return self; -} +}; UsergridResponse.prototype = { loadNextPage: function() { - var self = this - var args = UsergridHelpers.flattenArgs(arguments) - var callback = UsergridHelpers.callback(args) - if (!self.responseJSON.cursor) { - callback() + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var callback = UsergridHelpers.callback(args); + var cursor = _.get(self,'responseJSON.cursor'); + if (!cursor) { + callback(); } - var client = UsergridHelpers.validateAndRetrieveClient(args) - var type = _.last(_.get(self,'responseJSON.path').split('/')) - var limit = _.first(_.get(this,'responseJSON.params.limit')) - var query = new UsergridQuery(type).cursor(this.responseJSON.cursor).limit(limit) - return client.GET(query, callback) + var client = UsergridHelpers.validateAndRetrieveClient(args); + var type = _.last(_.get(self,'responseJSON.path').split('/')); + var limit = _.first(_.get(this,'responseJSON.params.limit')); + var ql = _.first(_.get(this,'responseJSON.params.ql')); + var query = new UsergridQuery(type).fromString(ql).cursor(cursor).limit(limit); + return client.GET(query, callback); } -} \ No newline at end of file +}; \ No newline at end of file diff --git a/lib/modules/UsergridUser.js b/lib/modules/UsergridUser.js index b004ccb..c31650b 100644 --- a/lib/modules/UsergridUser.js +++ b/lib/modules/UsergridUser.js @@ -12,144 +12,147 @@ limitations under the License. */ -'use strict' +'use strict'; var UsergridUser = function(obj) { if (! _.has(obj,'email') && !_.has(obj,'username')) { // This is not a user entity - throw new Error('"email" or "username" property is required when initializing a UsergridUser object') + throw new Error('"email" or "username" property is required when initializing a UsergridUser object'); } - var self = this + var self = this; - _.assign(self, obj, UsergridEntity) - UsergridEntity.call(self, "user") + _.assign(self, obj, UsergridEntity); + UsergridEntity.call(self, "user"); - UsergridHelpers.setWritable(self, 'name') - return self -} + UsergridHelpers.setWritable(self, 'name'); + return self; +}; UsergridUser.CheckAvailable = function() { - var args = UsergridHelpers.flattenArgs(arguments) - var client = UsergridHelpers.validateAndRetrieveClient(args) + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); if (args[0] instanceof UsergridClient) { - args.shift() + args.shift(); } - var callback = UsergridHelpers.callback(args) - var checkQuery + var callback = UsergridHelpers.callback(args); + var checkQuery; if (args[0].username && args[0].email) { - checkQuery = new UsergridQuery('users').eq('username', args[0].username).or.eq('email', args[0].email) + checkQuery = new UsergridQuery('users').eq('username', args[0].username).or.eq('email', args[0].email); } else if (args[0].username) { - checkQuery = new UsergridQuery('users').eq('username', args[0].username) + checkQuery = new UsergridQuery('users').eq('username', args[0].username); } else if (args[0].email) { - checkQuery = new UsergridQuery('users').eq('email', args[0].email) + checkQuery = new UsergridQuery('users').eq('email', args[0].email); } else { - throw new Error("'username' or 'email' property is required when checking for available users") + throw new Error("'username' or 'email' property is required when checking for available users"); } client.GET(checkQuery, function(usergridResponse) { - callback(usergridResponse, usergridResponse.entities.length > 0) + callback(usergridResponse, usergridResponse.entities.length > 0); }) -} -UsergridHelpers.inherits(UsergridUser, UsergridEntity) +}; +UsergridHelpers.inherits(UsergridUser, UsergridEntity); UsergridUser.prototype.uniqueId = function() { - var self = this - return _.first([self.uuid, self.username, self.email].filter(_.isString)) -} + var self = this; + return _.first([self.uuid, self.username, self.email].filter(_.isString)); +}; UsergridUser.prototype.create = function() { - var self = this - var args = UsergridHelpers.flattenArgs(arguments) - var client = UsergridHelpers.validateAndRetrieveClient(args) - var callback = UsergridHelpers.callback(args) + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + client.POST(self, function(usergridResponse) { - delete self.password - _.assign(self, usergridResponse.user) - callback(usergridResponse) - }.bind(self)) -} + delete self.password; + _.assign(self, usergridResponse.user); + callback(usergridResponse); + }.bind(self)); +}; UsergridUser.prototype.login = function() { - var self = this - var args = UsergridHelpers.flattenArgs(arguments) - var callback = UsergridHelpers.callback(args) - var client = UsergridHelpers.validateAndRetrieveClient(args) - - client.POST({ - path: 'token', - body: UsergridHelpers.userLoginBody(self) - }, function (usergridResponse) { - delete self.password + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + + client.POST('token', UsergridHelpers.userLoginBody(self), function (usergridResponse) { + delete self.password; if (usergridResponse.ok) { - var responseJSON = usergridResponse.responseJSON - self.auth = new UsergridUserAuth(self) - self.auth.token = _.get(responseJSON,'access_token') - var expiresIn = _.get(responseJSON,'expires_in') - self.auth.expiry = UsergridHelpers.calculateExpiry(expiresIn) - self.auth.tokenTtl = expiresIn + var responseJSON = usergridResponse.responseJSON; + self.auth = new UsergridUserAuth(self); + self.auth.token = _.get(responseJSON,'access_token'); + var expiresIn = _.get(responseJSON,'expires_in'); + self.auth.expiry = UsergridHelpers.calculateExpiry(expiresIn); + self.auth.tokenTtl = expiresIn; } - callback(self.auth, self, usergridResponse) - }) -} + callback(self.auth,self,usergridResponse); + }); +}; UsergridUser.prototype.logout = function() { - var self = this - var args = UsergridHelpers.flattenArgs(arguments) - var callback = UsergridHelpers.callback(args) + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + if (!self.auth || !self.auth.isValid) { - var response = new UsergridResponse() + var response = new UsergridResponse(); response.error = new UsergridResponseError({ error: 'no_valid_token', description: 'this user does not have a valid token' - }) - return callback(response) - } + }); + callback(response); + } else { + var revokeAll = _.first(args.filter(_.isBoolean)) || false; + var revokeTokenPath = ['users', self.uniqueId(), ('revoketoken' + ((revokeAll) ? "s" : ""))].join('/'); + var queryParams = undefined; + if (!revokeAll) { + queryParams = {token: self.auth.token}; + } - var revokeAll = _.first(args.filter(_.isBoolean)) || false - var revokeTokenPath = ['users', self.uniqueId(),('revoketoken' + ((revokeAll) ? "s" : "")) ].join('/') - var queryParams = undefined - if( !revokeAll ) { - queryParams = {token:self.auth.token} + var requestOptions = { + client: client, + path: revokeTokenPath, + method: UsergridHttpMethod.PUT, + queryParams: queryParams, + callback: function (usergridResponse) { + self.auth.destroy(); + callback(usergridResponse); + }.bind(self) + }; + var request = new UsergridRequest(requestOptions); + client.sendRequest(request); } - var client = UsergridHelpers.validateAndRetrieveClient(args) - - return client.PUT({ - path: revokeTokenPath, - queryParams: queryParams - }, function(usergridResponse) { - self.auth.destroy() - callback(usergridResponse) - }) -} +}; UsergridUser.prototype.logoutAllSessions = function() { - var args = UsergridHelpers.flattenArgs(arguments) - args = _.concat([UsergridHelpers.validateAndRetrieveClient(args), true], args) - return this.logout.apply(this, args) -} + var args = UsergridHelpers.flattenArgs(arguments); + args = _.concat([UsergridHelpers.validateAndRetrieveClient(args), true], args); + return this.logout.apply(this, args); +}; UsergridUser.prototype.resetPassword = function() { - var self = this - var args = UsergridHelpers.flattenArgs(arguments) - var callback = UsergridHelpers.callback(args) - var client = UsergridHelpers.validateAndRetrieveClient(args) + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + if (args[0] instanceof UsergridClient) { - args.shift() + args.shift(); } var body = { oldpassword: _.isPlainObject(args[0]) ? args[0].oldPassword : _.isString(args[0]) ? args[0] : undefined, newpassword: _.isPlainObject(args[0]) ? args[0].newPassword : _.isString(args[1]) ? args[1] : undefined - } + }; if (!body.oldpassword || !body.newpassword) { - throw new Error('"oldPassword" and "newPassword" properties are required when resetting a user password') + throw new Error('"oldPassword" and "newPassword" properties are required when resetting a user password'); } - return client.PUT({ - path: ['users',self.uniqueId(),'password'].join('/'), - body: body - }, function(usergridResponse) { - callback(usergridResponse) - }) -} \ No newline at end of file + + client.PUT(['users',self.uniqueId(),'password'].join('/'), body, function(usergridResponse) { + callback(usergridResponse); + }); +}; \ No newline at end of file diff --git a/lib/modules/util/UsergridHelpers.js b/lib/modules/util/UsergridHelpers.js index 63185c7..e5a8982 100644 --- a/lib/modules/util/UsergridHelpers.js +++ b/lib/modules/util/UsergridHelpers.js @@ -6,12 +6,12 @@ UsergridHelpers.validateAndRetrieveClient = function(args) { var client = undefined; - if (args instanceof UsergridClient) { client = args } - else if (args[0] instanceof UsergridClient) { client = args[0] } - else if (_.get(args,'client')) { client = args.client } - else if (Usergrid.isInitialized) { client = Usergrid } - else { throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument") } - return client + if (args instanceof UsergridClient) { client = args; } + else if (args[0] instanceof UsergridClient) { client = args[0]; } + else if (_.get(args,'client')) { client = args.client; } + else if (Usergrid.isInitialized) { client = Usergrid; } + else { throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument"); } + return client; }; UsergridHelpers.inherits = function(ctor, superCtor) { @@ -27,36 +27,24 @@ }; UsergridHelpers.flattenArgs = function(args) { - return _.flattenDeep(Array.prototype.slice.call(args)) + return _.flattenDeep(Array.prototype.slice.call(args)); }; UsergridHelpers.callback = function() { - var args = _.flattenDeep(Array.prototype.slice.call(arguments)).reverse(); + var args = UsergridHelpers.flattenArgs(arguments).reverse(); var emptyFunc = function() {}; - return _.first(_.flattenDeep([args, _.get(args,'0.callback'), emptyFunc]).filter(_.isFunction)) - }; - - UsergridHelpers.doCallback = function(callback, params, context) { - var returnValue; - if (_.isFunction(callback)) { - if (!params) params = []; - if (!context) context = this; - - params.push(context); - returnValue = callback.apply(context, params); - } - return returnValue; + return _.first(_.flattenDeep([args, _.get(args,'0.callback'), emptyFunc]).filter(_.isFunction)); }; UsergridHelpers.authForRequests = function(client) { var authForRequests = undefined; if( _.get(client,"tempAuth.isValid") ) { - authForRequests = client.tempAuth - client.tempAuth = undefined + authForRequests = client.tempAuth; + client.tempAuth = undefined; } else if( _.get(client,"currentUser.auth.isValid") && client.authMode === UsergridAuthMode.USER ) { - authForRequests = client.currentUser.auth + authForRequests = client.currentUser.auth; } else if( _.get(client,"appAuth.isValid") && client.authMode === UsergridAuthMode.APP ) { - authForRequests = client.appAuth + authForRequests = client.appAuth; } return authForRequests; } @@ -67,10 +55,10 @@ password: options.password }; if (options.tokenTtl) { - body.ttl = options.tokenTtl + body.ttl = options.tokenTtl; } body[(options.username) ? "username" : "email"] = (options.username) ? options.username : options.email; - return body + return body; }; UsergridHelpers.appLoginBody = function(options) { @@ -80,13 +68,13 @@ client_secret: options.clientSecret }; if (options.tokenTtl) { - body.ttl = options.tokenTtl + body.ttl = options.tokenTtl; } - return body + return body; }; UsergridHelpers.calculateExpiry = function(expires_in) { - return Date.now() + ((expires_in ? expires_in - 5 : 0) * 1000) + return Date.now() + ((expires_in ? expires_in - 5 : 0) * 1000); }; var uuidValueRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/; @@ -95,24 +83,20 @@ }; UsergridHelpers.useQuotesIfRequired = function(value) { - return (_.isFinite(value) || UsergridHelpers.isUUID(value) || _.isBoolean(value) || _.isObject(value) && !_.isFunction(value) || _.isArray(value)) ? value : ("'" + value + "'") + return (_.isFinite(value) || UsergridHelpers.isUUID(value) || _.isBoolean(value) || _.isObject(value) && !_.isFunction(value) || _.isArray(value)) ? value : ("'" + value + "'"); }; UsergridHelpers.setReadOnly = function(obj, key) { if (_.isArray(key)) { - return key.forEach(function(k) { - UsergridHelpers.setReadOnly(obj, k) - }) + return key.forEach(function(k) { UsergridHelpers.setReadOnly(obj, k); }); } else if (_.isPlainObject(obj[key])) { - return Object.freeze(obj[key]) + return Object.freeze(obj[key]); } else if (_.isPlainObject(obj) && key === undefined) { - return Object.freeze(obj) + return Object.freeze(obj); } else if (_.has(obj,key)) { - return Object.defineProperty(obj, key, { - writable: false - }) + return Object.defineProperty(obj, key, { writable: false }); } else { - return obj + return obj; } }; @@ -145,12 +129,12 @@ UsergridHelpers.normalize = function(str) { + // remove consecutive slashes + str = str.replace(/\/+/g, '/'); + // make sure protocol is followed by two slashes str = str.replace(/:\//g, '://'); - // remove consecutive slashes - str = str.replace(/([^:\s])\/+/g, '$1/'); - // remove trailing slash before parameters or hash str = str.replace(/\/(\?|&|#[^!])/g, '$1'); @@ -186,14 +170,14 @@ // if the header value has the string ": " in it. var index = headerPair.indexOf('\u003a\u0020'); if (index > 0) { - var key = headerPair.substring(0, index); + var key = headerPair.substring(0, index).toLowerCase(); headers[key] = headerPair.substring(index + 2); } } return headers; }; - UsergridHelpers.uri = function(client, method, options) { + UsergridHelpers.uri = function(client, options) { var path = ''; if( options instanceof UsergridEntity ) { path = options.type @@ -208,7 +192,7 @@ } var uuidOrName = ''; - if( method !== UsergridHttpMethod.POST ) { + if( options.method !== UsergridHttpMethod.POST ) { uuidOrName = _.first([ options.uuidOrName, options.uuid, @@ -223,70 +207,157 @@ return UsergridHelpers.urljoin(client.baseUrl, client.orgId, client.appId, path, uuidOrName) }; - UsergridHelpers.body = function(options) { - var rawBody = undefined; - if( options instanceof UsergridEntity ) { - rawBody = options - } else { - rawBody = options.body || options.entity || options.entities; - if( rawBody === undefined ) { - if( _.isArray(options) ) { - if( options[0] instanceof UsergridEntity ) { - rawBody = options - } - } - } - } - - var returnBody = rawBody; - if( rawBody instanceof UsergridEntity ) { - returnBody = rawBody.jsonValue() - } else if( rawBody instanceof Array ) { - if( rawBody[0] instanceof UsergridEntity ) { - returnBody = _.map(rawBody, function(entity){ return entity.jsonValue(); }) - } - } - return returnBody; - } - UsergridHelpers.updateEntityFromRemote = function(entity,usergridResponse) { UsergridHelpers.setWritable(entity, ['uuid', 'name', 'type', 'created']) _.assign(entity, usergridResponse.entity) UsergridHelpers.setReadOnly(entity, ['uuid', 'name', 'type', 'created']) } - UsergridHelpers.headers = function(client, options) { - var headers = { 'User-Agent':'usergrid-js/v' + UsergridSDKVersion }; - _.assign(headers, options.headers); + UsergridHelpers.headers = function(client, options, defaultHeaders) { + var returnHeaders = {} + _.assign(returnHeaders, defaultHeaders) + _.assign(returnHeaders, options.headers); + _.assign(returnHeaders, { 'User-Agent':'usergrid-js/v' + UsergridSDKVersion }) var authForRequests = UsergridHelpers.authForRequests(client); if (authForRequests) { - _.assign(headers, { - authorization: 'Bearer ' + authForRequests.token - }) + _.assign(returnHeaders, { authorization: 'Bearer ' + authForRequests.token }) } - return headers + return returnHeaders }; - UsergridHelpers.encode = function(data) { - var result = ""; - if (typeof data === "string") { - result = data; - } else { - var encode = encodeURIComponent; - _.forOwn(data,function(value,key){ - result += '&' + encode(key) + '=' + encode(value); - }) + UsergridHelpers.setEntity = function(options,args) { + options.entity = _.first([options.entity, args[0]].filter(function(property) { + return (property instanceof UsergridEntity) + })) + if (options.entity !== undefined) { + options.type = options.entity.type } - return result; - }; + return options + } + + UsergridHelpers.setAsset = function(options,args) { + options.asset = _.first([options.asset, _.get(options,'entity.asset'), args[1], args[0]].filter(function(property) { + return (property instanceof UsergridAsset) + })) + return options + } + + UsergridHelpers.setUuidOrName = function(options,args) { + options.uuidOrName = _.first([ + options.uuidOrName, + options.uuid, + options.name, + _.get(options,'entity.uuid'), + _.get(options,'body.uuid'), + _.get(options,'entity.name'), + _.get(options,'body.name'), + _.get(args,'0.uuid'), + _.get(args,'0.name'), + _.get(args,'2'), + _.get(args,'1') + ].filter(_.isString)) + return options + } + + UsergridHelpers.setPathOrType = function(options,args) { + var pathOrType = _.first([ + args.type, + _.get(args,'0.type'), + _.get(options,'entity.type'), + _.get(args,'body.type'), + _.get(options,'body.0.type'), + _.isArray(args) ? args[0] : undefined + ].filter(_.isString)) + options[(/\//.test(pathOrType)) ? 'path' : 'type'] = pathOrType + return options + } + + UsergridHelpers.setQs = function(options,args) { + if (options.path) { + options.qs = _.first([options.qs, args[2], args[1], args[0]].filter(_.isPlainObject)) + } + return options + } + + UsergridHelpers.setQuery = function(options,args) { + options.query = _.first([options,options.query, args[0]].filter(function(property) { + return (property instanceof UsergridQuery) + })) + return options + } + + UsergridHelpers.setAsset = function(options,args) { + options.asset = _.first([options.asset, _.get(options,'entity.asset'), args[1], args[0]].filter(function(property) { + return (property instanceof UsergridAsset) + })) + return options + } + + UsergridHelpers.setBody = function(options,args) { + options.body = _.first([args.entity, args.body, args[0].entity, args[0].body, args[2], args[1], args[0]].filter(function(property) { + return _.isObject(property) && !_.isFunction(property) && !(property instanceof UsergridQuery) && !(property instanceof UsergridAsset) + })) + if (options.body === undefined && options.asset === undefined) { + throw new Error('"body" is required when making a ' + options.method + ' request') + } + + if( options.body instanceof UsergridEntity ) { + options.body = options.body.jsonValue() + } else if( options.body instanceof Array ) { + if( options.body[0] instanceof UsergridEntity ) { + options.body = _.map(options.body, function(entity){ return entity.jsonValue(); }) + } + } + return options + } + + UsergridHelpers.buildReqest = function(client, method, args) { + var options = { + client: client, + method: method, + queryParams: args.queryParams || _.get(args,'0.queryParams'), + callback: UsergridHelpers.callback(args) + } + + UsergridHelpers.assignPrefabOptions(options, args) + UsergridHelpers.setEntity(options, args) + + if( method === UsergridHttpMethod.POST || method === UsergridHttpMethod.PUT ) { + UsergridHelpers.setAsset(options, args) + if( options.asset === undefined ) { + UsergridHelpers.setBody(options, args) + } + } + + UsergridHelpers.setUuidOrName(options, args) + UsergridHelpers.setPathOrType(options, args) + UsergridHelpers.setQs(options, args) + UsergridHelpers.setQuery(options, args) + + options.uri = UsergridHelpers.uri(client,options) + + return new UsergridRequest(options) + } + + UsergridHelpers.buildAppAuthRequest = function(client,auth,callback) { + var requestOptions = { + client: client, + method: UsergridHttpMethod.POST, + uri: UsergridHelpers.uri(client, {path: 'token'} ), + body: UsergridHelpers.appLoginBody(auth), + callback: callback + } + return new UsergridRequest(requestOptions) + } UsergridHelpers.buildConnectionRequest = function(client,method,args) { var options = { client: client, method: method, entity: {}, - to: {} + to: {}, + callback: UsergridHelpers.callback(args) } UsergridHelpers.assignPrefabOptions.call(options, args) @@ -358,7 +429,8 @@ UsergridHelpers.buildGetConnectionRequest = function(client,args) { var options = { client: client, - method: 'GET' + method: 'GET', + callback: UsergridHelpers.callback(args) } UsergridHelpers.assignPrefabOptions.call(options, args) diff --git a/tests/mocha/index.html b/tests/mocha/index.html index 6255fbb..5a55f07 100644 --- a/tests/mocha/index.html +++ b/tests/mocha/index.html @@ -30,10 +30,26 @@ } - + + + + + + + + + + + + + + + + + - + diff --git a/tests/mocha/test_asset.js b/tests/mocha/test_asset.js index 2a4d119..855a6a1 100644 --- a/tests/mocha/test_asset.js +++ b/tests/mocha/test_asset.js @@ -1,10 +1,12 @@ 'use strict' +configs.forEach(function(config) { -describe('UsergridAsset', function() { - var asset + var client = new UsergridClient(config) + + describe('UsergridAsset ' + config.target, function () { + var asset - describe('init from XMLHTTPRequest', function () { before(function (done) { var req = new XMLHttpRequest(); req.open('GET', testFile.uri, true); @@ -20,82 +22,103 @@ describe('UsergridAsset', function() { req.send(null); }); - it('asset.data should be a Javascript Blob', function () { - asset.data.should.be.an.instanceOf(Blob) - }) + describe('init from XMLHTTPRequest', function () { - it('asset.contentType should be inferred from Blob', function () { - asset.contentType.should.equal(testFile.contentType) - }) + it('asset.data should be a Javascript Blob', function () { + asset.data.should.be.an.instanceOf(Blob) + }) - it('asset.contentLength should be ' + testFile.contentLength + ' bytes', function () { - asset.contentLength.should.equal(testFile.contentLength) - }) - }) + it('asset.contentType should be inferred from Blob', function () { + asset.contentType.should.equal(testFile.contentType) + }) - describe('upload via UsergridClient.uploadAsset() to a specific entity', function () { - var entity = new UsergridEntity({ - type: config.test.collection, - name: "TestClientUploadAsset" - }) - before(function (done) { - entity.save(client, function(response){ - response.ok.should.be.true() - entity.should.have.property('uuid') - done() + it('asset.contentLength should be ' + testFile.contentLength + ' bytes', function () { + asset.contentLength.should.equal(testFile.contentLength) }) }) - it('should upload a binary asset to an entity', function (done) { - client.uploadAsset(entity, asset, function (asset, assetResponse, entityWithAsset) { - assetResponse.statusCode.should.equal(200) - entityWithAsset.uuid.should.be.equal(entity.uuid) - entityWithAsset.name.should.be.equal(entity.name) - entityWithAsset.should.have.property('file-metadata') - entityWithAsset['file-metadata'].should.have.property('content-type').equal(testFile.contentType) - entityWithAsset['file-metadata'].should.have.property('content-length').equal(testFile.contentLength) - done() + + describe('upload via UsergridClient.uploadAsset() to a specific entity', function () { + + var entity = new UsergridEntity({ + type: config.test.collection, + name: "TestClientUploadAsset" }) - }) - after(function (done) { - entity.remove(client, function(response){ - response.ok.should.be.true() - entity.uuid.should.be.equal(response.entity.uuid) - entity.name.should.be.equal(response.entity.name) - done() + before(function (done) { + entity.save(client, function (response) { + response.ok.should.be.true() + entity.should.have.property('uuid') + done() + }) + }) + after(function (done) { + entity.remove(client, function (response) { + response.ok.should.be.true() + entity.uuid.should.be.equal(response.entity.uuid) + entity.name.should.be.equal(response.entity.name) + done() + }) + }) + it('should upload a binary asset to an entity', function (done) { + client.uploadAsset(entity, asset, function (asset, assetResponse, entityWithAsset) { + assetResponse.statusCode.should.equal(200) + entityWithAsset.uuid.should.be.equal(entity.uuid) + entityWithAsset.name.should.be.equal(entity.name) + entityWithAsset.should.have.property('file-metadata') + entityWithAsset['file-metadata'].should.have.property('content-type').equal(testFile.contentType) + entityWithAsset['file-metadata'].should.have.property('content-length').equal(testFile.contentLength) + done() + }) }) }) - }) - describe('upload via entity.uploadAsset() to a specific entity', function () { - var entity = new UsergridEntity({ - type: config.test.collection, - name: "TestEntityUploadAsset" - }) - before(function (done) { - entity.save(client, function(response){ - response.ok.should.be.true() - entity.should.have.property('uuid') - done() + describe('upload via entity.uploadAsset() to a specific entity', function () { + + var entity = new UsergridEntity({ + type: config.test.collection, + name: "TestEntityUploadAsset" }) - }) - it('should upload a binary asset to an existing entity', function (done) { - entity.attachAsset(asset) - entity.uploadAsset(client, function (asset, assetResponse, entityWithAsset) { - assetResponse.statusCode.should.equal(200) - entityWithAsset.uuid.should.be.equal(entity.uuid) - entityWithAsset.name.should.be.equal(entity.name) - entityWithAsset.should.have.property('file-metadata') - entityWithAsset['file-metadata'].should.have.property('content-type').equal(testFile.contentType) - entityWithAsset['file-metadata'].should.have.property('content-length').equal(testFile.contentLength) - done() + + before(function (done) { + entity.save(client, function (response) { + response.ok.should.be.true() + entity.should.have.property('uuid') + done() + }) }) - }) - after(function (done) { - entity.remove(client, function(response){ - response.ok.should.be.true() - entity.uuid.should.be.equal(response.entity.uuid) - entity.name.should.be.equal(response.entity.name) - done() + + after(function (done) { + entity.remove(client, function (response) { + response.ok.should.be.true() + entity.uuid.should.be.equal(response.entity.uuid) + entity.name.should.be.equal(response.entity.name) + done() + }) + }) + + it('should upload a binary asset to an existing entity', function (done) { + entity.attachAsset(asset) + entity.save(client, function (response) { + entity.uploadAsset(client, function (asset, assetResponse, entityWithAsset) { + assetResponse.statusCode.should.equal(200) + entityWithAsset.uuid.should.be.equal(entity.uuid) + entityWithAsset.name.should.be.equal(entity.name) + entityWithAsset.should.have.property('file-metadata') + entityWithAsset['file-metadata'].should.have.property('content-type').equal(testFile.contentType) + entityWithAsset['file-metadata'].should.have.property('content-length').equal(testFile.contentLength) + done() + }) + }) + }) + it('should download a binary asset to an existing entity', function (done) { + entity.downloadAsset(client, function (asset, assetResponse, entityWithAsset) { + assetResponse.statusCode.should.equal(200) + entityWithAsset.uuid.should.be.equal(entity.uuid) + entityWithAsset.name.should.be.equal(entity.name) + entityWithAsset.should.have.property('file-metadata') + entityWithAsset['file-metadata'].should.have.property('content-type').equal(testFile.contentType) + entityWithAsset['file-metadata'].should.have.property('content-length').equal(testFile.contentLength) + done() + }) }) }) }) diff --git a/tests/mocha/test_client_auth.js b/tests/mocha/test_client_auth.js index 36dcbf3..c8e42f0 100644 --- a/tests/mocha/test_client_auth.js +++ b/tests/mocha/test_client_auth.js @@ -1,325 +1,342 @@ 'use strict' -describe('Client Auth Tests', function() { - - function getClient() { - return new UsergridClient({ - orgId: config.orgId, - appId: config.appId - }); - } - - describe('authFallback', function() { - var token, client = getClient() - before(function(done) { - // authenticate app and remove sandbox permissions - client.setAppAuth(config.clientId, config.clientSecret) - client.authenticateApp(function(response) { - token = client.appAuth.token - client.usingAuth(client.appAuth).DELETE({path:'roles/guest/permissions',queryParams:{permission:'get,post,put,delete:/**'}}, function(response) { - done() +configs.forEach(function(config) { + + describe('Client Auth Tests ' + config.target, function () { + + function getClient() { + return new UsergridClient(config); + } + + describe('authFallback', function () { + + var token, + client = getClient() + + before(function (done) { + // authenticate app and remove sandbox permissions + client.setAppAuth(config.clientId, config.clientSecret) + client.authenticateApp(function (response) { + token = client.appAuth.token + var permissionsQuery = new UsergridQuery('roles/guest/permissions').urlTerm('permission', 'get,post,put,delete:/**') + client.usingAuth(client.appAuth).DELETE(permissionsQuery, function (response) { + done() + }) }) }) - }) - it('should fall back to using no authentication when currentUser is not authenticated and authFallback is set to NONE', function(done) { - client.authMode = UsergridAuthMode.NONE - client.GET('users', function(usergridResponse) { - should(client.currentUser).be.undefined() - usergridResponse.request.headers.should.not.have.property('authorization') - usergridResponse.error.name.should.equal('unauthorized') - usergridResponse.ok.should.be.false() - done() + it('should fall back to using no authentication when currentUser is not authenticated and authFallback is set to NONE', function (done) { + client.authMode = UsergridAuthMode.NONE + client.GET('users', function (usergridResponse) { + should(client.currentUser).be.undefined() + usergridResponse.request.headers.should.not.have.property('authorization') + usergridResponse.error.name.should.equal('unauthorized') + usergridResponse.ok.should.be.false() + done() + }) }) - }) - it('should fall back to using the app token when currentUser is not authenticated and authFallback is set to APP', function(done) { - client.authMode = UsergridAuthMode.APP - client.GET('users', function(usergridResponse) { - should(client.currentUser).be.undefined() - usergridResponse.request.headers.should.have.property('authorization').equal('Bearer ' + token) - usergridResponse.ok.should.be.true() - usergridResponse.user.should.be.an.instanceof(UsergridUser) - done() + it('should fall back to using the app token when currentUser is not authenticated and authFallback is set to APP', function (done) { + client.authMode = UsergridAuthMode.APP + client.GET('users', function (usergridResponse) { + should(client.currentUser).be.undefined() + usergridResponse.request.headers.should.have.property('authorization').equal('Bearer ' + token) + usergridResponse.ok.should.be.true() + usergridResponse.user.should.be.an.instanceof(UsergridUser) + done() + }) }) - }) - after(function(done) { - client.authMode = UsergridAuthMode.NONE - client.usingAuth(client.appAuth).POST({path:'roles/guest/permissions',body:{ permission: "get,post,put,delete:/**" }}, function(usergridResponse) { - done() + after(function (done) { + client.authMode = UsergridAuthMode.NONE + client.usingAuth(client.appAuth).POST('roles/guest/permissions', {'permission': 'get,post,put,delete:/**'}, function (usergridResponse) { + done() + }) }) }) - }) - describe('authenticateApp()', function() { + describe('authenticateApp()', function () { - var response, token, client = getClient() - before(function(done) { - client.setAppAuth(config.clientId, config.clientSecret) - client.authenticateApp(function(usergridResponse) { - response = usergridResponse - token = client.appAuth.token - done() + var response, token, client = getClient() + before(function (done) { + client.setAppAuth(config.clientId, config.clientSecret) + client.authenticateApp(function (usergridResponse) { + response = usergridResponse + token = client.appAuth.token + done() + }) }) - }) - it('response.ok should be true', function() { - response.ok.should.be.true() - }) + it('response.ok should be true', function () { + response.ok.should.be.true() + }) - it('should have a valid token', function() { - token.should.be.a.String() - token.length.should.be.greaterThan(10) - }) + it('should have a valid token', function () { + token.should.be.a.String() + token.length.should.be.greaterThan(10) + }) - it('client.appAuth.token should be set to the token returned from Usergrid', function() { - client.appAuth.should.have.property('token').equal(token) - }) + it('client.appAuth.token should be set to the token returned from Usergrid', function () { + client.appAuth.should.have.property('token').equal(token) + }) - it('client.appAuth.isValid should be true', function() { - client.appAuth.should.have.property('isValid').which.is.true() - }) + it('client.appAuth.isValid should be true', function () { + client.appAuth.should.have.property('isValid').which.is.true() + }) - it('client.appAuth.expiry should be set to a future date', function() { - client.appAuth.should.have.property('expiry').greaterThan(Date.now()) - }) + it('client.appAuth.expiry should be set to a future date', function () { + client.appAuth.should.have.property('expiry').greaterThan(Date.now()) + }) - it('should fail when called without a clientId and clientSecret', function() { - should(function() { - var client = getClient() - client.setAppAuth(undefined, undefined, 0) - client.authenticateApp() - }).throw() - }) + it('should fail when called without a clientId and clientSecret', function () { + should(function () { + var client = new UsergridClient({orgId: config.orgId, appId: config.appId, baseUrl: config.baseUrl}) + client.setAppAuth(undefined, undefined, 0) + client.authenticateApp() + }).throw() + }) - it('should authenticate by passing clientId and clientSecret in an object', function(done) { - var isolatedClient = getClient() - isolatedClient.authenticateApp({clientId:config.clientId,clientSecret:config.clientSecret}, function(reponse) { - isolatedClient.appAuth.should.have.property('token') - done() + it('should authenticate by passing clientId and clientSecret in an object', function (done) { + var isolatedClient = new UsergridClient({ + orgId: config.orgId, + appId: config.appId, + baseUrl: config.baseUrl + }) + isolatedClient.authenticateApp({ + clientId: config.clientId, + clientSecret: config.clientSecret + }, function (reponse) { + isolatedClient.appAuth.should.have.property('token') + done() + }) }) - }) - it('should authenticate by passing a UsergridAppAuth instance with a custom ttl', function(done) { - var isolatedClient = getClient() - var ttlInMilliseconds = 500000 - var appAuth = new UsergridAppAuth(config.clientId, config.clientSecret, ttlInMilliseconds) - isolatedClient.authenticateApp(appAuth, function(response) { - isolatedClient.appAuth.should.have.property('token') - response.responseJSON.expires_in.should.equal(ttlInMilliseconds / 1000) - done() + it('should authenticate by passing a UsergridAppAuth instance with a custom ttl', function (done) { + var isolatedClient = new UsergridClient({ + orgId: config.orgId, + appId: config.appId, + baseUrl: config.baseUrl + }) + var ttlInMilliseconds = 500000 + var appAuth = new UsergridAppAuth(config.clientId, config.clientSecret, ttlInMilliseconds) + isolatedClient.authenticateApp(appAuth, function (response) { + isolatedClient.appAuth.should.have.property('token') + response.responseJSON.expires_in.should.equal(ttlInMilliseconds / 1000) + done() + }) }) - }) - it('should not set client.appAuth when authenticating with a bad clientId and clientSecret in an object', function(done) { - var failClient = getClient() - failClient.authenticateApp({ - clientId: 'BADCLIENTID', - clientSecret: 'BADCLIENTSECRET' - }, function(response) { - response.error.should.containDeep({ - name: 'invalid_grant', - description: 'invalid username or password' + it('should not set client.appAuth when authenticating with a bad clientId and clientSecret in an object', function (done) { + var failClient = new UsergridClient({orgId: config.orgId, appId: config.appId, baseUrl: config.baseUrl}) + failClient.authenticateApp({ + clientId: 'BADCLIENTID', + clientSecret: 'BADCLIENTSECRET' + }, function (response) { + response.error.should.containDeep({ + name: 'invalid_grant', + description: 'invalid username or password' + }) + should(failClient.appAuth).be.undefined() + done() }) - should(failClient.appAuth).be.undefined() - done() }) - }) - it('should not set client.appAuth when authenticating with a bad UsergridAppAuth instance (using an object)', function(done) { - var failClient = getClient() - failClient.authenticateApp(new UsergridAppAuth({ - clientId: 'BADCLIENTID', - clientSecret: 'BADCLIENTSECRET' - }), function(response) { - response.error.should.containDeep({ - name: 'invalid_grant', - description: 'invalid username or password' + it('should not set client.appAuth when authenticating with a bad UsergridAppAuth instance (using an object)', function (done) { + var failClient = new UsergridClient({orgId: config.orgId, appId: config.appId, baseUrl: config.baseUrl}) + failClient.authenticateApp(new UsergridAppAuth({ + clientId: 'BADCLIENTID', + clientSecret: 'BADCLIENTSECRET' + }), function (response) { + response.error.should.containDeep({ + name: 'invalid_grant', + description: 'invalid username or password' + }) + should(failClient.appAuth).be.undefined() + done() }) - should(failClient.appAuth).be.undefined() - done() }) - }) - it('should not set client.appAuth when authenticating with a bad UsergridAppAuth instance (using arguments)', function(done) { - var failClient = getClient() - failClient.authenticateApp(new UsergridAppAuth('BADCLIENTID', 'BADCLIENTSECRET'), function(response) { - response.error.should.containDeep({ - name: 'invalid_grant', - description: 'invalid username or password' + it('should not set client.appAuth when authenticating with a bad UsergridAppAuth instance (using arguments)', function (done) { + var failClient = new UsergridClient({orgId: config.orgId, appId: config.appId, baseUrl: config.baseUrl}) + failClient.authenticateApp(new UsergridAppAuth('BADCLIENTID', 'BADCLIENTSECRET'), function (response) { + response.error.should.containDeep({ + name: 'invalid_grant', + description: 'invalid username or password' + }) + should(failClient.appAuth).be.undefined() + done() }) - should(failClient.appAuth).be.undefined() - done() }) }) - }) - describe('authenticateUser()', function() { - - var response, token, email = randomWord() + '@' + randomWord() + '.com' - var client = getClient() - before(function(done) { - client.authenticateUser({ - username: config.test.username, - password: config.test.password, - email: email - }, function(auth,user,usergridResponse) { - response = usergridResponse - token = auth.token - done() + describe('authenticateUser()', function () { + + var response, token, email = randomWord() + '@' + randomWord() + '.com' + var client = getClient() + before(function (done) { + client.authenticateUser({ + username: config.test.username, + password: config.test.password, + email: email + }, function (auth, user, usergridResponse) { + response = usergridResponse + token = auth.token + done() + }) }) - }) - it('should fail when called without a email (or username) and password', function() { - should(function() { - var badClient = getClient() - badClient.authenticateUser({}) - }).throw() - }) + it('should fail when called without a email (or username) and password', function () { + should(function () { + var badClient = new UsergridClient({ + orgId: config.orgId, + appId: config.appId, + baseUrl: config.baseUrl + }) + badClient.authenticateUser({}) + }).throw() + }) - it('response.ok should be true', function() { - response.ok.should.be.true() - }) + it('response.ok should be true', function () { + response.ok.should.be.true() + }) - it('should have a valid token', function() { - token.should.be.a.String() - token.length.should.be.greaterThan(10) - }) + it('should have a valid token', function () { + token.should.be.a.String() + token.length.should.be.greaterThan(10) + }) - it('client.currentUser.auth.token should be set to the token returned from Usergrid', function() { - client.currentUser.auth.should.have.property('token').equal(token) - }) + it('client.currentUser.auth.token should be set to the token returned from Usergrid', function () { + client.currentUser.auth.should.have.property('token').equal(token) + }) - it('client.currentUser.auth.isValid should be true', function() { - client.currentUser.auth.should.have.property('isValid').which.is.true() - }) + it('client.currentUser.auth.isValid should be true', function () { + client.currentUser.auth.should.have.property('isValid').which.is.true() + }) - it('client.currentUser.auth.expiry should be set to a future date', function() { - client.currentUser.auth.should.have.property('expiry').greaterThan(Date.now()) - }) + it('client.currentUser.auth.expiry should be set to a future date', function () { + client.currentUser.auth.should.have.property('expiry').greaterThan(Date.now()) + }) - it('client.currentUser should have a username and email', function() { - client.currentUser.should.have.property('username') - client.currentUser.should.have.property('email').equal(email) - }) + it('client.currentUser should have a username and email', function () { + client.currentUser.should.have.property('username') + client.currentUser.should.have.property('email').equal(email) + }) - it('client.currentUser and client.currentUser.auth should not store password', function() { - client.currentUser.should.not.have.property('password') - client.currentUser.auth.should.not.have.property('password') - }) + it('client.currentUser and client.currentUser.auth should not store password', function () { + client.currentUser.should.not.have.property('password') + client.currentUser.auth.should.not.have.property('password') + }) - it('should support an optional bool to not set as current user', function(done) { - var noCurrentUserClient = getClient() - noCurrentUserClient.authenticateUser({ - username: config.test.username, - password: config.test.password, - email: config.test.email - }, false, function(response) { - should(noCurrentUserClient.currentUser).be.undefined() - done() + it('should support an optional bool to not set as current user', function (done) { + var noCurrentUserClient = new UsergridClient({ + orgId: config.orgId, + appId: config.appId, + baseUrl: config.baseUrl + }) + noCurrentUserClient.authenticateUser({ + username: config.test.username, + password: config.test.password, + email: config.test.email + }, false, function (response) { + should(noCurrentUserClient.currentUser).be.undefined() + done() + }) }) - }) - it('should support passing a UsergridUserAuth instance with a custom ttl', function(done) { - var newClient = getClient() - var ttlInMilliseconds = 500000 - var userAuth = new UsergridUserAuth(config.test.username, config.test.password, ttlInMilliseconds) - client.authenticateUser(userAuth, function(auth,user,usergridResponse) { - usergridResponse.ok.should.be.true() - client.currentUser.auth.token.should.equal(auth.token) - usergridResponse.responseJSON.expires_in.should.equal(ttlInMilliseconds / 1000) - done() + it('should support passing a UsergridUserAuth instance with a custom ttl', function (done) { + var newClient = new UsergridClient({orgId: config.orgId, appId: config.appId, baseUrl: config.baseUrl}) + var ttlInMilliseconds = 500000 + var userAuth = new UsergridUserAuth(config.test.username, config.test.password, ttlInMilliseconds) + newClient.authenticateUser(userAuth, function (auth, user, usergridResponse) { + usergridResponse.ok.should.be.true() + newClient.currentUser.auth.token.should.equal(auth.token) + usergridResponse.responseJSON.expires_in.should.equal(ttlInMilliseconds / 1000) + done() + }) }) }) - }) - describe('appAuth, setAppAuth()', function() { - var client = getClient() - it('should initialize by passing a list of arguments', function() { - client.setAppAuth(config.clientId, config.clientSecret, config.tokenTtl) - client.appAuth.should.be.instanceof(UsergridAppAuth) - }) + describe('appAuth, setAppAuth()', function () { + var client = getClient() + it('should initialize by passing a list of arguments', function () { + client.setAppAuth(config.clientId, config.clientSecret, config.tokenTtl) + client.appAuth.should.be.instanceof(UsergridAppAuth) + }) - it('should be a subclass of UsergridAuth', function() { - client.setAppAuth(config.clientId, config.clientSecret, config.tokenTtl) - client.appAuth.should.be.instanceof(UsergridAuth) - }) + it('should be a subclass of UsergridAuth', function () { + client.setAppAuth(config.clientId, config.clientSecret, config.tokenTtl) + client.appAuth.should.be.instanceof(UsergridAuth) + }) - it('should initialize by passing an object', function() { - client.setAppAuth({ - clientId: config.clientId, - clientSecret: config.clientSecret, - tokenTtl: config.tokenTtl + it('should initialize by passing an object', function () { + client.setAppAuth({ + clientId: config.clientId, + clientSecret: config.clientSecret, + tokenTtl: config.tokenTtl + }) + client.appAuth.should.be.instanceof(UsergridAppAuth) }) - client.appAuth.should.be.instanceof(UsergridAppAuth) - }) - it('should initialize by passing an instance of UsergridAppAuth', function() { - client.setAppAuth(new UsergridAppAuth(config.clientId, config.clientSecret, config.tokenTtl)) - client.appAuth.should.be.instanceof(UsergridAppAuth) - }) + it('should initialize by passing an instance of UsergridAppAuth', function () { + client.setAppAuth(new UsergridAppAuth(config.clientId, config.clientSecret, config.tokenTtl)) + client.appAuth.should.be.instanceof(UsergridAppAuth) + }) - it('should initialize by setting to an instance of UsergridAppAuth', function() { - client.appAuth = new UsergridAppAuth(config.clientId, config.clientSecret, config.tokenTtl) - client.appAuth.should.be.instanceof(UsergridAppAuth) + it('should initialize by setting to an instance of UsergridAppAuth', function () { + client.appAuth = new UsergridAppAuth(config.clientId, config.clientSecret, config.tokenTtl) + client.appAuth.should.be.instanceof(UsergridAppAuth) + }) }) - }) - describe('usingAuth()', function() { + describe('usingAuth()', function () { - var client = getClient(), - authFromToken + var client = getClient(), + authFromToken - before(function(done) { - client.authenticateUser({ - username: config.test.username, - password: config.test.password - }, function(auth, user, response) { - authFromToken = new UsergridAuth(auth.token) - done() + before(function (done) { + client.authenticateUser({ + username: config.test.username, + password: config.test.password + }, function (auth, user, response) { + authFromToken = new UsergridAuth(auth.token) + done() + }) }) - }) - it('should authenticate using an ad-hoc token', function(done) { - authFromToken.isValid.should.be.true() - authFromToken.should.have.property('token') - client.usingAuth(authFromToken).GET({ - path: '/users/me' - }, function(usergridResponse) { - usergridResponse.ok.should.be.true() - usergridResponse.should.have.property('user').which.is.an.instanceof(UsergridUser) - usergridResponse.user.should.have.property('uuid') - done() + it('should authenticate using an ad-hoc token', function (done) { + authFromToken.isValid.should.be.true() + authFromToken.should.have.property('token') + client.usingAuth(authFromToken).GET('/users/me', function (usergridResponse) { + usergridResponse.ok.should.be.true() + usergridResponse.should.have.property('user').which.is.an.instanceof(UsergridUser) + usergridResponse.user.should.have.property('uuid') + done() + }) }) - }) - it('client.tempAuth should be destroyed after making a request with ad-hoc authentication', function(done) { - should(client.tempAuth).be.undefined() - done() - }) - - it('should send an unauthenticated request when UsergridAuth.NO_AUTH is passed to .usingAuth()', function(done) { - client.authMode = UsergridAuthMode.NONE - client.GET({ - path: '/users/me' - }, function(usergridResponse) { - usergridResponse.ok.should.be.false() - usergridResponse.request.headers.should.not.have.property('authentication') - usergridResponse.should.not.have.property('user') + it('client.tempAuth should be destroyed after making a request with ad-hoc authentication', function (done) { + should(client.tempAuth).be.undefined() done() }) - }) - it('should send an unauthenticated request when no arguments are passed to .usingAuth()', function(done) { - client.usingAuth().GET({ - path: '/users/me' - }, function(usergridResponse) { - usergridResponse.ok.should.be.false() - usergridResponse.request.headers.should.not.have.property('authentication') - usergridResponse.should.not.have.property('user') - done() + it('should send an unauthenticated request when UsergridAuth.NO_AUTH is passed to .usingAuth()', function (done) { + client.authMode = UsergridAuthMode.NONE + client.GET('/users/me', function (usergridResponse) { + usergridResponse.ok.should.be.false() + usergridResponse.request.headers.should.not.have.property('authentication') + usergridResponse.should.not.have.property('user') + done() + }) + }) + + it('should send an unauthenticated request when no arguments are passed to .usingAuth()', function (done) { + client.usingAuth().GET('/users/me', function (usergridResponse) { + usergridResponse.ok.should.be.false() + usergridResponse.request.headers.should.not.have.property('authentication') + usergridResponse.should.not.have.property('user') + done() + }) }) }) }) diff --git a/tests/mocha/test_client_connections.js b/tests/mocha/test_client_connections.js index 3e45e8b..fe4591e 100644 --- a/tests/mocha/test_client_connections.js +++ b/tests/mocha/test_client_connections.js @@ -1,89 +1,159 @@ 'use strict' -describe('Client Connections', function() { +configs.forEach(function(config) { - var entity1, - entity2 + var client = new UsergridClient(config) - describe('connect()', function () { + describe('Client Connections ' + config.target, function () { + + var response, + entity1, + entity2 before(function (done) { // Create the entities we're going to use for connections - client.POST({type:config.test.collection, body:[{ "name": "testClientConnectOne"}, {"name": "testClientConnectTwo"}]}, function (postResponse) { - entity1 = postResponse.first - entity2 = postResponse.last + client.POST({ + type: config.test.collection, + body: [{"name": "testClientConnectOne"}, {"name": "testClientConnectTwo"}] + }, function (postResponse) { + response = postResponse + entity1 = response.first + entity2 = response.last done() }) }); - it('should connect entities by passing UsergridEntity objects as parameters', function (done) { - var relationship = "foos" + after(function (done) { + // Delete the entities we used for connections + _.forEach(response.entities, function (entity) { + entity.remove(client) + }) + done() + }); - client.connect(entity1, relationship, entity2, function (usergridResponse) { - usergridResponse.ok.should.be.true() - client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { - usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( - "", - config.test.collection, - entity1.uuid, - relationship, - entity2.uuid, - "connecting", - relationship - )) - done() + describe('connect()', function () { + + it('should connect entities by passing UsergridEntity objects as parameters', function (done) { + var relationship = "foos" + + client.connect(entity1, relationship, entity2, function (usergridResponse) { + usergridResponse.ok.should.be.true() + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { + usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( + "/", + config.test.collection, + entity1.uuid, + relationship, + entity2.uuid, + "connecting", + relationship + )) + done() + }) }) }) - }) - it('should connect entities by passing a source UsergridEntity object and a target uuid', function (done) { - var relationship = "bars" + it('should connect entities by passing a source UsergridEntity object and a target uuid', function (done) { + var relationship = "bars" + + client.connect(entity1, relationship, entity2.uuid, function (usergridResponse) { + usergridResponse.ok.should.be.true() + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { + usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( + "/", + config.test.collection, + entity1.uuid, + relationship, + entity2.uuid, + "connecting", + relationship + )) + done() + }) + }) + }) - client.connect(entity1, relationship, entity2.uuid, function (usergridResponse) { - usergridResponse.ok.should.be.true() - client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { - usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( - "", - config.test.collection, - entity1.uuid, - relationship, - entity2.uuid, - "connecting", - relationship - )) - done() + it('should connect entities by passing source type, source uuid, and target uuid as parameters', function (done) { + var relationship = "bazzes" + + client.connect(entity1.type, entity1.uuid, relationship, entity2.uuid, function (usergridResponse) { + usergridResponse.ok.should.be.true() + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { + usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( + "/", + config.test.collection, + entity1.uuid, + relationship, + entity2.uuid, + "connecting", + relationship + )) + done() + }) }) }) - }) - it('should connect entities by passing source type, source uuid, and target uuid as parameters', function (done) { - var relationship = "bazzes" + it('should connect entities by passing source type, source name, target type, and target name as parameters', function (done) { + var relationship = "quxes" + + client.connect(entity1.type, entity1.name, relationship, entity2.type, entity2.name, function (usergridResponse) { + usergridResponse.ok.should.be.true() + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { + usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( + "/", + config.test.collection, + entity1.uuid, + relationship, + entity2.uuid, + "connecting", + relationship + )) + done() + }) + }) + }) - client.connect(entity1.type, entity1.uuid, relationship, entity2.uuid, function (usergridResponse) { - usergridResponse.ok.should.be.true() - client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { - usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( - "", - config.test.collection, - entity1.uuid, - relationship, - entity2.uuid, - "connecting", - relationship - )) - done() + it('should connect entities by passing a preconfigured options object', function (done) { + var options = { + entity: entity1, + relationship: "quuxes", + to: entity2 + } + + client.connect(options, function (usergridResponse) { + usergridResponse.ok.should.be.true() + client.getConnections(UsergridDirection.OUT, entity1, options.relationship, function (usergridResponse) { + usergridResponse.first.metadata.connecting[options.relationship].should.equal(UsergridHelpers.urljoin( + "/", + config.test.collection, + entity1.uuid, + options.relationship, + entity2.uuid, + "connecting", + options.relationship + )) + done() + }) }) }) + + it('should fail to connect entities when specifying target name without type', function () { + should(function () { + client.connect(entity1.type, entity1.name, "fails", 'badName', function () { + }) + }).throw() + }) }) - it('should connect entities by passing source type, source name, target type, and target name as parameters', function (done) { - var relationship = "quxes" + describe('getConnections()', function () { + + it('should get an entity\'s outbound connections', function (done) { + + var relationship = "foos" - client.connect(entity1.type, entity1.name, relationship, entity2.type, entity2.name, function (usergridResponse) { - usergridResponse.ok.should.be.true() client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( - "", + "/", config.test.collection, entity1.uuid, relationship, @@ -94,150 +164,90 @@ describe('Client Connections', function() { done() }) }) - }) - it('should connect entities by passing a preconfigured options object', function (done) { - var options = { - entity: entity1, - relationship: "quuxes", - to: entity2 - } - - client.connect(options, function (usergridResponse) { - usergridResponse.ok.should.be.true() - client.getConnections(UsergridDirection.OUT, entity1, options.relationship, function (usergridResponse) { - usergridResponse.first.metadata.connecting[options.relationship].should.equal(UsergridHelpers.urljoin( - "", + it('should get an entity\'s inbound connections', function (done) { + + var relationship = "foos" + + client.getConnections(UsergridDirection.IN, entity2, relationship, function (usergridResponse) { + usergridResponse.first.metadata.connections[relationship].should.equal(UsergridHelpers.urljoin( + "/", config.test.collection, - entity1.uuid, - options.relationship, entity2.uuid, "connecting", - options.relationship + entity1.uuid, + relationship )) done() }) }) }) - it('should fail to connect entities when specifying target name without type', function () { - should(function () { - client.connect(entity1.type, entity1.name, "fails", 'badName', function () { - }) - }).throw() - }) - }) - - describe('getConnections()', function () { - - it('should get an entity\'s outbound connections', function (done) { - - var relationship = "foos" - - client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { - usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( - "", - config.test.collection, - entity1.uuid, - relationship, - entity2.uuid, - "connecting", - relationship - )) - done() - }) - }) - - it('should get an entity\'s inbound connections', function (done) { - - var relationship = "foos" - - client.getConnections(UsergridDirection.IN, entity2, relationship, function (usergridResponse) { - usergridResponse.first.metadata.connections[relationship].should.equal(UsergridHelpers.urljoin( - "", - config.test.collection, - entity2.uuid, - "connecting", - entity1.uuid, - relationship - )) - done() - }) - }) - }) - - describe('disconnect()', function () { + describe('disconnect()', function () { - after(function (done) { - // Delete the entities we used for connections - var deleteQuery = new UsergridQuery(config.test.collection).eq('uuid', entity1.uuid).or.eq('uuid', entity2.uuid) - client.DELETE(deleteQuery, function () { - done() - }) - }); - - it('should disconnect entities by passing UsergridEntity objects as parameters', function (done) { + it('should disconnect entities by passing UsergridEntity objects as parameters', function (done) { - var relationship = "foos" + var relationship = "foos" - client.disconnect(entity1, relationship, entity2, function (usergridResponse) { - usergridResponse.ok.should.be.true() - client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { - usergridResponse.entities.should.be.an.Array().with.lengthOf(0) - done() + client.disconnect(entity1, relationship, entity2, function (usergridResponse) { + usergridResponse.ok.should.be.true() + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { + usergridResponse.entities.should.be.an.Array().with.lengthOf(0) + done() + }) }) }) - }) - it('should disconnect entities by passing source type, source uuid, and target uuid as parameters', function (done) { + it('should disconnect entities by passing source type, source uuid, and target uuid as parameters', function (done) { - var relationship = "bars" + var relationship = "bars" - client.disconnect(entity1.type, entity1.uuid, relationship, entity2.uuid, function (usergridResponse) { - usergridResponse.ok.should.be.true() - client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { - usergridResponse.entities.should.be.an.Array().with.lengthOf(0) - done() + client.disconnect(entity1.type, entity1.uuid, relationship, entity2.uuid, function (usergridResponse) { + usergridResponse.ok.should.be.true() + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { + usergridResponse.entities.should.be.an.Array().with.lengthOf(0) + done() + }) }) }) - }) - it('should disconnect entities by passing source type, source name, target type, and target name as parameters', function (done) { + it('should disconnect entities by passing source type, source name, target type, and target name as parameters', function (done) { - var relationship = "bazzes" + var relationship = "bazzes" - client.disconnect(entity1.type, entity1.name, relationship, entity2.type, entity2.name, function (usergridResponse) { - usergridResponse.ok.should.be.true() - client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { - usergridResponse.entities.should.be.an.Array().with.lengthOf(0) - done() + client.disconnect(entity1.type, entity1.name, relationship, entity2.type, entity2.name, function (usergridResponse) { + usergridResponse.ok.should.be.true() + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { + usergridResponse.entities.should.be.an.Array().with.lengthOf(0) + done() + }) }) }) - }) - it('should disconnect entities by passing a preconfigured options object', function (done) { + it('should disconnect entities by passing a preconfigured options object', function (done) { - var options = { - entity: entity1, - relationship: "quxes", - to: entity2 - } + var options = { + entity: entity1, + relationship: "quxes", + to: entity2 + } - client.disconnect(options, function (usergridResponse) { - usergridResponse.ok.should.be.true() - client.getConnections(UsergridDirection.OUT, entity1, options.relationship, function (usergridResponse) { - usergridResponse.entities.should.be.an.Array().with.lengthOf(0) - done() + client.disconnect(options, function (usergridResponse) { + usergridResponse.ok.should.be.true() + client.getConnections(UsergridDirection.OUT, entity1, options.relationship, function (usergridResponse) { + usergridResponse.entities.should.be.an.Array().with.lengthOf(0) + done() + }) }) }) - }) - it('should fail to disconnect entities when specifying target name without type', function () { + it('should fail to disconnect entities when specifying target name without type', function () { - should(function () { - client.disconnect(entity1.type, entity1.name, "fails", entity2.name, function () { - }) - }).throw() + should(function () { + client.disconnect(entity1.type, entity1.name, "fails", entity2.name, function () { + }) + }).throw() + }) }) }) }) \ No newline at end of file diff --git a/tests/mocha/test_client_rest.js b/tests/mocha/test_client_rest.js index 9855c01..9e8579d 100644 --- a/tests/mocha/test_client_rest.js +++ b/tests/mocha/test_client_rest.js @@ -1,463 +1,491 @@ 'use strict' -describe('Client REST Tests', function() { +configs.forEach(function(config) { - var _uuid + var client = new UsergridClient(config) - describe('POST()', function () { + describe('Client REST Tests ' + config.target, function () { - var response - before(function (done) { - client.POST({ - type: config.test.collection, body: { - author: 'Sir Arthur Conan Doyle' - } - }, function (usergridResponse) { - response = usergridResponse - _uuid = usergridResponse.entity.uuid - done() - }) - }) + var _uuid - it('should not fail when a callback function is not passed', function () { - // note: this test will NOT fail gracefully inside the Mocha event chain - client.POST(config.test.collection, {}) - }) - - it('response.ok should be true', function () { - response.ok.should.be.true() - }) + describe('POST()', function () { - it('response.entities should be an array', function () { - response.entities.should.be.an.Array().with.a.lengthOf(1) - }) - - it('response.entity should exist and have a valid uuid', function () { - response.entity.should.be.an.instanceof(UsergridEntity).with.property('uuid')//.which.is.a.uuid() - }) - - it('response.entity.author should equal "Sir Arthur Conan Doyle"', function () { - response.entity.should.have.property('author').equal('Sir Arthur Conan Doyle') - }) - - it('should support creating an entity by passing a UsergridEntity object', function (done) { + var response + before(function (done) { + client.POST({ + type: config.test.collection, body: { + author: 'Sir Arthur Conan Doyle' + } + }, function (usergridResponse) { + response = usergridResponse + _uuid = usergridResponse.entity.uuid + done() + }) + }) - var entity = new UsergridEntity({ - type: config.test.collection, - restaurant: "Dino's Deep Dish", - cuisine: "pizza" + it('should not fail when a callback function is not passed', function () { + // note: this test will NOT fail gracefully inside the Mocha event chain + client.POST(config.test.collection, {}) }) - client.POST(entity, function (usergridResponse) { - usergridResponse.entity.should.be.an.Object().with.property('restaurant').equal(entity.restaurant) - client.DELETE(usergridResponse.entity, function (delResponse) { - delResponse.entity.should.have.property('uuid').equal(usergridResponse.entity.uuid) - done() - }) + it('response.ok should be true', function () { + response.ok.should.be.true() }) - }) - it('should support creating an entity by passing a UsergridEntity object with a unique name', function (done) { + it('response.entities should be an array', function () { + response.entities.should.be.an.Array().with.a.lengthOf(1) + }) - var entity = new UsergridEntity({ - type: config.test.collection, - name: randomWord() + it('response.entity should exist and have a valid uuid', function () { + response.entity.should.be.an.instanceof(UsergridEntity).with.property('uuid')//.which.is.a.uuid() }) - client.POST(entity, function (usergridResponse) { - usergridResponse.entity.should.be.an.Object().with.property('name').equal(entity.name) - client.DELETE(usergridResponse.entity, function (delResponse) { - delResponse.entity.should.have.property('uuid').equal(usergridResponse.entity.uuid) - done() - }) + + it('response.entity.author should equal "Sir Arthur Conan Doyle"', function () { + response.entity.should.have.property('author').equal('Sir Arthur Conan Doyle') }) - }) - it('should support creating an entity by passing type and a body object', function (done) { + it('should support creating an entity by passing a UsergridEntity object', function (done) { + this.timeout(_timeout + 4000) - var options = { - type: config.test.collection, - body: { + var entity = new UsergridEntity({ + type: config.test.collection, restaurant: "Dino's Deep Dish", cuisine: "pizza" - } - }; - client.POST(options, function (usergridResponse) { - usergridResponse.entity.should.be.an.Object().with.property('restaurant').equal("Dino's Deep Dish") - client.DELETE(usergridResponse.entity, function (delResponse) { - delResponse.entity.should.have.property('uuid').equal(usergridResponse.entity.uuid) - done() + }) + + client.POST(entity, function (usergridResponse) { + usergridResponse.entity.should.be.an.Object().with.property('restaurant').equal(entity.restaurant) + sleepFor(defaultSleepTime); + client.DELETE(usergridResponse.entity, function (delResponse) { + delResponse.entity.should.have.property('uuid').equal(usergridResponse.entity.uuid) + done() + }) }) }) - }) - it('should support creating an entity by passing a body object that includes type', function (done) { + it('should support creating an entity by passing a UsergridEntity object with a unique name', function (done) { + this.timeout(_timeout + 4000) - var options = { - body: { + var entity = new UsergridEntity({ type: config.test.collection, - restaurant: "Dino's Deep Dish", - cuisine: "pizza" - } - }; - client.POST(options, function (usergridResponse) { - usergridResponse.entity.should.be.an.Object().with.property('restaurant').equal("Dino's Deep Dish") - client.DELETE(usergridResponse.entity, function (delResponse) { - delResponse.entity.should.have.property('uuid').equal(usergridResponse.entity.uuid) - done() + name: randomWord() + }) + client.POST(entity, function (usergridResponse) { + usergridResponse.entity.should.be.an.Object().with.property('name').equal(entity.name) + sleepFor(defaultSleepTime); + client.DELETE(usergridResponse.entity, function (delResponse) { + delResponse.entity.should.have.property('uuid').equal(usergridResponse.entity.uuid) + done() + }) }) }) - }) - it('should support creating an entity by passing an array of UsergridEntity objects', function (done) { + it('should support creating an entity by passing type and a body object', function (done) { + this.timeout(_timeout + 4000) - var entities = [ - new UsergridEntity({ - type: config.test.collection, - restaurant: "Dino's Deep Dish", - cuisine: "pizza" - }), new UsergridEntity({ + var options = { type: config.test.collection, - restaurant: "Giordanos", - cuisine: "pizza" + body: { + restaurant: "Dino's Deep Dish", + cuisine: "pizza" + } + }; + client.POST(options, function (usergridResponse) { + usergridResponse.entity.should.be.an.Object().with.property('restaurant').equal("Dino's Deep Dish") + sleepFor(defaultSleepTime); + client.DELETE(usergridResponse.entity, function (delResponse) { + delResponse.entity.should.have.property('uuid').equal(usergridResponse.entity.uuid) + done() + }) }) - ] + }) + it('should support creating an entity by passing a body object that includes type', function (done) { + this.timeout(_timeout + 4000) + + var options = { + body: { + type: config.test.collection, + restaurant: "Dino's Deep Dish", + cuisine: "pizza" + } + }; + client.POST(options, function (usergridResponse) { + usergridResponse.entity.should.be.an.Object().with.property('restaurant').equal("Dino's Deep Dish") + sleepFor(defaultSleepTime); + client.DELETE(usergridResponse.entity, function (delResponse) { + delResponse.entity.should.have.property('uuid').equal(usergridResponse.entity.uuid) + done() + }) + }) + }) + + it('should support creating an entity by passing an array of UsergridEntity objects', function (done) { + + var entities = [ + new UsergridEntity({ + type: config.test.collection, + restaurant: "Dino's Deep Dish", + cuisine: "pizza" + }), new UsergridEntity({ + type: config.test.collection, + restaurant: "Giordanos", + cuisine: "pizza" + }) + ] - client.POST(entities, function (usergridResponse) { - usergridResponse.entities.should.be.an.Array().with.lengthOf(2) - _.forEach(usergridResponse.entities, function (entity) { - entity.should.be.an.Object().with.property('restaurant').equal(entity.restaurant) + + client.POST({ + body: entities, callback: function (usergridResponse) { + usergridResponse.entities.should.be.an.Array().with.lengthOf(2) + _.forEach(usergridResponse.entities, function (entity) { + entity.should.be.an.Object().with.property('restaurant').equal(entity.restaurant) + }) + done() + } }) - done() }) - }) - it('should support creating an entity by passing a preformatted POST builder object', function (done) { + it('should support creating an entity by passing a preformatted POST builder object', function (done) { - var options = { - type: config.test.collection, - body: { - restaurant: "Chipotle", - cuisine: "mexican" + var options = { + type: config.test.collection, + body: { + restaurant: "Chipotle", + cuisine: "mexican" + } } - } - client.POST(options, function (usergridResponse) { - usergridResponse.entity.should.be.an.Object().with.property('restaurant').equal(usergridResponse.entity.restaurant) - usergridResponse.entity.remove(client, function (delResponse) { - delResponse.entity.should.have.property('uuid').equal(usergridResponse.entity.uuid) - done() + client.POST(options, function (usergridResponse) { + usergridResponse.entity.should.be.an.Object().with.property('restaurant').equal(usergridResponse.entity.restaurant) + usergridResponse.entity.remove(client, function (delResponse) { + delResponse.entity.should.have.property('uuid').equal(usergridResponse.entity.uuid) + done() + }) }) }) }) - }) - describe('GET()', function () { + describe('GET()', function () { - var response - before(function (done) { - client.GET({type: config.test.collection}, function (usergridResponse) { - response = usergridResponse - done() + var response + before(function (done) { + client.GET({type: config.test.collection}, function (usergridResponse) { + response = usergridResponse + done() + }) }) - }) - it('should not fail when a callback function is not passed', function () { - // note: this test will NOT fail gracefully inside the Mocha event chain - client.GET(config.test.collection) - }) + it('should not fail when a callback function is not passed', function () { + // note: this test will NOT fail gracefully inside the Mocha event chain + client.GET(config.test.collection) + }) - it('response.ok should be true', function () { - response.ok.should.be.true() - }) + it('response.ok should be true', function () { + response.ok.should.be.true() + }) - it('response.entities should be an array', function () { - response.entities.should.be.an.Array() - }) + it('response.entities should be an array', function () { + response.entities.should.be.an.Array() + }) - it('response.first should exist and have a valid uuid', function () { - response.first.should.be.an.instanceof(UsergridEntity).with.property('uuid')//.which.is.a.uuid() - }) + it('response.first should exist and have a valid uuid', function () { + response.first.should.be.an.instanceof(UsergridEntity).with.property('uuid')//.which.is.a.uuid() + }) - it('response.entity should exist and have a valid uuid', function () { - response.entity.should.be.an.instanceof(UsergridEntity).with.property('uuid')//.which.is.a.uuid() - }) + it('response.entity should exist and have a valid uuid', function () { + response.entity.should.be.an.instanceof(UsergridEntity).with.property('uuid')//.which.is.a.uuid() + }) - it('response.last should exist and have a valid uuid', function () { - response.last.should.be.an.instanceof(UsergridEntity).with.property('uuid')//.which.is.a.uuid() - }) + it('response.last should exist and have a valid uuid', function () { + response.last.should.be.an.instanceof(UsergridEntity).with.property('uuid')//.which.is.a.uuid() + }) - it('each entity should match the search criteria when passing a UsergridQuery object', function (done) { - var query = new UsergridQuery(config.test.collection).eq('author', 'Sir Arthur Conan Doyle') - client.GET(query, function (usergridResponse) { - usergridResponse.entities.should.be.an.Array().with.lengthOf(1) - usergridResponse.entities.forEach(function (entity) { - entity.should.be.an.Object().with.property('author').equal('Sir Arthur Conan Doyle') + it('each entity should match the search criteria when passing a UsergridQuery object', function (done) { + var query = new UsergridQuery(config.test.collection).eq('author', 'Sir Arthur Conan Doyle') + client.GET(query, function (usergridResponse) { + usergridResponse.entities.should.be.an.Array().with.lengthOf(1) + usergridResponse.entities.forEach(function (entity) { + entity.should.be.an.Object().with.property('author').equal('Sir Arthur Conan Doyle') + }) + done() }) - done() }) - }) - it('a single entity should be retrieved when specifying a uuid', function (done) { - client.GET({type: config.test.collection, uuid: response.entity.uuid}, function (usergridResponse) { - usergridResponse.should.have.property('entity').which.is.an.instanceof(UsergridEntity) - usergridResponse.entities.should.be.an.Array().with.a.lengthOf(1) - done() + it('a single entity should be retrieved when specifying a uuid', function (done) { + client.GET(config.test.collection, response.entity.uuid, function (usergridResponse) { + usergridResponse.should.have.property('entity').which.is.an.instanceof(UsergridEntity) + usergridResponse.entities.should.be.an.Array().with.a.lengthOf(1) + done() + }) }) }) - }) - describe('PUT()', function () { + describe('PUT()', function () { - var response + var response - before(function (done) { - client.PUT({ - path: config.test.collection, - uuid: _uuid, - body: {narrator: 'Peter Doyle'} - }, function (usergridResponse) { - response = usergridResponse - done() + before(function (done) { + client.PUT(config.test.collection, _uuid, {narrator: 'Peter Doyle'}, function (usergridResponse) { + response = usergridResponse + done() + }) }) - }) - after(function (done) { - client.DELETE(response.entity, function (delResponse) { - delResponse.entity.should.have.property('uuid').equal(response.entity.uuid) - done() + after(function (done) { + client.DELETE(response.entity, function (delResponse) { + delResponse.entity.should.have.property('uuid').equal(response.entity.uuid) + done() + }) }) - }) - it('should not fail when a callback function is not passed', function () { - // note: this test will NOT fail gracefully inside the Mocha event chain - client.PUT(config.test.collection, _uuid, {}) - }) - - it('response.ok should be true', function () { - response.ok.should.be.true() - }) - - it('response.entities should be an array with a single entity', function () { - response.entities.should.be.an.Array().with.a.lengthOf(1) - }) - - it('response.entity should exist and its uuid should the uuid from the previous POST request', function () { - response.entity.should.be.an.Object().with.property('uuid').equal(_uuid) - }) + it('should not fail when a callback function is not passed', function () { + // note: this test will NOT fail gracefully inside the Mocha event chain + client.PUT(config.test.collection, _uuid, {}) + }) - it('response.entity.narrator should be updated to "Peter Doyle"', function () { - response.entity.should.have.property('narrator').equal('Peter Doyle') - }) + it('response.ok should be true', function () { + response.ok.should.be.true() + }) - it('should create a new entity when no uuid or name is passed', function (done) { + it('response.entities should be an array with a single entity', function () { + response.entities.should.be.an.Array().with.a.lengthOf(1) + }) - var newEntity = new UsergridEntity({ - type: config.test.collection, - author: 'Frank Mills' + it('response.entity should exist and its uuid should the uuid from the previous POST request', function () { + response.entity.should.be.an.Object().with.property('uuid').equal(_uuid) }) - client.PUT(newEntity, function (usergridResponse) { - usergridResponse.entity.should.be.an.Object() - usergridResponse.entity.should.be.an.instanceof(UsergridEntity).with.property('uuid')//.which.is.a.uuid() - usergridResponse.entity.should.have.property('author').equal('Frank Mills') - usergridResponse.entity.created.should.equal(usergridResponse.entity.modified) - client.DELETE(usergridResponse.entity, function (delResponse) { - delResponse.entity.should.be.an.Object() - delResponse.entity.should.have.property('uuid').equal(usergridResponse.entity.uuid) - done() - }) + it('response.entity.narrator should be updated to "Peter Doyle"', function () { + response.entity.should.have.property('narrator').equal('Peter Doyle') }) - }) - it('should support updating the entity by passing a UsergridEntity object', function (done) { + it('should create a new entity when no uuid or name is passed', function (done) { + this.timeout(_timeout + 4000) - var updateEntity = _.assign(response.entity, { - publisher: { - name: "George Newns", - date: "14 October 1892", - country: "United Kingdom" - } - }) + var newEntity = new UsergridEntity({ + type: config.test.collection, + author: 'Frank Mills' + }) - client.PUT(updateEntity, function (usergridResponse) { - usergridResponse.entity.should.be.an.Object().with.property('publisher').deepEqual(updateEntity.publisher) - done() + client.PUT(newEntity, function (usergridResponse) { + usergridResponse.entity.should.be.an.Object() + usergridResponse.entity.should.be.an.instanceof(UsergridEntity).with.property('uuid')//.which.is.a.uuid() + usergridResponse.entity.should.have.property('author').equal('Frank Mills') + usergridResponse.entity.created.should.equal(usergridResponse.entity.modified) + sleepFor(defaultSleepTime); + client.DELETE(usergridResponse.entity, function (delResponse) { + delResponse.entity.should.be.an.Object() + delResponse.entity.should.have.property('uuid').equal(usergridResponse.entity.uuid) + done() + }) + }) }) - }) - it('should support updating an entity by passing type and a body object', function (done) { + it('should support updating the entity by passing a UsergridEntity object', function (done) { - var options = { - type: config.test.collection, - body: { - uuid: response.entity.uuid, - updateByPassingTypeAndBody: true - } - }; - client.PUT(options, function (usergridResponse) { - usergridResponse.entity.should.be.an.Object().with.property('updateByPassingTypeAndBody').equal(true) - done() + var updateEntity = _.assign(response.entity, { + publisher: { + name: "George Newns", + date: "14 October 1892", + country: "United Kingdom" + } + }) + + client.PUT(updateEntity, function (usergridResponse) { + usergridResponse.entity.should.be.an.Object().with.property('publisher').deepEqual(updateEntity.publisher) + done() + }) }) - }) - it('should support updating an entity by passing a body object that includes type', function (done) { + it('should support updating an entity by passing type and a body object', function (done) { - var options = { - type: config.test.collection, - body: { + var options = { type: config.test.collection, - uuid: response.entity.uuid, - updateByPassingBodyIncludingType: true - } - }; - client.PUT(options, function (usergridResponse) { - usergridResponse.entity.should.be.an.Object().with.property('updateByPassingBodyIncludingType').equal(true) - done() + body: { + uuid: response.entity.uuid, + updateByPassingTypeAndBody: true + } + }; + client.PUT(options, function (usergridResponse) { + usergridResponse.entity.should.be.an.Object().with.property('updateByPassingTypeAndBody').equal(true) + done() + }) }) - }) - it('should support updating a set of entities by passing an UsergridQuery object', function (done) { + it('should support updating an entity by passing a body object that includes type', function (done) { - var query = new UsergridQuery(config.test.collection).eq('cuisine', 'pizza').limit(2) - var body = { - testUuid: uuid() - } - - client.PUT({query: query, body: body}, function (usergridResponse) { - usergridResponse.entities.should.be.an.Array().with.lengthOf(2) - usergridResponse.entities.forEach(function (entity) { - entity.should.be.an.Object().with.property('testUuid').equal(body.testUuid) - }) - var deleteQuery = new UsergridQuery(config.test.collection).eq('uuid', usergridResponse.entities[0].uuid).or.eq('uuid', usergridResponse.entities[1].uuid) - client.DELETE(deleteQuery, function (delResponse) { - delResponse.entities.should.be.an.Array().with.lengthOf(usergridResponse.entities.length) + var options = { + type: config.test.collection, + body: { + type: config.test.collection, + uuid: response.entity.uuid, + updateByPassingBodyIncludingType: true + } + }; + client.PUT(options, function (usergridResponse) { + usergridResponse.entity.should.be.an.Object().with.property('updateByPassingBodyIncludingType').equal(true) done() }) }) - }) - it('should support updating an entity by passing a preformatted PUT builder object', function (done) { + it('should support updating a set of entities by passing an UsergridQuery object', function (done) { + this.timeout(_timeout + 4000) - var options = { - uuidOrName: response.entity.uuid, - type: config.test.collection, - body: { - relatedUuid: uuid() + var query = new UsergridQuery(config.test.collection).eq('cuisine', 'pizza').limit(2) + var body = { + testUuid: uuid() } - } - client.PUT(options, function (usergridResponse) { - usergridResponse.entity.should.be.an.Object().with.property('relatedUuid').equal(options.body.relatedUuid) - done() + sleepFor(defaultSleepTime) + client.PUT(query, body, function (usergridResponse) { + usergridResponse.entities.should.be.an.Array().with.lengthOf(2) + usergridResponse.entities.forEach(function (entity) { + entity.should.be.an.Object().with.property('testUuid').equal(body.testUuid) + }) + var deleteQuery = new UsergridQuery(config.test.collection).eq('uuid', usergridResponse.entities[0].uuid).or.eq('uuid', usergridResponse.entities[1].uuid) + sleepFor(defaultSleepTime + 400); + client.DELETE(query, function (delResponse) { + delResponse.entities.should.be.an.Array().with.lengthOf(usergridResponse.entities.length) + done() + }) + }) }) - }) - }) - describe('DELETE()', function () { + it('should support updating an entity by passing a preformatted PUT builder object', function (done) { - var response - before(function (done) { - client.DELETE({type: config.test.collection, uuid: _uuid}, function () { - client.GET({type: config.test.collection, uuid: _uuid}, function (usergridResponse) { - response = usergridResponse + var options = { + uuid: response.entity.uuid, + type: config.test.collection, + body: { + relatedUuid: uuid() + } + } + + client.PUT(options, function (usergridResponse) { + usergridResponse.entity.should.be.an.Object().with.property('relatedUuid').equal(options.body.relatedUuid) done() }) }) }) - it('should not fail when a callback function is not passed', function () { - // note: this test will NOT fail gracefully inside the Mocha event chain - client.DELETE(config.test.collection, _uuid) - }) + describe('DELETE()', function () { - it('should return a 404 not found', function () { - response.statusCode.should.equal(404) - }) + var response + before(function (done) { + client.DELETE(config.test.collection, _uuid, function () { + client.GET(config.test.collection, _uuid, function (usergridResponse) { + response = usergridResponse + done() + }) + }) + }) - it('response.error.name should equal "entity_not_found"', function () { - response.error.name.should.equal((config.target === '1.0') ? 'service_resource_not_found' : 'entity_not_found') - }) + it('should not fail when a callback function is not passed', function () { + // note: this test will NOT fail gracefully inside the Mocha event chain + client.DELETE(config.test.collection, _uuid) + }) - it('should support deleting an entity by passing a UsergridEntity object', function (done) { + it('should return a 404 not found', function () { + response.statusCode.should.equal(404) + }) - var entity = new UsergridEntity({ - type: config.test.collection, - command: "CTRL+ALT+DEL" + it('response.error.name should equal "entity_not_found"', function () { + response.error.name.should.equal((config.target === '1.0') ? 'service_resource_not_found' : 'entity_not_found') }) - client.POST(entity, function (postResponse) { - postResponse.entity.should.have.property('uuid') - postResponse.entity.should.have.property('command').equal('CTRL+ALT+DEL') - client.DELETE(postResponse.entity, function (delResponse) { - delResponse.entity.should.have.property('uuid').equal(postResponse.entity.uuid) - client.GET({type: config.test.collection, uuid: postResponse.entity.uuid}, function (getResponse) { - getResponse.ok.should.be.false() - getResponse.error.name.should.equal((config.target === '1.0') ? 'service_resource_not_found' : 'entity_not_found') - done() + it('should support deleting an entity by passing a UsergridEntity object', function (done) { + this.timeout(_timeout + 4000) + var entity = new UsergridEntity({ + type: config.test.collection, + command: "CTRL+ALT+DEL" + }) + + client.POST(entity, function (postResponse) { + postResponse.entity.should.have.property('uuid') + postResponse.entity.should.have.property('command').equal('CTRL+ALT+DEL') + sleepFor(defaultSleepTime); + client.DELETE(postResponse.entity, function (delResponse) { + delResponse.entity.should.have.property('uuid').equal(postResponse.entity.uuid) + sleepFor(defaultSleepTime); + client.GET(config.test.collection, postResponse.entity.uuid, function (getResponse) { + getResponse.ok.should.be.false() + getResponse.error.name.should.equal((config.target === '1.0') ? 'service_resource_not_found' : 'entity_not_found') + done() + }) }) }) }) - }) - - it('should support deleting an entity by passing type and uuid', function (done) { - var body = { - command: "CTRL+ALT+DEL" - } + it('should support deleting an entity by passing type and uuid', function (done) { + this.timeout(_timeout + 4000) + var body = { + command: "CTRL+ALT+DEL" + } - client.POST({path: config.test.collection, body: body}, function (postResponse) { - postResponse.entity.should.have.property('uuid') - postResponse.entity.should.have.property('command').equal('CTRL+ALT+DEL') - client.DELETE({type: config.test.collection, uuid: postResponse.entity.uuid}, function (delResponse) { - delResponse.entity.should.have.property('uuid').equal(postResponse.entity.uuid) - client.GET({type: config.test.collection, uuid: postResponse.entity.uuid}, function (getResponse) { - getResponse.error.name.should.equal((config.target === '1.0') ? 'service_resource_not_found' : 'entity_not_found') - done() + client.POST(config.test.collection, body, function (postResponse) { + postResponse.entity.should.have.property('uuid') + postResponse.entity.should.have.property('command').equal('CTRL+ALT+DEL') + sleepFor(defaultSleepTime); + client.DELETE(config.test.collection, postResponse.entity.uuid, function (delResponse) { + delResponse.entity.should.have.property('uuid').equal(postResponse.entity.uuid) + sleepFor(defaultSleepTime); + client.GET(config.test.collection, postResponse.entity.uuid, function (getResponse) { + getResponse.error.name.should.equal((config.target === '1.0') ? 'service_resource_not_found' : 'entity_not_found') + done() + }) }) }) }) - }) - it('should support deleting multiple entities by passing a UsergridQuery object', function (done) { + it('should support deleting multiple entities by passing a UsergridQuery object', function (done) { + this.timeout(_timeout + 4000) - var entity = new UsergridEntity({ - type: config.test.collection, - command: "CMD" - }) - - var query = new UsergridQuery(config.test.collection).eq('command', 'CMD') + var entity = new UsergridEntity({ + type: config.test.collection, + command: "CMD" + }) - client.POST([entity, entity, entity, entity], function (postResponse) { - postResponse.entities.should.be.an.Array().with.lengthOf(4) - client.DELETE(query, function (delResponse) { - delResponse.entities.should.be.an.Array().with.lengthOf(4) - client.GET(query, function (getResponse) { - getResponse.entities.should.be.an.Array().with.lengthOf(0) - done() - }) + var query = new UsergridQuery(config.test.collection).eq('command', 'CMD') + + client.POST({ + body: [entity, entity, entity, entity], callback: function (postResponse) { + postResponse.entities.should.be.an.Array().with.lengthOf(4) + sleepFor(defaultSleepTime + 400); + client.DELETE(query, function (delResponse) { + delResponse.entities.should.be.an.Array().with.lengthOf(4) + sleepFor(defaultSleepTime); + client.GET(query, function (getResponse) { + getResponse.entities.should.be.an.Array().with.lengthOf(0) + done() + }) + }) + } }) }) - }) - it('should support deleting an entity by passing a preformatted DELETE builder object', function (done) { + it('should support deleting an entity by passing a preformatted DELETE builder object', function (done) { + this.timeout(_timeout + 4000) - var options = { - type: config.test.collection, - body: { - restaurant: "IHOP", - cuisine: "breakfast" + var options = { + type: config.test.collection, + body: { + restaurant: "IHOP", + cuisine: "breakfast" + } } - } - - client.POST(options, function (postResponse) { - postResponse.entity.should.have.property('uuid') - postResponse.entity.should.have.property('restaurant').equal('IHOP') - postResponse.entity.should.have.property('cuisine').equal('breakfast') - client.DELETE(_.assign(options, {uuid: postResponse.entity.uuid}), function (delResponse) { - delResponse.entity.should.have.property('uuid').equal(postResponse.entity.uuid) - client.GET({type: config.test.collection, uuid: postResponse.entity.uuid}, function (delResponse) { - delResponse.error.name.should.equal((config.target === '1.0') ? 'service_resource_not_found' : 'entity_not_found') - done() + + client.POST(options, function (postResponse) { + postResponse.entity.should.have.property('uuid') + postResponse.entity.should.have.property('restaurant').equal('IHOP') + postResponse.entity.should.have.property('cuisine').equal('breakfast') + sleepFor(defaultSleepTime); + client.DELETE(config.test.collection, postResponse.entity.uuid, function (delResponse) { + delResponse.entity.should.have.property('uuid').equal(postResponse.entity.uuid) + sleepFor(defaultSleepTime); + client.GET(config.test.collection, postResponse.entity.uuid, function (delResponse) { + delResponse.error.name.should.equal((config.target === '1.0') ? 'service_resource_not_found' : 'entity_not_found') + done() + }) }) }) }) diff --git a/tests/mocha/test_entity.js b/tests/mocha/test_entity.js index 964997c..75f2b94 100644 --- a/tests/mocha/test_entity.js +++ b/tests/mocha/test_entity.js @@ -1,363 +1,432 @@ -describe('UsergridEntity', function() { +configs.forEach(function(config) { - describe('putProperty()', function () { - it('should set the value for a given key if the key does not exist', function () { - var entity = new UsergridEntity('cat', 'Cosmo') - entity.putProperty('foo', ['bar']) - entity.should.have.property('foo').deepEqual(['bar']) - }) + var client = new UsergridClient(config) + + describe('UsergridEntity ' + config.target, function () { - it('should overwrite the value for a given key if the key exists', function () { - var entity = new UsergridEntity({ - type: 'cat', - name: 'Cosmo', - foo: 'baz' + describe('putProperty()', function () { + it('should set the value for a given key if the key does not exist', function () { + var entity = new UsergridEntity('cat', 'Cosmo') + entity.putProperty('foo', ['bar']) + entity.should.have.property('foo').deepEqual(['bar']) }) - entity.putProperty('foo', 'bar') - entity.should.have.property('foo').deepEqual('bar') - }) - it('should not be able to set the name key (name is immutable)', function () { - var entity = new UsergridEntity({ - type: 'cat', - name: 'Cosmo', - foo: 'baz' + it('should overwrite the value for a given key if the key exists', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: 'baz' + }) + entity.putProperty('foo', 'bar') + entity.should.have.property('foo').deepEqual('bar') }) - entity.putProperty('name', 'Bazinga') - entity.should.have.property('name').deepEqual('Cosmo') - }) - }) - describe('putProperties()', function () { - it('should set properties for a given object, overwriting properties that exist and creating those that don\'t', function () { - var entity = new UsergridEntity({ - type: 'cat', - name: 'Cosmo', - foo: 'bar' - }) - entity.putProperties({ - foo: 'baz', - qux: 'quux', - barray: [1, 2, 3, 4] - }) - entity.should.containEql({ - type: 'cat', - name: 'Cosmo', - foo: 'baz', - qux: 'quux', - barray: [1, 2, 3, 4] + it('should not be able to set the name key (name is immutable)', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: 'baz' + }); + entity.putProperty('name', 'Bazinga'); + entity.should.have.property('name').deepEqual('Cosmo'); }) }) - it('should not be able to set properties for immutable keys', function () { - var entity = new UsergridEntity({ - type: 'cat', - name: 'Cosmo', - foo: 'baz' - }) - entity.putProperties({ - name: 'Bazinga', - uuid: 'BadUuid', - bar: 'qux' + describe('putProperties()', function () { + it('should set properties for a given object, overwriting properties that exist and creating those that don\'t', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: 'bar' + }) + entity.putProperties({ + foo: 'baz', + qux: 'quux', + barray: [1, 2, 3, 4] + }) + entity.should.containEql({ + type: 'cat', + name: 'Cosmo', + foo: 'baz', + qux: 'quux', + barray: [1, 2, 3, 4] + }) }) - entity.should.containEql({ - type: 'cat', - name: 'Cosmo', - bar: 'qux', - foo: 'baz' + + it('should not be able to set properties for immutable keys', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: 'baz' + }) + entity.putProperties({ + name: 'Bazinga', + uuid: 'BadUuid', + bar: 'qux' + }) + entity.should.containEql({ + type: 'cat', + name: 'Cosmo', + bar: 'qux', + foo: 'baz' + }) }) }) - }) - describe('removeProperty()', function () { - it('should remove a given property if it exists', function () { - var entity = new UsergridEntity({ - type: 'cat', - name: 'Cosmo', - foo: 'baz' + describe('removeProperty()', function () { + it('should remove a given property if it exists', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: 'baz' + }) + entity.removeProperty('foo') + entity.should.not.have.property('foo') }) - entity.removeProperty('foo') - entity.should.not.have.property('foo') - }) - it('should fail gracefully when removing an undefined property', function () { - var entity = new UsergridEntity('cat', 'Cosmo') - entity.removeProperty('foo') - entity.should.not.have.property('foo') + it('should fail gracefully when removing an undefined property', function () { + var entity = new UsergridEntity('cat', 'Cosmo') + entity.removeProperty('foo') + entity.should.not.have.property('foo') + }) }) - }) - describe('removeProperties()', function () { - it('should remove an array of properties for a given object, failing gracefully for undefined properties', function () { - var entity = new UsergridEntity({ - type: 'cat', - name: 'Cosmo', - foo: 'bar', - baz: 'qux' - }) - entity.removeProperties(['foo', 'baz']) - entity.should.containEql({ - type: 'cat', - name: 'Cosmo' + describe('removeProperties()', function () { + it('should remove an array of properties for a given object, failing gracefully for undefined properties', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: 'bar', + baz: 'qux' + }) + entity.removeProperties(['foo', 'baz']) + entity.should.containEql({ + type: 'cat', + name: 'Cosmo' + }) }) }) - }) - describe('insert()', function () { - it('should insert a single value into an existing array at the specified index', function () { - var entity = new UsergridEntity({ - type: 'cat', - name: 'Cosmo', - foo: [1, 2, 3, 5, 6] + describe('insert()', function () { + it('should insert a single value into an existing array at the specified index', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: [1, 2, 3, 5, 6] + }) + entity.insert('foo', 4, 3) + entity.should.have.property('foo').deepEqual([1, 2, 3, 4, 5, 6]) }) - entity.insert('foo', 4, 3) - entity.should.have.property('foo').deepEqual([1, 2, 3, 4, 5, 6]) - }) - it('should merge an array of values into an existing array at the specified index', function () { - var entity = new UsergridEntity({ - type: 'cat', - name: 'Cosmo', - foo: [1, 2, 3, 7, 8] + it('should merge an array of values into an existing array at the specified index', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: [1, 2, 3, 7, 8] + }) + entity.insert('foo', [4, 5, 6], 3) + entity.should.have.property('foo').deepEqual([1, 2, 3, 4, 5, 6, 7, 8]) }) - entity.insert('foo', [4, 5, 6], 3) - entity.should.have.property('foo').deepEqual([1, 2, 3, 4, 5, 6, 7, 8]) - }) - it('should convert an existing value into an array when inserting a second value', function () { - var entity = new UsergridEntity({ - type: 'cat', - name: 'Cosmo', - foo: 'bar' + it('should convert an existing value into an array when inserting a second value', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: 'bar' + }) + entity.insert('foo', 'baz', 1) + entity.should.have.property('foo').deepEqual(['bar', 'baz']) }) - entity.insert('foo', 'baz', 1) - entity.should.have.property('foo').deepEqual(['bar', 'baz']) - }) - it('should create a new array when a property does not exist', function () { - var entity = new UsergridEntity({ - type: 'cat', - name: 'Cosmo' + it('should create a new array when a property does not exist', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo' + }) + entity.insert('foo', 'bar', 1000) + entity.should.have.property('foo').deepEqual(['bar']) }) - entity.insert('foo', 'bar', 1000) - entity.should.have.property('foo').deepEqual(['bar']) - }) - it('should gracefully handle indexes out of range', function () { - var entity = new UsergridEntity({ - type: 'cat', - name: 'Cosmo', - foo: ['bar'] + it('should gracefully handle indexes out of range', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: ['bar'] + }) + entity.insert('foo', 'baz', 1000) + entity.should.have.property('foo').deepEqual(['bar', 'baz']) + entity.insert('foo', 'qux', -1000) + entity.should.have.property('foo').deepEqual(['qux', 'bar', 'baz']) }) - entity.insert('foo', 'baz', 1000) - entity.should.have.property('foo').deepEqual(['bar', 'baz']) - entity.insert('foo', 'qux', -1000) - entity.should.have.property('foo').deepEqual(['qux', 'bar', 'baz']) }) - }) - describe('append()', function () { - it('should append a value to the end of an existing array', function () { - var entity = new UsergridEntity({ - type: 'cat', - name: 'Cosmo', - foo: [1, 2, 3] + describe('append()', function () { + it('should append a value to the end of an existing array', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: [1, 2, 3] + }) + entity.append('foo', 4) + entity.should.have.property('foo').deepEqual([1, 2, 3, 4]) }) - entity.append('foo', 4) - entity.should.have.property('foo').deepEqual([1, 2, 3, 4]) - }) - it('should create a new array if a property does not exist', function () { - var entity = new UsergridEntity({ - type: 'cat', - name: 'Cosmo' + it('should create a new array if a property does not exist', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo' + }) + entity.append('foo', 'bar') + entity.should.have.property('foo').deepEqual(['bar']) }) - entity.append('foo', 'bar') - entity.should.have.property('foo').deepEqual(['bar']) }) - }) - describe('prepend()', function () { - it('should prepend a value to the beginning of an existing array', function () { - var entity = new UsergridEntity({ - type: 'cat', - name: 'Cosmo', - foo: [1, 2, 3] + describe('prepend()', function () { + it('should prepend a value to the beginning of an existing array', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: [1, 2, 3] + }) + entity.prepend('foo', 0) + entity.should.have.property('foo').deepEqual([0, 1, 2, 3]) }) - entity.prepend('foo', 0) - entity.should.have.property('foo').deepEqual([0, 1, 2, 3]) - }) - it('should create a new array if a property does not exist', function () { - var entity = new UsergridEntity({ - type: 'cat', - name: 'Cosmo' + it('should create a new array if a property does not exist', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo' + }) + entity.prepend('foo', 'bar') + entity.should.have.property('foo').deepEqual(['bar']) }) - entity.prepend('foo', 'bar') - entity.should.have.property('foo').deepEqual(['bar']) }) - }) - describe('pop()', function () { - it('should remove the last value of an existing array', function () { - var entity = new UsergridEntity({ - type: 'cat', - name: 'Cosmo', - foo: [1, 2, 3] + describe('pop()', function () { + it('should remove the last value of an existing array', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: [1, 2, 3] + }) + entity.pop('foo') + entity.should.have.property('foo').deepEqual([1, 2]) }) - entity.pop('foo') - entity.should.have.property('foo').deepEqual([1, 2]) - }) - it('value should remain unchanged if it is not an array', function () { - var entity = new UsergridEntity({ - type: 'cat', - name: 'Cosmo', - foo: 'bar' + it('value should remain unchanged if it is not an array', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: 'bar' + }) + entity.pop('foo') + entity.should.have.property('foo').deepEqual('bar') }) - entity.pop('foo') - entity.should.have.property('foo').deepEqual('bar') - }) - it('should gracefully handle empty arrays', function () { - var entity = new UsergridEntity({ - type: 'cat', - name: 'Cosmo', - foo: [] + it('should gracefully handle empty arrays', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: [] + }) + entity.pop('foo') + entity.should.have.property('foo').deepEqual([]) }) - entity.pop('foo') - entity.should.have.property('foo').deepEqual([]) }) - }) - describe('shift()', function () { - it('should remove the first value of an existing array', function () { - var entity = new UsergridEntity({ - type: 'cat', - name: 'Cosmo', - foo: [1, 2, 3] + describe('shift()', function () { + it('should remove the first value of an existing array', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: [1, 2, 3] + }) + entity.shift('foo') + entity.should.have.property('foo').deepEqual([2, 3]) }) - entity.shift('foo') - entity.should.have.property('foo').deepEqual([2, 3]) - }) - it('value should remain unchanged if it is not an array', function () { - var entity = new UsergridEntity({ - type: 'cat', - name: 'Cosmo', - foo: 'bar' + it('value should remain unchanged if it is not an array', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: 'bar' + }) + entity.shift('foo') + entity.should.have.property('foo').deepEqual('bar') }) - entity.shift('foo') - entity.should.have.property('foo').deepEqual('bar') - }) - it('should gracefully handle empty arrays', function () { - var entity = new UsergridEntity({ - type: 'cat', - name: 'Cosmo', - foo: [] + it('should gracefully handle empty arrays', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: [] + }) + entity.shift('foo') + entity.should.have.property('foo').deepEqual([]) }) - entity.shift('foo') - entity.should.have.property('foo').deepEqual([]) }) - }) - var now = Date.now() - var entity = new UsergridEntity({type: config.test.collection, name: 'Cosmo'}) + var now = Date.now() + var entity = new UsergridEntity({type: config.test.collection, name: 'Cosmo'}) - describe('save()', function() { - it('should POST an entity without a uuid', function(done) { - entity.save(client, function(response){ - response.entity.should.have.property('uuid') - done() + describe('save()', function () { + + it('should POST an entity without a uuid', function (done) { + entity.save(client, function (response) { + response.entity.should.have.property('uuid') + done() + }) + }) + it('should PUT an entity without a uuid', function (done) { + entity.putProperty('saveTest', now) + entity.save(client, function (response) { + response.entity.should.have.property('saveTest').equal(now) + done() + }) }) }) - it('should PUT an entity without a uuid', function(done) { - entity.putProperty('saveTest',now) - entity.save(client, function(response){ - response.entity.should.have.property('saveTest').equal(now) - done() + + describe('reload()', function () { + + it('should refresh an entity with the latest server copy of itself', function (done) { + var modified = entity.modified + entity.putProperty('reloadTest', now) + client.PUT(entity, function (putResponse) { + entity.modified.should.equal(modified) + entity.reload(client, function (reloadResponse) { + entity.reloadTest.should.equal(now) + entity.modified.should.not.equal(modified) + done() + }) + }) }) }) - }) - describe('reload()', function() { - it('should refresh an entity with the latest server copy of itself', function(done) { - var modified = entity.modified - entity.putProperty('reloadTest', now) - client.PUT(entity, function(putResponse) { - entity.modified.should.equal(modified) - entity.reload(client, function(reloadResponse) { - entity.reloadTest.should.equal(now) - entity.modified.should.not.equal(modified) + describe('remove()', function () { + + it('should remove an entity from the server', function (done) { + entity.remove(client, function (deleteResponse) { + deleteResponse.ok.should.be.true() + // best practice is to destroy the 'entity' instance here, because it no longer exists on the server + entity = null done() }) }) }) - }) - describe('remove()', function() { + describe('connect()', function () { - it('should remove an entity from the server', function(done) { - entity.remove(client, function(deleteResponse) { - deleteResponse.ok.should.be.true() - // best practice is to destroy the 'entity' instance here, because it no longer exists on the server - entity = null - done() + var response, + entity1, + entity2 + + before(function (done) { + // Create the entities we're going to use for connections + client.POST({ + type: config.test.collection, body: [{ + "name": "testEntityConnectOne" + }, { + "name": "testEntityConnectTwo" + }], callback: function (postResponse) { + response = postResponse + entity1 = response.first + entity2 = response.last + done() + } + }) }) - }) - }) - describe('connect()', function() { - - var response, - entity1, - entity2, - query = new UsergridQuery(config.test.collection).eq('name', 'testEntityConnectOne').or.eq('name', 'testEntityConnectTwo').asc('name') - - before(function(done) { - // Create the entities we're going to use for connections - client.POST({type:config.test.collection, body:[{ - "name": "testEntityConnectOne" - }, { - "name": "testEntityConnectTwo" - }]}, function() { - client.GET(query, function(usergridResponse) { - response = usergridResponse - entity1 = response.first - entity2 = response.last - done() + it('should connect entities by passing a target UsergridEntity object as a parameter', function (done) { + var relationship = "foos" + entity1.connect(client, relationship, entity2, function (usergridResponse) { + sleepFor(defaultSleepTime) + usergridResponse.ok.should.be.true() + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { + usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( + "", + config.test.collection, + entity1.uuid, + relationship, + entity2.uuid, + "connecting", + relationship + )) + done() + }) }) }) + + it('should connect entities by passing target uuid as a parameter', function (done) { + var relationship = "bars" + + entity1.connect(client, relationship, entity2.uuid, function (usergridResponse) { + usergridResponse.ok.should.be.true() + sleepFor(defaultSleepTime) + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { + usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( + "", + config.test.collection, + entity1.uuid, + relationship, + entity2.uuid, + "connecting", + relationship + )) + done() + }) + }) + }) + + it('should connect entities by passing target type and name as parameters', function (done) { + var relationship = "bazzes" + + entity1.connect(client, relationship, entity2.type, entity2.name, function (usergridResponse) { + usergridResponse.ok.should.be.true() + sleepFor(defaultSleepTime) + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { + usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( + "", + config.test.collection, + entity1.uuid, + relationship, + entity2.uuid, + "connecting", + relationship + )) + done() + }) + }) + }) + + it('should fail to connect entities when specifying target name without type', function () { + should(function () { + entity1.connect("fails", 'badName', function () { + }) + }).throw() + }) }) - it('should connect entities by passing a target UsergridEntity object as a parameter', function(done) { - var relationship = "foos" + describe('getConnections()', function () { - entity1.connect(client, relationship, entity2, function(usergridResponse) { - usergridResponse.ok.should.be.true() - client.getConnections(UsergridDirection.OUT, entity1, relationship, function(usergridResponse) { - usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( - "", - config.test.collection, - entity1.uuid, - relationship, - entity2.uuid, - "connecting", - relationship - )) + var response, + query = new UsergridQuery(config.test.collection).eq('name', 'testEntityConnectOne').or.eq('name', 'testEntityConnectTwo').asc('name') + + before(function (done) { + sleepFor(defaultSleepTime + 200) + client.GET(query, function (usergridResponse) { + response = usergridResponse done() }) }) - }) - it('should connect entities by passing target uuid as a parameter', function(done) { - var relationship = "bars" + it('should get an entity\'s outbound connections', function (done) { + var entity1 = response.first + var entity2 = response.last - entity1.connect(client, relationship, entity2.uuid, function(usergridResponse) { - usergridResponse.ok.should.be.true() - client.getConnections(UsergridDirection.OUT, entity1, relationship, function(usergridResponse) { + var relationship = "foos" + + entity1.getConnections(client, UsergridDirection.OUT, relationship, function (usergridResponse) { usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( "", config.test.collection, @@ -370,21 +439,20 @@ describe('UsergridEntity', function() { done() }) }) - }) - it('should connect entities by passing target type and name as parameters', function(done) { - var relationship = "bazzes" + it('should get an entity\'s inbound connections', function (done) { + var entity1 = response.first + var entity2 = response.last - entity1.connect(client, relationship, entity2.type, entity2.name, function(usergridResponse) { - usergridResponse.ok.should.be.true() - client.getConnections(UsergridDirection.OUT, entity1, relationship, function(usergridResponse) { - usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( + var relationship = "foos" + + entity2.getConnections(client, UsergridDirection.IN, relationship, function (usergridResponse) { + usergridResponse.first.metadata.connections[relationship].should.equal(UsergridHelpers.urljoin( "", config.test.collection, - entity1.uuid, - relationship, entity2.uuid, "connecting", + entity1.uuid, relationship )) done() @@ -392,184 +460,130 @@ describe('UsergridEntity', function() { }) }) - it('should fail to connect entities when specifying target name without type', function() { - should(function() { - entity1.connect("fails", 'badName', function() {}) - }).throw() - }) - }) - - describe('getConnections()', function() { + describe('disconnect()', function () { - var response, - query = new UsergridQuery(config.test.collection).eq('name', 'testEntityConnectOne').or.eq('name', 'testEntityConnectTwo').asc('name') + var response, + entity1, + entity2, + query = new UsergridQuery(config.test.collection).eq('name', 'testEntityConnectOne').or.eq('name', 'testEntityConnectTwo').asc('name') - before(function(done) { - client.GET(query, function(usergridResponse) { - response = usergridResponse - done() - }) - }) - - it('should get an entity\'s outbound connections', function(done) { - var entity1 = response.first - var entity2 = response.last - - var relationship = "foos" - - entity1.getConnections(client, UsergridDirection.OUT, relationship, function(usergridResponse) { - usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( - "", - config.test.collection, - entity1.uuid, - relationship, - entity2.uuid, - "connecting", - relationship - )) - done() + before(function (done) { + client.GET(query, function (usergridResponse) { + response = usergridResponse + entity1 = response.first + entity2 = response.last + done() + }) }) - }) - - it('should get an entity\'s inbound connections', function(done) { - var entity1 = response.first - var entity2 = response.last - - var relationship = "foos" - - entity2.getConnections(client, UsergridDirection.IN, relationship, function(usergridResponse) { - usergridResponse.first.metadata.connections[relationship].should.equal(UsergridHelpers.urljoin( - "", - config.test.collection, - entity2.uuid, - "connecting", - entity1.uuid, - relationship - )) - done() + after(function (done) { + var deleteQuery = new UsergridQuery(config.test.collection).eq('uuid', entity1.uuid).or.eq('uuid', entity2.uuid) + client.DELETE(deleteQuery, function (delResponse) { + delResponse.entities.should.be.an.Array().with.lengthOf(2) + done() + }) }) - }) - }) - - describe('disconnect()', function() { - - var response, - entity1, - entity2, - query = new UsergridQuery(config.test.collection).eq('name', 'testEntityConnectOne').or.eq('name', 'testEntityConnectTwo').asc('name') - before(function(done) { - client.GET(query, function(usergridResponse) { - response = usergridResponse - entity1 = response.first - entity2 = response.last - done() - }) - }) - after(function(done) { - var deleteQuery = new UsergridQuery(config.test.collection).eq('uuid', entity1.uuid).or.eq('uuid', entity2.uuid) - client.DELETE(deleteQuery, function (delResponse) { - delResponse.entities.should.be.an.Array().with.lengthOf(2) - done() + it('should disconnect entities by passing a target UsergridEntity object as a parameter', function (done) { + var relationship = "foos" + entity1.disconnect(client, relationship, entity2, function (usergridResponse) { + usergridResponse.ok.should.be.true() + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { + usergridResponse.entities.should.be.an.Array().with.lengthOf(0) + done() + }) + }) }) - }) - it('should disconnect entities by passing a target UsergridEntity object as a parameter', function(done) { - var relationship = "foos" - entity1.disconnect(client, relationship, entity2, function(usergridResponse) { - usergridResponse.ok.should.be.true() - client.getConnections(UsergridDirection.OUT, entity1, relationship, function(usergridResponse) { - usergridResponse.entities.should.be.an.Array().with.lengthOf(0) - done() + it('should disconnect entities by passing target uuid as a parameter', function (done) { + var relationship = "bars" + entity1.disconnect(client, relationship, entity2.uuid, function (usergridResponse) { + usergridResponse.ok.should.be.true() + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { + usergridResponse.entities.should.be.an.Array().with.lengthOf(0) + done() + }) }) }) - }) - it('should disconnect entities by passing target uuid as a parameter', function(done) { - var relationship = "bars" - entity1.disconnect(client, relationship, entity2.uuid, function(usergridResponse) { - usergridResponse.ok.should.be.true() - client.getConnections(UsergridDirection.OUT, entity1, relationship, function(usergridResponse) { - usergridResponse.entities.should.be.an.Array().with.lengthOf(0) - done() + it('should disconnect entities by passing target type and name as parameters', function (done) { + var relationship = "bazzes" + entity1.disconnect(client, relationship, entity2.type, entity2.name, function (usergridResponse) { + usergridResponse.ok.should.be.true() + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { + usergridResponse.entities.should.be.an.Array().with.lengthOf(0) + done() + }) }) }) - }) - it('should disconnect entities by passing target type and name as parameters', function(done) { - var relationship = "bazzes" - entity1.disconnect(client, relationship, entity2.type, entity2.name, function(usergridResponse) { - usergridResponse.ok.should.be.true() - client.getConnections(UsergridDirection.OUT, entity1, relationship, function(usergridResponse) { - usergridResponse.entities.should.be.an.Array().with.lengthOf(0) - done() - }) + it('should fail to disconnect entities when specifying target name without type', function () { + should(function () { + entity1.disconnect("fails", entity2.name, function () { + }) + }).throw() }) }) - it('should fail to disconnect entities when specifying target name without type', function() { - should(function() { - entity1.disconnect("fails", entity2.name, function() {}) - }).throw() - }) - }) + var assetEntity = new UsergridEntity({type: config.test.collection, name: "attachAssetTest"}) - var assetEntity = new UsergridEntity({type: config.test.collection, name: "attachAssetTest"}) + describe('attachAsset() and uploadAsset()', function (done) { - describe('attachAsset() and uploadAsset()', function(done) { + var asset - var asset + before(function (done) { + assetEntity.save(client, function (response) { + response.ok.should.be.true() + assetEntity.should.have.property('uuid') + done() + }) + }) - before(function (done) { - assetEntity.save(client, function(response){ - response.ok.should.be.true() - assetEntity.should.have.property('uuid') + before(function (done) { + var req = new XMLHttpRequest(); + req.open('GET', testFile.uri, true); + req.responseType = 'blob'; + req.onload = function () { + asset = new UsergridAsset(req.response) + done(); + } + req.onerror = function (err) { + console.error(err); + done(); + }; + req.send(null); + }); + + it('should attach a UsergridAsset to the entity', function (done) { + assetEntity.attachAsset(asset) + assetEntity.should.have.property('asset').equal(asset) done() }) - }) - before(function (done) { - var req = new XMLHttpRequest(); - req.open('GET', testFile.uri, true); - req.responseType = 'blob'; - req.onload = function () { - asset = new UsergridAsset(req.response) - done(); - } - req.onerror = function (err) { - console.error(err); - done(); - }; - req.send(null); - }); - - it('should attach a UsergridAsset to the entity', function(done) { - assetEntity.attachAsset(asset) - assetEntity.should.have.property('asset').equal(asset) - done() - }) - - it('should upload an image asset to the remote entity', function(done) { - assetEntity.uploadAsset(client, function(asset, usergridResponse, entity) { - entity.should.have.property('file-metadata') - entity['file-metadata'].should.have.property('content-type').equal(testFile.contentType) - entity['file-metadata'].should.have.property('content-length').equal(testFile.contentLength) - done() + it('should upload an image asset to the remote entity', function (done) { + assetEntity.uploadAsset(client, function (asset, usergridResponse, entity) { + entity.should.have.property('file-metadata') + entity['file-metadata'].should.have.property('content-type').equal(testFile.contentType) + entity['file-metadata'].should.have.property('content-length').equal(testFile.contentLength) + done() + }) }) }) - }) - describe('downloadAsset()', function(done) { + describe('downloadAsset()', function (done) { - it('should download a an image from the remote entity', function(done) { - assetEntity.downloadAsset(client, function(asset, usergridResponse, entityWithAsset) { - entityWithAsset.should.have.property('asset').which.is.an.instanceof(UsergridAsset) - entityWithAsset.asset.should.have.property('contentType').equal(assetEntity['file-metadata']['content-type']) - entityWithAsset.asset.should.have.property('contentLength').equal(assetEntity['file-metadata']['content-length']) - // clean up the now un-needed asset entity - entityWithAsset.remove(client) + after(function (done) { + assetEntity.remove(client) done() }) + + it('should download a an image from the remote entity', function (done) { + assetEntity.downloadAsset(client, function (asset, usergridResponse, entityWithAsset) { + entityWithAsset.should.have.property('asset').which.is.an.instanceof(UsergridAsset) + entityWithAsset.asset.should.have.property('contentType').equal(assetEntity['file-metadata']['content-type']) + entityWithAsset.asset.should.have.property('contentLength').equal(assetEntity['file-metadata']['content-length']) + done() + }) + }) }) }) }) \ No newline at end of file diff --git a/tests/mocha/test_helpers.js b/tests/mocha/test_helpers.js index 554e7b0..0f55fec 100644 --- a/tests/mocha/test_helpers.js +++ b/tests/mocha/test_helpers.js @@ -1,18 +1,39 @@ -var config = { - "orgId": "rwalsh", - "appId": "jssdktestapp", - "clientId": "YXA6KPq8cIsPEea0i-W5Jx8cgw", - "clientSecret": "YXA6WaT7qsxh_eRS3ryBresi-HwoQAQ", - "target":"1.0", - "test": { - "collection":"nodejs", - "email": "authtest@test.com", - "password": "P@ssw0rd", - "username": "authtest" +var targetedConfigs = { + "1.0": { + "orgId": "rwalsh", + "appId": "jssdktestapp", + "baseUrl": UsergridClientDefaultOptions.baseUrl, + "clientId": "YXA6KPq8cIsPEea0i-W5Jx8cgw", + "clientSecret": "YXA6WaT7qsxh_eRS3ryBresi-HwoQAQ", + "target": "1.0", + "test": { + "collection": "nodejs", + "email": "authtest@test.com", + "password": "P@ssw0rd", + "username": "authtest" + } + }, + "2.1": { + "orgId": "api-connectors", + "appId": "sdksandbox", + "baseUrl": "https://api-connectors-prod.apigee.net/appservices", + "clientId": "YXA6WMhAuFJTEeWoggrRE9kXrQ", + "clientSecret": "YXA6zZbat7PKgOlN73rpByc36LWaUhw", + "target": "2.1", + "test": { + "collection": "nodejs", + "email": "authtest@test.com", + "password": "P@ssw0rd", + "username": "authtest" + } } + }; -var client = Usergrid.initSharedInstance({orgId: config.orgId, appId: config.appId}); + +var configs = [] +configs.push(_.get(targetedConfigs,'1.0')) +// configs.push(_.get(targetedConfigs,'2.1')) var testFile = { uri:'https://raw.githubusercontent.com/apache/usergrid-javascript/master/tests/resources/images/apigee.png', @@ -20,6 +41,21 @@ var testFile = { contentType: 'image/png' }; +var _slow = 3000, _timeout = 4000, defaultSleepTime = 200; + +function sleepFor( sleepDuration ){ + if( defaultSleepTime > 0 ) { + var now = new Date().getTime(); + while(new Date().getTime() < now + sleepDuration){ /* do nothing */ } + } +} + +beforeEach(function(done) { + this.slow(_slow); + this.timeout(_timeout); + done(); +}); + function randomWord() { var text = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; diff --git a/tests/mocha/test_response.js b/tests/mocha/test_response.js index 9fe2ae3..bd78602 100644 --- a/tests/mocha/test_response.js +++ b/tests/mocha/test_response.js @@ -1,169 +1,176 @@ 'use strict' -describe('UsergridResponse', function() { +configs.forEach(function(config) { - var _response, entitiesArray = [] + var client = new UsergridClient(config) - before(function (done){ - var entity = new UsergridEntity({ - type: config.test.collection, - info: 'responseTestEntity' + describe('UsergridResponse ' + config.target, function () { + + var _response, entitiesArray = [] + + before(function (done) { + var entity = new UsergridEntity({ + type: config.test.collection, + info: 'responseTestEntity' + }) + for (var i = 0; i < 20; i++) { + entitiesArray.push(entity) + } + client.POST({ + body: entitiesArray, callback: function (postResponse) { + postResponse.entities.should.be.an.Array().with.lengthOf(entitiesArray.length) + entitiesArray = postResponse.entities + done() + } + }) }) - for( var i = 0; i < 20; i++ ) { - entitiesArray.push(entity) - } - client.POST(entitiesArray, function (postResponse) { - postResponse.entities.should.be.an.Array().with.lengthOf(entitiesArray.length) - entitiesArray = postResponse.entities - done() + + before(function (done) { + client.GET(config.test.collection, function (usergridResponse) { + _response = usergridResponse + done() + }) }) - }) - before(function (done) { - client.GET({type:config.test.collection}, function (usergridResponse) { - _response = usergridResponse + after(function (done) { + client.DELETE(new UsergridQuery(config.test.collection).eq('info', 'responseTestEntity').limit(entitiesArray.length)) done() }) - }) - - after(function(done) { - client.DELETE(new UsergridQuery(config.test.collection).eq('info','responseTestEntity').limit(entitiesArray.length)) - done() - }) - describe('headers', function () { - it('should be an object', function () { - _response.headers.should.be.an.Object().with.property('Content-Type') + describe('headers', function () { + it('should be an object', function () { + _response.headers.should.be.an.Object().with.property('content-type') + }) }) - }) - describe('statusCode', function () { - it('should be a number', function () { - _response.statusCode.should.be.a.Number() + describe('statusCode', function () { + it('should be a number', function () { + _response.statusCode.should.be.a.Number() + }) }) - }) - describe('ok', function () { - it('should be a bool', function () { - _response.ok.should.be.a.Boolean() + describe('ok', function () { + it('should be a bool', function () { + _response.ok.should.be.a.Boolean() + }) }) - }) - describe('responseJSON', function () { - it('should be a read-only object', function () { - _response.responseJSON.should.be.an.Object().with.any.properties(['action', 'application', 'path', 'uri', 'timestamp', 'duration']) - Object.isFrozen(_response.responseJSON).should.be.true() - should(function () { - _response.responseJSON.uri = 'TEST' - }).throw() + describe('responseJSON', function () { + it('should be a read-only object', function () { + _response.responseJSON.should.be.an.Object().with.any.properties(['action', 'application', 'path', 'uri', 'timestamp', 'duration']) + Object.isFrozen(_response.responseJSON).should.be.true() + should(function () { + _response.responseJSON.uri = 'TEST' + }).throw() + }) }) - }) - describe('error', function () { - it('should be a UsergridResponseError object', function (done) { - client.GET({type:config.test.collection, uuid:'BADNAMEORUUID'}, function (usergridResponse) { - usergridResponse.error.should.be.an.instanceof(UsergridResponseError) - done() + describe('error', function () { + it('should be a UsergridResponseError object', function (done) { + client.GET(config.test.collection, 'BADNAMEORUUID', function (usergridResponse) { + usergridResponse.error.should.be.an.instanceof(UsergridResponseError) + done() + }) }) }) - }) - describe('users', function () { - it('response.users should be an array of UsergridUser objects', function (done) { - client.setAppAuth(config.clientId, config.clientSecret, config.tokenTtl) - client.authenticateApp(function (response) { - should(response.error).be.undefined() - client.GET({type:'users'}, function (usergridResponse) { - usergridResponse.ok.should.be.true() - usergridResponse.users.should.be.an.Array() - usergridResponse.users.forEach(function (user) { - user.should.be.an.instanceof(UsergridUser) + describe('users', function () { + it('response.users should be an array of UsergridUser objects', function (done) { + client.setAppAuth(config.clientId, config.clientSecret, config.tokenTtl) + client.authenticateApp(function (response) { + should(response.error).be.undefined() + client.GET('users', function (usergridResponse) { + usergridResponse.ok.should.be.true() + usergridResponse.users.should.be.an.Array() + usergridResponse.users.forEach(function (user) { + user.should.be.an.instanceof(UsergridUser) + }) + done() }) - done() }) }) }) - }) - describe('user', function () { - var user + describe('user', function () { + var user - it('response.user should be a UsergridUser object and have a valid uuid matching the first object in response.users', function (done) { - client.setAppAuth(config.clientId, config.clientSecret, config.tokenTtl) - client.authenticateApp(function (response) { - should(response.error).be.undefined() - client.GET('users', function (usergridResponse) { - user = usergridResponse.user - user.should.be.an.instanceof(UsergridUser).with.property('uuid').equal(_.first(usergridResponse.entities).uuid) - done() + it('response.user should be a UsergridUser object and have a valid uuid matching the first object in response.users', function (done) { + client.setAppAuth(config.clientId, config.clientSecret, config.tokenTtl) + client.authenticateApp(function (response) { + should(response.error).be.undefined() + client.GET('users', function (usergridResponse) { + user = usergridResponse.user + user.should.be.an.instanceof(UsergridUser).with.property('uuid').equal(_.first(usergridResponse.entities).uuid) + done() + }) }) }) - }) - it('response.user should be a subclass of UsergridEntity', function (done) { - user.isUser.should.be.true() - user.should.be.an.instanceof(UsergridEntity) - done() + it('response.user should be a subclass of UsergridEntity', function (done) { + user.isUser.should.be.true() + user.should.be.an.instanceof(UsergridEntity) + done() + }) }) - }) - describe('entities', function () { - it('should be an array of UsergridEntity objects', function () { - _response.entities.should.be.an.Array() - _response.entities.forEach(function (entity) { - entity.should.be.an.instanceof(UsergridEntity) + describe('entities', function () { + it('should be an array of UsergridEntity objects', function () { + _response.entities.should.be.an.Array() + _response.entities.forEach(function (entity) { + entity.should.be.an.instanceof(UsergridEntity) + }) }) }) - }) - describe('first, entity', function () { - it('response.first should be a UsergridEntity object and have a valid uuid matching the first object in response.entities', function () { - _response.first.should.be.an.instanceof(UsergridEntity).with.property('uuid').equal(_.first(_response.entities).uuid) - }) + describe('first, entity', function () { + it('response.first should be a UsergridEntity object and have a valid uuid matching the first object in response.entities', function () { + _response.first.should.be.an.instanceof(UsergridEntity).with.property('uuid').equal(_.first(_response.entities).uuid) + }) - it('response.entity should be a reference to response.first', function () { - _response.should.have.property('entity').deepEqual(_response.first) + it('response.entity should be a reference to response.first', function () { + _response.should.have.property('entity').deepEqual(_response.first) + }) }) - }) - describe('last', function () { - it('last should be a UsergridEntity object and have a valid uuid matching the last object in response.entities', function () { - _response.last.should.be.an.instanceof(UsergridEntity).with.property('uuid').equal(_.last(_response.entities).uuid) + describe('last', function () { + it('last should be a UsergridEntity object and have a valid uuid matching the last object in response.entities', function () { + _response.last.should.be.an.instanceof(UsergridEntity).with.property('uuid').equal(_.last(_response.entities).uuid) + }) }) - }) - describe('hasNextPage', function () { - it('should be true when more entities exist', function (done) { - client.GET({type:config.test.collection}, function (usergridResponse) { - usergridResponse.hasNextPage.should.be.true() - done() + describe('hasNextPage', function () { + it('should be true when more entities exist', function (done) { + client.GET({type: config.test.collection}, function (usergridResponse) { + usergridResponse.hasNextPage.should.be.true() + done() + }) }) - }) - it('should be false when no more entities exist', function (done) { - client.GET({type:'users'}, function (usergridResponse) { - usergridResponse.responseJSON.count.should.be.lessThan(10) - usergridResponse.hasNextPage.should.not.be.true() - done() + it('should be false when no more entities exist', function (done) { + client.GET({type: 'users'}, function (usergridResponse) { + usergridResponse.responseJSON.count.should.be.lessThan(10) + usergridResponse.hasNextPage.should.not.be.true() + done() + }) }) }) - }) - describe('loadNextPage()', function () { - var firstResponse + describe('loadNextPage()', function () { + var firstResponse - before(function (done) { - client.GET({type:config.test.collection}, function (usergridResponse) { - firstResponse = usergridResponse - done() + before(function (done) { + client.GET({type: config.test.collection}, function (usergridResponse) { + firstResponse = usergridResponse + done() + }) }) - }) - it('should load a new page of entities by passing an instance of UsergridClient', function (done) { - firstResponse.loadNextPage(client, function (usergridResponse) { - usergridResponse.first.uuid.should.not.equal(firstResponse.first.uuid) - usergridResponse.entities.length.should.equal(10) - done() + it('should load a new page of entities by passing an instance of UsergridClient', function (done) { + firstResponse.loadNextPage(client, function (usergridResponse) { + usergridResponse.first.uuid.should.not.equal(firstResponse.first.uuid) + usergridResponse.entities.length.should.equal(10) + done() + }) }) }) }) diff --git a/tests/mocha/test_response_error.js b/tests/mocha/test_response_error.js index eb02631..f0456bd 100644 --- a/tests/mocha/test_response_error.js +++ b/tests/mocha/test_response_error.js @@ -1,34 +1,38 @@ 'use strict' -describe('UsergridResponseError', function() { +configs.forEach(function(config) { - var _response + var client = new UsergridClient(config) - describe('name, description, exception', function () { + describe('UsergridResponseError ' + config.target, function () { + var _response - before(function (done) { - client.GET({type:config.test.collection, uuid:'BADNAMEORUUID'}, function (usergridResponse) { - _response = usergridResponse - done() + describe('name, description, exception', function () { + + before(function (done) { + client.GET(config.test.collection, 'BADNAMEORUUID', function (usergridResponse) { + _response = usergridResponse + done() + }) }) - }) - it('response.statusCode should be greater than or equal to 400', function () { - _response.ok.should.be.false() - }) + it('response.statusCode should be greater than or equal to 400', function () { + _response.ok.should.be.false() + }) - it('response.error should be a UsergridResponseError object with name, description, and exception keys', function () { - _response.ok.should.be.false() - _response.error.should.be.an.instanceof(UsergridResponseError).with.properties(['name', 'description', 'exception']) + it('response.error should be a UsergridResponseError object with name, description, and exception keys', function () { + _response.ok.should.be.false() + _response.error.should.be.an.instanceof(UsergridResponseError).with.properties(['name', 'description', 'exception']) + }) }) - }) - describe('undefined check', function () { - it('response.error should be undefined on a successful response', function (done) { - client.GET({type:config.test.collection}, function (usergridResponse) { - usergridResponse.ok.should.be.true() - should(usergridResponse.error).be.undefined() - done() + describe('undefined check', function () { + it('response.error should be undefined on a successful response', function (done) { + client.GET(config.test.collection, function (usergridResponse) { + usergridResponse.ok.should.be.true() + should(usergridResponse.error).be.undefined() + done() + }) }) }) }) diff --git a/tests/mocha/test_user.js b/tests/mocha/test_user.js index bdc6bcf..1e5e2cd 100644 --- a/tests/mocha/test_user.js +++ b/tests/mocha/test_user.js @@ -1,246 +1,251 @@ 'use strict' -describe('UsergridUser', function() { +configs.forEach(function(config) { - var _username1 = randomWord(), - _user1 = new UsergridUser({ - username: _username1, - password: config.test.password - }) + var client = new UsergridClient(config) + describe('UsergridUser ' + config.target, function () { - before(function (done) { - var query = new UsergridQuery('users').not.eq('username', config.test.username).limit(20) - // clean up old user entities as the UsergridResponse tests rely on this collection containing less than 10 entities - client.DELETE(query, function () { - _user1.create(client, function (err, usergridResponse, user) { - done() + var _username1 = randomWord(), + _user1 = new UsergridUser({ + username: _username1, + password: config.test.password }) - }) - }) - describe('create()', function () { - it("should create a new user with the username " + _username1, function () { - _user1.username.should.equal(_username1) - }) - - it('should have a valid uuid', function () { - _user1.should.have.property('uuid')//.which.is.a.uuid() + before(function (done) { + var query = new UsergridQuery('users').not.eq('username', config.test.username).limit(20) + // clean up old user entities as the UsergridResponse tests rely on this collection containing less than 10 entities + client.DELETE(query, function () { + _user1.create(client, function (err, usergridResponse, user) { + done() + }) + }) }) - it('should have a created date', function () { - _user1.should.have.property('created') - }) + describe('create()', function () { - it('should be activated (i.e. has a valid password)', function () { - _user1.should.have.property('activated').true() - }) + it("should create a new user with the username " + _username1, function () { + _user1.username.should.equal(_username1) + }) - it('should not have a password property', function () { - _user1.should.not.have.property('password') - }) + it('should have a valid uuid', function () { + _user1.should.have.property('uuid')//.which.is.a.uuid() + }) - it('should fail gracefully when a username already exists', function (done) { - var user = new UsergridUser({ - username: _username1, - password: config.test.password + it('should have a created date', function () { + _user1.should.have.property('created') }) - user.create(client, function (usergridResponse) { - usergridResponse.error.should.not.be.null() - usergridResponse.error.should.containDeep({ - name: 'duplicate_unique_property_exists' - }) - usergridResponse.ok.should.be.false() - done() + + it('should be activated (i.e. has a valid password)', function () { + _user1.should.have.property('activated').true() }) - }) - it('should create a new user on the server', function (done) { - var username = randomWord() - var user = new UsergridUser({ - username: username, - password: config.test.password + it('should not have a password property', function () { + _user1.should.not.have.property('password') }) - user.create(client, function (usergridResponse) { - user.username.should.equal(username) - user.should.have.property('uuid')//.which.is.a.uuid() - user.should.have.property('created') - user.should.have.property('activated').true() - user.should.not.have.property('password') - // cleanup - user.remove(client, function (response) { + + it('should fail gracefully when a username already exists', function (done) { + var user = new UsergridUser({ + username: _username1, + password: config.test.password + }) + user.create(client, function (usergridResponse) { + usergridResponse.error.should.not.be.null() + usergridResponse.error.should.containDeep({ + name: 'duplicate_unique_property_exists' + }) + usergridResponse.ok.should.be.false() done() }) }) - }) - }) - describe('login()', function () { - it("it should log in the user '" + _username1 + "' and receive a token", function (done) { - _user1.password = config.test.password - _user1.login(client, function (auth, user, response) { - _user1.auth.should.have.property('token').equal(auth.token) - _user1.should.not.have.property('password') - _user1.auth.should.not.have.property('password') - done() + it('should create a new user on the server', function (done) { + var username = randomWord() + var user = new UsergridUser({ + username: username, + password: config.test.password + }) + user.create(client, function (usergridResponse) { + user.username.should.equal(username) + user.should.have.property('uuid')//.which.is.a.uuid() + user.should.have.property('created') + user.should.have.property('activated').true() + user.should.not.have.property('password') + // cleanup + user.remove(client, function (response) { + done() + }) + }) }) }) - }) - describe('logout()', function () { - - it("it should log out " + _username1 + " and destroy the saved UsergridUserAuth instance", function (done) { - _user1.logout(client, function (response) { - response.ok.should.be.true() - response.responseJSON.action.should.equal("revoked user token") - _user1.auth.isValid.should.be.false() - done() + describe('login()', function () { + it("it should log in the user '" + _username1 + "' and receive a token", function (done) { + _user1.password = config.test.password + _user1.login(client, function (auth, user, response) { + _user1.auth.should.have.property('token').equal(auth.token) + _user1.should.not.have.property('password') + _user1.auth.should.not.have.property('password') + done() + }) }) }) - it("it should return an error when attempting to log out a user that does not have a valid token", function (done) { - _user1.logout(client, function (response) { - response.error.name.should.equal('no_valid_token') - done() - }) - }) - }) + describe('logout()', function () { - describe('logoutAllSessions()', function () { - it("it should log out all tokens for the user " + _username1 + " destroy the saved UsergridUserAuth instance", function (done) { - _user1.password = config.test.password - _user1.login(client, function (auth, user, response) { - _user1.logoutAllSessions(client, function (response) { + it("it should log out " + _username1 + " and destroy the saved UsergridUserAuth instance", function (done) { + _user1.logout(client, function (response) { response.ok.should.be.true() - response.responseJSON.action.should.equal("revoked user tokens") + response.responseJSON.action.should.equal("revoked user token") _user1.auth.isValid.should.be.false() done() }) }) - }) - }) - - describe('resetPassword()', function () { - it("it should reset the password for " + _username1 + " by passing parameters", function (done) { - _user1.resetPassword(client, config.test.password, '2cool4u', function (response) { - response.ok.should.be.true() - response.responseJSON.action.should.equal("set user password") - done() + it("it should return an error when attempting to log out a user that does not have a valid token", function (done) { + _user1.logout(client, function (response) { + response.error.name.should.equal('no_valid_token') + done() + }) }) }) - it("it should reset the password for " + _username1 + " by passing an object", function (done) { - _user1.resetPassword(client, { - oldPassword: '2cool4u', - newPassword: config.test.password - }, function (response) { - response.ok.should.be.true() - response.responseJSON.action.should.equal("set user password") - done() + describe('logoutAllSessions()', function () { + it("it should log out all tokens for the user " + _username1 + " destroy the saved UsergridUserAuth instance", function (done) { + _user1.password = config.test.password + _user1.login(client, function (auth, user, response) { + _user1.logoutAllSessions(client, function (response) { + response.ok.should.be.true() + response.responseJSON.action.should.equal("revoked user tokens") + _user1.auth.isValid.should.be.false() + done() + }) + }) }) }) - it("it should not reset the password for " + _username1 + " when passing a bad old password", function (done) { - _user1.resetPassword(client, { - oldPassword: 'BADOLDPASSWORD', - newPassword: config.test.password - }, function (response) { - response.ok.should.be.false() - response.error.name.should.equal('auth_invalid_username_or_password') - _user1.remove(client, function () { + describe('resetPassword()', function () { + + it("it should reset the password for " + _username1 + " by passing parameters", function (done) { + _user1.resetPassword(client, config.test.password, '2cool4u', function (response) { + response.ok.should.be.true() + response.responseJSON.action.should.equal("set user password") done() }) }) - }) - it("it should return an error when attempting to reset a password with missing arguments", function () { - should(function () { - _user1.resetPassword(client, 'NEWPASSWORD', function () { + it("it should reset the password for " + _username1 + " by passing an object", function (done) { + _user1.resetPassword(client, { + oldPassword: '2cool4u', + newPassword: config.test.password + }, function (response) { + response.ok.should.be.true() + response.responseJSON.action.should.equal("set user password") + done() }) - }).throw() + }) + + it("it should not reset the password for " + _username1 + " when passing a bad old password", function (done) { + _user1.resetPassword(client, { + oldPassword: 'BADOLDPASSWORD', + newPassword: config.test.password + }, function (response) { + response.ok.should.be.false() + response.error.name.should.equal('auth_invalid_username_or_password') + _user1.remove(client, function () { + done() + }) + }) + }) + + it("it should return an error when attempting to reset a password with missing arguments", function () { + should(function () { + _user1.resetPassword(client, 'NEWPASSWORD', function () { + }) + }).throw() + }) }) - }) - describe('CheckAvailable()', function () { + describe('CheckAvailable()', function () { - var nonExistentEmail = randomWord() + '@' + randomWord() + '.com' - var nonExistentUsername = randomWord() + var nonExistentEmail = randomWord() + '@' + randomWord() + '.com' + var nonExistentUsername = randomWord() - it("it should return true for username " + config.test.username, function (done) { - UsergridUser.CheckAvailable(client, { - username: config.test.username - }, function (response, exists) { - exists.should.be.true() - done() + it("it should return true for username " + config.test.username, function (done) { + UsergridUser.CheckAvailable(client, { + username: config.test.username + }, function (response, exists) { + exists.should.be.true() + done() + }) }) - }) - it("it should return true for email " + config.test.email, function (done) { - UsergridUser.CheckAvailable(client, { - email: config.test.email - }, function (response, exists) { - exists.should.be.true() - done() + it("it should return true for email " + config.test.email, function (done) { + UsergridUser.CheckAvailable(client, { + email: config.test.email + }, function (response, exists) { + exists.should.be.true() + done() + }) }) - }) - it("it should return true for email " + config.test.email + " and non-existent username " + nonExistentUsername, function (done) { - UsergridUser.CheckAvailable(client, { - email: config.test.email, - username: nonExistentUsername - }, function (response, exists) { - exists.should.be.true() - done() + it("it should return true for email " + config.test.email + " and non-existent username " + nonExistentUsername, function (done) { + UsergridUser.CheckAvailable(client, { + email: config.test.email, + username: nonExistentUsername + }, function (response, exists) { + exists.should.be.true() + done() + }) }) - }) - it("it should return true for non-existent email " + nonExistentEmail + " and username " + config.test.username, function (done) { - UsergridUser.CheckAvailable(client, { - email: nonExistentEmail, - username: config.test.username - }, function (response, exists) { - exists.should.be.true() - done() + it("it should return true for non-existent email " + nonExistentEmail + " and username " + config.test.username, function (done) { + UsergridUser.CheckAvailable(client, { + email: nonExistentEmail, + username: config.test.username + }, function (response, exists) { + exists.should.be.true() + done() + }) }) - }) - it("it should return true for email " + config.test.email + " and username " + config.test.username, function (done) { - UsergridUser.CheckAvailable(client, { - email: config.test.email, - username: config.test.useranme - }, function (response, exists) { - exists.should.be.true() - done() + it("it should return true for email " + config.test.email + " and username " + config.test.username, function (done) { + UsergridUser.CheckAvailable(client, { + email: config.test.email, + username: config.test.useranme + }, function (response, exists) { + exists.should.be.true() + done() + }) }) - }) - it("it should return false for non-existent email " + nonExistentEmail, function (done) { - UsergridUser.CheckAvailable(client, { - email: nonExistentEmail - }, function (response, exists) { - exists.should.be.false() - done() + it("it should return false for non-existent email " + nonExistentEmail, function (done) { + UsergridUser.CheckAvailable(client, { + email: nonExistentEmail + }, function (response, exists) { + exists.should.be.false() + done() + }) }) - }) - it("it should return false for non-existent username " + nonExistentUsername, function (done) { - UsergridUser.CheckAvailable(client, { - username: nonExistentUsername - }, function (response, exists) { - exists.should.be.false() - done() + it("it should return false for non-existent username " + nonExistentUsername, function (done) { + UsergridUser.CheckAvailable(client, { + username: nonExistentUsername + }, function (response, exists) { + exists.should.be.false() + done() + }) }) - }) - it("it should return false for non-existent email " + nonExistentEmail + " and non-existent username " + nonExistentUsername, function (done) { - UsergridUser.CheckAvailable(client, { - email: nonExistentEmail, - username: nonExistentUsername - }, function (response, exists) { - exists.should.be.false() - done() + it("it should return false for non-existent email " + nonExistentEmail + " and non-existent username " + nonExistentUsername, function (done) { + UsergridUser.CheckAvailable(client, { + email: nonExistentEmail, + username: nonExistentUsername + }, function (response, exists) { + exists.should.be.false() + done() + }) }) }) }) diff --git a/tests/mocha/test_usergrid_init.js b/tests/mocha/test_usergrid_init.js index 7d85230..d676e7f 100644 --- a/tests/mocha/test_usergrid_init.js +++ b/tests/mocha/test_usergrid_init.js @@ -1,15 +1,18 @@ 'use strict' -describe('Usergrid init() / initSharedInstance()', function() { - it('should be an instance of UsergridClient', function(done) { - Usergrid.init(config) - Usergrid.initSharedInstance(config) - Usergrid.should.be.an.instanceof(UsergridClient) - done() - }) - it('should be initialized when defined in another module', function(done) { - Usergrid.should.have.property('isInitialized').which.is.true() - Usergrid.should.have.property('isSharedInstance').which.is.true() - done() +configs.forEach(function(config) { + + describe('Usergrid init() / initSharedInstance() ' + config.target, function () { + it('should be an instance of UsergridClient', function (done) { + Usergrid.init(config) + Usergrid.initSharedInstance(config) + Usergrid.should.be.an.instanceof(UsergridClient) + done() + }) + it('should be initialized when defined in another module', function (done) { + Usergrid.should.have.property('isInitialized').which.is.true() + Usergrid.should.have.property('isSharedInstance').which.is.true() + done() + }) }) }) \ No newline at end of file diff --git a/usergrid.js b/usergrid.js index 46bad91..d489084 100644 --- a/usergrid.js +++ b/usergrid.js @@ -17,7 +17,7 @@ *under the License. * * - * usergrid@2.0.0 2016-10-09 + * usergrid@2.0.0 2016-10-12 */ (function(global) { var name = "Promise", overwrittenName = global[name], exports; @@ -5363,20 +5363,10 @@ var UsergridQuerySortOrder = Object.freeze({ return _.flattenDeep(Array.prototype.slice.call(args)); }; UsergridHelpers.callback = function() { - var args = _.flattenDeep(Array.prototype.slice.call(arguments)).reverse(); + var args = UsergridHelpers.flattenArgs(arguments).reverse(); var emptyFunc = function() {}; return _.first(_.flattenDeep([ args, _.get(args, "0.callback"), emptyFunc ]).filter(_.isFunction)); }; - UsergridHelpers.doCallback = function(callback, params, context) { - var returnValue; - if (_.isFunction(callback)) { - if (!params) params = []; - if (!context) context = this; - params.push(context); - returnValue = callback.apply(context, params); - } - return returnValue; - }; UsergridHelpers.authForRequests = function(client) { var authForRequests = undefined; if (_.get(client, "tempAuth.isValid")) { @@ -5462,8 +5452,8 @@ var UsergridQuerySortOrder = Object.freeze({ return this; }; UsergridHelpers.normalize = function(str) { + str = str.replace(/\/+/g, "/"); str = str.replace(/:\//g, "://"); - str = str.replace(/([^:\s])\/+/g, "$1/"); str = str.replace(/\/(\?|&|#[^!])/g, "$1"); str = str.replace(/(\?.+)\?/g, "$1&"); return str; @@ -5488,13 +5478,13 @@ var UsergridQuerySortOrder = Object.freeze({ var headerPair = headerPairs[i]; var index = headerPair.indexOf(": "); if (index > 0) { - var key = headerPair.substring(0, index); + var key = headerPair.substring(0, index).toLowerCase(); headers[key] = headerPair.substring(index + 2); } } return headers; }; - UsergridHelpers.uri = function(client, method, options) { + UsergridHelpers.uri = function(client, options) { var path = ""; if (options instanceof UsergridEntity) { path = options.type; @@ -5508,73 +5498,132 @@ var UsergridQuerySortOrder = Object.freeze({ path = options.path || options.type || _.get(options, "entity.type") || _.get(options, "query._type") || _.get(options, "body.type") || _.get(options, "body.path"); } var uuidOrName = ""; - if (method !== UsergridHttpMethod.POST) { + if (options.method !== UsergridHttpMethod.POST) { uuidOrName = _.first([ options.uuidOrName, options.uuid, options.name, _.get(options, "entity.uuid"), _.get(options, "entity.name"), _.get(options, "body.uuid"), _.get(options, "body.name"), "" ].filter(_.isString)); } return UsergridHelpers.urljoin(client.baseUrl, client.orgId, client.appId, path, uuidOrName); }; - UsergridHelpers.body = function(options) { - var rawBody = undefined; - if (options instanceof UsergridEntity) { - rawBody = options; - } else { - rawBody = options.body || options.entity || options.entities; - if (rawBody === undefined) { - if (_.isArray(options)) { - if (options[0] instanceof UsergridEntity) { - rawBody = options; - } - } - } - } - var returnBody = rawBody; - if (rawBody instanceof UsergridEntity) { - returnBody = rawBody.jsonValue(); - } else if (rawBody instanceof Array) { - if (rawBody[0] instanceof UsergridEntity) { - returnBody = _.map(rawBody, function(entity) { - return entity.jsonValue(); - }); - } - } - return returnBody; - }; UsergridHelpers.updateEntityFromRemote = function(entity, usergridResponse) { UsergridHelpers.setWritable(entity, [ "uuid", "name", "type", "created" ]); _.assign(entity, usergridResponse.entity); UsergridHelpers.setReadOnly(entity, [ "uuid", "name", "type", "created" ]); }; - UsergridHelpers.headers = function(client, options) { - var headers = { + UsergridHelpers.headers = function(client, options, defaultHeaders) { + var returnHeaders = {}; + _.assign(returnHeaders, defaultHeaders); + _.assign(returnHeaders, options.headers); + _.assign(returnHeaders, { "User-Agent": "usergrid-js/v" + UsergridSDKVersion - }; - _.assign(headers, options.headers); + }); var authForRequests = UsergridHelpers.authForRequests(client); if (authForRequests) { - _.assign(headers, { + _.assign(returnHeaders, { authorization: "Bearer " + authForRequests.token }); } - return headers; + return returnHeaders; }; - UsergridHelpers.encode = function(data) { - var result = ""; - if (typeof data === "string") { - result = data; - } else { - var encode = encodeURIComponent; - _.forOwn(data, function(value, key) { - result += "&" + encode(key) + "=" + encode(value); - }); + UsergridHelpers.setEntity = function(options, args) { + options.entity = _.first([ options.entity, args[0] ].filter(function(property) { + return property instanceof UsergridEntity; + })); + if (options.entity !== undefined) { + options.type = options.entity.type; } - return result; + return options; + }; + UsergridHelpers.setAsset = function(options, args) { + options.asset = _.first([ options.asset, _.get(options, "entity.asset"), args[1], args[0] ].filter(function(property) { + return property instanceof UsergridAsset; + })); + return options; + }; + UsergridHelpers.setUuidOrName = function(options, args) { + options.uuidOrName = _.first([ options.uuidOrName, options.uuid, options.name, _.get(options, "entity.uuid"), _.get(options, "body.uuid"), _.get(options, "entity.name"), _.get(options, "body.name"), _.get(args, "0.uuid"), _.get(args, "0.name"), _.get(args, "2"), _.get(args, "1") ].filter(_.isString)); + return options; + }; + UsergridHelpers.setPathOrType = function(options, args) { + var pathOrType = _.first([ args.type, _.get(args, "0.type"), _.get(options, "entity.type"), _.get(args, "body.type"), _.get(options, "body.0.type"), _.isArray(args) ? args[0] : undefined ].filter(_.isString)); + options[/\//.test(pathOrType) ? "path" : "type"] = pathOrType; + return options; + }; + UsergridHelpers.setQs = function(options, args) { + if (options.path) { + options.qs = _.first([ options.qs, args[2], args[1], args[0] ].filter(_.isPlainObject)); + } + return options; + }; + UsergridHelpers.setQuery = function(options, args) { + options.query = _.first([ options, options.query, args[0] ].filter(function(property) { + return property instanceof UsergridQuery; + })); + return options; + }; + UsergridHelpers.setAsset = function(options, args) { + options.asset = _.first([ options.asset, _.get(options, "entity.asset"), args[1], args[0] ].filter(function(property) { + return property instanceof UsergridAsset; + })); + return options; + }; + UsergridHelpers.setBody = function(options, args) { + options.body = _.first([ args.entity, args.body, args[0].entity, args[0].body, args[2], args[1], args[0] ].filter(function(property) { + return _.isObject(property) && !_.isFunction(property) && !(property instanceof UsergridQuery) && !(property instanceof UsergridAsset); + })); + if (options.body === undefined && options.asset === undefined) { + throw new Error('"body" is required when making a ' + options.method + " request"); + } + if (options.body instanceof UsergridEntity) { + options.body = options.body.jsonValue(); + } else if (options.body instanceof Array) { + if (options.body[0] instanceof UsergridEntity) { + options.body = _.map(options.body, function(entity) { + return entity.jsonValue(); + }); + } + } + return options; + }; + UsergridHelpers.buildReqest = function(client, method, args) { + var options = { + client: client, + method: method, + queryParams: args.queryParams || _.get(args, "0.queryParams"), + callback: UsergridHelpers.callback(args) + }; + UsergridHelpers.assignPrefabOptions(options, args); + UsergridHelpers.setEntity(options, args); + if (method === UsergridHttpMethod.POST || method === UsergridHttpMethod.PUT) { + UsergridHelpers.setAsset(options, args); + if (options.asset === undefined) { + UsergridHelpers.setBody(options, args); + } + } + UsergridHelpers.setUuidOrName(options, args); + UsergridHelpers.setPathOrType(options, args); + UsergridHelpers.setQs(options, args); + UsergridHelpers.setQuery(options, args); + options.uri = UsergridHelpers.uri(client, options); + return new UsergridRequest(options); + }; + UsergridHelpers.buildAppAuthRequest = function(client, auth, callback) { + var requestOptions = { + client: client, + method: UsergridHttpMethod.POST, + uri: UsergridHelpers.uri(client, { + path: "token" + }), + body: UsergridHelpers.appLoginBody(auth), + callback: callback + }; + return new UsergridRequest(requestOptions); }; UsergridHelpers.buildConnectionRequest = function(client, method, args) { var options = { client: client, method: method, entity: {}, - to: {} + to: {}, + callback: UsergridHelpers.callback(args) }; UsergridHelpers.assignPrefabOptions.call(options, args); if (_.isObject(options.from)) { @@ -5620,7 +5669,8 @@ var UsergridQuerySortOrder = Object.freeze({ UsergridHelpers.buildGetConnectionRequest = function(client, args) { var options = { client: client, - method: "GET" + method: "GET", + callback: UsergridHelpers.callback(args) }; UsergridHelpers.assignPrefabOptions.call(options, args); if (_.isObject(args[1]) && !_.isFunction(args[1])) { @@ -5653,7 +5703,7 @@ var UsergridQuerySortOrder = Object.freeze({ "use strict"; -var defaultOptions = { +var UsergridClientDefaultOptions = { baseUrl: "https://api.usergrid.com", authMode: UsergridAuthMode.USER }; @@ -5667,7 +5717,7 @@ var UsergridClient = function(options) { self.orgId = arguments[0]; self.appId = arguments[1]; } - _.defaults(self, options, defaultOptions); + _.defaults(self, options, UsergridClientDefaultOptions); if (!self.orgId || !self.appId) { throw new Error('"orgId" and "appId" parameters are required when instantiating UsergridClient'); } @@ -5696,68 +5746,54 @@ var UsergridClient = function(options) { }; UsergridClient.prototype = { - GET: function(options, callback) { - var self = this; - return self.performRequest(new UsergridRequest({ - client: self, - method: UsergridHttpMethod.GET, - uri: UsergridHelpers.uri(self, UsergridHttpMethod.GET, options), - query: options instanceof UsergridQuery ? options : options.query, - queryParams: options.queryParams, - body: UsergridHelpers.body(options) - }), callback); + sendRequest: function(usergridRequest) { + return usergridRequest.sendRequest(); }, - PUT: function(options, callback) { - var self = this; - return self.performRequest(new UsergridRequest({ - client: self, - method: UsergridHttpMethod.PUT, - uri: UsergridHelpers.uri(self, UsergridHttpMethod.PUT, options), - query: options instanceof UsergridQuery ? options : options.query, - queryParams: options.queryParams, - body: UsergridHelpers.body(options) - }), callback); + GET: function() { + var usergridRequest = UsergridHelpers.buildReqest(this, UsergridHttpMethod.GET, UsergridHelpers.flattenArgs(arguments)); + return this.sendRequest(usergridRequest); }, - POST: function(options, callback) { - var self = this; - return self.performRequest(new UsergridRequest({ - client: self, - method: UsergridHttpMethod.POST, - uri: UsergridHelpers.uri(self, UsergridHttpMethod.POST, options), - query: options instanceof UsergridQuery ? options : options.query, - queryParams: options.queryParams, - body: UsergridHelpers.body(options) - }), callback); + PUT: function() { + var usergridRequest = UsergridHelpers.buildReqest(this, UsergridHttpMethod.PUT, UsergridHelpers.flattenArgs(arguments)); + return this.sendRequest(usergridRequest); }, - DELETE: function(options, callback) { - var self = this; - return self.performRequest(new UsergridRequest({ - client: self, - method: UsergridHttpMethod.DELETE, - uri: UsergridHelpers.uri(self, UsergridHttpMethod.DELETE, options), - query: options instanceof UsergridQuery ? options : options.query, - queryParams: options.queryParams, - body: UsergridHelpers.body(options) - }), callback); + POST: function() { + var usergridRequest = UsergridHelpers.buildReqest(this, UsergridHttpMethod.POST, UsergridHelpers.flattenArgs(arguments)); + return this.sendRequest(usergridRequest); + }, + DELETE: function() { + var usergridRequest = UsergridHelpers.buildReqest(this, UsergridHttpMethod.DELETE, UsergridHelpers.flattenArgs(arguments)); + return this.sendRequest(usergridRequest); }, connect: function() { - var self = this; - return self.performRequest(UsergridHelpers.buildConnectionRequest(self, UsergridHttpMethod.POST, UsergridHelpers.flattenArgs(arguments)), UsergridHelpers.callback(arguments)); + var usergridRequest = UsergridHelpers.buildConnectionRequest(this, UsergridHttpMethod.POST, UsergridHelpers.flattenArgs(arguments)); + return this.sendRequest(usergridRequest); }, disconnect: function() { - var self = this; - return self.performRequest(UsergridHelpers.buildConnectionRequest(self, UsergridHttpMethod.DELETE, UsergridHelpers.flattenArgs(arguments)), UsergridHelpers.callback(arguments)); + var usergridRequest = UsergridHelpers.buildConnectionRequest(this, UsergridHttpMethod.DELETE, UsergridHelpers.flattenArgs(arguments)); + return this.sendRequest(usergridRequest); }, getConnections: function() { + var usergridRequest = UsergridHelpers.buildGetConnectionRequest(this, UsergridHelpers.flattenArgs(arguments)); + return this.sendRequest(usergridRequest); + }, + usingAuth: function(auth) { var self = this; - return self.performRequest(UsergridHelpers.buildGetConnectionRequest(self, UsergridHelpers.flattenArgs(arguments)), UsergridHelpers.callback(arguments)); + if (_.isString(auth)) { + self.tempAuth = new UsergridAuth(auth); + } else if (auth instanceof UsergridAuth) { + self.tempAuth = auth; + } else { + self.tempAuth = undefined; + } + return self; }, setAppAuth: function() { this.appAuth = new UsergridAppAuth(UsergridHelpers.flattenArgs(arguments)); }, authenticateApp: function(options) { var self = this; - var callback = UsergridHelpers.callback(UsergridHelpers.flattenArgs(arguments)); + var authenticateAppCallback = UsergridHelpers.callback(UsergridHelpers.flattenArgs(arguments)); var auth = _.first([ options, self.appAuth, new UsergridAppAuth(options), new UsergridAppAuth(self.clientId, self.clientSecret) ].filter(function(p) { return p instanceof UsergridAppAuth; })); @@ -5766,7 +5802,7 @@ UsergridClient.prototype = { } else if (!auth.clientId || !auth.clientSecret) { throw new Error("authenticateApp() failed because clientId or clientSecret are missing"); } - var authCallback = function(usergridResponse) { + var callback = function(usergridResponse) { if (usergridResponse.ok) { if (!self.appAuth) { self.appAuth = auth; @@ -5776,123 +5812,62 @@ UsergridClient.prototype = { self.appAuth.expiry = UsergridHelpers.calculateExpiry(expiresIn); self.appAuth.tokenTtl = expiresIn; } - callback(usergridResponse); + authenticateAppCallback(usergridResponse); }; - return self.performRequest(new UsergridRequest({ - client: self, - method: UsergridHttpMethod.POST, - uri: UsergridHelpers.uri(self, UsergridHttpMethod.POST, { - path: "token" - }), - body: UsergridHelpers.appLoginBody(auth) - }), authCallback); + var usergridRequest = UsergridHelpers.buildAppAuthRequest(self, auth, callback); + return self.sendRequest(usergridRequest); }, authenticateUser: function(options) { var self = this; var args = UsergridHelpers.flattenArgs(arguments); var callback = UsergridHelpers.callback(args); var setAsCurrentUser = _.last(args.filter(_.isBoolean)) !== undefined ? _.last(args.filter(_.isBoolean)) : true; - var currentUser = new UsergridUser(options); - currentUser.login(self, function(auth, user, usergridResponse) { + var userToAuthenticate = new UsergridUser(options); + userToAuthenticate.login(self, function(auth, user, usergridResponse) { if (usergridResponse.ok && setAsCurrentUser) { - self.currentUser = currentUser; + self.currentUser = userToAuthenticate; } callback(auth, user, usergridResponse); }); }, - usingAuth: function(auth) { - if (_.isString(auth)) { - this.tempAuth = new UsergridAuth(auth); - } else if (auth instanceof UsergridAuth) { - this.tempAuth = auth; - } else { - this.tempAuth = undefined; - } - return this; - }, - downloadAsset: function(entity, callback) { - var self = this; - var uploadRequest = new UsergridRequest({ - client: self, - method: UsergridHttpMethod.GET, - uri: UsergridHelpers.uri(self, UsergridHttpMethod.GET, entity) - }); - return self.performAssetDownloadRequest(uploadRequest, entity, callback); - }, - uploadAsset: function(entity, asset, callback) { - var self = this; - var method = UsergridHttpMethod.PUT; - var uploadRequest = new UsergridRequest({ - client: self, - method: method, - uri: UsergridHelpers.uri(self, method, entity), - asset: asset - }); - return self.performAssetUploadRequest(uploadRequest, entity, callback); - }, - performRequest: function(usergridRequest, callback) { + downloadAsset: function() { var self = this; - var requestPromise = function() { - var promise = new Promise(); - var xmlHttpRequest = new XMLHttpRequest(); - xmlHttpRequest.open(usergridRequest.method.toString(), usergridRequest.uri); - _.forOwn(usergridRequest.headers, function(value, key) { - xmlHttpRequest.setRequestHeader(key, value); + var usergridRequest = UsergridHelpers.buildReqest(self, UsergridHttpMethod.GET, UsergridHelpers.flattenArgs(arguments)); + var assetContentType = _.get(usergridRequest, "entity.file-metadata.content-type"); + if (assetContentType !== undefined) { + _.assign(usergridRequest.headers, { + Accept: assetContentType }); - xmlHttpRequest.open = function() { - if (usergridRequest.body !== undefined) { - xmlHttpRequest.setRequestHeader("Content-Type", "application/json"); - xmlHttpRequest.setRequestHeader("Accept", "application/json"); - } - }; - xmlHttpRequest.onreadystatechange = function() { - if (this.readyState === XMLHttpRequest.DONE) { - promise.done(xmlHttpRequest); - } - }; - xmlHttpRequest.send(UsergridHelpers.encode(usergridRequest.body)); - return promise; - }.bind(self); - var responsePromise = function(xmlRequest) { - var promise = new Promise(); - var usergridResponse = new UsergridResponse(xmlRequest); - promise.done(usergridResponse); - return promise; - }.bind(self); - var onCompletePromise = function(response) { - var promise = new Promise(); - response.request = usergridRequest; - promise.done(response); - UsergridHelpers.doCallback(callback, [ response ]); - }.bind(self); - Promise.chain([ requestPromise, responsePromise ]).then(onCompletePromise); - return usergridRequest; - }, - performAssetDownloadRequest: function(usergridRequest, entity, callback) { - var req = new XMLHttpRequest(); - req.open("GET", usergridRequest.uri, true); - req.setRequestHeader("Accept", _.get(entity, "file-metadata.content-type")); - req.responseType = "blob"; - req.onload = function() { - entity.asset = new UsergridAsset(req.response); - UsergridHelpers.doCallback(callback, [ entity.asset, null, entity ]); + } + var realDownloadAssetCallback = usergridRequest.callback; + usergridRequest.callback = function(usergridResponse) { + var entity = usergridRequest.entity; + entity.asset = usergridResponse.asset; + realDownloadAssetCallback(entity.asset, usergridResponse, entity); }; - req.send(null); - return usergridRequest; + return self.sendRequest(usergridRequest); }, - performAssetUploadRequest: function(usergridRequest, entity, callback) { - var asset = usergridRequest.asset; - var xmlHttpRequest = new XMLHttpRequest(); - xmlHttpRequest.open(usergridRequest.method, usergridRequest.uri, true); - xmlHttpRequest.onload = function() { - var response = new UsergridResponse(xmlHttpRequest); - UsergridHelpers.updateEntityFromRemote(entity, response); - UsergridHelpers.doCallback(callback, [ asset, response, entity ]); + uploadAsset: function() { + var self = this; + var usergridRequest = UsergridHelpers.buildReqest(self, UsergridHttpMethod.PUT, UsergridHelpers.flattenArgs(arguments)); + if (usergridRequest.asset === undefined) { + throw new Error("An UsergridAsset was not defined when attempting to call .uploadAsset()"); + } + var realUploadAssetCallback = usergridRequest.callback; + usergridRequest.callback = function(usergridResponse) { + var requestEntity = usergridRequest.entity; + var responseEntity = usergridResponse.entity; + var requestAsset = usergridRequest.asset; + if (usergridResponse.ok && responseEntity !== undefined) { + UsergridHelpers.updateEntityFromRemote(requestEntity, usergridResponse); + requestEntity.asset = requestAsset; + if (responseEntity) { + responseEntity.asset = requestAsset; + } + } + realUploadAssetCallback(requestAsset, usergridResponse, requestEntity); }; - var formData = new FormData(); - formData.append("file", asset.data); - xmlHttpRequest.send(formData); - return usergridRequest; + return self.sendRequest(usergridRequest); } }; @@ -5928,7 +5903,7 @@ Usergrid.init = Usergrid.initSharedInstance; var UsergridQuery = function(type) { var self = this; - var query = "", queryString, sort, __nextIsNot = false; + var query = "", queryString, sort, urlTerms = {}, __nextIsNot = false; self._type = type; _.assign(self, { type: function(value) { @@ -5996,6 +5971,14 @@ var UsergridQuery = function(type) { queryString = string; return self; }, + urlTerm: function(key, value) { + if (key === "ql") { + self.fromString(); + } else { + urlTerms[key] = value; + } + return self; + }, andJoin: function(append) { if (__nextIsNot) { append = "not " + append; @@ -6015,13 +5998,14 @@ var UsergridQuery = function(type) { }); Object.defineProperty(self, "_ql", { get: function() { + var ql = "select * "; if (queryString !== undefined) { - return queryString; + ql = queryString; } else { - var qL = "select * " + (query.length > 0 ? "where " + (query || "") : ""); - qL += sort !== undefined ? sort : ""; - return qL; + ql += query.length > 0 ? "where " + (query || "") : ""; + ql += sort !== undefined ? sort : ""; } + return ql; } }); Object.defineProperty(self, "encodedStringValue", { @@ -6030,30 +6014,38 @@ var UsergridQuery = function(type) { var limit = self._limit; var cursor = self._cursor; var requirementsString = self._ql; - var encodedStringValue = undefined; + var returnString = undefined; if (limit !== undefined) { - encodedStringValue = "limit" + UsergridQueryOperator.EQUAL + limit; + returnString = "limit" + UsergridQueryOperator.EQUAL + limit; } if (!_.isEmpty(cursor)) { var cursorString = "cursor" + UsergridQueryOperator.EQUAL + cursor; - if (_.isEmpty(encodedStringValue)) { - encodedStringValue = cursorString; + if (_.isEmpty(returnString)) { + returnString = cursorString; } else { - encodedStringValue += "&" + cursorString; + returnString += "&" + cursorString; } } + _.forEach(urlTerms, function(value, key) { + var encodedURLTermString = encodeURIComponent(key) + UsergridQueryOperator.EQUAL + encodeURIComponent(value); + if (_.isEmpty(returnString)) { + returnString = encodedURLTermString; + } else { + returnString += "&" + encodedURLTermString; + } + }); if (!_.isEmpty(requirementsString)) { var qLString = "ql=" + encodeURIComponent(requirementsString); - if (_.isEmpty(encodedStringValue)) { - encodedStringValue = qLString; + if (_.isEmpty(returnString)) { + returnString = qLString; } else { - encodedStringValue += "&" + qLString; + returnString += "&" + qLString; } } - if (!_.isEmpty(encodedStringValue)) { - encodedStringValue = "?" + encodedStringValue; + if (!_.isEmpty(returnString)) { + returnString = "?" + returnString; } - return !_.isEmpty(encodedStringValue) ? encodedStringValue : undefined; + return !_.isEmpty(returnString) ? returnString : undefined; } }); Object.defineProperty(self, "and", { @@ -6079,6 +6071,11 @@ var UsergridQuery = function(type) { "use strict"; +var UsergridRequestDefaultHeaders = Object.freeze({ + "Content-Type": "application/json", + Accept: "application/json" +}); + var UsergridRequest = function(options) { var self = this; var client = UsergridHelpers.validateAndRetrieveClient(options); @@ -6089,29 +6086,69 @@ var UsergridRequest = function(options) { throw new Error('"method" parameter is required when initializing a UsergridRequest'); } self.method = options.method; + self.callback = options.callback; self.uri = options.uri || UsergridHelpers.uri(client, options); - self.headers = UsergridHelpers.headers(client, options); + self.entity = options.entity; self.body = options.body || undefined; self.asset = options.asset || undefined; self.query = options.query; + self.queryParams = options.queryParams || options.qs; + var defaultHeadersToUse = self.asset === undefined ? UsergridRequestDefaultHeaders : {}; + self.headers = UsergridHelpers.headers(client, options, defaultHeadersToUse); if (self.query !== undefined) { self.uri += UsergridHelpers.normalize(self.query.encodedStringValue, {}); } - self.queryParams = options.queryParams; if (self.queryParams !== undefined) { _.forOwn(self.queryParams, function(value, key) { self.uri += "?" + encodeURIComponent(key) + "=" + encodeURIComponent(value); }); self.uri = UsergridHelpers.normalize(self.uri, {}); } - try { - if (_.isPlainObject(self.body)) { - self.body = JSON.stringify(self.body); - } - if (_.isArray(self.body)) { - self.body = JSON.stringify(self.body); - } - } catch (exception) {} + if (self.asset !== undefined) { + self.body = new FormData(); + self.body.append("file", self.asset.data); + } else { + try { + if (_.isPlainObject(self.body)) { + self.body = JSON.stringify(self.body); + } else if (_.isArray(self.body)) { + self.body = JSON.stringify(self.body); + } + } catch (exception) {} + } + return self; +}; + +UsergridRequest.prototype.sendRequest = function() { + var self = this; + var requestPromise = function() { + var promise = new Promise(); + var xmlHttpRequest = new XMLHttpRequest(); + xmlHttpRequest.open(self.method, self.uri, true); + xmlHttpRequest.onload = function() { + promise.done(xmlHttpRequest); + }; + _.forOwn(self.headers, function(value, key) { + xmlHttpRequest.setRequestHeader(key, value); + }); + if (self.method === UsergridHttpMethod.GET && _.get(self.headers, "Accept") !== "application/json") { + xmlHttpRequest.responseType = "blob"; + } + xmlHttpRequest.send(self.body); + return promise; + }.bind(self); + var responsePromise = function(xmlRequest) { + var promise = new Promise(); + var usergridResponse = new UsergridResponse(xmlRequest, self); + promise.done(usergridResponse); + return promise; + }.bind(self); + var onCompletePromise = function(response) { + var promise = new Promise(); + promise.done(response); + self.callback(response); + }.bind(self); + Promise.chain([ requestPromise, responsePromise ]).then(onCompletePromise); return self; }; @@ -6274,57 +6311,83 @@ UsergridEntity.prototype = { } }, reload: function() { + var self = this; var args = UsergridHelpers.flattenArgs(arguments); var client = UsergridHelpers.validateAndRetrieveClient(args); var callback = UsergridHelpers.callback(args); - client.GET(this, function(usergridResponse) { - UsergridHelpers.updateEntityFromRemote(this, usergridResponse); - callback(usergridResponse); - }.bind(this)); + client.GET(self, function(usergridResponse) { + UsergridHelpers.updateEntityFromRemote(self, usergridResponse); + callback(usergridResponse, self); + }.bind(self)); }, save: function() { + var self = this; var args = UsergridHelpers.flattenArgs(arguments); var client = UsergridHelpers.validateAndRetrieveClient(args); var callback = UsergridHelpers.callback(args); - var uuid = this.uuid; + var currentAsset = self.asset; + var uuid = self.uuid; if (uuid === undefined) { - client.POST(this, function(usergridResponse) { - UsergridHelpers.updateEntityFromRemote(this, usergridResponse); - callback(usergridResponse, this); - }.bind(this)); + client.POST(self, function(usergridResponse) { + UsergridHelpers.updateEntityFromRemote(self, usergridResponse); + if (self.hasAsset) { + self.asset = currentAsset; + } + callback(usergridResponse, self); + }.bind(self)); } else { - client.PUT(this, function(usergridResponse) { - UsergridHelpers.updateEntityFromRemote(this, usergridResponse); - callback(usergridResponse, this); - }.bind(this)); + client.PUT(self, function(usergridResponse) { + UsergridHelpers.updateEntityFromRemote(self, usergridResponse); + if (self.hasAsset) { + self.asset = currentAsset; + } + callback(usergridResponse, self); + }.bind(self)); } }, remove: function() { + var self = this; var args = UsergridHelpers.flattenArgs(arguments); var client = UsergridHelpers.validateAndRetrieveClient(args); var callback = UsergridHelpers.callback(args); - client.DELETE(this, function(usergridResponse) { - callback(usergridResponse, this); - }.bind(this)); + client.DELETE(self, function(usergridResponse) { + callback(usergridResponse, self); + }.bind(self)); }, attachAsset: function(asset) { this.asset = asset; }, uploadAsset: function() { + var self = this; var args = UsergridHelpers.flattenArgs(arguments); var client = UsergridHelpers.validateAndRetrieveClient(args); var callback = UsergridHelpers.callback(args); - client.uploadAsset(this, this.asset, function(asset, usergridResponse) { - UsergridHelpers.updateEntityFromRemote(this, usergridResponse); - this.asset = asset; - callback(asset, usergridResponse, this); - }.bind(this)); + if (_.has(self, "asset.contentType")) { + client.uploadAsset(self, callback); + } else { + var response = new UsergridResponse(); + response.error = new UsergridResponseError({ + error: "asset_not_found", + description: "The specified entity does not have a valid asset attached" + }); + callback(null, response, self); + } }, downloadAsset: function() { + var self = this; var args = UsergridHelpers.flattenArgs(arguments); var client = UsergridHelpers.validateAndRetrieveClient(args); var callback = UsergridHelpers.callback(args); - client.downloadAsset(this, callback); + if (_.has(self, "asset.contentType")) { + client.downloadAsset(self, callback); + } else { + var response = new UsergridResponse(); + response.error = new UsergridResponseError({ + error: "asset_not_found", + description: "The specified entity does not have a valid asset attached" + }); + callback(null, response, self); + } }, connect: function() { var args = UsergridHelpers.flattenArgs(arguments); @@ -6404,12 +6467,9 @@ UsergridUser.prototype.create = function() { UsergridUser.prototype.login = function() { var self = this; var args = UsergridHelpers.flattenArgs(arguments); - var callback = UsergridHelpers.callback(args); var client = UsergridHelpers.validateAndRetrieveClient(args); - client.POST({ - path: "token", - body: UsergridHelpers.userLoginBody(self) - }, function(usergridResponse) { + var callback = UsergridHelpers.callback(args); + client.POST("token", UsergridHelpers.userLoginBody(self), function(usergridResponse) { delete self.password; if (usergridResponse.ok) { var responseJSON = usergridResponse.responseJSON; @@ -6426,6 +6486,7 @@ UsergridUser.prototype.login = function() { UsergridUser.prototype.logout = function() { var self = this; var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); var callback = UsergridHelpers.callback(args); if (!self.auth || !self.auth.isValid) { var response = new UsergridResponse(); @@ -6433,24 +6494,29 @@ UsergridUser.prototype.logout = function() { error: "no_valid_token", description: "this user does not have a valid token" }); - return callback(response); - } - var revokeAll = _.first(args.filter(_.isBoolean)) || false; - var revokeTokenPath = [ "users", self.uniqueId(), "revoketoken" + (revokeAll ? "s" : "") ].join("/"); - var queryParams = undefined; - if (!revokeAll) { - queryParams = { - token: self.auth.token + callback(response); + } else { + var revokeAll = _.first(args.filter(_.isBoolean)) || false; + var revokeTokenPath = [ "users", self.uniqueId(), "revoketoken" + (revokeAll ? "s" : "") ].join("/"); + var queryParams = undefined; + if (!revokeAll) { + queryParams = { + token: self.auth.token + }; + } + var requestOptions = { + client: client, + path: revokeTokenPath, + method: UsergridHttpMethod.PUT, + queryParams: queryParams, + callback: function(usergridResponse) { + self.auth.destroy(); + callback(usergridResponse); + }.bind(self) }; + var request = new UsergridRequest(requestOptions); + client.sendRequest(request); } - var client = UsergridHelpers.validateAndRetrieveClient(args); - return client.PUT({ - path: revokeTokenPath, - queryParams: queryParams - }, function(usergridResponse) { - self.auth.destroy(); - callback(usergridResponse); - }); }; UsergridUser.prototype.logoutAllSessions = function() { @@ -6462,8 +6528,8 @@ UsergridUser.prototype.logoutAllSessions = function() { UsergridUser.prototype.resetPassword = function() { var self = this; var args = UsergridHelpers.flattenArgs(arguments); - var callback = UsergridHelpers.callback(args); var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); if (args[0] instanceof UsergridClient) { args.shift(); } @@ -6474,10 +6540,7 @@ UsergridUser.prototype.resetPassword = function() { if (!body.oldpassword || !body.newpassword) { throw new Error('"oldPassword" and "newPassword" properties are required when resetting a user password'); } - return client.PUT({ - path: [ "users", self.uniqueId(), "password" ].join("/"), - body: body - }, function(usergridResponse) { + client.PUT([ "users", self.uniqueId(), "password" ].join("/"), body, function(usergridResponse) { callback(usergridResponse); }); }; @@ -6490,56 +6553,64 @@ var UsergridResponseError = function(responseErrorObject) { return; } self.name = responseErrorObject.error; - self.description = responseErrorObject.error_description || responseErrorObject.description; + self.description = _.get(responseErrorObject, "error_description") || responseErrorObject.description; self.exception = responseErrorObject.exception; return self; }; -var UsergridResponse = function(request) { +var UsergridResponse = function(xmlRequest, usergridRequest) { var self = this; self.ok = false; - if (request) { - self.statusCode = parseInt(request.status); - self.headers = UsergridHelpers.parseResponseHeaders(request.getAllResponseHeaders()); - try { - var responseText = request.responseText; - var responseJSON = JSON.parse(responseText); - } catch (e) { - responseJSON = {}; - } - if (self.statusCode < 400) { - self.ok = true; - _.assign(self, { - responseJSON: _.cloneDeep(responseJSON) - }); - if (_.has(responseJSON, "entities")) { - var entities = _.map(responseJSON.entities, function(en) { - var entity = new UsergridEntity(en); - if (entity.isUser) { - entity = new UsergridUser(entity); - } - return entity; - }); - _.assign(self, { - entities: entities - }); - delete self.responseJSON.entities; - self.first = _.first(entities) || undefined; - self.entity = self.first; - self.last = _.last(entities) || undefined; - if (_.get(self, "responseJSON.path") === "/users") { - self.user = self.first; - self.users = self.entities; - } - Object.defineProperty(self, "hasNextPage", { - get: function() { - return _.has(self, "responseJSON.cursor"); + self.request = usergridRequest; + if (xmlRequest) { + self.statusCode = parseInt(xmlRequest.status); + self.ok = self.statusCode < 400; + self.headers = UsergridHelpers.parseResponseHeaders(xmlRequest.getAllResponseHeaders()); + var responseContentType = _.get(self.headers, "content-type"); + if (responseContentType === "application/json") { + try { + var responseText = xmlRequest.responseText; + var responseJSON = JSON.parse(responseText); + } catch (e) { + responseJSON = {}; + } + if (self.ok) { + if (responseJSON !== undefined) { + _.assign(self, { + responseJSON: _.cloneDeep(responseJSON) + }); + if (_.has(responseJSON, "entities")) { + var entities = _.map(responseJSON.entities, function(en) { + var entity = new UsergridEntity(en); + if (entity.isUser) { + entity = new UsergridUser(entity); + } + return entity; + }); + _.assign(self, { + entities: entities + }); + delete self.responseJSON.entities; + self.first = _.first(entities) || undefined; + self.entity = self.first; + self.last = _.last(entities) || undefined; + if (_.get(self, "responseJSON.path") === "/users") { + self.user = self.first; + self.users = self.entities; + } + Object.defineProperty(self, "hasNextPage", { + get: function() { + return _.has(self, "responseJSON.cursor"); + } + }); + UsergridHelpers.setReadOnly(self.responseJSON); } - }); - UsergridHelpers.setReadOnly(self.responseJSON); + } + } else { + self.error = new UsergridResponseError(responseJSON); } } else { - self.error = new UsergridResponseError(responseJSON); + self.asset = new UsergridAsset(xmlRequest.response); } } return self; @@ -6550,13 +6621,15 @@ UsergridResponse.prototype = { var self = this; var args = UsergridHelpers.flattenArgs(arguments); var callback = UsergridHelpers.callback(args); - if (!self.responseJSON.cursor) { + var cursor = _.get(self, "responseJSON.cursor"); + if (!cursor) { callback(); } var client = UsergridHelpers.validateAndRetrieveClient(args); var type = _.last(_.get(self, "responseJSON.path").split("/")); var limit = _.first(_.get(this, "responseJSON.params.limit")); - var query = new UsergridQuery(type).fromString(_.get(self,'responseJSON.params.ql.0')).cursor(this.responseJSON.cursor).limit(limit); + var ql = _.first(_.get(this, "responseJSON.params.ql")); + var query = new UsergridQuery(type).fromString(ql).cursor(cursor).limit(limit); return client.GET(query, callback); } }; diff --git a/usergrid.min.js b/usergrid.min.js index 1d0bac7..07196e6 100644 --- a/usergrid.min.js +++ b/usergrid.min.js @@ -17,11 +17,11 @@ *under the License. * * - * usergrid@2.0.0 2016-10-09 + * usergrid@2.0.0 2016-10-12 */ "use strict";!function(global){function Promise(){this.complete=!1,this.result=null,this.callbacks=[]}var name="Promise",overwrittenName=global[name];return Promise.prototype.then=function(callback,context){var f=function(){return callback.apply(context,arguments)};this.complete?f(this.result):this.callbacks.push(f)},Promise.prototype.done=function(result){if(this.complete=!0,this.result=result,this.callbacks){for(var i=0;ii;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,result){var p=new Promise;return null===promises||0===promises.length?p.done(result):promises[0](result).then(function(res){promises.splice(0,1),promises?Promise.chain(promises,res).then(function(r){p.done(r)}):p.done(res)}),p},global[name]=Promise,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Promise},global[name]}(this),function(){function addMapEntry(map,pair){return map.set(pair[0],pair[1]),map}function addSetEntry(set,value){return set.add(value),set}function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}function arrayAggregator(array,setter,iteratee,accumulator){for(var index=-1,length=array?array.length:0;++index-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1;);return index}function charsEndIndex(strSymbols,chrSymbols){for(var index=strSymbols.length;index--&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1;);return index}function countHolders(array,placeholder){for(var length=array.length,result=0;length--;)array[length]===placeholder&&++result;return result}function escapeStringChar(chr){return"\\"+stringEscapes[chr]}function getValue(object,key){return null==object?undefined:object[key]}function hasUnicode(string){return reHasUnicode.test(string)}function hasUnicodeWord(string){return reHasUnicodeWord.test(string)}function iteratorToArray(iterator){for(var data,result=[];!(data=iterator.next()).done;)result.push(data.value);return result}function mapToArray(map){var index=-1,result=Array(map.size);return map.forEach(function(value,key){result[++index]=[key,value]}),result}function overArg(func,transform){return function(arg){return func(transform(arg))}}function replaceHolders(array,placeholder){for(var index=-1,length=array.length,resIndex=0,result=[];++indexdir,arrLength=isArr?array.length:0,view=getView(0,arrLength,this.__views__),start=view.start,end=view.end,length=end-start,index=isRight?end:start-1,iteratees=this.__iteratees__,iterLength=iteratees.length,resIndex=0,takeCount=nativeMin(length,this.__takeCount__);if(!isArr||LARGE_ARRAY_SIZE>arrLength||arrLength==length&&takeCount==length)return baseWrapperValue(array,this.__actions__);var result=[];outer:for(;length--&&takeCount>resIndex;){index+=dir;for(var iterIndex=-1,value=array[index];++iterIndexindex)return!1;var lastIndex=data.length-1;return index==lastIndex?data.pop():splice.call(data,index,1),--this.size,!0}function listCacheGet(key){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?undefined:data[index][1]}function listCacheHas(key){return assocIndexOf(this.__data__,key)>-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?(++this.size,data.push([key,value])):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index=number?number:upper),lower!==undefined&&(number=number>=lower?number:lower)),number}function baseClone(value,isDeep,isFull,customizer,key,object,stack){var result;if(customizer&&(result=object?customizer(value,key,object,stack):customizer(value)),result!==undefined)return result;if(!isObject(value))return value;var isArr=isArray(value);if(isArr){if(result=initCloneArray(value),!isDeep)return copyArray(value,result)}else{var tag=getTag(value),isFunc=tag==funcTag||tag==genTag;if(isBuffer(value))return cloneBuffer(value,isDeep);if(tag==objectTag||tag==argsTag||isFunc&&!object){if(result=initCloneObject(isFunc?{}:value),!isDeep)return copySymbols(value,baseAssign(result,value))}else{if(!cloneableTags[tag])return object?value:{};result=initCloneByTag(value,tag,baseClone,isDeep)}}stack||(stack=new Stack);var stacked=stack.get(value);if(stacked)return stacked;if(stack.set(value,result),!isArr)var props=isFull?getAllKeys(value):keys(value);return arrayEach(props||value,function(subValue,key){props&&(key=subValue,subValue=value[key]),assignValue(result,key,baseClone(subValue,isDeep,isFull,customizer,key,value,stack))}),result}function baseConforms(source){var props=keys(source);return function(object){return baseConformsTo(object,source,props)}}function baseConformsTo(object,source,props){var length=props.length;if(null==object)return!length;for(object=Object(object);length--;){var key=props[length],predicate=source[key],value=object[key];if(value===undefined&&!(key in object)||!predicate(value))return!1}return!0}function baseCreate(proto){return isObject(proto)?objectCreate(proto):{}}function baseDelay(func,wait,args){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return setTimeout(function(){func.apply(undefined,args)},wait)}function baseDifference(array,values,iteratee,comparator){var index=-1,includes=arrayIncludes,isCommon=!0,length=array.length,result=[],valuesLength=values.length;if(!length)return result;iteratee&&(values=arrayMap(values,baseUnary(iteratee))),comparator?(includes=arrayIncludesWith,isCommon=!1):values.length>=LARGE_ARRAY_SIZE&&(includes=cacheHas,isCommon=!1,values=new SetCache(values));outer:for(;++indexstart&&(start=-start>length?0:length+start),end=end===undefined||end>length?length:toInteger(end),0>end&&(end+=length),end=start>end?0:toLength(end);end>start;)array[start++]=value;return array}function baseFilter(collection,predicate){var result=[];return baseEach(collection,function(value,index,collection){predicate(value,index,collection)&&result.push(value)}),result}function baseFlatten(array,depth,predicate,isStrict,result){var index=-1,length=array.length;for(predicate||(predicate=isFlattenable),result||(result=[]);++index0&&predicate(value)?depth>1?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}function baseForOwn(object,iteratee){return object&&baseFor(object,iteratee,keys)}function baseForOwnRight(object,iteratee){return object&&baseForRight(object,iteratee,keys)}function baseFunctions(object,props){return arrayFilter(props,function(key){return isFunction(object[key])})}function baseGet(object,path){path=isKey(path,object)?[path]:castPath(path);for(var index=0,length=path.length;null!=object&&length>index;)object=object[toKey(path[index++])];return index&&index==length?object:undefined}function baseGetAllKeys(object,keysFunc,symbolsFunc){var result=keysFunc(object);return isArray(object)?result:arrayPush(result,symbolsFunc(object))}function baseGetTag(value){return objectToString.call(value)}function baseGt(value,other){return value>other}function baseHas(object,key){return null!=object&&hasOwnProperty.call(object,key)}function baseHasIn(object,key){return null!=object&&key in Object(object)}function baseInRange(number,start,end){return number>=nativeMin(start,end)&&number=120&&array.length>=120)?new SetCache(othIndex&&array):undefined}array=arrays[0];var index=-1,seen=caches[0];outer:for(;++indexvalue}function baseMap(collection,iteratee){var index=-1,result=isArrayLike(collection)?Array(collection.length):[];return baseEach(collection,function(value,key,collection){result[++index]=iteratee(value,key,collection)}),result}function baseMatches(source){var matchData=getMatchData(source);return 1==matchData.length&&matchData[0][2]?matchesStrictComparable(matchData[0][0],matchData[0][1]):function(object){return object===source||baseIsMatch(object,source,matchData)}}function baseMatchesProperty(path,srcValue){return isKey(path)&&isStrictComparable(srcValue)?matchesStrictComparable(toKey(path),srcValue):function(object){var objValue=get(object,path);return objValue===undefined&&objValue===srcValue?hasIn(object,path):baseIsEqual(srcValue,objValue,undefined,UNORDERED_COMPARE_FLAG|PARTIAL_COMPARE_FLAG)}}function baseMerge(object,source,srcIndex,customizer,stack){if(object!==source){if(!isArray(source)&&!isTypedArray(source))var props=baseKeysIn(source);arrayEach(props||source,function(srcValue,key){if(props&&(key=srcValue,srcValue=source[key]),isObject(srcValue))stack||(stack=new Stack),baseMergeDeep(object,source,key,srcIndex,baseMerge,customizer,stack);else{var newValue=customizer?customizer(object[key],srcValue,key+"",object,source,stack):undefined;newValue===undefined&&(newValue=srcValue),assignMergeValue(object,key,newValue)}})}}function baseMergeDeep(object,source,key,srcIndex,mergeFunc,customizer,stack){var objValue=object[key],srcValue=source[key],stacked=stack.get(srcValue);if(stacked)return void assignMergeValue(object,key,stacked);var newValue=customizer?customizer(objValue,srcValue,key+"",object,source,stack):undefined,isCommon=newValue===undefined;isCommon&&(newValue=srcValue,isArray(srcValue)||isTypedArray(srcValue)?isArray(objValue)?newValue=objValue:isArrayLikeObject(objValue)?newValue=copyArray(objValue):(isCommon=!1,newValue=baseClone(srcValue,!0)):isPlainObject(srcValue)||isArguments(srcValue)?isArguments(objValue)?newValue=toPlainObject(objValue):!isObject(objValue)||srcIndex&&isFunction(objValue)?(isCommon=!1,newValue=baseClone(srcValue,!0)):newValue=objValue:isCommon=!1),isCommon&&(stack.set(srcValue,newValue),mergeFunc(newValue,srcValue,srcIndex,customizer,stack),stack["delete"](srcValue)),assignMergeValue(object,key,newValue)}function baseNth(array,n){var length=array.length;if(length)return n+=0>n?length:0,isIndex(n,length)?array[n]:undefined}function baseOrderBy(collection,iteratees,orders){var index=-1;iteratees=arrayMap(iteratees.length?iteratees:[identity],baseUnary(getIteratee()));var result=baseMap(collection,function(value,key,collection){var criteria=arrayMap(iteratees,function(iteratee){return iteratee(value)});return{criteria:criteria,index:++index,value:value}});return baseSortBy(result,function(object,other){return compareMultiple(object,other,orders)})}function basePick(object,props){return object=Object(object),basePickBy(object,props,function(value,key){return key in object})}function basePickBy(object,props,predicate){for(var index=-1,length=props.length,result={};++index-1;)seen!==array&&splice.call(seen,fromIndex,1),splice.call(array,fromIndex,1);return array}function basePullAt(array,indexes){for(var length=array?indexes.length:0,lastIndex=length-1;length--;){var index=indexes[length];if(length==lastIndex||index!==previous){var previous=index;if(isIndex(index))splice.call(array,index,1);else if(isKey(index,array))delete array[toKey(index)];else{var path=castPath(index),object=parent(array,path);null!=object&&delete object[toKey(last(path))]}}}return array}function baseRandom(lower,upper){return lower+nativeFloor(nativeRandom()*(upper-lower+1))}function baseRange(start,end,step,fromRight){for(var index=-1,length=nativeMax(nativeCeil((end-start)/(step||1)),0),result=Array(length);length--;)result[fromRight?length:++index]=start,start+=step;return result}function baseRepeat(string,n){var result="";if(!string||1>n||n>MAX_SAFE_INTEGER)return result;do n%2&&(result+=string),n=nativeFloor(n/2),n&&(string+=string);while(n);return result}function baseRest(func,start){return setToString(overRest(func,start,identity),func+"")}function baseSet(object,path,value,customizer){if(!isObject(object))return object;path=isKey(path,object)?[path]:castPath(path);for(var index=-1,length=path.length,lastIndex=length-1,nested=object;null!=nested&&++indexstart&&(start=-start>length?0:length+start),end=end>length?length:end,0>end&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index=high){for(;high>low;){var mid=low+high>>>1,computed=array[mid];null!==computed&&!isSymbol(computed)&&(retHighest?value>=computed:value>computed)?low=mid+1:high=mid}return high}return baseSortedIndexBy(array,value,identity,retHighest)}function baseSortedIndexBy(array,value,iteratee,retHighest){value=iteratee(value);for(var low=0,high=array?array.length:0,valIsNaN=value!==value,valIsNull=null===value,valIsSymbol=isSymbol(value),valIsUndefined=value===undefined;high>low;){var mid=nativeFloor((low+high)/2),computed=iteratee(array[mid]),othIsDefined=computed!==undefined,othIsNull=null===computed,othIsReflexive=computed===computed,othIsSymbol=isSymbol(computed);if(valIsNaN)var setLow=retHighest||othIsReflexive;else setLow=valIsUndefined?othIsReflexive&&(retHighest||othIsDefined):valIsNull?othIsReflexive&&othIsDefined&&(retHighest||!othIsNull):valIsSymbol?othIsReflexive&&othIsDefined&&!othIsNull&&(retHighest||!othIsSymbol):othIsNull||othIsSymbol?!1:retHighest?value>=computed:value>computed; setLow?low=mid+1:high=mid}return nativeMin(high,MAX_ARRAY_INDEX)}function baseSortedUniq(array,iteratee){for(var index=-1,length=array.length,resIndex=0,result=[];++index=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++indexindex?values[index]:undefined;assignFunc(result,props[index],value)}return result}function castArrayLikeObject(value){return isArrayLikeObject(value)?value:[]}function castFunction(value){return"function"==typeof value?value:identity}function castPath(value){return isArray(value)?value:stringToPath(value)}function castSlice(array,start,end){var length=array.length;return end=end===undefined?length:end,!start&&end>=length?array:baseSlice(array,start,end)}function cloneBuffer(buffer,isDeep){if(isDeep)return buffer.slice();var result=new buffer.constructor(buffer.length);return buffer.copy(result),result}function cloneArrayBuffer(arrayBuffer){var result=new arrayBuffer.constructor(arrayBuffer.byteLength);return new Uint8Array(result).set(new Uint8Array(arrayBuffer)),result}function cloneDataView(dataView,isDeep){var buffer=isDeep?cloneArrayBuffer(dataView.buffer):dataView.buffer;return new dataView.constructor(buffer,dataView.byteOffset,dataView.byteLength)}function cloneMap(map,isDeep,cloneFunc){var array=isDeep?cloneFunc(mapToArray(map),!0):mapToArray(map);return arrayReduce(array,addMapEntry,new map.constructor)}function cloneRegExp(regexp){var result=new regexp.constructor(regexp.source,reFlags.exec(regexp));return result.lastIndex=regexp.lastIndex,result}function cloneSet(set,isDeep,cloneFunc){var array=isDeep?cloneFunc(setToArray(set),!0):setToArray(set);return arrayReduce(array,addSetEntry,new set.constructor)}function cloneSymbol(symbol){return symbolValueOf?Object(symbolValueOf.call(symbol)):{}}function cloneTypedArray(typedArray,isDeep){var buffer=isDeep?cloneArrayBuffer(typedArray.buffer):typedArray.buffer;return new typedArray.constructor(buffer,typedArray.byteOffset,typedArray.length)}function compareAscending(value,other){if(value!==other){var valIsDefined=value!==undefined,valIsNull=null===value,valIsReflexive=value===value,valIsSymbol=isSymbol(value),othIsDefined=other!==undefined,othIsNull=null===other,othIsReflexive=other===other,othIsSymbol=isSymbol(other);if(!othIsNull&&!othIsSymbol&&!valIsSymbol&&value>other||valIsSymbol&&othIsDefined&&othIsReflexive&&!othIsNull&&!othIsSymbol||valIsNull&&othIsDefined&&othIsReflexive||!valIsDefined&&othIsReflexive||!valIsReflexive)return 1;if(!valIsNull&&!valIsSymbol&&!othIsSymbol&&other>value||othIsSymbol&&valIsDefined&&valIsReflexive&&!valIsNull&&!valIsSymbol||othIsNull&&valIsDefined&&valIsReflexive||!othIsDefined&&valIsReflexive||!othIsReflexive)return-1}return 0}function compareMultiple(object,other,orders){for(var index=-1,objCriteria=object.criteria,othCriteria=other.criteria,length=objCriteria.length,ordersLength=orders.length;++index=ordersLength)return result;var order=orders[index];return result*("desc"==order?-1:1)}}return object.index-other.index}function composeArgs(args,partials,holders,isCurried){for(var argsIndex=-1,argsLength=args.length,holdersLength=holders.length,leftIndex=-1,leftLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(leftLength+rangeLength),isUncurried=!isCurried;++leftIndexargsIndex)&&(result[holders[argsIndex]]=args[argsIndex]);for(;rangeLength--;)result[leftIndex++]=args[argsIndex++];return result}function composeArgsRight(args,partials,holders,isCurried){for(var argsIndex=-1,argsLength=args.length,holdersIndex=-1,holdersLength=holders.length,rightIndex=-1,rightLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(rangeLength+rightLength),isUncurried=!isCurried;++argsIndexargsIndex)&&(result[offset+holders[holdersIndex]]=args[argsIndex++]);return result}function copyArray(source,array){var index=-1,length=source.length;for(array||(array=Array(length));++index1?sources[length-1]:undefined,guard=length>2?sources[2]:undefined;for(customizer=assigner.length>3&&"function"==typeof customizer?(length--,customizer):undefined,guard&&isIterateeCall(sources[0],sources[1],guard)&&(customizer=3>length?undefined:customizer,length=1),object=Object(object);++indexlength&&args[0]!==placeholder&&args[length-1]!==placeholder?[]:replaceHolders(args,placeholder);if(length-=holders.length,arity>length)return createRecurry(func,bitmask,createHybrid,wrapper.placeholder,undefined,args,holders,undefined,undefined,arity-length);var fn=this&&this!==root&&this instanceof wrapper?Ctor:func;return apply(fn,this,args)}var Ctor=createCtor(func);return wrapper}function createFind(findIndexFunc){return function(collection,predicate,fromIndex){var iterable=Object(collection);if(!isArrayLike(collection)){var iteratee=getIteratee(predicate,3);collection=keys(collection),predicate=function(key){return iteratee(iterable[key],key,iterable)}}var index=findIndexFunc(collection,predicate,fromIndex);return index>-1?iterable[iteratee?collection[index]:index]:undefined}}function createFlow(fromRight){return flatRest(function(funcs){var length=funcs.length,index=length,prereq=LodashWrapper.prototype.thru;for(fromRight&&funcs.reverse();index--;){var func=funcs[index];if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);if(prereq&&!wrapper&&"wrapper"==getFuncName(func))var wrapper=new LodashWrapper([],!0)}for(index=wrapper?index:length;++index=LARGE_ARRAY_SIZE)return wrapper.plant(value).value();for(var index=0,result=length?funcs[index].apply(this,args):value;++indexlength){var newHolders=replaceHolders(args,placeholder);return createRecurry(func,bitmask,createHybrid,wrapper.placeholder,thisArg,args,newHolders,argPos,ary,arity-length)}var thisBinding=isBind?thisArg:this,fn=isBindKey?thisBinding[func]:func;return length=args.length,argPos?args=reorder(args,argPos):isFlip&&length>1&&args.reverse(),isAry&&length>ary&&(args.length=ary),this&&this!==root&&this instanceof wrapper&&(fn=Ctor||createCtor(fn)),fn.apply(thisBinding,args)}var isAry=bitmask&ARY_FLAG,isBind=bitmask&BIND_FLAG,isBindKey=bitmask&BIND_KEY_FLAG,isCurried=bitmask&(CURRY_FLAG|CURRY_RIGHT_FLAG),isFlip=bitmask&FLIP_FLAG,Ctor=isBindKey?undefined:createCtor(func);return wrapper}function createInverter(setter,toIteratee){return function(object,iteratee){return baseInverter(object,setter,toIteratee(iteratee),{})}}function createMathOperation(operator,defaultValue){return function(value,other){var result;if(value===undefined&&other===undefined)return defaultValue;if(value!==undefined&&(result=value),other!==undefined){if(result===undefined)return other;"string"==typeof value||"string"==typeof other?(value=baseToString(value),other=baseToString(other)):(value=baseToNumber(value),other=baseToNumber(other)),result=operator(value,other)}return result}}function createOver(arrayFunc){return flatRest(function(iteratees){return iteratees=arrayMap(iteratees,baseUnary(getIteratee())),baseRest(function(args){var thisArg=this;return arrayFunc(iteratees,function(iteratee){return apply(iteratee,thisArg,args)})})})}function createPadding(length,chars){chars=chars===undefined?" ":baseToString(chars);var charsLength=chars.length;if(2>charsLength)return charsLength?baseRepeat(chars,length):chars;var result=baseRepeat(chars,nativeCeil(length/stringSize(chars)));return hasUnicode(chars)?castSlice(stringToArray(result),0,length).join(""):result.slice(0,length)}function createPartial(func,bitmask,thisArg,partials){function wrapper(){for(var argsIndex=-1,argsLength=arguments.length,leftIndex=-1,leftLength=partials.length,args=Array(leftLength+argsLength),fn=this&&this!==root&&this instanceof wrapper?Ctor:func;++leftIndexstart?1:-1:toFinite(step),baseRange(start,end,step,fromRight)}}function createRelationalOperation(operator){return function(value,other){return("string"!=typeof value||"string"!=typeof other)&&(value=toNumber(value),other=toNumber(other)),operator(value,other)}}function createRecurry(func,bitmask,wrapFunc,placeholder,thisArg,partials,holders,argPos,ary,arity){var isCurry=bitmask&CURRY_FLAG,newHolders=isCurry?holders:undefined,newHoldersRight=isCurry?undefined:holders,newPartials=isCurry?partials:undefined,newPartialsRight=isCurry?undefined:partials;bitmask|=isCurry?PARTIAL_FLAG:PARTIAL_RIGHT_FLAG,bitmask&=~(isCurry?PARTIAL_RIGHT_FLAG:PARTIAL_FLAG),bitmask&CURRY_BOUND_FLAG||(bitmask&=~(BIND_FLAG|BIND_KEY_FLAG));var newData=[func,bitmask,thisArg,newPartials,newHolders,newPartialsRight,newHoldersRight,argPos,ary,arity],result=wrapFunc.apply(undefined,newData);return isLaziable(func)&&setData(result,newData),result.placeholder=placeholder,setWrapToString(result,func,bitmask)}function createRound(methodName){var func=Math[methodName];return function(number,precision){if(number=toNumber(number),precision=nativeMin(toInteger(precision),292)){var pair=(toString(number)+"e").split("e"),value=func(pair[0]+"e"+(+pair[1]+precision));return pair=(toString(value)+"e").split("e"),+(pair[0]+"e"+(+pair[1]-precision))}return func(number)}}function createToPairs(keysFunc){return function(object){var tag=getTag(object);return tag==mapTag?mapToArray(object):tag==setTag?setToPairs(object):baseToPairs(object,keysFunc(object))}}function createWrap(func,bitmask,thisArg,partials,holders,argPos,ary,arity){var isBindKey=bitmask&BIND_KEY_FLAG;if(!isBindKey&&"function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);var length=partials?partials.length:0;if(length||(bitmask&=~(PARTIAL_FLAG|PARTIAL_RIGHT_FLAG),partials=holders=undefined),ary=ary===undefined?ary:nativeMax(toInteger(ary),0),arity=arity===undefined?arity:toInteger(arity),length-=holders?holders.length:0,bitmask&PARTIAL_RIGHT_FLAG){var partialsRight=partials,holdersRight=holders;partials=holders=undefined}var data=isBindKey?undefined:getData(func),newData=[func,bitmask,thisArg,partials,holders,partialsRight,holdersRight,argPos,ary,arity];if(data&&mergeData(newData,data),func=newData[0],bitmask=newData[1],thisArg=newData[2],partials=newData[3],holders=newData[4],arity=newData[9]=null==newData[9]?isBindKey?0:func.length:nativeMax(newData[9]-length,0),!arity&&bitmask&(CURRY_FLAG|CURRY_RIGHT_FLAG)&&(bitmask&=~(CURRY_FLAG|CURRY_RIGHT_FLAG)),bitmask&&bitmask!=BIND_FLAG)result=bitmask==CURRY_FLAG||bitmask==CURRY_RIGHT_FLAG?createCurry(func,bitmask,arity):bitmask!=PARTIAL_FLAG&&bitmask!=(BIND_FLAG|PARTIAL_FLAG)||holders.length?createHybrid.apply(undefined,newData):createPartial(func,bitmask,thisArg,partials);else var result=createBind(func,bitmask,thisArg);var setter=data?baseSetData:setData;return setWrapToString(setter(result,newData),func,bitmask)}function equalArrays(array,other,equalFunc,customizer,bitmask,stack){var isPartial=bitmask&PARTIAL_COMPARE_FLAG,arrLength=array.length,othLength=other.length;if(arrLength!=othLength&&!(isPartial&&othLength>arrLength))return!1;var stacked=stack.get(array);if(stacked&&stack.get(other))return stacked==other;var index=-1,result=!0,seen=bitmask&UNORDERED_COMPARE_FLAG?new SetCache:undefined;for(stack.set(array,other),stack.set(other,array);++index1?"& ":"")+details[lastIndex],details=details.join(length>2?", ":" "),source.replace(reWrapComment,"{\n/* [wrapped with "+details+"] */\n")}function isFlattenable(value){return isArray(value)||isArguments(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol])}function isIndex(value,length){return length=null==length?MAX_SAFE_INTEGER:length,!!length&&("number"==typeof value||reIsUint.test(value))&&value>-1&&value%1==0&&length>value}function isIterateeCall(value,index,object){if(!isObject(object))return!1;var type=typeof index;return("number"==type?isArrayLike(object)&&isIndex(index,object.length):"string"==type&&index in object)?eq(object[index],value):!1}function isKey(value,object){if(isArray(value))return!1;var type=typeof value;return"number"==type||"symbol"==type||"boolean"==type||null==value||isSymbol(value)?!0:reIsPlainProp.test(value)||!reIsDeepProp.test(value)||null!=object&&value in Object(object)}function isKeyable(value){var type=typeof value;return"string"==type||"number"==type||"symbol"==type||"boolean"==type?"__proto__"!==value:null===value}function isLaziable(func){var funcName=getFuncName(func),other=lodash[funcName];if("function"!=typeof other||!(funcName in LazyWrapper.prototype))return!1;if(func===other)return!0;var data=getData(other);return!!data&&func===data[0]}function isMasked(func){return!!maskSrcKey&&maskSrcKey in func}function isPrototype(value){var Ctor=value&&value.constructor,proto="function"==typeof Ctor&&Ctor.prototype||objectProto;return value===proto}function isStrictComparable(value){return value===value&&!isObject(value)}function matchesStrictComparable(key,srcValue){return function(object){return null==object?!1:object[key]===srcValue&&(srcValue!==undefined||key in Object(object))}}function memoizeCapped(func){var result=memoize(func,function(key){return cache.size===MAX_MEMOIZE_SIZE&&cache.clear(),key}),cache=result.cache;return result}function mergeData(data,source){var bitmask=data[1],srcBitmask=source[1],newBitmask=bitmask|srcBitmask,isCommon=(BIND_FLAG|BIND_KEY_FLAG|ARY_FLAG)>newBitmask,isCombo=srcBitmask==ARY_FLAG&&bitmask==CURRY_FLAG||srcBitmask==ARY_FLAG&&bitmask==REARG_FLAG&&data[7].length<=source[8]||srcBitmask==(ARY_FLAG|REARG_FLAG)&&source[7].length<=source[8]&&bitmask==CURRY_FLAG;if(!isCommon&&!isCombo)return data;srcBitmask&BIND_FLAG&&(data[2]=source[2],newBitmask|=bitmask&BIND_FLAG?0:CURRY_BOUND_FLAG);var value=source[3];if(value){var partials=data[3];data[3]=partials?composeArgs(partials,value,source[4]):value,data[4]=partials?replaceHolders(data[3],PLACEHOLDER):source[4]}return value=source[5],value&&(partials=data[5],data[5]=partials?composeArgsRight(partials,value,source[6]):value,data[6]=partials?replaceHolders(data[5],PLACEHOLDER):source[6]),value=source[7],value&&(data[7]=value),srcBitmask&ARY_FLAG&&(data[8]=null==data[8]?source[8]:nativeMin(data[8],source[8])),null==data[9]&&(data[9]=source[9]),data[0]=source[0],data[1]=newBitmask,data}function mergeDefaults(objValue,srcValue,key,object,source,stack){return isObject(objValue)&&isObject(srcValue)&&(stack.set(srcValue,objValue),baseMerge(objValue,srcValue,undefined,mergeDefaults,stack),stack["delete"](srcValue)),objValue}function nativeKeysIn(object){var result=[];if(null!=object)for(var key in Object(object))result.push(key);return result}function overRest(func,start,transform){return start=nativeMax(start===undefined?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index0){if(++count>=HOT_COUNT)return arguments[0]}else count=0;return func.apply(undefined,arguments)}}function shuffleSelf(array){for(var index=-1,length=array.length,lastIndex=length-1;++indexsize)return[];for(var index=0,resIndex=0,result=Array(nativeCeil(length/size));length>index;)result[resIndex++]=baseSlice(array,index,index+=size);return result}function compact(array){for(var index=-1,length=array?array.length:0,resIndex=0,result=[];++indexn?0:n,length)):[]}function dropRight(array,n,guard){var length=array?array.length:0;return length?(n=guard||n===undefined?1:toInteger(n),n=length-n,baseSlice(array,0,0>n?0:n)):[]}function dropRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!0,!0):[]}function dropWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!0):[]}function fill(array,value,start,end){var length=array?array.length:0;return length?(start&&"number"!=typeof start&&isIterateeCall(array,value,start)&&(start=0,end=length),baseFill(array,value,start,end)):[]}function findIndex(array,predicate,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=null==fromIndex?0:toInteger(fromIndex);return 0>index&&(index=nativeMax(length+index,0)), baseFindIndex(array,getIteratee(predicate,3),index)}function findLastIndex(array,predicate,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=length-1;return fromIndex!==undefined&&(index=toInteger(fromIndex),index=0>fromIndex?nativeMax(length+index,0):nativeMin(index,length-1)),baseFindIndex(array,getIteratee(predicate,3),index,!0)}function flatten(array){var length=array?array.length:0;return length?baseFlatten(array,1):[]}function flattenDeep(array){var length=array?array.length:0;return length?baseFlatten(array,INFINITY):[]}function flattenDepth(array,depth){var length=array?array.length:0;return length?(depth=depth===undefined?1:toInteger(depth),baseFlatten(array,depth)):[]}function fromPairs(pairs){for(var index=-1,length=pairs?pairs.length:0,result={};++indexindex&&(index=nativeMax(length+index,0)),baseIndexOf(array,value,index)}function initial(array){var length=array?array.length:0;return length?baseSlice(array,0,-1):[]}function join(array,separator){return array?nativeJoin.call(array,separator):""}function last(array){var length=array?array.length:0;return length?array[length-1]:undefined}function lastIndexOf(array,value,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=length;return fromIndex!==undefined&&(index=toInteger(fromIndex),index=0>index?nativeMax(length+index,0):nativeMin(index,length-1)),value===value?strictLastIndexOf(array,value,index):baseFindIndex(array,baseIsNaN,index,!0)}function nth(array,n){return array&&array.length?baseNth(array,toInteger(n)):undefined}function pullAll(array,values){return array&&array.length&&values&&values.length?basePullAll(array,values):array}function pullAllBy(array,values,iteratee){return array&&array.length&&values&&values.length?basePullAll(array,values,getIteratee(iteratee,2)):array}function pullAllWith(array,values,comparator){return array&&array.length&&values&&values.length?basePullAll(array,values,undefined,comparator):array}function remove(array,predicate){var result=[];if(!array||!array.length)return result;var index=-1,indexes=[],length=array.length;for(predicate=getIteratee(predicate,3);++indexindex&&eq(array[index],value))return index}return-1}function sortedLastIndex(array,value){return baseSortedIndex(array,value,!0)}function sortedLastIndexBy(array,value,iteratee){return baseSortedIndexBy(array,value,getIteratee(iteratee,2),!0)}function sortedLastIndexOf(array,value){var length=array?array.length:0;if(length){var index=baseSortedIndex(array,value,!0)-1;if(eq(array[index],value))return index}return-1}function sortedUniq(array){return array&&array.length?baseSortedUniq(array):[]}function sortedUniqBy(array,iteratee){return array&&array.length?baseSortedUniq(array,getIteratee(iteratee,2)):[]}function tail(array){var length=array?array.length:0;return length?baseSlice(array,1,length):[]}function take(array,n,guard){return array&&array.length?(n=guard||n===undefined?1:toInteger(n),baseSlice(array,0,0>n?0:n)):[]}function takeRight(array,n,guard){var length=array?array.length:0;return length?(n=guard||n===undefined?1:toInteger(n),n=length-n,baseSlice(array,0>n?0:n,length)):[]}function takeRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!1,!0):[]}function takeWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3)):[]}function uniq(array){return array&&array.length?baseUniq(array):[]}function uniqBy(array,iteratee){return array&&array.length?baseUniq(array,getIteratee(iteratee,2)):[]}function uniqWith(array,comparator){return array&&array.length?baseUniq(array,undefined,comparator):[]}function unzip(array){if(!array||!array.length)return[];var length=0;return array=arrayFilter(array,function(group){return isArrayLikeObject(group)?(length=nativeMax(group.length,length),!0):void 0}),baseTimes(length,function(index){return arrayMap(array,baseProperty(index))})}function unzipWith(array,iteratee){if(!array||!array.length)return[];var result=unzip(array);return null==iteratee?result:arrayMap(result,function(group){return apply(iteratee,undefined,group)})}function zipObject(props,values){return baseZipObject(props||[],values||[],assignValue)}function zipObjectDeep(props,values){return baseZipObject(props||[],values||[],baseSet)}function chain(value){var result=lodash(value);return result.__chain__=!0,result}function tap(value,interceptor){return interceptor(value),value}function thru(value,interceptor){return interceptor(value)}function wrapperChain(){return chain(this)}function wrapperCommit(){return new LodashWrapper(this.value(),this.__chain__)}function wrapperNext(){this.__values__===undefined&&(this.__values__=toArray(this.value()));var done=this.__index__>=this.__values__.length,value=done?undefined:this.__values__[this.__index__++];return{done:done,value:value}}function wrapperToIterator(){return this}function wrapperPlant(value){for(var result,parent=this;parent instanceof baseLodash;){var clone=wrapperClone(parent);clone.__index__=0,clone.__values__=undefined,result?previous.__wrapped__=clone:result=clone;var previous=clone;parent=parent.__wrapped__}return previous.__wrapped__=value,result}function wrapperReverse(){var value=this.__wrapped__;if(value instanceof LazyWrapper){var wrapped=value;return this.__actions__.length&&(wrapped=new LazyWrapper(this)),wrapped=wrapped.reverse(),wrapped.__actions__.push({func:thru,args:[reverse],thisArg:undefined}),new LodashWrapper(wrapped,this.__chain__)}return this.thru(reverse)}function wrapperValue(){return baseWrapperValue(this.__wrapped__,this.__actions__)}function every(collection,predicate,guard){var func=isArray(collection)?arrayEvery:baseEvery;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=undefined),func(collection,getIteratee(predicate,3))}function filter(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,getIteratee(predicate,3))}function flatMap(collection,iteratee){return baseFlatten(map(collection,iteratee),1)}function flatMapDeep(collection,iteratee){return baseFlatten(map(collection,iteratee),INFINITY)}function flatMapDepth(collection,iteratee,depth){return depth=depth===undefined?1:toInteger(depth),baseFlatten(map(collection,iteratee),depth)}function forEach(collection,iteratee){var func=isArray(collection)?arrayEach:baseEach;return func(collection,getIteratee(iteratee,3))}function forEachRight(collection,iteratee){var func=isArray(collection)?arrayEachRight:baseEachRight;return func(collection,getIteratee(iteratee,3))}function includes(collection,value,fromIndex,guard){collection=isArrayLike(collection)?collection:values(collection),fromIndex=fromIndex&&!guard?toInteger(fromIndex):0;var length=collection.length;return 0>fromIndex&&(fromIndex=nativeMax(length+fromIndex,0)),isString(collection)?length>=fromIndex&&collection.indexOf(value,fromIndex)>-1:!!length&&baseIndexOf(collection,value,fromIndex)>-1}function map(collection,iteratee){var func=isArray(collection)?arrayMap:baseMap;return func(collection,getIteratee(iteratee,3))}function orderBy(collection,iteratees,orders,guard){return null==collection?[]:(isArray(iteratees)||(iteratees=null==iteratees?[]:[iteratees]),orders=guard?undefined:orders,isArray(orders)||(orders=null==orders?[]:[orders]),baseOrderBy(collection,iteratees,orders))}function reduce(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduce:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEach)}function reduceRight(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduceRight:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEachRight)}function reject(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,negate(getIteratee(predicate,3)))}function sample(collection){return arraySample(isArrayLike(collection)?collection:values(collection))}function sampleSize(collection,n,guard){return n=(guard?isIterateeCall(collection,n,guard):n===undefined)?1:toInteger(n),arraySampleSize(isArrayLike(collection)?collection:values(collection),n)}function shuffle(collection){return shuffleSelf(isArrayLike(collection)?copyArray(collection):values(collection))}function size(collection){if(null==collection)return 0;if(isArrayLike(collection))return isString(collection)?stringSize(collection):collection.length;var tag=getTag(collection);return tag==mapTag||tag==setTag?collection.size:baseKeys(collection).length}function some(collection,predicate,guard){var func=isArray(collection)?arraySome:baseSome;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=undefined),func(collection,getIteratee(predicate,3))}function after(n,func){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return n=toInteger(n),function(){return--n<1?func.apply(this,arguments):void 0}}function ary(func,n,guard){return n=guard?undefined:n,n=func&&null==n?func.length:n,createWrap(func,ARY_FLAG,undefined,undefined,undefined,undefined,n)}function before(n,func){var result;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return n=toInteger(n),function(){return--n>0&&(result=func.apply(this,arguments)),1>=n&&(func=undefined),result}}function curry(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,CURRY_FLAG,undefined,undefined,undefined,undefined,undefined,arity);return result.placeholder=curry.placeholder,result}function curryRight(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,CURRY_RIGHT_FLAG,undefined,undefined,undefined,undefined,undefined,arity);return result.placeholder=curryRight.placeholder,result}function debounce(func,wait,options){function invokeFunc(time){var args=lastArgs,thisArg=lastThis;return lastArgs=lastThis=undefined,lastInvokeTime=time,result=func.apply(thisArg,args)}function leadingEdge(time){return lastInvokeTime=time,timerId=setTimeout(timerExpired,wait),leading?invokeFunc(time):result}function remainingWait(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime,result=wait-timeSinceLastCall;return maxing?nativeMin(result,maxWait-timeSinceLastInvoke):result}function shouldInvoke(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime;return lastCallTime===undefined||timeSinceLastCall>=wait||0>timeSinceLastCall||maxing&&timeSinceLastInvoke>=maxWait}function timerExpired(){var time=now();return shouldInvoke(time)?trailingEdge(time):void(timerId=setTimeout(timerExpired,remainingWait(time)))}function trailingEdge(time){return timerId=undefined,trailing&&lastArgs?invokeFunc(time):(lastArgs=lastThis=undefined,result)}function cancel(){timerId!==undefined&&clearTimeout(timerId),lastInvokeTime=0,lastArgs=lastCallTime=lastThis=timerId=undefined}function flush(){return timerId===undefined?result:trailingEdge(now())}function debounced(){var time=now(),isInvoking=shouldInvoke(time);if(lastArgs=arguments,lastThis=this,lastCallTime=time,isInvoking){if(timerId===undefined)return leadingEdge(lastCallTime);if(maxing)return timerId=setTimeout(timerExpired,wait),invokeFunc(lastCallTime)}return timerId===undefined&&(timerId=setTimeout(timerExpired,wait)),result}var lastArgs,lastThis,maxWait,result,timerId,lastCallTime,lastInvokeTime=0,leading=!1,maxing=!1,trailing=!0;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return wait=toNumber(wait)||0,isObject(options)&&(leading=!!options.leading,maxing="maxWait"in options,maxWait=maxing?nativeMax(toNumber(options.maxWait)||0,wait):maxWait,trailing="trailing"in options?!!options.trailing:trailing),debounced.cancel=cancel,debounced.flush=flush,debounced}function flip(func){return createWrap(func,FLIP_FLAG)}function memoize(func,resolver){if("function"!=typeof func||resolver&&"function"!=typeof resolver)throw new TypeError(FUNC_ERROR_TEXT);var memoized=function(){var args=arguments,key=resolver?resolver.apply(this,args):args[0],cache=memoized.cache;if(cache.has(key))return cache.get(key);var result=func.apply(this,args);return memoized.cache=cache.set(key,result)||cache,result};return memoized.cache=new(memoize.Cache||MapCache),memoized}function negate(predicate){if("function"!=typeof predicate)throw new TypeError(FUNC_ERROR_TEXT);return function(){var args=arguments;switch(args.length){case 0:return!predicate.call(this);case 1:return!predicate.call(this,args[0]);case 2:return!predicate.call(this,args[0],args[1]);case 3:return!predicate.call(this,args[0],args[1],args[2])}return!predicate.apply(this,args)}}function once(func){return before(2,func)}function rest(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=start===undefined?start:toInteger(start),baseRest(func,start)}function spread(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=start===undefined?0:nativeMax(toInteger(start),0),baseRest(function(args){var array=args[start],otherArgs=castSlice(args,0,start);return array&&arrayPush(otherArgs,array),apply(func,this,otherArgs)})}function throttle(func,wait,options){var leading=!0,trailing=!0;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return isObject(options)&&(leading="leading"in options?!!options.leading:leading,trailing="trailing"in options?!!options.trailing:trailing),debounce(func,wait,{leading:leading,maxWait:wait,trailing:trailing})}function unary(func){return ary(func,1)}function wrap(value,wrapper){return wrapper=null==wrapper?identity:wrapper,partial(wrapper,value)}function castArray(){if(!arguments.length)return[];var value=arguments[0];return isArray(value)?value:[value]}function clone(value){return baseClone(value,!1,!0)}function cloneWith(value,customizer){return baseClone(value,!1,!0,customizer)}function cloneDeep(value){return baseClone(value,!0,!0)}function cloneDeepWith(value,customizer){return baseClone(value,!0,!0,customizer)}function conformsTo(object,source){return null==source||baseConformsTo(object,source,keys(source))}function eq(value,other){return value===other||value!==value&&other!==other}function isArguments(value){return isArrayLikeObject(value)&&hasOwnProperty.call(value,"callee")&&(!propertyIsEnumerable.call(value,"callee")||objectToString.call(value)==argsTag)}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value)}function isBoolean(value){return value===!0||value===!1||isObjectLike(value)&&objectToString.call(value)==boolTag}function isElement(value){return null!=value&&1===value.nodeType&&isObjectLike(value)&&!isPlainObject(value)}function isEmpty(value){if(isArrayLike(value)&&(isArray(value)||"string"==typeof value||"function"==typeof value.splice||isBuffer(value)||isArguments(value)))return!value.length;var tag=getTag(value);if(tag==mapTag||tag==setTag)return!value.size;if(isPrototype(value))return!nativeKeys(value).length;for(var key in value)if(hasOwnProperty.call(value,key))return!1;return!0}function isEqual(value,other){return baseIsEqual(value,other)}function isEqualWith(value,other,customizer){customizer="function"==typeof customizer?customizer:undefined;var result=customizer?customizer(value,other):undefined;return result===undefined?baseIsEqual(value,other,customizer):!!result}function isError(value){return isObjectLike(value)?objectToString.call(value)==errorTag||"string"==typeof value.message&&"string"==typeof value.name:!1}function isFinite(value){return"number"==typeof value&&nativeIsFinite(value)}function isFunction(value){var tag=isObject(value)?objectToString.call(value):"";return tag==funcTag||tag==genTag}function isInteger(value){return"number"==typeof value&&value==toInteger(value)}function isLength(value){return"number"==typeof value&&value>-1&&value%1==0&&MAX_SAFE_INTEGER>=value}function isObject(value){var type=typeof value;return null!=value&&("object"==type||"function"==type)}function isObjectLike(value){return null!=value&&"object"==typeof value}function isMatch(object,source){return object===source||baseIsMatch(object,source,getMatchData(source))}function isMatchWith(object,source,customizer){return customizer="function"==typeof customizer?customizer:undefined,baseIsMatch(object,source,getMatchData(source),customizer)}function isNaN(value){return isNumber(value)&&value!=+value}function isNative(value){if(isMaskable(value))throw new Error("This method is not supported with core-js. Try https://github.com/es-shims.");return baseIsNative(value)}function isNull(value){return null===value}function isNil(value){return null==value}function isNumber(value){return"number"==typeof value||isObjectLike(value)&&objectToString.call(value)==numberTag}function isPlainObject(value){if(!isObjectLike(value)||objectToString.call(value)!=objectTag)return!1;var proto=getPrototype(value);if(null===proto)return!0;var Ctor=hasOwnProperty.call(proto,"constructor")&&proto.constructor;return"function"==typeof Ctor&&Ctor instanceof Ctor&&funcToString.call(Ctor)==objectCtorString}function isSafeInteger(value){return isInteger(value)&&value>=-MAX_SAFE_INTEGER&&MAX_SAFE_INTEGER>=value}function isString(value){return"string"==typeof value||!isArray(value)&&isObjectLike(value)&&objectToString.call(value)==stringTag}function isSymbol(value){return"symbol"==typeof value||isObjectLike(value)&&objectToString.call(value)==symbolTag}function isUndefined(value){return value===undefined}function isWeakMap(value){return isObjectLike(value)&&getTag(value)==weakMapTag}function isWeakSet(value){return isObjectLike(value)&&objectToString.call(value)==weakSetTag}function toArray(value){if(!value)return[];if(isArrayLike(value))return isString(value)?stringToArray(value):copyArray(value);if(iteratorSymbol&&value[iteratorSymbol])return iteratorToArray(value[iteratorSymbol]());var tag=getTag(value),func=tag==mapTag?mapToArray:tag==setTag?setToArray:values;return func(value)}function toFinite(value){if(!value)return 0===value?value:0;if(value=toNumber(value),value===INFINITY||value===-INFINITY){var sign=0>value?-1:1;return sign*MAX_INTEGER}return value===value?value:0}function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0}function toLength(value){return value?baseClamp(toInteger(value),0,MAX_ARRAY_LENGTH):0}function toNumber(value){if("number"==typeof value)return value;if(isSymbol(value))return NAN;if(isObject(value)){var other="function"==typeof value.valueOf?value.valueOf():value;value=isObject(other)?other+"":other}if("string"!=typeof value)return 0===value?value:+value;value=value.replace(reTrim,"");var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value}function toPlainObject(value){return copyObject(value,keysIn(value))}function toSafeInteger(value){return baseClamp(toInteger(value),-MAX_SAFE_INTEGER,MAX_SAFE_INTEGER)}function toString(value){return null==value?"":baseToString(value)}function create(prototype,properties){var result=baseCreate(prototype);return properties?baseAssign(result,properties):result}function findKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwn)}function findLastKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwnRight)}function forIn(object,iteratee){return null==object?object:baseFor(object,getIteratee(iteratee,3),keysIn)}function forInRight(object,iteratee){return null==object?object:baseForRight(object,getIteratee(iteratee,3),keysIn)}function forOwn(object,iteratee){return object&&baseForOwn(object,getIteratee(iteratee,3))}function forOwnRight(object,iteratee){return object&&baseForOwnRight(object,getIteratee(iteratee,3))}function functions(object){return null==object?[]:baseFunctions(object,keys(object))}function functionsIn(object){return null==object?[]:baseFunctions(object,keysIn(object))}function get(object,path,defaultValue){var result=null==object?undefined:baseGet(object,path);return result===undefined?defaultValue:result}function has(object,path){return null!=object&&hasPath(object,path,baseHas)}function hasIn(object,path){return null!=object&&hasPath(object,path,baseHasIn)}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function keysIn(object){return isArrayLike(object)?arrayLikeKeys(object,!0):baseKeysIn(object)}function mapKeys(object,iteratee){var result={};return iteratee=getIteratee(iteratee,3),baseForOwn(object,function(value,key,object){baseAssignValue(result,iteratee(value,key,object),value)}),result}function mapValues(object,iteratee){var result={};return iteratee=getIteratee(iteratee,3),baseForOwn(object,function(value,key,object){baseAssignValue(result,key,iteratee(value,key,object))}),result}function omitBy(object,predicate){return pickBy(object,negate(getIteratee(predicate)))}function pickBy(object,predicate){return null==object?{}:basePickBy(object,getAllKeysIn(object),getIteratee(predicate))}function result(object,path,defaultValue){path=isKey(path,object)?[path]:castPath(path);var index=-1,length=path.length;for(length||(object=undefined,length=1);++indexupper){var temp=lower;lower=upper,upper=temp}if(floating||lower%1||upper%1){var rand=nativeRandom();return nativeMin(lower+rand*(upper-lower+freeParseFloat("1e-"+((rand+"").length-1))),upper)}return baseRandom(lower,upper)}function capitalize(string){return upperFirst(toString(string).toLowerCase())}function deburr(string){return string=toString(string),string&&string.replace(reLatin,deburrLetter).replace(reComboMark,"")}function endsWith(string,target,position){string=toString(string),target=baseToString(target);var length=string.length;position=position===undefined?length:baseClamp(toInteger(position),0,length);var end=position;return position-=target.length,position>=0&&string.slice(position,end)==target}function escape(string){return string=toString(string),string&&reHasUnescapedHtml.test(string)?string.replace(reUnescapedHtml,escapeHtmlChar):string}function escapeRegExp(string){return string=toString(string),string&&reHasRegExpChar.test(string)?string.replace(reRegExpChar,"\\$&"):string}function pad(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;if(!length||strLength>=length)return string;var mid=(length-strLength)/2;return createPadding(nativeFloor(mid),chars)+string+createPadding(nativeCeil(mid),chars)}function padEnd(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;return length&&length>strLength?string+createPadding(length-strLength,chars):string}function padStart(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;return length&&length>strLength?createPadding(length-strLength,chars)+string:string}function parseInt(string,radix,guard){return guard||null==radix?radix=0:radix&&(radix=+radix),nativeParseInt(toString(string),radix||0)}function repeat(string,n,guard){return n=(guard?isIterateeCall(string,n,guard):n===undefined)?1:toInteger(n),baseRepeat(toString(string),n)}function replace(){var args=arguments,string=toString(args[0]);return args.length<3?string:string.replace(args[1],args[2])}function split(string,separator,limit){return limit&&"number"!=typeof limit&&isIterateeCall(string,separator,limit)&&(separator=limit=undefined),(limit=limit===undefined?MAX_ARRAY_LENGTH:limit>>>0)?(string=toString(string),string&&("string"==typeof separator||null!=separator&&!isRegExp(separator))&&(separator=baseToString(separator),!separator&&hasUnicode(string))?castSlice(stringToArray(string),0,limit):string.split(separator,limit)):[]}function startsWith(string,target,position){return string=toString(string),position=baseClamp(toInteger(position),0,string.length),target=baseToString(target),string.slice(position,position+target.length)==target}function template(string,options,guard){var settings=lodash.templateSettings;guard&&isIterateeCall(string,options,guard)&&(options=undefined),string=toString(string),options=assignInWith({},options,settings,assignInDefaults);var isEscaping,isEvaluating,imports=assignInWith({},options.imports,settings.imports,assignInDefaults),importsKeys=keys(imports),importsValues=baseValues(imports,importsKeys),index=0,interpolate=options.interpolate||reNoMatch,source="__p += '",reDelimiters=RegExp((options.escape||reNoMatch).source+"|"+interpolate.source+"|"+(interpolate===reInterpolate?reEsTemplate:reNoMatch).source+"|"+(options.evaluate||reNoMatch).source+"|$","g"),sourceURL="//# sourceURL="+("sourceURL"in options?options.sourceURL:"lodash.templateSources["+ ++templateCounter+"]")+"\n";string.replace(reDelimiters,function(match,escapeValue,interpolateValue,esTemplateValue,evaluateValue,offset){return interpolateValue||(interpolateValue=esTemplateValue),source+=string.slice(index,offset).replace(reUnescapedString,escapeStringChar),escapeValue&&(isEscaping=!0,source+="' +\n__e("+escapeValue+") +\n'"),evaluateValue&&(isEvaluating=!0,source+="';\n"+evaluateValue+";\n__p += '"),interpolateValue&&(source+="' +\n((__t = ("+interpolateValue+")) == null ? '' : __t) +\n'"),index=offset+match.length,match}),source+="';\n";var variable=options.variable;variable||(source="with (obj) {\n"+source+"\n}\n"),source=(isEvaluating?source.replace(reEmptyStringLeading,""):source).replace(reEmptyStringMiddle,"$1").replace(reEmptyStringTrailing,"$1;"),source="function("+(variable||"obj")+") {\n"+(variable?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(isEscaping?", __e = _.escape":"")+(isEvaluating?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+source+"return __p\n}";var result=attempt(function(){return Function(importsKeys,sourceURL+"return "+source).apply(undefined,importsValues)});if(result.source=source,isError(result))throw result;return result}function toLower(value){return toString(value).toLowerCase()}function toUpper(value){return toString(value).toUpperCase()}function trim(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrim,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),chrSymbols=stringToArray(chars),start=charsStartIndex(strSymbols,chrSymbols),end=charsEndIndex(strSymbols,chrSymbols)+1;return castSlice(strSymbols,start,end).join("")}function trimEnd(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrimEnd,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),end=charsEndIndex(strSymbols,stringToArray(chars))+1;return castSlice(strSymbols,0,end).join("")}function trimStart(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrimStart,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),start=charsStartIndex(strSymbols,stringToArray(chars));return castSlice(strSymbols,start).join("")}function truncate(string,options){var length=DEFAULT_TRUNC_LENGTH,omission=DEFAULT_TRUNC_OMISSION;if(isObject(options)){var separator="separator"in options?options.separator:separator;length="length"in options?toInteger(options.length):length,omission="omission"in options?baseToString(options.omission):omission}string=toString(string);var strLength=string.length;if(hasUnicode(string)){var strSymbols=stringToArray(string);strLength=strSymbols.length}if(length>=strLength)return string;var end=length-stringSize(omission);if(1>end)return omission;var result=strSymbols?castSlice(strSymbols,0,end).join(""):string.slice(0,end);if(separator===undefined)return result+omission;if(strSymbols&&(end+=result.length-end),isRegExp(separator)){if(string.slice(end).search(separator)){var match,substring=result;for(separator.global||(separator=RegExp(separator.source,toString(reFlags.exec(separator))+"g")),separator.lastIndex=0;match=separator.exec(substring);)var newEnd=match.index;result=result.slice(0,newEnd===undefined?end:newEnd)}}else if(string.indexOf(baseToString(separator),end)!=end){var index=result.lastIndexOf(separator);index>-1&&(result=result.slice(0,index))}return result+omission}function unescape(string){return string=toString(string),string&&reHasEscapedHtml.test(string)?string.replace(reEscapedHtml,unescapeHtmlChar):string}function words(string,pattern,guard){ return string=toString(string),pattern=guard?undefined:pattern,pattern===undefined?hasUnicodeWord(string)?unicodeWords(string):asciiWords(string):string.match(pattern)||[]}function cond(pairs){var length=pairs?pairs.length:0,toIteratee=getIteratee();return pairs=length?arrayMap(pairs,function(pair){if("function"!=typeof pair[1])throw new TypeError(FUNC_ERROR_TEXT);return[toIteratee(pair[0]),pair[1]]}):[],baseRest(function(args){for(var index=-1;++indexn||n>MAX_SAFE_INTEGER)return[];var index=MAX_ARRAY_LENGTH,length=nativeMin(n,MAX_ARRAY_LENGTH);iteratee=getIteratee(iteratee),n-=MAX_ARRAY_LENGTH;for(var result=baseTimes(length,iteratee);++index1?arrays[length-1]:undefined;return iteratee="function"==typeof iteratee?(arrays.pop(),iteratee):undefined,unzipWith(arrays,iteratee)}),wrapperAt=flatRest(function(paths){var length=paths.length,start=length?paths[0]:0,value=this.__wrapped__,interceptor=function(object){return baseAt(object,paths)};return!(length>1||this.__actions__.length)&&value instanceof LazyWrapper&&isIndex(start)?(value=value.slice(start,+start+(length?1:0)),value.__actions__.push({func:thru,args:[interceptor],thisArg:undefined}),new LodashWrapper(value,this.__chain__).thru(function(array){return length&&!array.length&&array.push(undefined),array})):this.thru(interceptor)}),countBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?++result[key]:baseAssignValue(result,key,1)}),find=createFind(findIndex),findLast=createFind(findLastIndex),groupBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?result[key].push(value):baseAssignValue(result,key,[value])}),invokeMap=baseRest(function(collection,path,args){var index=-1,isFunc="function"==typeof path,isProp=isKey(path),result=isArrayLike(collection)?Array(collection.length):[];return baseEach(collection,function(value){var func=isFunc?path:isProp&&null!=value?value[path]:undefined;result[++index]=func?apply(func,value,args):baseInvoke(value,path,args)}),result}),keyBy=createAggregator(function(result,value,key){baseAssignValue(result,key,value)}),partition=createAggregator(function(result,value,key){result[key?0:1].push(value)},function(){return[[],[]]}),sortBy=baseRest(function(collection,iteratees){if(null==collection)return[];var length=iteratees.length;return length>1&&isIterateeCall(collection,iteratees[0],iteratees[1])?iteratees=[]:length>2&&isIterateeCall(iteratees[0],iteratees[1],iteratees[2])&&(iteratees=[iteratees[0]]),baseOrderBy(collection,baseFlatten(iteratees,1),[])}),now=ctxNow||function(){return root.Date.now()},bind=baseRest(function(func,thisArg,partials){var bitmask=BIND_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bind));bitmask|=PARTIAL_FLAG}return createWrap(func,bitmask,thisArg,partials,holders)}),bindKey=baseRest(function(object,key,partials){var bitmask=BIND_FLAG|BIND_KEY_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bindKey));bitmask|=PARTIAL_FLAG}return createWrap(key,bitmask,object,partials,holders)}),defer=baseRest(function(func,args){return baseDelay(func,1,args)}),delay=baseRest(function(func,wait,args){return baseDelay(func,toNumber(wait)||0,args)});memoize.Cache=MapCache;var overArgs=castRest(function(func,transforms){transforms=1==transforms.length&&isArray(transforms[0])?arrayMap(transforms[0],baseUnary(getIteratee())):arrayMap(baseFlatten(transforms,1),baseUnary(getIteratee()));var funcsLength=transforms.length;return baseRest(function(args){for(var index=-1,length=nativeMin(args.length,funcsLength);++index=other}),isArray=Array.isArray,isArrayBuffer=nodeIsArrayBuffer?baseUnary(nodeIsArrayBuffer):baseIsArrayBuffer,isBuffer=nativeIsBuffer||stubFalse,isDate=nodeIsDate?baseUnary(nodeIsDate):baseIsDate,isMap=nodeIsMap?baseUnary(nodeIsMap):baseIsMap,isRegExp=nodeIsRegExp?baseUnary(nodeIsRegExp):baseIsRegExp,isSet=nodeIsSet?baseUnary(nodeIsSet):baseIsSet,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray,lt=createRelationalOperation(baseLt),lte=createRelationalOperation(function(value,other){return other>=value}),assign=createAssigner(function(object,source){if(isPrototype(source)||isArrayLike(source))return void copyObject(source,keys(source),object);for(var key in source)hasOwnProperty.call(source,key)&&assignValue(object,key,source[key])}),assignIn=createAssigner(function(object,source){copyObject(source,keysIn(source),object)}),assignInWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keysIn(source),object,customizer)}),assignWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keys(source),object,customizer)}),at=flatRest(baseAt),defaults=baseRest(function(args){return args.push(undefined,assignInDefaults),apply(assignInWith,undefined,args)}),defaultsDeep=baseRest(function(args){return args.push(undefined,mergeDefaults),apply(mergeWith,undefined,args)}),invert=createInverter(function(result,value,key){result[value]=key},constant(identity)),invertBy=createInverter(function(result,value,key){hasOwnProperty.call(result,value)?result[value].push(key):result[value]=[key]},getIteratee),invoke=baseRest(baseInvoke),merge=createAssigner(function(object,source,srcIndex){baseMerge(object,source,srcIndex)}),mergeWith=createAssigner(function(object,source,srcIndex,customizer){baseMerge(object,source,srcIndex,customizer)}),omit=flatRest(function(object,props){return null==object?{}:(props=arrayMap(props,toKey),basePick(object,baseDifference(getAllKeysIn(object),props)))}),pick=flatRest(function(object,props){return null==object?{}:basePick(object,arrayMap(props,toKey))}),toPairs=createToPairs(keys),toPairsIn=createToPairs(keysIn),camelCase=createCompounder(function(result,word,index){return word=word.toLowerCase(),result+(index?capitalize(word):word)}),kebabCase=createCompounder(function(result,word,index){return result+(index?"-":"")+word.toLowerCase()}),lowerCase=createCompounder(function(result,word,index){return result+(index?" ":"")+word.toLowerCase()}),lowerFirst=createCaseFirst("toLowerCase"),snakeCase=createCompounder(function(result,word,index){return result+(index?"_":"")+word.toLowerCase()}),startCase=createCompounder(function(result,word,index){return result+(index?" ":"")+upperFirst(word)}),upperCase=createCompounder(function(result,word,index){return result+(index?" ":"")+word.toUpperCase()}),upperFirst=createCaseFirst("toUpperCase"),attempt=baseRest(function(func,args){try{return apply(func,undefined,args)}catch(e){return isError(e)?e:new Error(e)}}),bindAll=flatRest(function(object,methodNames){return arrayEach(methodNames,function(key){key=toKey(key),baseAssignValue(object,key,bind(object[key],object))}),object}),flow=createFlow(),flowRight=createFlow(!0),method=baseRest(function(path,args){return function(object){return baseInvoke(object,path,args)}}),methodOf=baseRest(function(object,args){return function(path){return baseInvoke(object,path,args)}}),over=createOver(arrayMap),overEvery=createOver(arrayEvery),overSome=createOver(arraySome),range=createRange(),rangeRight=createRange(!0),add=createMathOperation(function(augend,addend){return augend+addend},0),ceil=createRound("ceil"),divide=createMathOperation(function(dividend,divisor){return dividend/divisor},1),floor=createRound("floor"),multiply=createMathOperation(function(multiplier,multiplicand){return multiplier*multiplicand},1),round=createRound("round"),subtract=createMathOperation(function(minuend,subtrahend){return minuend-subtrahend},0);return lodash.after=after,lodash.ary=ary,lodash.assign=assign,lodash.assignIn=assignIn,lodash.assignInWith=assignInWith,lodash.assignWith=assignWith,lodash.at=at,lodash.before=before,lodash.bind=bind,lodash.bindAll=bindAll,lodash.bindKey=bindKey,lodash.castArray=castArray,lodash.chain=chain,lodash.chunk=chunk,lodash.compact=compact,lodash.concat=concat,lodash.cond=cond,lodash.conforms=conforms,lodash.constant=constant,lodash.countBy=countBy,lodash.create=create,lodash.curry=curry,lodash.curryRight=curryRight,lodash.debounce=debounce,lodash.defaults=defaults,lodash.defaultsDeep=defaultsDeep,lodash.defer=defer,lodash.delay=delay,lodash.difference=difference,lodash.differenceBy=differenceBy,lodash.differenceWith=differenceWith,lodash.drop=drop,lodash.dropRight=dropRight,lodash.dropRightWhile=dropRightWhile,lodash.dropWhile=dropWhile,lodash.fill=fill,lodash.filter=filter,lodash.flatMap=flatMap,lodash.flatMapDeep=flatMapDeep,lodash.flatMapDepth=flatMapDepth,lodash.flatten=flatten,lodash.flattenDeep=flattenDeep,lodash.flattenDepth=flattenDepth,lodash.flip=flip,lodash.flow=flow,lodash.flowRight=flowRight,lodash.fromPairs=fromPairs,lodash.functions=functions,lodash.functionsIn=functionsIn,lodash.groupBy=groupBy,lodash.initial=initial,lodash.intersection=intersection,lodash.intersectionBy=intersectionBy,lodash.intersectionWith=intersectionWith,lodash.invert=invert,lodash.invertBy=invertBy,lodash.invokeMap=invokeMap,lodash.iteratee=iteratee,lodash.keyBy=keyBy,lodash.keys=keys,lodash.keysIn=keysIn,lodash.map=map,lodash.mapKeys=mapKeys,lodash.mapValues=mapValues,lodash.matches=matches,lodash.matchesProperty=matchesProperty,lodash.memoize=memoize,lodash.merge=merge,lodash.mergeWith=mergeWith,lodash.method=method,lodash.methodOf=methodOf,lodash.mixin=mixin,lodash.negate=negate,lodash.nthArg=nthArg,lodash.omit=omit,lodash.omitBy=omitBy,lodash.once=once,lodash.orderBy=orderBy,lodash.over=over,lodash.overArgs=overArgs,lodash.overEvery=overEvery,lodash.overSome=overSome,lodash.partial=partial,lodash.partialRight=partialRight,lodash.partition=partition,lodash.pick=pick,lodash.pickBy=pickBy,lodash.property=property,lodash.propertyOf=propertyOf,lodash.pull=pull,lodash.pullAll=pullAll,lodash.pullAllBy=pullAllBy,lodash.pullAllWith=pullAllWith,lodash.pullAt=pullAt,lodash.range=range,lodash.rangeRight=rangeRight,lodash.rearg=rearg,lodash.reject=reject,lodash.remove=remove,lodash.rest=rest,lodash.reverse=reverse,lodash.sampleSize=sampleSize,lodash.set=set,lodash.setWith=setWith,lodash.shuffle=shuffle,lodash.slice=slice,lodash.sortBy=sortBy,lodash.sortedUniq=sortedUniq,lodash.sortedUniqBy=sortedUniqBy,lodash.split=split,lodash.spread=spread,lodash.tail=tail,lodash.take=take,lodash.takeRight=takeRight,lodash.takeRightWhile=takeRightWhile,lodash.takeWhile=takeWhile,lodash.tap=tap,lodash.throttle=throttle,lodash.thru=thru,lodash.toArray=toArray,lodash.toPairs=toPairs,lodash.toPairsIn=toPairsIn,lodash.toPath=toPath,lodash.toPlainObject=toPlainObject,lodash.transform=transform,lodash.unary=unary,lodash.union=union,lodash.unionBy=unionBy,lodash.unionWith=unionWith,lodash.uniq=uniq,lodash.uniqBy=uniqBy,lodash.uniqWith=uniqWith,lodash.unset=unset,lodash.unzip=unzip,lodash.unzipWith=unzipWith,lodash.update=update,lodash.updateWith=updateWith,lodash.values=values,lodash.valuesIn=valuesIn,lodash.without=without,lodash.words=words,lodash.wrap=wrap,lodash.xor=xor,lodash.xorBy=xorBy,lodash.xorWith=xorWith,lodash.zip=zip,lodash.zipObject=zipObject,lodash.zipObjectDeep=zipObjectDeep,lodash.zipWith=zipWith,lodash.entries=toPairs,lodash.entriesIn=toPairsIn,lodash.extend=assignIn,lodash.extendWith=assignInWith,mixin(lodash,lodash),lodash.add=add,lodash.attempt=attempt,lodash.camelCase=camelCase,lodash.capitalize=capitalize,lodash.ceil=ceil,lodash.clamp=clamp,lodash.clone=clone,lodash.cloneDeep=cloneDeep,lodash.cloneDeepWith=cloneDeepWith,lodash.cloneWith=cloneWith,lodash.conformsTo=conformsTo,lodash.deburr=deburr,lodash.defaultTo=defaultTo,lodash.divide=divide,lodash.endsWith=endsWith,lodash.eq=eq,lodash.escape=escape,lodash.escapeRegExp=escapeRegExp,lodash.every=every,lodash.find=find,lodash.findIndex=findIndex,lodash.findKey=findKey,lodash.findLast=findLast,lodash.findLastIndex=findLastIndex,lodash.findLastKey=findLastKey,lodash.floor=floor,lodash.forEach=forEach,lodash.forEachRight=forEachRight,lodash.forIn=forIn,lodash.forInRight=forInRight,lodash.forOwn=forOwn,lodash.forOwnRight=forOwnRight,lodash.get=get,lodash.gt=gt,lodash.gte=gte,lodash.has=has,lodash.hasIn=hasIn,lodash.head=head,lodash.identity=identity,lodash.includes=includes,lodash.indexOf=indexOf,lodash.inRange=inRange,lodash.invoke=invoke,lodash.isArguments=isArguments,lodash.isArray=isArray,lodash.isArrayBuffer=isArrayBuffer,lodash.isArrayLike=isArrayLike,lodash.isArrayLikeObject=isArrayLikeObject,lodash.isBoolean=isBoolean,lodash.isBuffer=isBuffer,lodash.isDate=isDate,lodash.isElement=isElement,lodash.isEmpty=isEmpty,lodash.isEqual=isEqual,lodash.isEqualWith=isEqualWith,lodash.isError=isError,lodash.isFinite=isFinite,lodash.isFunction=isFunction,lodash.isInteger=isInteger,lodash.isLength=isLength,lodash.isMap=isMap,lodash.isMatch=isMatch,lodash.isMatchWith=isMatchWith,lodash.isNaN=isNaN,lodash.isNative=isNative,lodash.isNil=isNil,lodash.isNull=isNull,lodash.isNumber=isNumber,lodash.isObject=isObject,lodash.isObjectLike=isObjectLike,lodash.isPlainObject=isPlainObject,lodash.isRegExp=isRegExp,lodash.isSafeInteger=isSafeInteger,lodash.isSet=isSet,lodash.isString=isString,lodash.isSymbol=isSymbol,lodash.isTypedArray=isTypedArray,lodash.isUndefined=isUndefined,lodash.isWeakMap=isWeakMap,lodash.isWeakSet=isWeakSet,lodash.join=join,lodash.kebabCase=kebabCase,lodash.last=last,lodash.lastIndexOf=lastIndexOf,lodash.lowerCase=lowerCase,lodash.lowerFirst=lowerFirst,lodash.lt=lt,lodash.lte=lte,lodash.max=max,lodash.maxBy=maxBy,lodash.mean=mean,lodash.meanBy=meanBy,lodash.min=min,lodash.minBy=minBy,lodash.stubArray=stubArray,lodash.stubFalse=stubFalse,lodash.stubObject=stubObject,lodash.stubString=stubString,lodash.stubTrue=stubTrue,lodash.multiply=multiply,lodash.nth=nth,lodash.noConflict=noConflict,lodash.noop=noop,lodash.now=now,lodash.pad=pad,lodash.padEnd=padEnd,lodash.padStart=padStart,lodash.parseInt=parseInt,lodash.random=random,lodash.reduce=reduce,lodash.reduceRight=reduceRight,lodash.repeat=repeat,lodash.replace=replace,lodash.result=result,lodash.round=round,lodash.runInContext=runInContext,lodash.sample=sample,lodash.size=size,lodash.snakeCase=snakeCase,lodash.some=some,lodash.sortedIndex=sortedIndex,lodash.sortedIndexBy=sortedIndexBy,lodash.sortedIndexOf=sortedIndexOf,lodash.sortedLastIndex=sortedLastIndex,lodash.sortedLastIndexBy=sortedLastIndexBy,lodash.sortedLastIndexOf=sortedLastIndexOf,lodash.startCase=startCase,lodash.startsWith=startsWith,lodash.subtract=subtract,lodash.sum=sum,lodash.sumBy=sumBy,lodash.template=template,lodash.times=times,lodash.toFinite=toFinite,lodash.toInteger=toInteger,lodash.toLength=toLength,lodash.toLower=toLower,lodash.toNumber=toNumber,lodash.toSafeInteger=toSafeInteger,lodash.toString=toString,lodash.toUpper=toUpper,lodash.trim=trim,lodash.trimEnd=trimEnd,lodash.trimStart=trimStart,lodash.truncate=truncate,lodash.unescape=unescape,lodash.uniqueId=uniqueId,lodash.upperCase=upperCase,lodash.upperFirst=upperFirst,lodash.each=forEach,lodash.eachRight=forEachRight,lodash.first=head,mixin(lodash,function(){var source={};return baseForOwn(lodash,function(func,methodName){hasOwnProperty.call(lodash.prototype,methodName)||(source[methodName]=func)}),source}(),{chain:!1}),lodash.VERSION=VERSION,arrayEach(["bind","bindKey","curry","curryRight","partial","partialRight"],function(methodName){lodash[methodName].placeholder=lodash}),arrayEach(["drop","take"],function(methodName,index){LazyWrapper.prototype[methodName]=function(n){var filtered=this.__filtered__;if(filtered&&!index)return new LazyWrapper(this);n=n===undefined?1:nativeMax(toInteger(n),0);var result=this.clone();return filtered?result.__takeCount__=nativeMin(n,result.__takeCount__):result.__views__.push({size:nativeMin(n,MAX_ARRAY_LENGTH),type:methodName+(result.__dir__<0?"Right":"")}),result},LazyWrapper.prototype[methodName+"Right"]=function(n){return this.reverse()[methodName](n).reverse()}}),arrayEach(["filter","map","takeWhile"],function(methodName,index){var type=index+1,isFilter=type==LAZY_FILTER_FLAG||type==LAZY_WHILE_FLAG;LazyWrapper.prototype[methodName]=function(iteratee){var result=this.clone();return result.__iteratees__.push({iteratee:getIteratee(iteratee,3),type:type}),result.__filtered__=result.__filtered__||isFilter,result}}),arrayEach(["head","last"],function(methodName,index){var takeName="take"+(index?"Right":"");LazyWrapper.prototype[methodName]=function(){return this[takeName](1).value()[0]}}),arrayEach(["initial","tail"],function(methodName,index){var dropName="drop"+(index?"":"Right");LazyWrapper.prototype[methodName]=function(){return this.__filtered__?new LazyWrapper(this):this[dropName](1)}}),LazyWrapper.prototype.compact=function(){return this.filter(identity)},LazyWrapper.prototype.find=function(predicate){return this.filter(predicate).head()},LazyWrapper.prototype.findLast=function(predicate){return this.reverse().find(predicate)},LazyWrapper.prototype.invokeMap=baseRest(function(path,args){return"function"==typeof path?new LazyWrapper(this):this.map(function(value){return baseInvoke(value,path,args)})}),LazyWrapper.prototype.reject=function(predicate){return this.filter(negate(getIteratee(predicate)))},LazyWrapper.prototype.slice=function(start,end){start=toInteger(start);var result=this;return result.__filtered__&&(start>0||0>end)?new LazyWrapper(result):(0>start?result=result.takeRight(-start):start&&(result=result.drop(start)),end!==undefined&&(end=toInteger(end),result=0>end?result.dropRight(-end):result.take(end-start)),result)},LazyWrapper.prototype.takeRightWhile=function(predicate){return this.reverse().takeWhile(predicate).reverse()},LazyWrapper.prototype.toArray=function(){return this.take(MAX_ARRAY_LENGTH)},baseForOwn(LazyWrapper.prototype,function(func,methodName){var checkIteratee=/^(?:filter|find|map|reject)|While$/.test(methodName),isTaker=/^(?:head|last)$/.test(methodName),lodashFunc=lodash[isTaker?"take"+("last"==methodName?"Right":""):methodName],retUnwrapped=isTaker||/^find/.test(methodName);lodashFunc&&(lodash.prototype[methodName]=function(){var value=this.__wrapped__,args=isTaker?[1]:arguments,isLazy=value instanceof LazyWrapper,iteratee=args[0],useLazy=isLazy||isArray(value),interceptor=function(value){var result=lodashFunc.apply(lodash,arrayPush([value],args));return isTaker&&chainAll?result[0]:result};useLazy&&checkIteratee&&"function"==typeof iteratee&&1!=iteratee.length&&(isLazy=useLazy=!1);var chainAll=this.__chain__,isHybrid=!!this.__actions__.length,isUnwrapped=retUnwrapped&&!chainAll,onlyLazy=isLazy&&!isHybrid;if(!retUnwrapped&&useLazy){value=onlyLazy?value:new LazyWrapper(this);var result=func.apply(value,args);return result.__actions__.push({func:thru,args:[interceptor],thisArg:undefined}),new LodashWrapper(result,chainAll)}return isUnwrapped&&onlyLazy?func.apply(this,args):(result=this.thru(interceptor),isUnwrapped?isTaker?result.value()[0]:result.value():result)})}),arrayEach(["pop","push","shift","sort","splice","unshift"],function(methodName){var func=arrayProto[methodName],chainName=/^(?:push|sort|unshift)$/.test(methodName)?"tap":"thru",retUnwrapped=/^(?:pop|shift)$/.test(methodName);lodash.prototype[methodName]=function(){var args=arguments;if(retUnwrapped&&!this.__chain__){var value=this.value();return func.apply(isArray(value)?value:[],args)}return this[chainName](function(value){return func.apply(isArray(value)?value:[],args)})}}),baseForOwn(LazyWrapper.prototype,function(func,methodName){var lodashFunc=lodash[methodName];if(lodashFunc){var key=lodashFunc.name+"",names=realNames[key]||(realNames[key]=[]);names.push({name:methodName,func:lodashFunc})}}),realNames[createHybrid(undefined,BIND_KEY_FLAG).name]=[{name:"wrapper",func:undefined}],LazyWrapper.prototype.clone=lazyClone,LazyWrapper.prototype.reverse=lazyReverse,LazyWrapper.prototype.value=lazyValue,lodash.prototype.at=wrapperAt,lodash.prototype.chain=wrapperChain,lodash.prototype.commit=wrapperCommit,lodash.prototype.next=wrapperNext,lodash.prototype.plant=wrapperPlant,lodash.prototype.reverse=wrapperReverse,lodash.prototype.toJSON=lodash.prototype.valueOf=lodash.prototype.value=wrapperValue, -lodash.prototype.first=lodash.prototype.head,iteratorSymbol&&(lodash.prototype[iteratorSymbol]=wrapperToIterator),lodash}var undefined,VERSION="4.16.0",LARGE_ARRAY_SIZE=200,FUNC_ERROR_TEXT="Expected a function",HASH_UNDEFINED="__lodash_hash_undefined__",MAX_MEMOIZE_SIZE=500,PLACEHOLDER="__lodash_placeholder__",BIND_FLAG=1,BIND_KEY_FLAG=2,CURRY_BOUND_FLAG=4,CURRY_FLAG=8,CURRY_RIGHT_FLAG=16,PARTIAL_FLAG=32,PARTIAL_RIGHT_FLAG=64,ARY_FLAG=128,REARG_FLAG=256,FLIP_FLAG=512,UNORDERED_COMPARE_FLAG=1,PARTIAL_COMPARE_FLAG=2,DEFAULT_TRUNC_LENGTH=30,DEFAULT_TRUNC_OMISSION="...",HOT_COUNT=500,HOT_SPAN=16,LAZY_FILTER_FLAG=1,LAZY_MAP_FLAG=2,LAZY_WHILE_FLAG=3,INFINITY=1/0,MAX_SAFE_INTEGER=9007199254740991,MAX_INTEGER=1.7976931348623157e308,NAN=NaN,MAX_ARRAY_LENGTH=4294967295,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH-1,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH>>>1,wrapFlags=[["ary",ARY_FLAG],["bind",BIND_FLAG],["bindKey",BIND_KEY_FLAG],["curry",CURRY_FLAG],["curryRight",CURRY_RIGHT_FLAG],["flip",FLIP_FLAG],["partial",PARTIAL_FLAG],["partialRight",PARTIAL_RIGHT_FLAG],["rearg",REARG_FLAG]],argsTag="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",genTag="[object GeneratorFunction]",mapTag="[object Map]",numberTag="[object Number]",objectTag="[object Object]",promiseTag="[object Promise]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]",weakMapTag="[object WeakMap]",weakSetTag="[object WeakSet]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]",reEmptyStringLeading=/\b__p \+= '';/g,reEmptyStringMiddle=/\b(__p \+=) '' \+/g,reEmptyStringTrailing=/(__e\(.*?\)|\b__t\)) \+\n'';/g,reEscapedHtml=/&(?:amp|lt|gt|quot|#39|#96);/g,reUnescapedHtml=/[&<>"'`]/g,reHasEscapedHtml=RegExp(reEscapedHtml.source),reHasUnescapedHtml=RegExp(reUnescapedHtml.source),reEscape=/<%-([\s\S]+?)%>/g,reEvaluate=/<%([\s\S]+?)%>/g,reInterpolate=/<%=([\s\S]+?)%>/g,reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/,reLeadingDot=/^\./,rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reHasRegExpChar=RegExp(reRegExpChar.source),reTrim=/^\s+|\s+$/g,reTrimStart=/^\s+/,reTrimEnd=/\s+$/,reWrapComment=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,reWrapDetails=/\{\n\/\* \[wrapped with (.+)\] \*/,reSplitDetails=/,? & /,reAsciiWord=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,reEscapeChar=/\\(\\)?/g,reEsTemplate=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,reFlags=/\w*$/,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsHostCtor=/^\[object .+?Constructor\]$/,reIsOctal=/^0o[0-7]+$/i,reIsUint=/^(?:0|[1-9]\d*)$/,reLatin=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,reNoMatch=/($^)/,reUnescapedString=/['\n\r\u2028\u2029\\]/g,rsAstralRange="\\ud800-\\udfff",rsComboMarksRange="\\u0300-\\u036f\\ufe20-\\ufe23",rsComboSymbolsRange="\\u20d0-\\u20f0",rsDingbatRange="\\u2700-\\u27bf",rsLowerRange="a-z\\xdf-\\xf6\\xf8-\\xff",rsMathOpRange="\\xac\\xb1\\xd7\\xf7",rsNonCharRange="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",rsPunctuationRange="\\u2000-\\u206f",rsSpaceRange=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",rsUpperRange="A-Z\\xc0-\\xd6\\xd8-\\xde",rsVarRange="\\ufe0e\\ufe0f",rsBreakRange=rsMathOpRange+rsNonCharRange+rsPunctuationRange+rsSpaceRange,rsApos="['’]",rsAstral="["+rsAstralRange+"]",rsBreak="["+rsBreakRange+"]",rsCombo="["+rsComboMarksRange+rsComboSymbolsRange+"]",rsDigits="\\d+",rsDingbat="["+rsDingbatRange+"]",rsLower="["+rsLowerRange+"]",rsMisc="[^"+rsAstralRange+rsBreakRange+rsDigits+rsDingbatRange+rsLowerRange+rsUpperRange+"]",rsFitz="\\ud83c[\\udffb-\\udfff]",rsModifier="(?:"+rsCombo+"|"+rsFitz+")",rsNonAstral="[^"+rsAstralRange+"]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",rsUpper="["+rsUpperRange+"]",rsZWJ="\\u200d",rsLowerMisc="(?:"+rsLower+"|"+rsMisc+")",rsUpperMisc="(?:"+rsUpper+"|"+rsMisc+")",rsOptLowerContr="(?:"+rsApos+"(?:d|ll|m|re|s|t|ve))?",rsOptUpperContr="(?:"+rsApos+"(?:D|LL|M|RE|S|T|VE))?",reOptMod=rsModifier+"?",rsOptVar="["+rsVarRange+"]?",rsOptJoin="(?:"+rsZWJ+"(?:"+[rsNonAstral,rsRegional,rsSurrPair].join("|")+")"+rsOptVar+reOptMod+")*",rsSeq=rsOptVar+reOptMod+rsOptJoin,rsEmoji="(?:"+[rsDingbat,rsRegional,rsSurrPair].join("|")+")"+rsSeq,rsSymbol="(?:"+[rsNonAstral+rsCombo+"?",rsCombo,rsRegional,rsSurrPair,rsAstral].join("|")+")",reApos=RegExp(rsApos,"g"),reComboMark=RegExp(rsCombo,"g"),reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g"),reUnicodeWord=RegExp([rsUpper+"?"+rsLower+"+"+rsOptLowerContr+"(?="+[rsBreak,rsUpper,"$"].join("|")+")",rsUpperMisc+"+"+rsOptUpperContr+"(?="+[rsBreak,rsUpper+rsLowerMisc,"$"].join("|")+")",rsUpper+"?"+rsLowerMisc+"+"+rsOptLowerContr,rsUpper+"+"+rsOptUpperContr,rsDigits,rsEmoji].join("|"),"g"),reHasUnicode=RegExp("["+rsZWJ+rsAstralRange+rsComboMarksRange+rsComboSymbolsRange+rsVarRange+"]"),reHasUnicodeWord=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,contextProps=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],templateCounter=-1,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[dataViewTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[mapTag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[setTag]=cloneableTags[stringTag]=cloneableTags[symbolTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=!0,cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[weakMapTag]=!1;var deburredLetters={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"},htmlEscapes={"&":"&","<":"<",">":">",'"':""","'":"'"},htmlUnescapes={"&":"&","<":"<",">":">",""":'"',"'":"'"},stringEscapes={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},freeParseFloat=parseFloat,freeParseInt=parseInt,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,freeProcess=moduleExports&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding("util")}catch(e){}}(),nodeIsArrayBuffer=nodeUtil&&nodeUtil.isArrayBuffer,nodeIsDate=nodeUtil&&nodeUtil.isDate,nodeIsMap=nodeUtil&&nodeUtil.isMap,nodeIsRegExp=nodeUtil&&nodeUtil.isRegExp,nodeIsSet=nodeUtil&&nodeUtil.isSet,nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,asciiSize=baseProperty("length"),deburrLetter=basePropertyOf(deburredLetters),escapeHtmlChar=basePropertyOf(htmlEscapes),unescapeHtmlChar=basePropertyOf(htmlUnescapes),_=runInContext();"function"==typeof define&&"object"==typeof define.amd&&define.amd?(root._=_,define(function(){return _})):freeModule?((freeModule.exports=_)._=_,freeExports._=_):root._=_}.call(this);var UsergridAuthMode=Object.freeze({NONE:"none",USER:"user",APP:"app"}),UsergridDirection=Object.freeze({IN:"connecting",OUT:"connections"}),UsergridHttpMethod=Object.freeze({GET:"GET",PUT:"PUT",POST:"POST",DELETE:"DELETE"}),UsergridQueryOperator=Object.freeze({EQUAL:"=",GREATER_THAN:">",GREATER_THAN_EQUAL_TO:">=",LESS_THAN:"<",LESS_THAN_EQUAL_TO:"<="}),UsergridQuerySortOrder=Object.freeze({ASC:"asc",DESC:"desc"});!function(global){function UsergridHelpers(){}var name="UsergridHelpers",overwrittenName=global[name];UsergridHelpers.validateAndRetrieveClient=function(args){var client=void 0;if(args instanceof UsergridClient)client=args;else if(args[0]instanceof UsergridClient)client=args[0];else if(_.get(args,"client"))client=args.client;else{if(!Usergrid.isInitialized)throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument");client=Usergrid}return client},UsergridHelpers.inherits=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})},UsergridHelpers.flattenArgs=function(args){return _.flattenDeep(Array.prototype.slice.call(args))},UsergridHelpers.callback=function(){var args=_.flattenDeep(Array.prototype.slice.call(arguments)).reverse(),emptyFunc=function(){};return _.first(_.flattenDeep([args,_.get(args,"0.callback"),emptyFunc]).filter(_.isFunction))},UsergridHelpers.doCallback=function(callback,params,context){var returnValue;return _.isFunction(callback)&&(params||(params=[]),context||(context=this),params.push(context),returnValue=callback.apply(context,params)),returnValue},UsergridHelpers.authForRequests=function(client){var authForRequests=void 0;return _.get(client,"tempAuth.isValid")?(authForRequests=client.tempAuth,client.tempAuth=void 0):_.get(client,"currentUser.auth.isValid")&&client.authMode===UsergridAuthMode.USER?authForRequests=client.currentUser.auth:_.get(client,"appAuth.isValid")&&client.authMode===UsergridAuthMode.APP&&(authForRequests=client.appAuth),authForRequests},UsergridHelpers.userLoginBody=function(options){var body={grant_type:"password",password:options.password};return options.tokenTtl&&(body.ttl=options.tokenTtl),body[options.username?"username":"email"]=options.username?options.username:options.email,body},UsergridHelpers.appLoginBody=function(options){var body={grant_type:"client_credentials",client_id:options.clientId,client_secret:options.clientSecret};return options.tokenTtl&&(body.ttl=options.tokenTtl),body},UsergridHelpers.calculateExpiry=function(expires_in){return Date.now()+1e3*(expires_in?expires_in-5:0)};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;return UsergridHelpers.isUUID=function(uuid){return uuid?uuidValueRegex.test(uuid):!1},UsergridHelpers.useQuotesIfRequired=function(value){return _.isFinite(value)||UsergridHelpers.isUUID(value)||_.isBoolean(value)||_.isObject(value)&&!_.isFunction(value)||_.isArray(value)?value:"'"+value+"'"},UsergridHelpers.setReadOnly=function(obj,key){return _.isArray(key)?key.forEach(function(k){UsergridHelpers.setReadOnly(obj,k)}):_.isPlainObject(obj[key])?Object.freeze(obj[key]):_.isPlainObject(obj)&&void 0===key?Object.freeze(obj):_.has(obj,key)?Object.defineProperty(obj,key,{writable:!1}):obj},UsergridHelpers.setWritable=function(obj,key){return _.isArray(key)?key.forEach(function(k){UsergridHelpers.setWritable(obj,k)}):_.isPlainObject(obj[key])?_.clone(obj[key]):_.isPlainObject(obj)&&void 0===key?_.clone(obj):_.has(obj,key)?Object.defineProperty(obj,key,{writable:!0}):obj},UsergridHelpers.assignPrefabOptions=function(args){return _.isObject(args[0])&&!_.isFunction(args[0])&&_.has(args,"method")&&_.assign(this,args[0]),this},UsergridHelpers.normalize=function(str){return str=str.replace(/:\//g,"://"),str=str.replace(/([^:\s])\/+/g,"$1/"),str=str.replace(/\/(\?|&|#[^!])/g,"$1"),str=str.replace(/(\?.+)\?/g,"$1&")},UsergridHelpers.urljoin=function(){var input=arguments,options={};"object"==typeof arguments[0]&&(input=arguments[0],options=arguments[1]||{});var joined=[].slice.call(input,0).join("/");return UsergridHelpers.normalize(joined,options)},UsergridHelpers.parseResponseHeaders=function(headerStr){var headers={};if(!headerStr)return headers;for(var headerPairs=headerStr.split("\r\n"),i=0;i0){var key=headerPair.substring(0,index);headers[key]=headerPair.substring(index+2)}}return headers},UsergridHelpers.uri=function(client,method,options){var path="";path=options instanceof UsergridEntity?options.type:options instanceof UsergridQuery?options._type:_.isString(options)?options:_.isArray(options)?_.get(options,"0.type")||_.get(options,"0.path"):options.path||options.type||_.get(options,"entity.type")||_.get(options,"query._type")||_.get(options,"body.type")||_.get(options,"body.path");var uuidOrName="";return method!==UsergridHttpMethod.POST&&(uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,_.get(options,"entity.uuid"),_.get(options,"entity.name"),_.get(options,"body.uuid"),_.get(options,"body.name"),""].filter(_.isString))),UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,path,uuidOrName)},UsergridHelpers.body=function(options){var rawBody=void 0;options instanceof UsergridEntity?rawBody=options:(rawBody=options.body||options.entity||options.entities,void 0===rawBody&&_.isArray(options)&&options[0]instanceof UsergridEntity&&(rawBody=options));var returnBody=rawBody;return rawBody instanceof UsergridEntity?returnBody=rawBody.jsonValue():rawBody instanceof Array&&rawBody[0]instanceof UsergridEntity&&(returnBody=_.map(rawBody,function(entity){return entity.jsonValue()})),returnBody},UsergridHelpers.updateEntityFromRemote=function(entity,usergridResponse){UsergridHelpers.setWritable(entity,["uuid","name","type","created"]),_.assign(entity,usergridResponse.entity),UsergridHelpers.setReadOnly(entity,["uuid","name","type","created"])},UsergridHelpers.headers=function(client,options){var headers={"User-Agent":"usergrid-js/v"+UsergridSDKVersion};_.assign(headers,options.headers);var authForRequests=UsergridHelpers.authForRequests(client);return authForRequests&&_.assign(headers,{authorization:"Bearer "+authForRequests.token}),headers},UsergridHelpers.encode=function(data){var result="";if("string"==typeof data)result=data;else{var encode=encodeURIComponent;_.forOwn(data,function(value,key){result+="&"+encode(key)+"="+encode(value)})}return result},UsergridHelpers.buildConnectionRequest=function(client,method,args){var options={client:client,method:method,entity:{},to:{}};if(UsergridHelpers.assignPrefabOptions.call(options,args),_.isObject(options.from)&&(options.to=options.from),_.isObject(args[0])&&_.has(args[0],"entity")&&_.has(args[0],"to")&&(_.assign(options.entity,args[0].entity),options.relationship=_.get(args,"0.relationship"),_.assign(options.to,args[0].to)),_.isObject(args[0])&&!_.isFunction(args[0])&&_.isString(args[1])&&(_.assign(options.entity,args[0]),options.relationship=_.first([options.relationship,args[1]].filter(_.isString))),_.isObject(args[2])&&!_.isFunction(args[2])&&_.assign(options.to,args[2]),options.entity.uuidOrName=_.first([options.entity.uuidOrName,options.entity.uuid,options.entity.name,args[1]].filter(_.isString)),options.entity.type||(options.entity.type=_.first([options.entity.type,args[0]].filter(_.isString))),options.relationship=_.first([options.relationship,args[2]].filter(_.isString)),_.isString(args[3])&&!UsergridHelpers.isUUID(args[3])&&_.isString(args[4])?options.to.type=args[3]:_.isString(args[2])&&!UsergridHelpers.isUUID(args[2])&&_.isString(args[3])&&_.isObject(args[0])&&!_.isFunction(args[0])&&(options.to.type=args[2]),options.to.uuidOrName=_.first([options.to.uuidOrName,options.to.uuid,options.to.name,args[4],args[3],args[2]].filter(function(property){return _.isString(options.to.type)&&_.isString(property)||UsergridHelpers.isUUID(property)})),!_.isString(options.entity.uuidOrName))throw new Error('source entity "uuidOrName" is required when connecting or disconnecting entities');if(!_.isString(options.to.uuidOrName))throw new Error('target entity "uuidOrName" is required when connecting or disconnecting entities');if(!_.isString(options.to.type)&&!UsergridHelpers.isUUID(options.to.uuidOrName))throw new Error('target "type" (collection name) parameter is required connecting or disconnecting entities by name');return options.uri=UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,_.isString(options.entity.type)?options.entity.type:"",_.isString(options.entity.uuidOrName)?options.entity.uuidOrName:"",options.relationship,_.isString(options.to.type)?options.to.type:"",_.isString(options.to.uuidOrName)?options.to.uuidOrName:""),new UsergridRequest(options)},UsergridHelpers.buildGetConnectionRequest=function(client,args){var options={client:client,method:"GET"};if(UsergridHelpers.assignPrefabOptions.call(options,args),_.isObject(args[1])&&!_.isFunction(args[1])&&_.assign(options,args[1]),options.direction=_.first([options.direction,args[0]].filter(function(property){return property===UsergridDirection.IN||property===UsergridDirection.OUT})),options.relationship=_.first([options.relationship,args[3],args[2]].filter(_.isString)),options.uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,args[2]].filter(_.isString)),options.type=_.first([options.type,args[1]].filter(_.isString)),!_.isString(options.type))throw new Error('"type" (collection name) parameter is required when retrieving connections');if(!_.isString(options.uuidOrName))throw new Error('target entity "uuidOrName" is required when retrieving connections');return options.uri=UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,_.isString(options.type)?options.type:"",_.isString(options.uuidOrName)?options.uuidOrName:"",options.direction,options.relationship),new UsergridRequest(options)},global[name]=UsergridHelpers,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),UsergridHelpers},global[name]}(this);var defaultOptions={baseUrl:"https://api.usergrid.com",authMode:UsergridAuthMode.USER},UsergridClient=function(options){var __appAuth,self=this;if(self.tempAuth=void 0,self.isSharedInstance=!1,2===arguments.length&&(self.orgId=arguments[0],self.appId=arguments[1]),_.defaults(self,options,defaultOptions),!self.orgId||!self.appId)throw new Error('"orgId" and "appId" parameters are required when instantiating UsergridClient');return Object.defineProperty(self,"clientId",{enumerable:!1}),Object.defineProperty(self,"clientSecret",{enumerable:!1}),Object.defineProperty(self,"appAuth",{get:function(){return __appAuth},set:function(options){options instanceof UsergridAppAuth?__appAuth=options:"undefined"!=typeof options&&(__appAuth=new UsergridAppAuth(options))}}),self.clientId&&self.clientSecret&&self.setAppAuth(self.clientId,self.clientSecret),self};UsergridClient.prototype={GET:function(options,callback){var self=this;return self.performRequest(new UsergridRequest({client:self,method:UsergridHttpMethod.GET,uri:UsergridHelpers.uri(self,UsergridHttpMethod.GET,options),query:options instanceof UsergridQuery?options:options.query,queryParams:options.queryParams,body:UsergridHelpers.body(options)}),callback)},PUT:function(options,callback){var self=this;return self.performRequest(new UsergridRequest({client:self,method:UsergridHttpMethod.PUT,uri:UsergridHelpers.uri(self,UsergridHttpMethod.PUT,options),query:options instanceof UsergridQuery?options:options.query,queryParams:options.queryParams,body:UsergridHelpers.body(options)}),callback)},POST:function(options,callback){var self=this;return self.performRequest(new UsergridRequest({client:self,method:UsergridHttpMethod.POST,uri:UsergridHelpers.uri(self,UsergridHttpMethod.POST,options),query:options instanceof UsergridQuery?options:options.query,queryParams:options.queryParams,body:UsergridHelpers.body(options)}),callback)},DELETE:function(options,callback){var self=this;return self.performRequest(new UsergridRequest({client:self,method:UsergridHttpMethod.DELETE,uri:UsergridHelpers.uri(self,UsergridHttpMethod.DELETE,options),query:options instanceof UsergridQuery?options:options.query,queryParams:options.queryParams,body:UsergridHelpers.body(options)}),callback)},connect:function(){var self=this;return self.performRequest(UsergridHelpers.buildConnectionRequest(self,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments)),UsergridHelpers.callback(arguments))},disconnect:function(){var self=this;return self.performRequest(UsergridHelpers.buildConnectionRequest(self,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments)),UsergridHelpers.callback(arguments))},getConnections:function(){var self=this;return self.performRequest(UsergridHelpers.buildGetConnectionRequest(self,UsergridHelpers.flattenArgs(arguments)),UsergridHelpers.callback(arguments))},setAppAuth:function(){this.appAuth=new UsergridAppAuth(UsergridHelpers.flattenArgs(arguments))},authenticateApp:function(options){var self=this,callback=UsergridHelpers.callback(UsergridHelpers.flattenArgs(arguments)),auth=_.first([options,self.appAuth,new UsergridAppAuth(options),new UsergridAppAuth(self.clientId,self.clientSecret)].filter(function(p){return p instanceof UsergridAppAuth}));if(!(auth instanceof UsergridAppAuth))throw new Error("App auth context was not defined when attempting to call .authenticateApp()");if(!auth.clientId||!auth.clientSecret)throw new Error("authenticateApp() failed because clientId or clientSecret are missing");var authCallback=function(usergridResponse){if(usergridResponse.ok){self.appAuth||(self.appAuth=auth),self.appAuth.token=_.get(usergridResponse.responseJSON,"access_token");var expiresIn=_.get(usergridResponse.responseJSON,"expires_in");self.appAuth.expiry=UsergridHelpers.calculateExpiry(expiresIn),self.appAuth.tokenTtl=expiresIn}callback(usergridResponse)};return self.performRequest(new UsergridRequest({client:self,method:UsergridHttpMethod.POST,uri:UsergridHelpers.uri(self,UsergridHttpMethod.POST,{path:"token"}),body:UsergridHelpers.appLoginBody(auth)}),authCallback)},authenticateUser:function(options){var self=this,args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args),setAsCurrentUser=void 0!==_.last(args.filter(_.isBoolean))?_.last(args.filter(_.isBoolean)):!0,currentUser=new UsergridUser(options);currentUser.login(self,function(auth,user,usergridResponse){usergridResponse.ok&&setAsCurrentUser&&(self.currentUser=currentUser),callback(auth,user,usergridResponse)})},usingAuth:function(auth){return _.isString(auth)?this.tempAuth=new UsergridAuth(auth):auth instanceof UsergridAuth?this.tempAuth=auth:this.tempAuth=void 0,this},downloadAsset:function(entity,callback){var self=this,uploadRequest=new UsergridRequest({client:self,method:UsergridHttpMethod.GET,uri:UsergridHelpers.uri(self,UsergridHttpMethod.GET,entity)});return self.performAssetDownloadRequest(uploadRequest,entity,callback)},uploadAsset:function(entity,asset,callback){var self=this,method=UsergridHttpMethod.PUT,uploadRequest=new UsergridRequest({client:self,method:method,uri:UsergridHelpers.uri(self,method,entity),asset:asset});return self.performAssetUploadRequest(uploadRequest,entity,callback)},performRequest:function(usergridRequest,callback){var self=this,requestPromise=function(){var promise=new Promise,xmlHttpRequest=new XMLHttpRequest;return xmlHttpRequest.open(usergridRequest.method.toString(),usergridRequest.uri),_.forOwn(usergridRequest.headers,function(value,key){xmlHttpRequest.setRequestHeader(key,value)}),xmlHttpRequest.open=function(){void 0!==usergridRequest.body&&(xmlHttpRequest.setRequestHeader("Content-Type","application/json"),xmlHttpRequest.setRequestHeader("Accept","application/json"))},xmlHttpRequest.onreadystatechange=function(){this.readyState===XMLHttpRequest.DONE&&promise.done(xmlHttpRequest)},xmlHttpRequest.send(UsergridHelpers.encode(usergridRequest.body)),promise}.bind(self),responsePromise=function(xmlRequest){var promise=new Promise,usergridResponse=new UsergridResponse(xmlRequest);return promise.done(usergridResponse),promise}.bind(self),onCompletePromise=function(response){var promise=new Promise;response.request=usergridRequest,promise.done(response),UsergridHelpers.doCallback(callback,[response])}.bind(self);return Promise.chain([requestPromise,responsePromise]).then(onCompletePromise),usergridRequest},performAssetDownloadRequest:function(usergridRequest,entity,callback){var req=new XMLHttpRequest;return req.open("GET",usergridRequest.uri,!0),req.setRequestHeader("Accept",_.get(entity,"file-metadata.content-type")),req.responseType="blob",req.onload=function(){entity.asset=new UsergridAsset(req.response),UsergridHelpers.doCallback(callback,[entity.asset,null,entity])},req.send(null),usergridRequest},performAssetUploadRequest:function(usergridRequest,entity,callback){var asset=usergridRequest.asset,xmlHttpRequest=new XMLHttpRequest;xmlHttpRequest.open(usergridRequest.method,usergridRequest.uri,!0),xmlHttpRequest.onload=function(){var response=new UsergridResponse(xmlHttpRequest);UsergridHelpers.updateEntityFromRemote(entity,response),UsergridHelpers.doCallback(callback,[asset,response,entity])};var formData=new FormData;return formData.append("file",asset.data),xmlHttpRequest.send(formData),usergridRequest}};var UsergridSDKVersion="2.0.0",UsergridClientSharedInstance=function(){var self=this;return self.isInitialized=!1,self.isSharedInstance=!0,self};UsergridHelpers.inherits(UsergridClientSharedInstance,UsergridClient);var Usergrid=new UsergridClientSharedInstance;Usergrid.initSharedInstance=function(options){return Usergrid.isInitialized?console.log("Usergrid shared instance is already initialized"):(_.assign(Usergrid,new UsergridClient(options)),Usergrid.isInitialized=!0,Usergrid.isSharedInstance=!0),Usergrid},Usergrid.init=Usergrid.initSharedInstance;var UsergridQuery=function(type){var queryString,sort,self=this,query="",__nextIsNot=!1;return self._type=type,_.assign(self,{type:function(value){return self._type=value,self},collection:function(value){return self._type=value,self},limit:function(value){return self._limit=value,self},cursor:function(value){return self._cursor=value,self},eq:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.EQUAL+" "+UsergridHelpers.useQuotesIfRequired(value)),self},equal:this.eq,gt:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.GREATER_THAN+" "+UsergridHelpers.useQuotesIfRequired(value)),self},greaterThan:this.gt,gte:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.GREATER_THAN_EQUAL_TO+" "+UsergridHelpers.useQuotesIfRequired(value)),self},greaterThanOrEqual:this.gte,lt:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.LESS_THAN+" "+UsergridHelpers.useQuotesIfRequired(value)),self},lessThan:this.lt,lte:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.LESS_THAN_EQUAL_TO+" "+UsergridHelpers.useQuotesIfRequired(value)),self},lessThanOrEqual:this.lte,contains:function(key,value){return query=self.andJoin(key+" contains "+UsergridHelpers.useQuotesIfRequired(value)),self},locationWithin:function(distanceInMeters,lat,lng){return query=self.andJoin("location within "+distanceInMeters+" of "+lat+", "+lng),self},asc:function(key){return self.sort(key,UsergridQuerySortOrder.ASC),self},desc:function(key){return self.sort(key,UsergridQuerySortOrder.DESC),self},sort:function(key,order){return sort=key&&order?" order by "+key+" "+order:"",self},fromString:function(string){return queryString=string,self},andJoin:function(append){return __nextIsNot&&(append="not "+append,__nextIsNot=!1),append?0===query.length?append:_.endsWith(query,"and")||_.endsWith(query,"or")?query+" "+append:query+" and "+append:query},orJoin:function(){return query.length>0&&!_.endsWith(query,"or")?query+" or":query}}),Object.defineProperty(self,"_ql",{get:function(){if(void 0!==queryString)return queryString;var qL="select * "+(query.length>0?"where "+(query||""):"");return qL+=void 0!==sort?sort:""}}),Object.defineProperty(self,"encodedStringValue",{get:function(){var self=this,limit=self._limit,cursor=self._cursor,requirementsString=self._ql,encodedStringValue=void 0;if(void 0!==limit&&(encodedStringValue="limit"+UsergridQueryOperator.EQUAL+limit),!_.isEmpty(cursor)){var cursorString="cursor"+UsergridQueryOperator.EQUAL+cursor;_.isEmpty(encodedStringValue)?encodedStringValue=cursorString:encodedStringValue+="&"+cursorString}if(!_.isEmpty(requirementsString)){var qLString="ql="+encodeURIComponent(requirementsString);_.isEmpty(encodedStringValue)?encodedStringValue=qLString:encodedStringValue+="&"+qLString}return _.isEmpty(encodedStringValue)||(encodedStringValue="?"+encodedStringValue),_.isEmpty(encodedStringValue)?void 0:encodedStringValue}}),Object.defineProperty(self,"and",{get:function(){return query=self.andJoin(""),self}}),Object.defineProperty(self,"or",{get:function(){return query=self.orJoin(),self}}),Object.defineProperty(self,"not",{get:function(){return __nextIsNot=!0,self}}),self},UsergridRequest=function(options){var self=this,client=UsergridHelpers.validateAndRetrieveClient(options);if(!_.isString(options.type)&&!_.isString(options.path)&&!_.isString(options.uri))throw new Error('one of "type" (collection name), "path", or "uri" parameters are required when initializing a UsergridRequest');if(!_.includes(["GET","PUT","POST","DELETE"],options.method))throw new Error('"method" parameter is required when initializing a UsergridRequest');self.method=options.method,self.uri=options.uri||UsergridHelpers.uri(client,options), -self.headers=UsergridHelpers.headers(client,options),self.body=options.body||void 0,self.asset=options.asset||void 0,self.query=options.query,void 0!==self.query&&(self.uri+=UsergridHelpers.normalize(self.query.encodedStringValue,{})),self.queryParams=options.queryParams,void 0!==self.queryParams&&(_.forOwn(self.queryParams,function(value,key){self.uri+="?"+encodeURIComponent(key)+"="+encodeURIComponent(value)}),self.uri=UsergridHelpers.normalize(self.uri,{}));try{_.isPlainObject(self.body)&&(self.body=JSON.stringify(self.body)),_.isArray(self.body)&&(self.body=JSON.stringify(self.body))}catch(exception){}return self},UsergridAuth=function(token,expiry){var self=this;self.token=token,self.expiry=expiry||0;var usingToken=token?!0:!1;return Object.defineProperty(self,"hasToken",{get:function(){return void 0!==self.token},configurable:!0}),Object.defineProperty(self,"isExpired",{get:function(){return usingToken?!1:Date.now()>=self.expiry},configurable:!0}),Object.defineProperty(self,"isValid",{get:function(){return!self.isExpired&&self.hasToken},configurable:!0}),Object.defineProperty(self,"tokenTtl",{configurable:!0,writable:!0}),_.assign(self,{destroy:function(){self.token=void 0,self.expiry=0,self.tokenTtl=void 0}}),self},UsergridAppAuth=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments);return _.isPlainObject(args[0])?(self.clientId=args[0].clientId,self.clientSecret=args[0].clientSecret,self.tokenTtl=args[0].tokenTtl):(self.clientId=args[0],self.clientSecret=args[1],self.tokenTtl=args[2]),UsergridAuth.call(self),_.assign(self,UsergridAuth),self};UsergridHelpers.inherits(UsergridAppAuth,UsergridAuth);var UsergridUserAuth=function(options){var self=this,args=_.flattenDeep(UsergridHelpers.flattenArgs(arguments));return _.isPlainObject(args[0])&&(options=args[0]),self.username=options.username||args[0],self.email=options.email,(options.password||args[1])&&(self.password=options.password||args[1]),self.tokenTtl=options.tokenTtl||args[2],UsergridAuth.call(self),_.assign(self,UsergridAuth),self};UsergridHelpers.inherits(UsergridUserAuth,UsergridAuth);var UsergridEntity=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments);if(0===args.length)throw new Error("A UsergridEntity object cannot be initialized without passing one or more arguments");if(self.asset=void 0,_.isPlainObject(args[0])?_.assign(self,args[0]):(self.type||(self.type=_.isString(args[0])?args[0]:void 0),self.name||(self.name=_.isString(args[1])?args[1]:void 0)),!_.isString(self.type))throw new Error('"type" (or "collection") parameter is required when initializing a UsergridEntity object');return Object.defineProperty(self,"isUser",{get:function(){return"user"===self.type.toLowerCase()}}),Object.defineProperty(self,"hasAsset",{get:function(){return _.has(self,"file-metadata")}}),UsergridHelpers.setReadOnly(self,["uuid","name","type","created"]),self};UsergridEntity.prototype={jsonValue:function(){var jsonValue={};return _.forOwn(this,function(value,key){jsonValue[key]=value}),jsonValue},putProperty:function(key,value){this[key]=value},putProperties:function(obj){_.assign(this,obj)},removeProperty:function(key){this.removeProperties([key])},removeProperties:function(keys){var self=this;keys.forEach(function(key){delete self[key]})},insert:function(key,value,idx){_.isArray(this[key])||(this[key]=this[key]?[this[key]]:[]),this[key].splice.apply(this[key],[idx,0].concat(value))},append:function(key,value){this.insert(key,value,Number.MAX_VALUE)},prepend:function(key,value){this.insert(key,value,0)},pop:function(key){_.isArray(this[key])&&this[key].pop()},shift:function(key){_.isArray(this[key])&&this[key].shift()},reload:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.GET(this,function(usergridResponse){UsergridHelpers.updateEntityFromRemote(this,usergridResponse),callback(usergridResponse)}.bind(this))},save:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args),uuid=this.uuid;void 0===uuid?client.POST(this,function(usergridResponse){UsergridHelpers.updateEntityFromRemote(this,usergridResponse),callback(usergridResponse,this)}.bind(this)):client.PUT(this,function(usergridResponse){UsergridHelpers.updateEntityFromRemote(this,usergridResponse),callback(usergridResponse,this)}.bind(this))},remove:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.DELETE(this,function(usergridResponse){callback(usergridResponse,this)}.bind(this))},attachAsset:function(asset){this.asset=asset},uploadAsset:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.uploadAsset(this,this.asset,function(asset,usergridResponse){UsergridHelpers.updateEntityFromRemote(this,usergridResponse),this.asset=asset,callback(asset,usergridResponse,this)}.bind(this))},downloadAsset:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.downloadAsset(this,callback)},connect:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args[0]=this,client.connect.apply(client,args)},disconnect:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args[0]=this,client.disconnect.apply(client,args)},getConnections:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args.shift(),args.splice(1,0,this),client.getConnections.apply(client,args)}};var UsergridUser=function(obj){if(!_.has(obj,"email")&&!_.has(obj,"username"))throw new Error('"email" or "username" property is required when initializing a UsergridUser object');var self=this;return _.assign(self,obj,UsergridEntity),UsergridEntity.call(self,"user"),UsergridHelpers.setWritable(self,"name"),self};UsergridUser.CheckAvailable=function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);args[0]instanceof UsergridClient&&args.shift();var checkQuery,callback=UsergridHelpers.callback(args);if(args[0].username&&args[0].email)checkQuery=new UsergridQuery("users").eq("username",args[0].username).or.eq("email",args[0].email);else if(args[0].username)checkQuery=new UsergridQuery("users").eq("username",args[0].username);else{if(!args[0].email)throw new Error("'username' or 'email' property is required when checking for available users");checkQuery=new UsergridQuery("users").eq("email",args[0].email)}client.GET(checkQuery,function(usergridResponse){callback(usergridResponse,usergridResponse.entities.length>0)})},UsergridHelpers.inherits(UsergridUser,UsergridEntity),UsergridUser.prototype.uniqueId=function(){var self=this;return _.first([self.uuid,self.username,self.email].filter(_.isString))},UsergridUser.prototype.create=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.POST(self,function(usergridResponse){delete self.password,_.assign(self,usergridResponse.user),callback(usergridResponse)}.bind(self))},UsergridUser.prototype.login=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args),client=UsergridHelpers.validateAndRetrieveClient(args);client.POST({path:"token",body:UsergridHelpers.userLoginBody(self)},function(usergridResponse){if(delete self.password,usergridResponse.ok){var responseJSON=usergridResponse.responseJSON;self.auth=new UsergridUserAuth(self),self.auth.token=_.get(responseJSON,"access_token");var expiresIn=_.get(responseJSON,"expires_in");self.auth.expiry=UsergridHelpers.calculateExpiry(expiresIn),self.auth.tokenTtl=expiresIn}callback(self.auth,self,usergridResponse)})},UsergridUser.prototype.logout=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args);if(!self.auth||!self.auth.isValid){var response=new UsergridResponse;return response.error=new UsergridResponseError({error:"no_valid_token",description:"this user does not have a valid token"}),callback(response)}var revokeAll=_.first(args.filter(_.isBoolean))||!1,revokeTokenPath=["users",self.uniqueId(),"revoketoken"+(revokeAll?"s":"")].join("/"),queryParams=void 0;revokeAll||(queryParams={token:self.auth.token});var client=UsergridHelpers.validateAndRetrieveClient(args);return client.PUT({path:revokeTokenPath,queryParams:queryParams},function(usergridResponse){self.auth.destroy(),callback(usergridResponse)})},UsergridUser.prototype.logoutAllSessions=function(){var args=UsergridHelpers.flattenArgs(arguments);return args=_.concat([UsergridHelpers.validateAndRetrieveClient(args),!0],args),this.logout.apply(this,args)},UsergridUser.prototype.resetPassword=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args),client=UsergridHelpers.validateAndRetrieveClient(args);args[0]instanceof UsergridClient&&args.shift();var body={oldpassword:_.isPlainObject(args[0])?args[0].oldPassword:_.isString(args[0])?args[0]:void 0,newpassword:_.isPlainObject(args[0])?args[0].newPassword:_.isString(args[1])?args[1]:void 0};if(!body.oldpassword||!body.newpassword)throw new Error('"oldPassword" and "newPassword" properties are required when resetting a user password');return client.PUT({path:["users",self.uniqueId(),"password"].join("/"),body:body},function(usergridResponse){callback(usergridResponse)})};var UsergridResponseError=function(responseErrorObject){var self=this;if(_.has(responseErrorObject,"error")!==!1)return self.name=responseErrorObject.error,self.description=responseErrorObject.error_description||responseErrorObject.description,self.exception=responseErrorObject.exception,self},UsergridResponse=function(request){var self=this;if(self.ok=!1,request){self.statusCode=parseInt(request.status),self.headers=UsergridHelpers.parseResponseHeaders(request.getAllResponseHeaders());try{var responseText=request.responseText,responseJSON=JSON.parse(responseText)}catch(e){responseJSON={}}if(self.statusCode<400){if(self.ok=!0,_.assign(self,{responseJSON:_.cloneDeep(responseJSON)}),_.has(responseJSON,"entities")){var entities=_.map(responseJSON.entities,function(en){var entity=new UsergridEntity(en);return entity.isUser&&(entity=new UsergridUser(entity)),entity});_.assign(self,{entities:entities}),delete self.responseJSON.entities,self.first=_.first(entities)||void 0,self.entity=self.first,self.last=_.last(entities)||void 0,"/users"===_.get(self,"responseJSON.path")&&(self.user=self.first,self.users=self.entities),Object.defineProperty(self,"hasNextPage",{get:function(){return _.has(self,"responseJSON.cursor")}}),UsergridHelpers.setReadOnly(self.responseJSON)}}else self.error=new UsergridResponseError(responseJSON)}return self};UsergridResponse.prototype={loadNextPage:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args);self.responseJSON.cursor||callback();var client=UsergridHelpers.validateAndRetrieveClient(args),type=_.last(_.get(self,"responseJSON.path").split("/")),limit=_.first(_.get(this,"responseJSON.params.limit")),query=new UsergridQuery(type).cursor(this.responseJSON.cursor).limit(limit);return client.GET(query,callback)}};var UsergridAssetDefaultFileName="file",UsergridAsset=function(fileOrBlob){if(!fileOrBlob instanceof File||!fileOrBlob instanceof Blob)throw new Error("UsergridAsset must be initialized with a 'File' or 'Blob'");var self=this;return self.data=fileOrBlob,self.filename=fileOrBlob.name||UsergridAssetDefaultFileName,self.contentLength=fileOrBlob.size,self.contentType=fileOrBlob.type,self}; \ No newline at end of file +lodash.prototype.first=lodash.prototype.head,iteratorSymbol&&(lodash.prototype[iteratorSymbol]=wrapperToIterator),lodash}var undefined,VERSION="4.16.0",LARGE_ARRAY_SIZE=200,FUNC_ERROR_TEXT="Expected a function",HASH_UNDEFINED="__lodash_hash_undefined__",MAX_MEMOIZE_SIZE=500,PLACEHOLDER="__lodash_placeholder__",BIND_FLAG=1,BIND_KEY_FLAG=2,CURRY_BOUND_FLAG=4,CURRY_FLAG=8,CURRY_RIGHT_FLAG=16,PARTIAL_FLAG=32,PARTIAL_RIGHT_FLAG=64,ARY_FLAG=128,REARG_FLAG=256,FLIP_FLAG=512,UNORDERED_COMPARE_FLAG=1,PARTIAL_COMPARE_FLAG=2,DEFAULT_TRUNC_LENGTH=30,DEFAULT_TRUNC_OMISSION="...",HOT_COUNT=500,HOT_SPAN=16,LAZY_FILTER_FLAG=1,LAZY_MAP_FLAG=2,LAZY_WHILE_FLAG=3,INFINITY=1/0,MAX_SAFE_INTEGER=9007199254740991,MAX_INTEGER=1.7976931348623157e308,NAN=NaN,MAX_ARRAY_LENGTH=4294967295,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH-1,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH>>>1,wrapFlags=[["ary",ARY_FLAG],["bind",BIND_FLAG],["bindKey",BIND_KEY_FLAG],["curry",CURRY_FLAG],["curryRight",CURRY_RIGHT_FLAG],["flip",FLIP_FLAG],["partial",PARTIAL_FLAG],["partialRight",PARTIAL_RIGHT_FLAG],["rearg",REARG_FLAG]],argsTag="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",genTag="[object GeneratorFunction]",mapTag="[object Map]",numberTag="[object Number]",objectTag="[object Object]",promiseTag="[object Promise]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]",weakMapTag="[object WeakMap]",weakSetTag="[object WeakSet]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]",reEmptyStringLeading=/\b__p \+= '';/g,reEmptyStringMiddle=/\b(__p \+=) '' \+/g,reEmptyStringTrailing=/(__e\(.*?\)|\b__t\)) \+\n'';/g,reEscapedHtml=/&(?:amp|lt|gt|quot|#39|#96);/g,reUnescapedHtml=/[&<>"'`]/g,reHasEscapedHtml=RegExp(reEscapedHtml.source),reHasUnescapedHtml=RegExp(reUnescapedHtml.source),reEscape=/<%-([\s\S]+?)%>/g,reEvaluate=/<%([\s\S]+?)%>/g,reInterpolate=/<%=([\s\S]+?)%>/g,reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/,reLeadingDot=/^\./,rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reHasRegExpChar=RegExp(reRegExpChar.source),reTrim=/^\s+|\s+$/g,reTrimStart=/^\s+/,reTrimEnd=/\s+$/,reWrapComment=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,reWrapDetails=/\{\n\/\* \[wrapped with (.+)\] \*/,reSplitDetails=/,? & /,reAsciiWord=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,reEscapeChar=/\\(\\)?/g,reEsTemplate=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,reFlags=/\w*$/,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsHostCtor=/^\[object .+?Constructor\]$/,reIsOctal=/^0o[0-7]+$/i,reIsUint=/^(?:0|[1-9]\d*)$/,reLatin=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,reNoMatch=/($^)/,reUnescapedString=/['\n\r\u2028\u2029\\]/g,rsAstralRange="\\ud800-\\udfff",rsComboMarksRange="\\u0300-\\u036f\\ufe20-\\ufe23",rsComboSymbolsRange="\\u20d0-\\u20f0",rsDingbatRange="\\u2700-\\u27bf",rsLowerRange="a-z\\xdf-\\xf6\\xf8-\\xff",rsMathOpRange="\\xac\\xb1\\xd7\\xf7",rsNonCharRange="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",rsPunctuationRange="\\u2000-\\u206f",rsSpaceRange=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",rsUpperRange="A-Z\\xc0-\\xd6\\xd8-\\xde",rsVarRange="\\ufe0e\\ufe0f",rsBreakRange=rsMathOpRange+rsNonCharRange+rsPunctuationRange+rsSpaceRange,rsApos="['’]",rsAstral="["+rsAstralRange+"]",rsBreak="["+rsBreakRange+"]",rsCombo="["+rsComboMarksRange+rsComboSymbolsRange+"]",rsDigits="\\d+",rsDingbat="["+rsDingbatRange+"]",rsLower="["+rsLowerRange+"]",rsMisc="[^"+rsAstralRange+rsBreakRange+rsDigits+rsDingbatRange+rsLowerRange+rsUpperRange+"]",rsFitz="\\ud83c[\\udffb-\\udfff]",rsModifier="(?:"+rsCombo+"|"+rsFitz+")",rsNonAstral="[^"+rsAstralRange+"]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",rsUpper="["+rsUpperRange+"]",rsZWJ="\\u200d",rsLowerMisc="(?:"+rsLower+"|"+rsMisc+")",rsUpperMisc="(?:"+rsUpper+"|"+rsMisc+")",rsOptLowerContr="(?:"+rsApos+"(?:d|ll|m|re|s|t|ve))?",rsOptUpperContr="(?:"+rsApos+"(?:D|LL|M|RE|S|T|VE))?",reOptMod=rsModifier+"?",rsOptVar="["+rsVarRange+"]?",rsOptJoin="(?:"+rsZWJ+"(?:"+[rsNonAstral,rsRegional,rsSurrPair].join("|")+")"+rsOptVar+reOptMod+")*",rsSeq=rsOptVar+reOptMod+rsOptJoin,rsEmoji="(?:"+[rsDingbat,rsRegional,rsSurrPair].join("|")+")"+rsSeq,rsSymbol="(?:"+[rsNonAstral+rsCombo+"?",rsCombo,rsRegional,rsSurrPair,rsAstral].join("|")+")",reApos=RegExp(rsApos,"g"),reComboMark=RegExp(rsCombo,"g"),reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g"),reUnicodeWord=RegExp([rsUpper+"?"+rsLower+"+"+rsOptLowerContr+"(?="+[rsBreak,rsUpper,"$"].join("|")+")",rsUpperMisc+"+"+rsOptUpperContr+"(?="+[rsBreak,rsUpper+rsLowerMisc,"$"].join("|")+")",rsUpper+"?"+rsLowerMisc+"+"+rsOptLowerContr,rsUpper+"+"+rsOptUpperContr,rsDigits,rsEmoji].join("|"),"g"),reHasUnicode=RegExp("["+rsZWJ+rsAstralRange+rsComboMarksRange+rsComboSymbolsRange+rsVarRange+"]"),reHasUnicodeWord=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,contextProps=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],templateCounter=-1,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[dataViewTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[mapTag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[setTag]=cloneableTags[stringTag]=cloneableTags[symbolTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=!0,cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[weakMapTag]=!1;var deburredLetters={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"},htmlEscapes={"&":"&","<":"<",">":">",'"':""","'":"'"},htmlUnescapes={"&":"&","<":"<",">":">",""":'"',"'":"'"},stringEscapes={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},freeParseFloat=parseFloat,freeParseInt=parseInt,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,freeProcess=moduleExports&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding("util")}catch(e){}}(),nodeIsArrayBuffer=nodeUtil&&nodeUtil.isArrayBuffer,nodeIsDate=nodeUtil&&nodeUtil.isDate,nodeIsMap=nodeUtil&&nodeUtil.isMap,nodeIsRegExp=nodeUtil&&nodeUtil.isRegExp,nodeIsSet=nodeUtil&&nodeUtil.isSet,nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,asciiSize=baseProperty("length"),deburrLetter=basePropertyOf(deburredLetters),escapeHtmlChar=basePropertyOf(htmlEscapes),unescapeHtmlChar=basePropertyOf(htmlUnescapes),_=runInContext();"function"==typeof define&&"object"==typeof define.amd&&define.amd?(root._=_,define(function(){return _})):freeModule?((freeModule.exports=_)._=_,freeExports._=_):root._=_}.call(this);var UsergridAuthMode=Object.freeze({NONE:"none",USER:"user",APP:"app"}),UsergridDirection=Object.freeze({IN:"connecting",OUT:"connections"}),UsergridHttpMethod=Object.freeze({GET:"GET",PUT:"PUT",POST:"POST",DELETE:"DELETE"}),UsergridQueryOperator=Object.freeze({EQUAL:"=",GREATER_THAN:">",GREATER_THAN_EQUAL_TO:">=",LESS_THAN:"<",LESS_THAN_EQUAL_TO:"<="}),UsergridQuerySortOrder=Object.freeze({ASC:"asc",DESC:"desc"});!function(global){function UsergridHelpers(){}var name="UsergridHelpers",overwrittenName=global[name];UsergridHelpers.validateAndRetrieveClient=function(args){var client=void 0;if(args instanceof UsergridClient)client=args;else if(args[0]instanceof UsergridClient)client=args[0];else if(_.get(args,"client"))client=args.client;else{if(!Usergrid.isInitialized)throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument");client=Usergrid}return client},UsergridHelpers.inherits=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})},UsergridHelpers.flattenArgs=function(args){return _.flattenDeep(Array.prototype.slice.call(args))},UsergridHelpers.callback=function(){var args=UsergridHelpers.flattenArgs(arguments).reverse(),emptyFunc=function(){};return _.first(_.flattenDeep([args,_.get(args,"0.callback"),emptyFunc]).filter(_.isFunction))},UsergridHelpers.authForRequests=function(client){var authForRequests=void 0;return _.get(client,"tempAuth.isValid")?(authForRequests=client.tempAuth,client.tempAuth=void 0):_.get(client,"currentUser.auth.isValid")&&client.authMode===UsergridAuthMode.USER?authForRequests=client.currentUser.auth:_.get(client,"appAuth.isValid")&&client.authMode===UsergridAuthMode.APP&&(authForRequests=client.appAuth),authForRequests},UsergridHelpers.userLoginBody=function(options){var body={grant_type:"password",password:options.password};return options.tokenTtl&&(body.ttl=options.tokenTtl),body[options.username?"username":"email"]=options.username?options.username:options.email,body},UsergridHelpers.appLoginBody=function(options){var body={grant_type:"client_credentials",client_id:options.clientId,client_secret:options.clientSecret};return options.tokenTtl&&(body.ttl=options.tokenTtl),body},UsergridHelpers.calculateExpiry=function(expires_in){return Date.now()+1e3*(expires_in?expires_in-5:0)};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;return UsergridHelpers.isUUID=function(uuid){return uuid?uuidValueRegex.test(uuid):!1},UsergridHelpers.useQuotesIfRequired=function(value){return _.isFinite(value)||UsergridHelpers.isUUID(value)||_.isBoolean(value)||_.isObject(value)&&!_.isFunction(value)||_.isArray(value)?value:"'"+value+"'"},UsergridHelpers.setReadOnly=function(obj,key){return _.isArray(key)?key.forEach(function(k){UsergridHelpers.setReadOnly(obj,k)}):_.isPlainObject(obj[key])?Object.freeze(obj[key]):_.isPlainObject(obj)&&void 0===key?Object.freeze(obj):_.has(obj,key)?Object.defineProperty(obj,key,{writable:!1}):obj},UsergridHelpers.setWritable=function(obj,key){return _.isArray(key)?key.forEach(function(k){UsergridHelpers.setWritable(obj,k)}):_.isPlainObject(obj[key])?_.clone(obj[key]):_.isPlainObject(obj)&&void 0===key?_.clone(obj):_.has(obj,key)?Object.defineProperty(obj,key,{writable:!0}):obj},UsergridHelpers.assignPrefabOptions=function(args){return _.isObject(args[0])&&!_.isFunction(args[0])&&_.has(args,"method")&&_.assign(this,args[0]),this},UsergridHelpers.normalize=function(str){return str=str.replace(/\/+/g,"/"),str=str.replace(/:\//g,"://"),str=str.replace(/\/(\?|&|#[^!])/g,"$1"),str=str.replace(/(\?.+)\?/g,"$1&")},UsergridHelpers.urljoin=function(){var input=arguments,options={};"object"==typeof arguments[0]&&(input=arguments[0],options=arguments[1]||{});var joined=[].slice.call(input,0).join("/");return UsergridHelpers.normalize(joined,options)},UsergridHelpers.parseResponseHeaders=function(headerStr){var headers={};if(!headerStr)return headers;for(var headerPairs=headerStr.split("\r\n"),i=0;i0){var key=headerPair.substring(0,index).toLowerCase();headers[key]=headerPair.substring(index+2)}}return headers},UsergridHelpers.uri=function(client,options){var path="";path=options instanceof UsergridEntity?options.type:options instanceof UsergridQuery?options._type:_.isString(options)?options:_.isArray(options)?_.get(options,"0.type")||_.get(options,"0.path"):options.path||options.type||_.get(options,"entity.type")||_.get(options,"query._type")||_.get(options,"body.type")||_.get(options,"body.path");var uuidOrName="";return options.method!==UsergridHttpMethod.POST&&(uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,_.get(options,"entity.uuid"),_.get(options,"entity.name"),_.get(options,"body.uuid"),_.get(options,"body.name"),""].filter(_.isString))),UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,path,uuidOrName)},UsergridHelpers.updateEntityFromRemote=function(entity,usergridResponse){UsergridHelpers.setWritable(entity,["uuid","name","type","created"]),_.assign(entity,usergridResponse.entity),UsergridHelpers.setReadOnly(entity,["uuid","name","type","created"])},UsergridHelpers.headers=function(client,options,defaultHeaders){var returnHeaders={};_.assign(returnHeaders,defaultHeaders),_.assign(returnHeaders,options.headers),_.assign(returnHeaders,{"User-Agent":"usergrid-js/v"+UsergridSDKVersion});var authForRequests=UsergridHelpers.authForRequests(client);return authForRequests&&_.assign(returnHeaders,{authorization:"Bearer "+authForRequests.token}),returnHeaders},UsergridHelpers.setEntity=function(options,args){return options.entity=_.first([options.entity,args[0]].filter(function(property){return property instanceof UsergridEntity})),void 0!==options.entity&&(options.type=options.entity.type),options},UsergridHelpers.setAsset=function(options,args){return options.asset=_.first([options.asset,_.get(options,"entity.asset"),args[1],args[0]].filter(function(property){return property instanceof UsergridAsset})),options},UsergridHelpers.setUuidOrName=function(options,args){return options.uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,_.get(options,"entity.uuid"),_.get(options,"body.uuid"),_.get(options,"entity.name"),_.get(options,"body.name"),_.get(args,"0.uuid"),_.get(args,"0.name"),_.get(args,"2"),_.get(args,"1")].filter(_.isString)),options},UsergridHelpers.setPathOrType=function(options,args){var pathOrType=_.first([args.type,_.get(args,"0.type"),_.get(options,"entity.type"),_.get(args,"body.type"),_.get(options,"body.0.type"),_.isArray(args)?args[0]:void 0].filter(_.isString));return options[/\//.test(pathOrType)?"path":"type"]=pathOrType,options},UsergridHelpers.setQs=function(options,args){return options.path&&(options.qs=_.first([options.qs,args[2],args[1],args[0]].filter(_.isPlainObject))),options},UsergridHelpers.setQuery=function(options,args){return options.query=_.first([options,options.query,args[0]].filter(function(property){return property instanceof UsergridQuery})),options},UsergridHelpers.setAsset=function(options,args){return options.asset=_.first([options.asset,_.get(options,"entity.asset"),args[1],args[0]].filter(function(property){return property instanceof UsergridAsset})),options},UsergridHelpers.setBody=function(options,args){if(options.body=_.first([args.entity,args.body,args[0].entity,args[0].body,args[2],args[1],args[0]].filter(function(property){return _.isObject(property)&&!_.isFunction(property)&&!(property instanceof UsergridQuery)&&!(property instanceof UsergridAsset)})),void 0===options.body&&void 0===options.asset)throw new Error('"body" is required when making a '+options.method+" request");return options.body instanceof UsergridEntity?options.body=options.body.jsonValue():options.body instanceof Array&&options.body[0]instanceof UsergridEntity&&(options.body=_.map(options.body,function(entity){return entity.jsonValue()})),options},UsergridHelpers.buildReqest=function(client,method,args){var options={client:client,method:method,queryParams:args.queryParams||_.get(args,"0.queryParams"),callback:UsergridHelpers.callback(args)};return UsergridHelpers.assignPrefabOptions(options,args),UsergridHelpers.setEntity(options,args),(method===UsergridHttpMethod.POST||method===UsergridHttpMethod.PUT)&&(UsergridHelpers.setAsset(options,args),void 0===options.asset&&UsergridHelpers.setBody(options,args)),UsergridHelpers.setUuidOrName(options,args),UsergridHelpers.setPathOrType(options,args),UsergridHelpers.setQs(options,args),UsergridHelpers.setQuery(options,args),options.uri=UsergridHelpers.uri(client,options),new UsergridRequest(options)},UsergridHelpers.buildAppAuthRequest=function(client,auth,callback){var requestOptions={client:client,method:UsergridHttpMethod.POST,uri:UsergridHelpers.uri(client,{path:"token"}),body:UsergridHelpers.appLoginBody(auth),callback:callback};return new UsergridRequest(requestOptions)},UsergridHelpers.buildConnectionRequest=function(client,method,args){var options={client:client,method:method,entity:{},to:{},callback:UsergridHelpers.callback(args)};if(UsergridHelpers.assignPrefabOptions.call(options,args),_.isObject(options.from)&&(options.to=options.from),_.isObject(args[0])&&_.has(args[0],"entity")&&_.has(args[0],"to")&&(_.assign(options.entity,args[0].entity),options.relationship=_.get(args,"0.relationship"),_.assign(options.to,args[0].to)),_.isObject(args[0])&&!_.isFunction(args[0])&&_.isString(args[1])&&(_.assign(options.entity,args[0]),options.relationship=_.first([options.relationship,args[1]].filter(_.isString))),_.isObject(args[2])&&!_.isFunction(args[2])&&_.assign(options.to,args[2]),options.entity.uuidOrName=_.first([options.entity.uuidOrName,options.entity.uuid,options.entity.name,args[1]].filter(_.isString)),options.entity.type||(options.entity.type=_.first([options.entity.type,args[0]].filter(_.isString))),options.relationship=_.first([options.relationship,args[2]].filter(_.isString)),_.isString(args[3])&&!UsergridHelpers.isUUID(args[3])&&_.isString(args[4])?options.to.type=args[3]:_.isString(args[2])&&!UsergridHelpers.isUUID(args[2])&&_.isString(args[3])&&_.isObject(args[0])&&!_.isFunction(args[0])&&(options.to.type=args[2]),options.to.uuidOrName=_.first([options.to.uuidOrName,options.to.uuid,options.to.name,args[4],args[3],args[2]].filter(function(property){return _.isString(options.to.type)&&_.isString(property)||UsergridHelpers.isUUID(property)})),!_.isString(options.entity.uuidOrName))throw new Error('source entity "uuidOrName" is required when connecting or disconnecting entities');if(!_.isString(options.to.uuidOrName))throw new Error('target entity "uuidOrName" is required when connecting or disconnecting entities');if(!_.isString(options.to.type)&&!UsergridHelpers.isUUID(options.to.uuidOrName))throw new Error('target "type" (collection name) parameter is required connecting or disconnecting entities by name');return options.uri=UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,_.isString(options.entity.type)?options.entity.type:"",_.isString(options.entity.uuidOrName)?options.entity.uuidOrName:"",options.relationship,_.isString(options.to.type)?options.to.type:"",_.isString(options.to.uuidOrName)?options.to.uuidOrName:""),new UsergridRequest(options)},UsergridHelpers.buildGetConnectionRequest=function(client,args){var options={client:client,method:"GET",callback:UsergridHelpers.callback(args)};if(UsergridHelpers.assignPrefabOptions.call(options,args),_.isObject(args[1])&&!_.isFunction(args[1])&&_.assign(options,args[1]),options.direction=_.first([options.direction,args[0]].filter(function(property){return property===UsergridDirection.IN||property===UsergridDirection.OUT})),options.relationship=_.first([options.relationship,args[3],args[2]].filter(_.isString)),options.uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,args[2]].filter(_.isString)),options.type=_.first([options.type,args[1]].filter(_.isString)),!_.isString(options.type))throw new Error('"type" (collection name) parameter is required when retrieving connections');if(!_.isString(options.uuidOrName))throw new Error('target entity "uuidOrName" is required when retrieving connections');return options.uri=UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,_.isString(options.type)?options.type:"",_.isString(options.uuidOrName)?options.uuidOrName:"",options.direction,options.relationship),new UsergridRequest(options)},global[name]=UsergridHelpers,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),UsergridHelpers},global[name]}(this);var UsergridClientDefaultOptions={baseUrl:"https://api.usergrid.com",authMode:UsergridAuthMode.USER},UsergridClient=function(options){var __appAuth,self=this;if(self.tempAuth=void 0,self.isSharedInstance=!1,2===arguments.length&&(self.orgId=arguments[0],self.appId=arguments[1]),_.defaults(self,options,UsergridClientDefaultOptions),!self.orgId||!self.appId)throw new Error('"orgId" and "appId" parameters are required when instantiating UsergridClient');return Object.defineProperty(self,"clientId",{enumerable:!1}),Object.defineProperty(self,"clientSecret",{enumerable:!1}),Object.defineProperty(self,"appAuth",{get:function(){return __appAuth},set:function(options){options instanceof UsergridAppAuth?__appAuth=options:"undefined"!=typeof options&&(__appAuth=new UsergridAppAuth(options))}}),self.clientId&&self.clientSecret&&self.setAppAuth(self.clientId,self.clientSecret),self};UsergridClient.prototype={sendRequest:function(usergridRequest){return usergridRequest.sendRequest()},GET:function(){var usergridRequest=UsergridHelpers.buildReqest(this,UsergridHttpMethod.GET,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},PUT:function(){var usergridRequest=UsergridHelpers.buildReqest(this,UsergridHttpMethod.PUT,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},POST:function(){var usergridRequest=UsergridHelpers.buildReqest(this,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},DELETE:function(){var usergridRequest=UsergridHelpers.buildReqest(this,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},connect:function(){var usergridRequest=UsergridHelpers.buildConnectionRequest(this,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},disconnect:function(){var usergridRequest=UsergridHelpers.buildConnectionRequest(this,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},getConnections:function(){var usergridRequest=UsergridHelpers.buildGetConnectionRequest(this,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},usingAuth:function(auth){var self=this;return _.isString(auth)?self.tempAuth=new UsergridAuth(auth):auth instanceof UsergridAuth?self.tempAuth=auth:self.tempAuth=void 0,self},setAppAuth:function(){this.appAuth=new UsergridAppAuth(UsergridHelpers.flattenArgs(arguments))},authenticateApp:function(options){var self=this,authenticateAppCallback=UsergridHelpers.callback(UsergridHelpers.flattenArgs(arguments)),auth=_.first([options,self.appAuth,new UsergridAppAuth(options),new UsergridAppAuth(self.clientId,self.clientSecret)].filter(function(p){return p instanceof UsergridAppAuth}));if(!(auth instanceof UsergridAppAuth))throw new Error("App auth context was not defined when attempting to call .authenticateApp()");if(!auth.clientId||!auth.clientSecret)throw new Error("authenticateApp() failed because clientId or clientSecret are missing");var callback=function(usergridResponse){if(usergridResponse.ok){self.appAuth||(self.appAuth=auth),self.appAuth.token=_.get(usergridResponse.responseJSON,"access_token");var expiresIn=_.get(usergridResponse.responseJSON,"expires_in");self.appAuth.expiry=UsergridHelpers.calculateExpiry(expiresIn),self.appAuth.tokenTtl=expiresIn}authenticateAppCallback(usergridResponse)},usergridRequest=UsergridHelpers.buildAppAuthRequest(self,auth,callback);return self.sendRequest(usergridRequest)},authenticateUser:function(options){var self=this,args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args),setAsCurrentUser=void 0!==_.last(args.filter(_.isBoolean))?_.last(args.filter(_.isBoolean)):!0,userToAuthenticate=new UsergridUser(options);userToAuthenticate.login(self,function(auth,user,usergridResponse){usergridResponse.ok&&setAsCurrentUser&&(self.currentUser=userToAuthenticate),callback(auth,user,usergridResponse)})},downloadAsset:function(){var self=this,usergridRequest=UsergridHelpers.buildReqest(self,UsergridHttpMethod.GET,UsergridHelpers.flattenArgs(arguments)),assetContentType=_.get(usergridRequest,"entity.file-metadata.content-type");void 0!==assetContentType&&_.assign(usergridRequest.headers,{Accept:assetContentType});var realDownloadAssetCallback=usergridRequest.callback;return usergridRequest.callback=function(usergridResponse){var entity=usergridRequest.entity;entity.asset=usergridResponse.asset,realDownloadAssetCallback(entity.asset,usergridResponse,entity)},self.sendRequest(usergridRequest)},uploadAsset:function(){var self=this,usergridRequest=UsergridHelpers.buildReqest(self,UsergridHttpMethod.PUT,UsergridHelpers.flattenArgs(arguments));if(void 0===usergridRequest.asset)throw new Error("An UsergridAsset was not defined when attempting to call .uploadAsset()");var realUploadAssetCallback=usergridRequest.callback;return usergridRequest.callback=function(usergridResponse){var requestEntity=usergridRequest.entity,responseEntity=usergridResponse.entity,requestAsset=usergridRequest.asset;usergridResponse.ok&&void 0!==responseEntity&&(UsergridHelpers.updateEntityFromRemote(requestEntity,usergridResponse),requestEntity.asset=requestAsset,responseEntity&&(responseEntity.asset=requestAsset)),realUploadAssetCallback(requestAsset,usergridResponse,requestEntity)},self.sendRequest(usergridRequest)}};var UsergridSDKVersion="2.0.0",UsergridClientSharedInstance=function(){var self=this;return self.isInitialized=!1,self.isSharedInstance=!0,self};UsergridHelpers.inherits(UsergridClientSharedInstance,UsergridClient);var Usergrid=new UsergridClientSharedInstance;Usergrid.initSharedInstance=function(options){return Usergrid.isInitialized?console.log("Usergrid shared instance is already initialized"):(_.assign(Usergrid,new UsergridClient(options)),Usergrid.isInitialized=!0,Usergrid.isSharedInstance=!0),Usergrid},Usergrid.init=Usergrid.initSharedInstance;var UsergridQuery=function(type){var queryString,sort,self=this,query="",urlTerms={},__nextIsNot=!1;return self._type=type,_.assign(self,{type:function(value){return self._type=value,self},collection:function(value){return self._type=value,self},limit:function(value){return self._limit=value,self},cursor:function(value){return self._cursor=value,self},eq:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.EQUAL+" "+UsergridHelpers.useQuotesIfRequired(value)),self},equal:this.eq,gt:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.GREATER_THAN+" "+UsergridHelpers.useQuotesIfRequired(value)),self},greaterThan:this.gt,gte:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.GREATER_THAN_EQUAL_TO+" "+UsergridHelpers.useQuotesIfRequired(value)),self},greaterThanOrEqual:this.gte,lt:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.LESS_THAN+" "+UsergridHelpers.useQuotesIfRequired(value)),self},lessThan:this.lt,lte:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.LESS_THAN_EQUAL_TO+" "+UsergridHelpers.useQuotesIfRequired(value)),self},lessThanOrEqual:this.lte,contains:function(key,value){return query=self.andJoin(key+" contains "+UsergridHelpers.useQuotesIfRequired(value)),self},locationWithin:function(distanceInMeters,lat,lng){return query=self.andJoin("location within "+distanceInMeters+" of "+lat+", "+lng),self},asc:function(key){return self.sort(key,UsergridQuerySortOrder.ASC),self},desc:function(key){return self.sort(key,UsergridQuerySortOrder.DESC),self},sort:function(key,order){return sort=key&&order?" order by "+key+" "+order:"",self},fromString:function(string){return queryString=string,self},urlTerm:function(key,value){return"ql"===key?self.fromString():urlTerms[key]=value,self},andJoin:function(append){return __nextIsNot&&(append="not "+append,__nextIsNot=!1),append?0===query.length?append:_.endsWith(query,"and")||_.endsWith(query,"or")?query+" "+append:query+" and "+append:query},orJoin:function(){return query.length>0&&!_.endsWith(query,"or")?query+" or":query}}),Object.defineProperty(self,"_ql",{get:function(){var ql="select * ";return void 0!==queryString?ql=queryString:(ql+=query.length>0?"where "+(query||""):"",ql+=void 0!==sort?sort:""),ql}}),Object.defineProperty(self,"encodedStringValue",{get:function(){var self=this,limit=self._limit,cursor=self._cursor,requirementsString=self._ql,returnString=void 0;if(void 0!==limit&&(returnString="limit"+UsergridQueryOperator.EQUAL+limit),!_.isEmpty(cursor)){var cursorString="cursor"+UsergridQueryOperator.EQUAL+cursor;_.isEmpty(returnString)?returnString=cursorString:returnString+="&"+cursorString}if(_.forEach(urlTerms,function(value,key){var encodedURLTermString=encodeURIComponent(key)+UsergridQueryOperator.EQUAL+encodeURIComponent(value);_.isEmpty(returnString)?returnString=encodedURLTermString:returnString+="&"+encodedURLTermString}),!_.isEmpty(requirementsString)){var qLString="ql="+encodeURIComponent(requirementsString); +_.isEmpty(returnString)?returnString=qLString:returnString+="&"+qLString}return _.isEmpty(returnString)||(returnString="?"+returnString),_.isEmpty(returnString)?void 0:returnString}}),Object.defineProperty(self,"and",{get:function(){return query=self.andJoin(""),self}}),Object.defineProperty(self,"or",{get:function(){return query=self.orJoin(),self}}),Object.defineProperty(self,"not",{get:function(){return __nextIsNot=!0,self}}),self},UsergridRequestDefaultHeaders=Object.freeze({"Content-Type":"application/json",Accept:"application/json"}),UsergridRequest=function(options){var self=this,client=UsergridHelpers.validateAndRetrieveClient(options);if(!_.isString(options.type)&&!_.isString(options.path)&&!_.isString(options.uri))throw new Error('one of "type" (collection name), "path", or "uri" parameters are required when initializing a UsergridRequest');if(!_.includes(["GET","PUT","POST","DELETE"],options.method))throw new Error('"method" parameter is required when initializing a UsergridRequest');self.method=options.method,self.callback=options.callback,self.uri=options.uri||UsergridHelpers.uri(client,options),self.entity=options.entity,self.body=options.body||void 0,self.asset=options.asset||void 0,self.query=options.query,self.queryParams=options.queryParams||options.qs;var defaultHeadersToUse=void 0===self.asset?UsergridRequestDefaultHeaders:{};if(self.headers=UsergridHelpers.headers(client,options,defaultHeadersToUse),void 0!==self.query&&(self.uri+=UsergridHelpers.normalize(self.query.encodedStringValue,{})),void 0!==self.queryParams&&(_.forOwn(self.queryParams,function(value,key){self.uri+="?"+encodeURIComponent(key)+"="+encodeURIComponent(value)}),self.uri=UsergridHelpers.normalize(self.uri,{})),void 0!==self.asset)self.body=new FormData,self.body.append("file",self.asset.data);else try{_.isPlainObject(self.body)?self.body=JSON.stringify(self.body):_.isArray(self.body)&&(self.body=JSON.stringify(self.body))}catch(exception){}return self};UsergridRequest.prototype.sendRequest=function(){var self=this,requestPromise=function(){var promise=new Promise,xmlHttpRequest=new XMLHttpRequest;return xmlHttpRequest.open(self.method,self.uri,!0),xmlHttpRequest.onload=function(){promise.done(xmlHttpRequest)},_.forOwn(self.headers,function(value,key){xmlHttpRequest.setRequestHeader(key,value)}),self.method===UsergridHttpMethod.GET&&"application/json"!==_.get(self.headers,"Accept")&&(xmlHttpRequest.responseType="blob"),xmlHttpRequest.send(self.body),promise}.bind(self),responsePromise=function(xmlRequest){var promise=new Promise,usergridResponse=new UsergridResponse(xmlRequest,self);return promise.done(usergridResponse),promise}.bind(self),onCompletePromise=function(response){var promise=new Promise;promise.done(response),self.callback(response)}.bind(self);return Promise.chain([requestPromise,responsePromise]).then(onCompletePromise),self};var UsergridAuth=function(token,expiry){var self=this;self.token=token,self.expiry=expiry||0;var usingToken=token?!0:!1;return Object.defineProperty(self,"hasToken",{get:function(){return void 0!==self.token},configurable:!0}),Object.defineProperty(self,"isExpired",{get:function(){return usingToken?!1:Date.now()>=self.expiry},configurable:!0}),Object.defineProperty(self,"isValid",{get:function(){return!self.isExpired&&self.hasToken},configurable:!0}),Object.defineProperty(self,"tokenTtl",{configurable:!0,writable:!0}),_.assign(self,{destroy:function(){self.token=void 0,self.expiry=0,self.tokenTtl=void 0}}),self},UsergridAppAuth=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments);return _.isPlainObject(args[0])?(self.clientId=args[0].clientId,self.clientSecret=args[0].clientSecret,self.tokenTtl=args[0].tokenTtl):(self.clientId=args[0],self.clientSecret=args[1],self.tokenTtl=args[2]),UsergridAuth.call(self),_.assign(self,UsergridAuth),self};UsergridHelpers.inherits(UsergridAppAuth,UsergridAuth);var UsergridUserAuth=function(options){var self=this,args=_.flattenDeep(UsergridHelpers.flattenArgs(arguments));return _.isPlainObject(args[0])&&(options=args[0]),self.username=options.username||args[0],self.email=options.email,(options.password||args[1])&&(self.password=options.password||args[1]),self.tokenTtl=options.tokenTtl||args[2],UsergridAuth.call(self),_.assign(self,UsergridAuth),self};UsergridHelpers.inherits(UsergridUserAuth,UsergridAuth);var UsergridEntity=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments);if(0===args.length)throw new Error("A UsergridEntity object cannot be initialized without passing one or more arguments");if(self.asset=void 0,_.isPlainObject(args[0])?_.assign(self,args[0]):(self.type||(self.type=_.isString(args[0])?args[0]:void 0),self.name||(self.name=_.isString(args[1])?args[1]:void 0)),!_.isString(self.type))throw new Error('"type" (or "collection") parameter is required when initializing a UsergridEntity object');return Object.defineProperty(self,"isUser",{get:function(){return"user"===self.type.toLowerCase()}}),Object.defineProperty(self,"hasAsset",{get:function(){return _.has(self,"file-metadata")}}),UsergridHelpers.setReadOnly(self,["uuid","name","type","created"]),self};UsergridEntity.prototype={jsonValue:function(){var jsonValue={};return _.forOwn(this,function(value,key){jsonValue[key]=value}),jsonValue},putProperty:function(key,value){this[key]=value},putProperties:function(obj){_.assign(this,obj)},removeProperty:function(key){this.removeProperties([key])},removeProperties:function(keys){var self=this;keys.forEach(function(key){delete self[key]})},insert:function(key,value,idx){_.isArray(this[key])||(this[key]=this[key]?[this[key]]:[]),this[key].splice.apply(this[key],[idx,0].concat(value))},append:function(key,value){this.insert(key,value,Number.MAX_VALUE)},prepend:function(key,value){this.insert(key,value,0)},pop:function(key){_.isArray(this[key])&&this[key].pop()},shift:function(key){_.isArray(this[key])&&this[key].shift()},reload:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.GET(self,function(usergridResponse){UsergridHelpers.updateEntityFromRemote(self,usergridResponse),callback(usergridResponse,self)}.bind(self))},save:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args),currentAsset=self.asset,uuid=self.uuid;void 0===uuid?client.POST(self,function(usergridResponse){UsergridHelpers.updateEntityFromRemote(self,usergridResponse),self.hasAsset&&(self.asset=currentAsset),callback(usergridResponse,self)}.bind(self)):client.PUT(self,function(usergridResponse){UsergridHelpers.updateEntityFromRemote(self,usergridResponse),self.hasAsset&&(self.asset=currentAsset),callback(usergridResponse,self)}.bind(self))},remove:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.DELETE(self,function(usergridResponse){callback(usergridResponse,self)}.bind(self))},attachAsset:function(asset){this.asset=asset},uploadAsset:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(_.has(self,"asset.contentType"))client.uploadAsset(self,callback);else{var response=new UsergridResponse;response.error=new UsergridResponseError({error:"asset_not_found",description:"The specified entity does not have a valid asset attached"}),callback(null,response,self)}},downloadAsset:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(_.has(self,"asset.contentType"))client.downloadAsset(self,callback);else{var response=new UsergridResponse;response.error=new UsergridResponseError({error:"asset_not_found",description:"The specified entity does not have a valid asset attached"}),callback(null,response,self)}},connect:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args[0]=this,client.connect.apply(client,args)},disconnect:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args[0]=this,client.disconnect.apply(client,args)},getConnections:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args.shift(),args.splice(1,0,this),client.getConnections.apply(client,args)}};var UsergridUser=function(obj){if(!_.has(obj,"email")&&!_.has(obj,"username"))throw new Error('"email" or "username" property is required when initializing a UsergridUser object');var self=this;return _.assign(self,obj,UsergridEntity),UsergridEntity.call(self,"user"),UsergridHelpers.setWritable(self,"name"),self};UsergridUser.CheckAvailable=function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);args[0]instanceof UsergridClient&&args.shift();var checkQuery,callback=UsergridHelpers.callback(args);if(args[0].username&&args[0].email)checkQuery=new UsergridQuery("users").eq("username",args[0].username).or.eq("email",args[0].email);else if(args[0].username)checkQuery=new UsergridQuery("users").eq("username",args[0].username);else{if(!args[0].email)throw new Error("'username' or 'email' property is required when checking for available users");checkQuery=new UsergridQuery("users").eq("email",args[0].email)}client.GET(checkQuery,function(usergridResponse){callback(usergridResponse,usergridResponse.entities.length>0)})},UsergridHelpers.inherits(UsergridUser,UsergridEntity),UsergridUser.prototype.uniqueId=function(){var self=this;return _.first([self.uuid,self.username,self.email].filter(_.isString))},UsergridUser.prototype.create=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.POST(self,function(usergridResponse){delete self.password,_.assign(self,usergridResponse.user),callback(usergridResponse)}.bind(self))},UsergridUser.prototype.login=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.POST("token",UsergridHelpers.userLoginBody(self),function(usergridResponse){if(delete self.password,usergridResponse.ok){var responseJSON=usergridResponse.responseJSON;self.auth=new UsergridUserAuth(self),self.auth.token=_.get(responseJSON,"access_token");var expiresIn=_.get(responseJSON,"expires_in");self.auth.expiry=UsergridHelpers.calculateExpiry(expiresIn),self.auth.tokenTtl=expiresIn}callback(self.auth,self,usergridResponse)})},UsergridUser.prototype.logout=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(self.auth&&self.auth.isValid){var revokeAll=_.first(args.filter(_.isBoolean))||!1,revokeTokenPath=["users",self.uniqueId(),"revoketoken"+(revokeAll?"s":"")].join("/"),queryParams=void 0;revokeAll||(queryParams={token:self.auth.token});var requestOptions={client:client,path:revokeTokenPath,method:UsergridHttpMethod.PUT,queryParams:queryParams,callback:function(usergridResponse){self.auth.destroy(),callback(usergridResponse)}.bind(self)},request=new UsergridRequest(requestOptions);client.sendRequest(request)}else{var response=new UsergridResponse;response.error=new UsergridResponseError({error:"no_valid_token",description:"this user does not have a valid token"}),callback(response)}},UsergridUser.prototype.logoutAllSessions=function(){var args=UsergridHelpers.flattenArgs(arguments);return args=_.concat([UsergridHelpers.validateAndRetrieveClient(args),!0],args),this.logout.apply(this,args)},UsergridUser.prototype.resetPassword=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);args[0]instanceof UsergridClient&&args.shift();var body={oldpassword:_.isPlainObject(args[0])?args[0].oldPassword:_.isString(args[0])?args[0]:void 0,newpassword:_.isPlainObject(args[0])?args[0].newPassword:_.isString(args[1])?args[1]:void 0};if(!body.oldpassword||!body.newpassword)throw new Error('"oldPassword" and "newPassword" properties are required when resetting a user password');client.PUT(["users",self.uniqueId(),"password"].join("/"),body,function(usergridResponse){callback(usergridResponse)})};var UsergridResponseError=function(responseErrorObject){var self=this;if(_.has(responseErrorObject,"error")!==!1)return self.name=responseErrorObject.error,self.description=_.get(responseErrorObject,"error_description")||responseErrorObject.description,self.exception=responseErrorObject.exception,self},UsergridResponse=function(xmlRequest,usergridRequest){var self=this;if(self.ok=!1,self.request=usergridRequest,xmlRequest){self.statusCode=parseInt(xmlRequest.status),self.ok=self.statusCode<400,self.headers=UsergridHelpers.parseResponseHeaders(xmlRequest.getAllResponseHeaders());var responseContentType=_.get(self.headers,"content-type");if("application/json"===responseContentType){try{var responseText=xmlRequest.responseText,responseJSON=JSON.parse(responseText)}catch(e){responseJSON={}}if(self.ok){if(void 0!==responseJSON&&(_.assign(self,{responseJSON:_.cloneDeep(responseJSON)}),_.has(responseJSON,"entities"))){var entities=_.map(responseJSON.entities,function(en){var entity=new UsergridEntity(en);return entity.isUser&&(entity=new UsergridUser(entity)),entity});_.assign(self,{entities:entities}),delete self.responseJSON.entities,self.first=_.first(entities)||void 0,self.entity=self.first,self.last=_.last(entities)||void 0,"/users"===_.get(self,"responseJSON.path")&&(self.user=self.first,self.users=self.entities),Object.defineProperty(self,"hasNextPage",{get:function(){return _.has(self,"responseJSON.cursor")}}),UsergridHelpers.setReadOnly(self.responseJSON)}}else self.error=new UsergridResponseError(responseJSON)}else self.asset=new UsergridAsset(xmlRequest.response)}return self};UsergridResponse.prototype={loadNextPage:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args),cursor=_.get(self,"responseJSON.cursor");cursor||callback();var client=UsergridHelpers.validateAndRetrieveClient(args),type=_.last(_.get(self,"responseJSON.path").split("/")),limit=_.first(_.get(this,"responseJSON.params.limit")),ql=_.first(_.get(this,"responseJSON.params.ql")),query=new UsergridQuery(type).fromString(ql).cursor(cursor).limit(limit);return client.GET(query,callback)}};var UsergridAssetDefaultFileName="file",UsergridAsset=function(fileOrBlob){if(!fileOrBlob instanceof File||!fileOrBlob instanceof Blob)throw new Error("UsergridAsset must be initialized with a 'File' or 'Blob'");var self=this;return self.data=fileOrBlob,self.filename=fileOrBlob.name||UsergridAssetDefaultFileName,self.contentLength=fileOrBlob.size,self.contentType=fileOrBlob.type,self}; \ No newline at end of file From 861f7131581c30111f65409c0dac31d1bf229820 Mon Sep 17 00:00:00 2001 From: Robert Walsh Date: Thu, 13 Oct 2016 15:45:18 -0500 Subject: [PATCH 27/36] Mainly cleanup with some fixes. --- Gruntfile.js | 2 +- examples/all-calls/app.js | 10 +- examples/dogs/app.js | 22 +- lib/modules/UsergridEntity.js | 10 +- lib/modules/UsergridRequest.js | 16 +- lib/modules/UsergridResponse.js | 136 ++++++----- lib/modules/UsergridUser.js | 15 +- lib/modules/util/Promise.js | 6 +- lib/modules/util/UsergridHelpers.js | 219 +++++++++-------- tests/mocha/index.html | 6 +- tests/mocha/test_asset.js | 100 ++++---- tests/mocha/test_client_auth.js | 229 ++++++++--------- tests/mocha/test_client_connections.js | 104 ++++---- tests/mocha/test_client_init.js | 20 +- tests/mocha/test_client_rest.js | 286 ++++++++++------------ tests/mocha/test_entity.js | 326 +++++++++++++------------ tests/mocha/test_helpers.js | 22 +- tests/mocha/test_query.js | 64 ++--- tests/mocha/test_response.js | 102 ++++---- tests/mocha/test_response_error.js | 25 +- tests/mocha/test_user.js | 136 ++++++----- tests/mocha/test_usergrid_init.js | 16 +- usergrid.js | 216 +++++++++------- usergrid.min.js | 10 +- 24 files changed, 1077 insertions(+), 1021 deletions(-) diff --git a/Gruntfile.js b/Gruntfile.js index 0fb6af6..df52419 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -34,7 +34,7 @@ module.exports = function(grunt) { * \n\ * \n\ * <%= meta.package.name %>@<%= meta.package.version %> <%= grunt.template.today('yyyy-mm-dd') %> \n\ - */\n" + */\n"; // Project configuration. grunt.initConfig({ diff --git a/examples/all-calls/app.js b/examples/all-calls/app.js index 194b4f0..c1a629e 100755 --- a/examples/all-calls/app.js +++ b/examples/all-calls/app.js @@ -128,7 +128,7 @@ $(document).ready(function () { function _get() { var endpoint = $("#get-path").val(); client.GET(endpoint, function(usergridResponse) { - var err = usergridResponse.error + var err = usergridResponse.error; if (err) { $("#response").html('
    ERROR: '+JSON.stringify(err,null,2)+'
    '); } else { @@ -142,7 +142,7 @@ $(document).ready(function () { var data = $("#post-data").val(); data = JSON.parse(data); client.POST(endpoint, data, function (usergridResponse) { - var err = usergridResponse.error + var err = usergridResponse.error; if (err) { $("#response").html('
    ERROR: '+JSON.stringify(err,null,2)+'
    '); } else { @@ -156,7 +156,7 @@ $(document).ready(function () { var data = $("#put-data").val(); data = JSON.parse(data); client.PUT(endpoint, data, function (usergridResponse) { - var err = usergridResponse.error + var err = usergridResponse.error; if (err) { $("#response").html('
    ERROR: '+JSON.stringify(err,null,2)+'
    '); } else { @@ -168,7 +168,7 @@ $(document).ready(function () { function _delete() { var endpoint = $("#delete-path").val(); client.DELETE(endpoint, function (usergridResponse) { - var err = usergridResponse.error + var err = usergridResponse.error; if (err) { $("#response").html('
    ERROR: '+JSON.stringify(err,null,2)+'
    '); } else { @@ -181,7 +181,7 @@ $(document).ready(function () { var username = $("#username").val(); var password = $("#password").val(); client.authenticateUser({username:username, password:password}, function (auth,user,usergridResponse) { - var err = usergridResponse.error + var err = usergridResponse.error; if (err) { $("#response").html('
    ERROR: '+JSON.stringify(err,null,2)+'
    '); } else { diff --git a/examples/dogs/app.js b/examples/dogs/app.js index ed68063..b8ad732 100755 --- a/examples/dogs/app.js +++ b/examples/dogs/app.js @@ -17,7 +17,7 @@ $(document).ready(function () { var client = new UsergridClient({orgId: "rwalsh", appId: "jssdktestapp", authMode: UsergridAuthMode.NONE}), lastResponse, lastQueryUsed, - previousCursors = [] + previousCursors = []; var message = $('#message'), nextButton = $('#next-button'), @@ -27,12 +27,12 @@ $(document).ready(function () { newDog = $('#new-dog'), newDogButton = $('#new-dog-button'), createDogButton = $('#create-dog'), - cancelCreateDogButton = $('#cancel-create-dog') + cancelCreateDogButton = $('#cancel-create-dog'); nextButton.bind('click', function() { message.html(''); - previousCursors.push(lastQueryUsed._cursor) - lastQueryUsed = new UsergridQuery('dogs').desc('created').cursor(_.get(lastResponse,'responseJSON.cursor')) + previousCursors.push(lastQueryUsed._cursor); + lastQueryUsed = new UsergridQuery('dogs').desc('created').cursor(_.get(lastResponse,'responseJSON.cursor')); lastResponse.loadNextPage(client,function(usergridResponse) { handleGETDogResponse(usergridResponse) }) @@ -40,9 +40,9 @@ $(document).ready(function () { previousButton.bind('click', function() { message.html(''); - var cursor = previousCursors.pop() + var cursor = previousCursors.pop(); if( cursor === '' ) { - previousCursors = '' + previousCursors = ''; cursor = undefined } drawDogs(cursor) @@ -67,7 +67,7 @@ $(document).ready(function () { }); function drawDogs(cursor) { - lastQueryUsed = new UsergridQuery('dogs').desc('created') + lastQueryUsed = new UsergridQuery('dogs').desc('created'); if( cursor !== undefined && !_.isEmpty(cursor) ) { lastQueryUsed.cursor(cursor) } @@ -77,7 +77,7 @@ $(document).ready(function () { } function handleGETDogResponse(usergridResponse) { - lastResponse = usergridResponse + lastResponse = usergridResponse; if(lastResponse.error) { alert('there was an error getting the dogs'); } else { @@ -87,7 +87,7 @@ $(document).ready(function () { _.forEach(lastResponse.entities,function(dog) { myDogList.append('
  • '+ dog.name + '
  • '); - }) + }); if (lastResponse.hasNextPage) { nextButton.show(); @@ -103,7 +103,7 @@ $(document).ready(function () { var name = $("#name").val(), nameHelp = $("#name-help"), - nameControl = $("#name-control") + nameControl = $("#name-control"); nameHelp.hide(); nameControl.removeClass('error'); @@ -124,7 +124,7 @@ $(document).ready(function () { newDog.hide(); dogsList.show(); createDogButton.removeClass("disabled"); - previousCursors = [] + previousCursors = []; drawDogs(); } }) diff --git a/lib/modules/UsergridEntity.js b/lib/modules/UsergridEntity.js index 1a3f7eb..9e87c01 100644 --- a/lib/modules/UsergridEntity.js +++ b/lib/modules/UsergridEntity.js @@ -161,9 +161,8 @@ UsergridEntity.prototype = { if( _.has(self,'asset.contentType') ) { client.uploadAsset(self,callback); } else { - var response = new UsergridResponse(); - response.error = new UsergridResponseError({ - error: 'asset_not_found', + var response = new UsergridResponse.responseWithError({ + name: 'asset_not_found', description: 'The specified entity does not have a valid asset attached' }); callback(null,response,self); @@ -179,9 +178,8 @@ UsergridEntity.prototype = { if( _.has(self,'asset.contentType') ) { client.downloadAsset(self,callback); } else { - var response = new UsergridResponse(); - response.error = new UsergridResponseError({ - error: 'asset_not_found', + var response = new UsergridResponse.responseWithError({ + name: 'asset_not_found', description: 'The specified entity does not have a valid asset attached' }); callback(null,response,self); diff --git a/lib/modules/UsergridRequest.js b/lib/modules/UsergridRequest.js index bf451cc..1cae541 100644 --- a/lib/modules/UsergridRequest.js +++ b/lib/modules/UsergridRequest.js @@ -14,8 +14,6 @@ 'use strict'; -var UsergridRequestDefaultHeaders = Object.freeze({"Content-Type":"application/json","Accept":"application/json"}); - var UsergridRequest = function(options) { var self = this; var client = UsergridHelpers.validateAndRetrieveClient(options); @@ -37,7 +35,7 @@ var UsergridRequest = function(options) { self.query = options.query; self.queryParams = options.queryParams || options.qs; - var defaultHeadersToUse = self.asset === undefined ? UsergridRequestDefaultHeaders : {}; + var defaultHeadersToUse = self.asset === undefined ? UsergridHelpers.DefaultHeaders : {}; self.headers = UsergridHelpers.headers(client, options, defaultHeadersToUse); if( self.query !== undefined ) { @@ -46,14 +44,14 @@ var UsergridRequest = function(options) { if( self.queryParams !== undefined ) { _.forOwn(self.queryParams, function(value,key){ - self.uri += '?' + encodeURIComponent(key) + '=' + encodeURIComponent(value); + self.uri += '?' + encodeURIComponent(key) + UsergridQueryOperator.EQUAL + encodeURIComponent(value); }); self.uri = UsergridHelpers.normalize(self.uri,{}); } if( self.asset !== undefined ) { self.body = new FormData(); - self.body.append("file", self.asset.data); + self.body.append(self.asset.filename, self.asset.data); } else { try{ if( _.isPlainObject(self.body) ) { @@ -83,26 +81,26 @@ UsergridRequest.prototype.sendRequest = function() { }); // If we are getting something that is not JSON we must be getting an asset so set the responseType to 'blob'. - if ( self.method === UsergridHttpMethod.GET && _.get(self.headers, "Accept") !== "application/json") { + if ( self.method === UsergridHttpMethod.GET && _.get(self.headers, "Accept") !== UsergridApplicationJSONHeaderValue) { xmlHttpRequest.responseType = "blob"; } xmlHttpRequest.send(self.body); return promise; - }.bind(self); + }; var responsePromise = function(xmlRequest) { var promise = new Promise(); var usergridResponse = new UsergridResponse(xmlRequest,self); promise.done(usergridResponse); return promise; - }.bind(self); + }; var onCompletePromise = function(response) { var promise = new Promise(); promise.done(response); self.callback(response); - }.bind(self); + }; Promise.chain([requestPromise, responsePromise]).then(onCompletePromise); return self; diff --git a/lib/modules/UsergridResponse.js b/lib/modules/UsergridResponse.js index df067e5..506d800 100644 --- a/lib/modules/UsergridResponse.js +++ b/lib/modules/UsergridResponse.js @@ -14,17 +14,25 @@ 'use strict'; -var UsergridResponseError = function(responseErrorObject) { +var UsergridResponseError = function(options) { var self = this; - if (_.has(responseErrorObject,'error') === false) { - return; - } - self.name = responseErrorObject.error; - self.description = _.get(responseErrorObject,'error_description') || responseErrorObject.description; - self.exception = responseErrorObject.exception; + _.assign(self, options); return self; }; +UsergridResponseError.fromJSON = function(responseErrorObject) { + var usergridResponseError = undefined; + var error = { name: _.get(responseErrorObject,'error') }; + if ( error.name !== undefined ) { + _.assign(error, { + exception: _.get(responseErrorObject,'exception'), + description: _.get(responseErrorObject,'error_description') || _.get(responseErrorObject,'description') + }); + usergridResponseError = new UsergridResponseError(error); + } + return usergridResponseError; +} + var UsergridResponse = function(xmlRequest,usergridRequest) { var self = this; self.ok = false; @@ -38,50 +46,24 @@ var UsergridResponse = function(xmlRequest,usergridRequest) { var responseContentType = _.get(self.headers,'content-type'); if( responseContentType === 'application/json' ) { try { - var responseText = xmlRequest.responseText; - var responseJSON = JSON.parse(responseText); + var responseJSON = JSON.parse(xmlRequest.responseText); } catch (e) { responseJSON = {}; } - if (self.ok) { - if( responseJSON !== undefined ) { - _.assign(self, { - responseJSON: _.cloneDeep(responseJSON) - }); - if (_.has(responseJSON, 'entities')) { - var entities = _.map(responseJSON.entities,function(en) { - var entity = new UsergridEntity(en); - if (entity.isUser) { - entity = new UsergridUser(entity); - } - return entity; - }); - _.assign(self, { - entities: entities - }); - delete self.responseJSON.entities; - - self.first = _.first(entities) || undefined; - self.entity = self.first; - self.last = _.last(entities) || undefined; - - if (_.get(self, 'responseJSON.path') === '/users') { - self.user = self.first; - self.users = self.entities; - } - Object.defineProperty(self, 'hasNextPage', { - get: function () { - return _.has(self, 'responseJSON.cursor'); - } - }); + self.parseResponseJSON(responseJSON); - UsergridHelpers.setReadOnly(self.responseJSON); - } + Object.defineProperty(self, 'cursor', { + get: function() { + return _.get(self,'responseJSON.cursor'); } - } else { - self.error = new UsergridResponseError(responseJSON); - } + }); + + Object.defineProperty(self, 'hasNextPage', { + get: function () { + return self.cursor !== undefined; + } + }); } else { self.asset = new UsergridAsset(xmlRequest.response); } @@ -89,20 +71,64 @@ var UsergridResponse = function(xmlRequest,usergridRequest) { return self; }; +UsergridResponse.responseWithError = function(options) { + var usergridResponse = new UsergridResponse(); + usergridResponse.error = new UsergridResponseError(options); + return usergridResponse; +}; + UsergridResponse.prototype = { + parseResponseJSON: function(responseJSON) { + var self = this; + if( responseJSON !== undefined ) { + _.assign(self, { responseJSON: _.cloneDeep(responseJSON) }); + if (self.ok) { + var entitiesJSON = _.get(responseJSON,'entities'); + if (entitiesJSON) { + var entities = _.map(entitiesJSON,function(entityJSON) { + var entity = new UsergridEntity(entityJSON); + if (entity.isUser) { + entity = new UsergridUser(entity); + } + return entity; + }); + _.assign(self, { entities: entities }); + delete self.responseJSON.entities; + + self.first = _.first(entities) || undefined; + self.entity = self.first; + self.last = _.last(entities) || undefined; + + if (_.get(responseJSON, 'path') === '/users') { + self.user = self.first; + self.users = self.entities; + } + UsergridHelpers.setReadOnly(self.responseJSON); + } + } else { + self.error = UsergridResponseError.fromJSON(responseJSON); + } + } + }, loadNextPage: function() { var self = this; - var args = UsergridHelpers.flattenArgs(arguments); - var callback = UsergridHelpers.callback(args); - var cursor = _.get(self,'responseJSON.cursor'); + var cursor = self.cursor; if (!cursor) { - callback(); + callback(UsergridResponse.responseWithError({ + name:'cursor_not_found', + description:'Cursor must be present in order perform loadNextPage().'}) + ); + } else { + var args = UsergridHelpers.flattenArgs(arguments); + var callback = UsergridHelpers.callback(args); + var client = UsergridHelpers.validateAndRetrieveClient(args); + + var type = _.last(_.get(self,'responseJSON.path').split('/')); + var limit = _.first(_.get(self,'responseJSON.params.limit')); + var ql = _.first(_.get(self,'responseJSON.params.ql')); + + var query = new UsergridQuery(type).fromString(ql).cursor(cursor).limit(limit); + client.GET(query, callback); } - var client = UsergridHelpers.validateAndRetrieveClient(args); - var type = _.last(_.get(self,'responseJSON.path').split('/')); - var limit = _.first(_.get(this,'responseJSON.params.limit')); - var ql = _.first(_.get(this,'responseJSON.params.ql')); - var query = new UsergridQuery(type).fromString(ql).cursor(cursor).limit(limit); - return client.GET(query, callback); } }; \ No newline at end of file diff --git a/lib/modules/UsergridUser.js b/lib/modules/UsergridUser.js index c31650b..13f5ee3 100644 --- a/lib/modules/UsergridUser.js +++ b/lib/modules/UsergridUser.js @@ -69,7 +69,7 @@ UsergridUser.prototype.create = function() { client.POST(self, function(usergridResponse) { delete self.password; _.assign(self, usergridResponse.user); - callback(usergridResponse); + callback(usergridResponse, usergridResponse.user); }.bind(self)); }; @@ -100,15 +100,13 @@ UsergridUser.prototype.logout = function() { var callback = UsergridHelpers.callback(args); if (!self.auth || !self.auth.isValid) { - var response = new UsergridResponse(); - response.error = new UsergridResponseError({ - error: 'no_valid_token', + var response = new UsergridResponse.responseWithError({ + name: 'no_valid_token', description: 'this user does not have a valid token' }); callback(response); } else { var revokeAll = _.first(args.filter(_.isBoolean)) || false; - var revokeTokenPath = ['users', self.uniqueId(), ('revoketoken' + ((revokeAll) ? "s" : ""))].join('/'); var queryParams = undefined; if (!revokeAll) { queryParams = {token: self.auth.token}; @@ -116,7 +114,7 @@ UsergridUser.prototype.logout = function() { var requestOptions = { client: client, - path: revokeTokenPath, + path: ['users', self.uniqueId(), ('revoketoken' + ((revokeAll) ? "s" : ""))].join('/'), method: UsergridHttpMethod.PUT, queryParams: queryParams, callback: function (usergridResponse) { @@ -148,11 +146,10 @@ UsergridUser.prototype.resetPassword = function() { oldpassword: _.isPlainObject(args[0]) ? args[0].oldPassword : _.isString(args[0]) ? args[0] : undefined, newpassword: _.isPlainObject(args[0]) ? args[0].newPassword : _.isString(args[1]) ? args[1] : undefined }; + if (!body.oldpassword || !body.newpassword) { throw new Error('"oldPassword" and "newPassword" properties are required when resetting a user password'); } - client.PUT(['users',self.uniqueId(),'password'].join('/'), body, function(usergridResponse) { - callback(usergridResponse); - }); + client.PUT(['users',self.uniqueId(),'password'].join('/'), body, callback); }; \ No newline at end of file diff --git a/lib/modules/util/Promise.js b/lib/modules/util/Promise.js index 0784ed6..5ba5a86 100644 --- a/lib/modules/util/Promise.js +++ b/lib/modules/util/Promise.js @@ -21,7 +21,7 @@ //Promise (function(global) { - var name = 'Promise', overwrittenName = global[name], exports; + var name = 'Promise', overwrittenName = global[name]; function Promise() { this.complete = false; @@ -42,7 +42,9 @@ this.complete = true; this.result = result; if(this.callbacks){ - for (var i = 0; i < this.callbacks.length; i++) this.callbacks[i](result); + _.forEach(this.callbacks,function(callback){ + callback(result) + }); this.callbacks.length = 0; } }; diff --git a/lib/modules/util/UsergridHelpers.js b/lib/modules/util/UsergridHelpers.js index e5a8982..21e7c6d 100644 --- a/lib/modules/util/UsergridHelpers.js +++ b/lib/modules/util/UsergridHelpers.js @@ -1,9 +1,18 @@ +'use strict'; + +var UsergridApplicationJSONHeaderValue = 'application/json'; + (function(global) { var name = 'UsergridHelpers', overwrittenName = global[name]; function UsergridHelpers() { } + UsergridHelpers.DefaultHeaders = Object.freeze({ + 'Content-Type': UsergridApplicationJSONHeaderValue, + 'Accept': UsergridApplicationJSONHeaderValue + }); + UsergridHelpers.validateAndRetrieveClient = function(args) { var client = undefined; if (args instanceof UsergridClient) { client = args; } @@ -47,7 +56,7 @@ authForRequests = client.appAuth; } return authForRequests; - } + }; UsergridHelpers.userLoginBody = function(options) { var body = { @@ -160,18 +169,19 @@ UsergridHelpers.parseResponseHeaders = function(headerStr) { var headers = {}; - if (!headerStr) { - return headers; - } - var headerPairs = headerStr.split('\u000d\u000a'); - for (var i = 0; i < headerPairs.length; i++) { - var headerPair = headerPairs[i]; - // Can't use split() here because it does the wrong thing - // if the header value has the string ": " in it. - var index = headerPair.indexOf('\u003a\u0020'); - if (index > 0) { - var key = headerPair.substring(0, index).toLowerCase(); - headers[key] = headerPair.substring(index + 2); + if (headerStr) { + var headerPairs = headerStr.split('\u000d\u000a'); + for (var i = 0; i < headerPairs.length; i++) { + + // Can't use split() here because it does the wrong thing + // if the header value has the string ": " in it. + + var headerPair = headerPairs[i]; + var index = headerPair.indexOf('\u003a\u0020'); + if (index > 0) { + var key = headerPair.substring(0, index).toLowerCase(); + headers[key] = headerPair.substring(index + 2); + } } } return headers; @@ -202,46 +212,45 @@ _.get(options,'body.uuid'), _.get(options,'body.name'), '' - ].filter(_.isString)) + ].filter(_.isString)); } - return UsergridHelpers.urljoin(client.baseUrl, client.orgId, client.appId, path, uuidOrName) + return UsergridHelpers.urljoin(client.baseUrl, client.orgId, client.appId, path, uuidOrName); }; UsergridHelpers.updateEntityFromRemote = function(entity,usergridResponse) { - UsergridHelpers.setWritable(entity, ['uuid', 'name', 'type', 'created']) - _.assign(entity, usergridResponse.entity) - UsergridHelpers.setReadOnly(entity, ['uuid', 'name', 'type', 'created']) - } + UsergridHelpers.setWritable(entity, ['uuid', 'name', 'type', 'created']); + _.assign(entity, usergridResponse.entity); + UsergridHelpers.setReadOnly(entity, ['uuid', 'name', 'type', 'created']); + }; UsergridHelpers.headers = function(client, options, defaultHeaders) { - var returnHeaders = {} - _.assign(returnHeaders, defaultHeaders) - _.assign(returnHeaders, options.headers); - _.assign(returnHeaders, { 'User-Agent':'usergrid-js/v' + UsergridSDKVersion }) + var returnHeaders = {}; + _.defaults(returnHeaders, options.headers, defaultHeaders); + _.assign(returnHeaders, { 'User-Agent':'usergrid-js/v' + UsergridSDKVersion } ); var authForRequests = UsergridHelpers.authForRequests(client); if (authForRequests) { - _.assign(returnHeaders, { authorization: 'Bearer ' + authForRequests.token }) + _.assign(returnHeaders, { authorization: 'Bearer ' + authForRequests.token }); } - return returnHeaders + return returnHeaders; }; UsergridHelpers.setEntity = function(options,args) { options.entity = _.first([options.entity, args[0]].filter(function(property) { - return (property instanceof UsergridEntity) - })) + return (property instanceof UsergridEntity); + })); if (options.entity !== undefined) { - options.type = options.entity.type + options.type = options.entity.type; } - return options - } + return options; + }; UsergridHelpers.setAsset = function(options,args) { options.asset = _.first([options.asset, _.get(options,'entity.asset'), args[1], args[0]].filter(function(property) { - return (property instanceof UsergridAsset) - })) - return options - } + return (property instanceof UsergridAsset); + })); + return options; + }; UsergridHelpers.setUuidOrName = function(options,args) { options.uuidOrName = _.first([ @@ -256,9 +265,9 @@ _.get(args,'0.name'), _.get(args,'2'), _.get(args,'1') - ].filter(_.isString)) - return options - } + ].filter(_.isString)); + return options; + }; UsergridHelpers.setPathOrType = function(options,args) { var pathOrType = _.first([ @@ -268,49 +277,49 @@ _.get(args,'body.type'), _.get(options,'body.0.type'), _.isArray(args) ? args[0] : undefined - ].filter(_.isString)) - options[(/\//.test(pathOrType)) ? 'path' : 'type'] = pathOrType - return options - } + ].filter(_.isString)); + options[(/\//.test(pathOrType)) ? 'path' : 'type'] = pathOrType; + return options; + }; UsergridHelpers.setQs = function(options,args) { if (options.path) { - options.qs = _.first([options.qs, args[2], args[1], args[0]].filter(_.isPlainObject)) + options.qs = _.first([options.qs, args[2], args[1], args[0]].filter(_.isPlainObject)); } - return options - } + return options; + }; UsergridHelpers.setQuery = function(options,args) { options.query = _.first([options,options.query, args[0]].filter(function(property) { - return (property instanceof UsergridQuery) - })) - return options - } + return (property instanceof UsergridQuery); + })); + return options; + }; UsergridHelpers.setAsset = function(options,args) { options.asset = _.first([options.asset, _.get(options,'entity.asset'), args[1], args[0]].filter(function(property) { - return (property instanceof UsergridAsset) - })) - return options - } + return (property instanceof UsergridAsset); + })); + return options; + }; UsergridHelpers.setBody = function(options,args) { options.body = _.first([args.entity, args.body, args[0].entity, args[0].body, args[2], args[1], args[0]].filter(function(property) { - return _.isObject(property) && !_.isFunction(property) && !(property instanceof UsergridQuery) && !(property instanceof UsergridAsset) - })) + return _.isObject(property) && !_.isFunction(property) && !(property instanceof UsergridQuery) && !(property instanceof UsergridAsset); + })); if (options.body === undefined && options.asset === undefined) { - throw new Error('"body" is required when making a ' + options.method + ' request') + throw new Error('"body" is required when making a ' + options.method + ' request'); } if( options.body instanceof UsergridEntity ) { - options.body = options.body.jsonValue() + options.body = options.body.jsonValue(); } else if( options.body instanceof Array ) { if( options.body[0] instanceof UsergridEntity ) { - options.body = _.map(options.body, function(entity){ return entity.jsonValue(); }) + options.body = _.map(options.body, function(entity){ return entity.jsonValue(); }); } } - return options - } + return options; + }; UsergridHelpers.buildReqest = function(client, method, args) { var options = { @@ -318,27 +327,27 @@ method: method, queryParams: args.queryParams || _.get(args,'0.queryParams'), callback: UsergridHelpers.callback(args) - } + }; - UsergridHelpers.assignPrefabOptions(options, args) - UsergridHelpers.setEntity(options, args) + UsergridHelpers.assignPrefabOptions(options, args); + UsergridHelpers.setEntity(options, args); if( method === UsergridHttpMethod.POST || method === UsergridHttpMethod.PUT ) { - UsergridHelpers.setAsset(options, args) + UsergridHelpers.setAsset(options, args); if( options.asset === undefined ) { - UsergridHelpers.setBody(options, args) + UsergridHelpers.setBody(options, args); } } - UsergridHelpers.setUuidOrName(options, args) - UsergridHelpers.setPathOrType(options, args) - UsergridHelpers.setQs(options, args) - UsergridHelpers.setQuery(options, args) + UsergridHelpers.setUuidOrName(options, args); + UsergridHelpers.setPathOrType(options, args); + UsergridHelpers.setQs(options, args); + UsergridHelpers.setQuery(options, args); - options.uri = UsergridHelpers.uri(client,options) + options.uri = UsergridHelpers.uri(client,options); - return new UsergridRequest(options) - } + return new UsergridRequest(options); + }; UsergridHelpers.buildAppAuthRequest = function(client,auth,callback) { var requestOptions = { @@ -347,9 +356,9 @@ uri: UsergridHelpers.uri(client, {path: 'token'} ), body: UsergridHelpers.appLoginBody(auth), callback: callback - } - return new UsergridRequest(requestOptions) - } + }; + return new UsergridRequest(requestOptions); + }; UsergridHelpers.buildConnectionRequest = function(client,method,args) { var options = { @@ -358,58 +367,58 @@ entity: {}, to: {}, callback: UsergridHelpers.callback(args) - } + }; - UsergridHelpers.assignPrefabOptions.call(options, args) + UsergridHelpers.assignPrefabOptions.call(options, args); // handle DELETE using "from" preposition if (_.isObject(options.from)) { - options.to = options.from + options.to = options.from; } if( _.isObject(args[0]) && _.has(args[0],'entity') && _.has(args[0],'to') ) { _.assign(options.entity,args[0].entity); - options.relationship = _.get(args,'0.relationship') + options.relationship = _.get(args,'0.relationship'); _.assign(options.to,args[0].to); } // if an entity object or UsergridEntity instance is the first argument (source) if (_.isObject(args[0]) && !_.isFunction(args[0]) && _.isString(args[1])) { - _.assign(options.entity, args[0]) - options.relationship = _.first([options.relationship, args[1]].filter(_.isString)) + _.assign(options.entity, args[0]); + options.relationship = _.first([options.relationship, args[1]].filter(_.isString)); } // if an entity object or UsergridEntity instance is the third argument (target) if (_.isObject(args[2]) && !_.isFunction(args[2])) { - _.assign(options.to, args[2]) + _.assign(options.to, args[2]); } - options.entity.uuidOrName = _.first([options.entity.uuidOrName, options.entity.uuid, options.entity.name, args[1]].filter(_.isString)) + options.entity.uuidOrName = _.first([options.entity.uuidOrName, options.entity.uuid, options.entity.name, args[1]].filter(_.isString)); if (!options.entity.type) { - options.entity.type = _.first([options.entity.type, args[0]].filter(_.isString)) + options.entity.type = _.first([options.entity.type, args[0]].filter(_.isString)); } - options.relationship = _.first([options.relationship, args[2]].filter(_.isString)) + options.relationship = _.first([options.relationship, args[2]].filter(_.isString)); if (_.isString(args[3]) && !UsergridHelpers.isUUID(args[3]) && _.isString(args[4])) { - options.to.type = args[3] + options.to.type = args[3]; } else if (_.isString(args[2]) && !UsergridHelpers.isUUID(args[2]) && _.isString(args[3]) && _.isObject(args[0]) && !_.isFunction(args[0])) { - options.to.type = args[2] + options.to.type = args[2]; } options.to.uuidOrName = _.first([options.to.uuidOrName, options.to.uuid, options.to.name, args[4], args[3], args[2]].filter(function(property) { - return (_.isString(options.to.type) && _.isString(property) || UsergridHelpers.isUUID(property)) - })) + return (_.isString(options.to.type) && _.isString(property) || UsergridHelpers.isUUID(property)); + })); if (!_.isString(options.entity.uuidOrName)) { - throw new Error('source entity "uuidOrName" is required when connecting or disconnecting entities') + throw new Error('source entity "uuidOrName" is required when connecting or disconnecting entities'); } if (!_.isString(options.to.uuidOrName)) { - throw new Error('target entity "uuidOrName" is required when connecting or disconnecting entities') + throw new Error('target entity "uuidOrName" is required when connecting or disconnecting entities'); } if (!_.isString(options.to.type) && !UsergridHelpers.isUUID(options.to.uuidOrName)) { - throw new Error('target "type" (collection name) parameter is required connecting or disconnecting entities by name') + throw new Error('target "type" (collection name) parameter is required connecting or disconnecting entities by name'); } options.uri = UsergridHelpers.urljoin( @@ -421,9 +430,9 @@ options.relationship, _.isString(options.to.type) ? options.to.type : "", _.isString(options.to.uuidOrName) ? options.to.uuidOrName : "" - ) + ); - return new UsergridRequest(options) + return new UsergridRequest(options); }; UsergridHelpers.buildGetConnectionRequest = function(client,args) { @@ -431,27 +440,27 @@ client: client, method: 'GET', callback: UsergridHelpers.callback(args) - } + }; - UsergridHelpers.assignPrefabOptions.call(options, args) + UsergridHelpers.assignPrefabOptions.call(options, args); if (_.isObject(args[1]) && !_.isFunction(args[1])) { - _.assign(options, args[1]) + _.assign(options, args[1]); } options.direction = _.first([options.direction, args[0]].filter(function(property) { - return (property === UsergridDirection.IN || property === UsergridDirection.OUT) - })) + return (property === UsergridDirection.IN || property === UsergridDirection.OUT); + })); - options.relationship = _.first([options.relationship, args[3], args[2]].filter(_.isString)) - options.uuidOrName = _.first([options.uuidOrName, options.uuid, options.name, args[2]].filter(_.isString)) - options.type = _.first([options.type, args[1]].filter(_.isString)) + options.relationship = _.first([options.relationship, args[3], args[2]].filter(_.isString)); + options.uuidOrName = _.first([options.uuidOrName, options.uuid, options.name, args[2]].filter(_.isString)); + options.type = _.first([options.type, args[1]].filter(_.isString)); if (!_.isString(options.type)) { - throw new Error('"type" (collection name) parameter is required when retrieving connections') + throw new Error('"type" (collection name) parameter is required when retrieving connections'); } if (!_.isString(options.uuidOrName)) { - throw new Error('target entity "uuidOrName" is required when retrieving connections') + throw new Error('target entity "uuidOrName" is required when retrieving connections'); } options.uri = UsergridHelpers.urljoin( @@ -462,9 +471,9 @@ _.isString(options.uuidOrName) ? options.uuidOrName : "", options.direction, options.relationship - ) + ); - return new UsergridRequest(options) + return new UsergridRequest(options); }; global[name] = UsergridHelpers; diff --git a/tests/mocha/index.html b/tests/mocha/index.html index 5a55f07..68168a9 100644 --- a/tests/mocha/index.html +++ b/tests/mocha/index.html @@ -26,7 +26,9 @@ @@ -61,7 +63,7 @@ - - - - - - - - - - - - - + + + + + + + + + + + + + + diff --git a/tests/mocha/test_client_rest.js b/tests/mocha/test_client_rest.js index bf5a0ac..49b16e6 100644 --- a/tests/mocha/test_client_rest.js +++ b/tests/mocha/test_client_rest.js @@ -330,8 +330,7 @@ configs.forEach(function(config) { usergridResponse.entities.forEach(function (entity) { entity.should.be.an.Object().with.property('testUuid').equal(body.testUuid) }); - var deleteQuery = new UsergridQuery(config.test.collection).eq('uuid', usergridResponse.entities[0].uuid).or.eq('uuid', usergridResponse.entities[1].uuid); - sleepFor(config.defaultLongSleepTime); + sleepFor(config.defaultLongSleepTime + config.defaultSleepTime); client.DELETE(query, function (delResponse) { delResponse.entities.should.be.an.Array().with.lengthOf(usergridResponse.entities.length); done() diff --git a/tests/mocha/test_entity.js b/tests/mocha/test_entity.js index fdc6c65..d5569ed 100644 --- a/tests/mocha/test_entity.js +++ b/tests/mocha/test_entity.js @@ -30,7 +30,9 @@ configs.forEach(function(config) { name: 'Cosmo', foo: 'baz' }); - entity.putProperty('name', 'Bazinga'); + should(function() { + entity.putProperty('name', 'Bazinga'); + }).throw(); entity.should.have.property('name').deepEqual('Cosmo'); }) }); @@ -62,15 +64,16 @@ configs.forEach(function(config) { name: 'Cosmo', foo: 'baz' }); - entity.putProperties({ - name: 'Bazinga', - uuid: 'BadUuid', - bar: 'qux' - }); + should(function() { + entity.putProperties({ + name: 'Bazinga', + uuid: 'BadUuid', + bar: 'qux' + }); + }).throw(); entity.should.containEql({ type: 'cat', name: 'Cosmo', - bar: 'qux', foo: 'baz' }) }) diff --git a/tests/mocha/test_helpers.js b/tests/mocha/test_helpers.js index 44b0ef0..7cf4bbd 100644 --- a/tests/mocha/test_helpers.js +++ b/tests/mocha/test_helpers.js @@ -7,8 +7,8 @@ var targetedConfigs = { "clientId": "YXA6KPq8cIsPEea0i-W5Jx8cgw", "clientSecret": "YXA6WaT7qsxh_eRS3ryBresi-HwoQAQ", "target": "1.0", - defaultSleepTime:0, - defaultLongSleepTime:0, + "defaultSleepTime":0, + "defaultLongSleepTime":0, "test": { "collection": "nodejs", "email": "authtest@test.com", @@ -23,8 +23,8 @@ var targetedConfigs = { "clientId": "YXA6WMhAuFJTEeWoggrRE9kXrQ", "clientSecret": "YXA6zZbat7PKgOlN73rpByc36LWaUhw", "target": "2.1", - defaultSleepTime:200, - defaultLongSleepTime:600, + "defaultSleepTime":200, + "defaultLongSleepTime":600, "test": { "collection": "nodejs", "email": "authtest@test.com", diff --git a/usergrid.js b/usergrid.js index 8cd28bb..3c0a560 100644 --- a/usergrid.js +++ b/usergrid.js @@ -19,6 +19,8 @@ * * usergrid@2.0.0 2016-10-13 */ +"use strict"; + (function(global) { var name = "Promise", overwrittenName = global[name]; function Promise() { @@ -91,10 +93,11 @@ })(this); (function() { + "use strict"; var undefined; - var VERSION = "4.16.0"; + var VERSION = "4.16.4"; var LARGE_ARRAY_SIZE = 200; - var FUNC_ERROR_TEXT = "Expected a function"; + var CORE_ERROR_TEXT = "Unsupported core-js use. Try https://github.com/es-shims.", FUNC_ERROR_TEXT = "Expected a function"; var HASH_UNDEFINED = "__lodash_hash_undefined__"; var MAX_MEMOIZE_SIZE = 500; var PLACEHOLDER = "__lodash_placeholder__"; @@ -106,10 +109,10 @@ var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991, MAX_INTEGER = 1.7976931348623157e308, NAN = 0 / 0; var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; var wrapFlags = [ [ "ary", ARY_FLAG ], [ "bind", BIND_FLAG ], [ "bindKey", BIND_KEY_FLAG ], [ "curry", CURRY_FLAG ], [ "curryRight", CURRY_RIGHT_FLAG ], [ "flip", FLIP_FLAG ], [ "partial", PARTIAL_FLAG ], [ "partialRight", PARTIAL_RIGHT_FLAG ], [ "rearg", REARG_FLAG ] ]; - var argsTag = "[object Arguments]", arrayTag = "[object Array]", boolTag = "[object Boolean]", dateTag = "[object Date]", errorTag = "[object Error]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", mapTag = "[object Map]", numberTag = "[object Number]", objectTag = "[object Object]", promiseTag = "[object Promise]", regexpTag = "[object RegExp]", setTag = "[object Set]", stringTag = "[object String]", symbolTag = "[object Symbol]", weakMapTag = "[object WeakMap]", weakSetTag = "[object WeakSet]"; + var argsTag = "[object Arguments]", arrayTag = "[object Array]", boolTag = "[object Boolean]", dateTag = "[object Date]", errorTag = "[object Error]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", mapTag = "[object Map]", numberTag = "[object Number]", objectTag = "[object Object]", promiseTag = "[object Promise]", proxyTag = "[object Proxy]", regexpTag = "[object RegExp]", setTag = "[object Set]", stringTag = "[object String]", symbolTag = "[object Symbol]", weakMapTag = "[object WeakMap]", weakSetTag = "[object WeakSet]"; var arrayBufferTag = "[object ArrayBuffer]", dataViewTag = "[object DataView]", float32Tag = "[object Float32Array]", float64Tag = "[object Float64Array]", int8Tag = "[object Int8Array]", int16Tag = "[object Int16Array]", int32Tag = "[object Int32Array]", uint8Tag = "[object Uint8Array]", uint8ClampedTag = "[object Uint8ClampedArray]", uint16Tag = "[object Uint16Array]", uint32Tag = "[object Uint32Array]"; var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; - var reEscapedHtml = /&(?:amp|lt|gt|quot|#39|#96);/g, reUnescapedHtml = /[&<>"'`]/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, reUnescapedHtml = /[&<>"']/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source); var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g; var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, reLeadingDot = /^\./, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source); @@ -716,7 +719,7 @@ function unicodeWords(string) { return string.match(reUnicodeWord) || []; } - function runInContext(context) { + var runInContext = function runInContext(context) { context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root; var Array = context.Array, Date = context.Date, Error = context.Error, Function = context.Function, Math = context.Math, Object = context.Object, RegExp = context.RegExp, String = context.String, TypeError = context.TypeError; var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; @@ -732,10 +735,17 @@ var objectToString = objectProto.toString; var oldDash = root._; var reIsNative = RegExp("^" + funcToString.call(hasOwnProperty).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"); - var Buffer = moduleExports ? context.Buffer : undefined, Symbol = context.Symbol, Uint8Array = context.Uint8Array, defineProperty = Object.defineProperty, getPrototype = overArg(Object.getPrototypeOf, Object), iteratorSymbol = Symbol ? Symbol.iterator : undefined, objectCreate = Object.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; + var Buffer = moduleExports ? context.Buffer : undefined, Symbol = context.Symbol, Uint8Array = context.Uint8Array, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, getPrototype = overArg(Object.getPrototypeOf, Object), iteratorSymbol = Symbol ? Symbol.iterator : undefined, objectCreate = Object.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; + var defineProperty = function() { + try { + var func = getNative(Object, "defineProperty"); + func({}, "", {}); + return func; + } catch (e) {} + }(); var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, ctxNow = Date && Date.now !== root.Date.now && Date.now, ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; var nativeCeil = Math.ceil, nativeFloor = Math.floor, nativeGetSymbols = Object.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, nativeIsFinite = context.isFinite, nativeJoin = arrayProto.join, nativeKeys = overArg(Object.keys, Object), nativeMax = Math.max, nativeMin = Math.min, nativeNow = Date.now, nativeParseInt = context.parseInt, nativeRandom = Math.random, nativeReverse = arrayProto.reverse; - var DataView = getNative(context, "DataView"), Map = getNative(context, "Map"), Promise = getNative(context, "Promise"), Set = getNative(context, "Set"), WeakMap = getNative(context, "WeakMap"), nativeCreate = getNative(Object, "create"), nativeDefineProperty = getNative(Object, "defineProperty"); + var DataView = getNative(context, "DataView"), Map = getNative(context, "Map"), Promise = getNative(context, "Promise"), Set = getNative(context, "Set"), WeakMap = getNative(context, "WeakMap"), nativeCreate = getNative(Object, "create"); var metaMap = WeakMap && new WeakMap(); var realNames = {}; var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); @@ -751,6 +761,21 @@ } return new LodashWrapper(value); } + var baseCreate = function() { + function object() {} + return function(proto) { + if (!isObject(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object(); + object.prototype = undefined; + return result; + }; + }(); function baseLodash() {} function LodashWrapper(value, chainAll) { this.__wrapped__ = value; @@ -1011,10 +1036,9 @@ Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; function arrayLikeKeys(value, inherited) { - var result = isArray(value) || isArguments(value) ? baseTimes(value.length, String) : []; - var length = result.length, skipIndexes = !!length; + var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { - if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && (key == "length" || isIndex(key, length)))) { + if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && (key == "length" || isBuff && (key == "offset" || key == "parent") || isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || isIndex(key, length)))) { result.push(key); } } @@ -1025,9 +1049,7 @@ return length ? array[baseRandom(0, length - 1)] : undefined; } function arraySampleSize(array, n) { - var result = arrayShuffle(array); - result.length = baseClamp(n, 0, result.length); - return result; + return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); } function arrayShuffle(array) { return shuffleSelf(copyArray(array)); @@ -1039,7 +1061,7 @@ return objValue; } function assignMergeValue(object, key, value) { - if (value !== undefined && !eq(object[key], value) || typeof key == "number" && value === undefined && !(key in object)) { + if (value !== undefined && !eq(object[key], value) || value === undefined && !(key in object)) { baseAssignValue(object, key, value); } } @@ -1137,9 +1159,7 @@ return stacked; } stack.set(value, result); - if (!isArr) { - var props = isFull ? getAllKeys(value) : keys(value); - } + var props = isArr ? undefined : (isFull ? getAllKeys : keys)(value); arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; @@ -1169,9 +1189,6 @@ } return true; } - function baseCreate(proto) { - return isObject(proto) ? objectCreate(proto) : {}; - } function baseDelay(func, wait, args) { if (typeof func != "function") { throw new TypeError(FUNC_ERROR_TEXT); @@ -1362,6 +1379,9 @@ var func = object == null ? object : object[toKey(path)]; return func == null ? undefined : apply(func, object, args); } + function baseIsArguments(value) { + return isObjectLike(value) && objectToString.call(value) == argsTag; + } function baseIsArrayBuffer(value) { return isObjectLike(value) && objectToString.call(value) == arrayBufferTag; } @@ -1388,6 +1408,13 @@ othTag = othTag == argsTag ? objectTag : othTag; } var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } if (isSameTag && !objIsObj) { stack || (stack = new Stack()); return objIsArr || isTypedArray(object) ? equalArrays(object, other, equalFunc, customizer, bitmask, stack) : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack); @@ -1524,14 +1551,7 @@ if (object === source) { return; } - if (!(isArray(source) || isTypedArray(source))) { - var props = baseKeysIn(source); - } - arrayEach(props || source, function(srcValue, key) { - if (props) { - key = srcValue; - srcValue = source[key]; - } + baseFor(source, function(srcValue, key) { if (isObject(srcValue)) { stack || (stack = new Stack()); baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); @@ -1542,7 +1562,7 @@ } assignMergeValue(object, key, newValue); } - }); + }, keysIn); } function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = object[key], srcValue = source[key], stacked = stack.get(srcValue); @@ -1553,24 +1573,28 @@ var newValue = customizer ? customizer(objValue, srcValue, key + "", object, source, stack) : undefined; var isCommon = newValue === undefined; if (isCommon) { + var isArr = isArray(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue); newValue = srcValue; - if (isArray(srcValue) || isTypedArray(srcValue)) { + if (isArr || isBuff || isTyped) { if (isArray(objValue)) { newValue = objValue; } else if (isArrayLikeObject(objValue)) { newValue = copyArray(objValue); - } else { + } else if (isBuff) { isCommon = false; - newValue = baseClone(srcValue, true); + newValue = cloneBuffer(srcValue, true); + } else if (isTyped) { + isCommon = false; + newValue = cloneTypedArray(srcValue, true); + } else { + newValue = []; } } else if (isPlainObject(srcValue) || isArguments(srcValue)) { + newValue = objValue; if (isArguments(objValue)) { newValue = toPlainObject(objValue); } else if (!isObject(objValue) || srcIndex && isFunction(objValue)) { - isCommon = false; - newValue = baseClone(srcValue, true); - } else { - newValue = objValue; + newValue = initCloneObject(srcValue); } } else { isCommon = false; @@ -1698,6 +1722,13 @@ function baseRest(func, start) { return setToString(overRest(func, start, identity), func + ""); } + function baseSample(collection) { + return arraySample(values(collection)); + } + function baseSampleSize(collection, n) { + var array = values(collection); + return shuffleSelf(array, baseClamp(n, 0, array.length)); + } function baseSet(object, path, value, customizer) { if (!isObject(object)) { return object; @@ -1722,14 +1753,17 @@ metaMap.set(func, data); return func; }; - var baseSetToString = !nativeDefineProperty ? identity : function(func, string) { - return nativeDefineProperty(func, "toString", { + var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, "toString", { configurable: true, enumerable: false, value: constant(string), writable: true }); }; + function baseShuffle(collection) { + return shuffleSelf(values(collection)); + } function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { @@ -1820,6 +1854,9 @@ if (typeof value == "string") { return value; } + if (isArray(value)) { + return arrayMap(value, baseToString) + ""; + } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ""; } @@ -1925,7 +1962,7 @@ if (isDeep) { return buffer.slice(); } - var result = new buffer.constructor(buffer.length); + var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } @@ -2937,13 +2974,15 @@ return func.apply(undefined, arguments); }; } - function shuffleSelf(array) { + function shuffleSelf(array, size) { var index = -1, length = array.length, lastIndex = length - 1; - while (++index < length) { + size = size === undefined ? length : size; + while (++index < size) { var rand = baseRandom(index, lastIndex), value = array[rand]; array[rand] = array[index]; array[index] = value; } + array.length = size; return array; } var stringToPath = memoizeCapped(function(string) { @@ -3579,7 +3618,8 @@ return func(collection, negate(getIteratee(predicate, 3))); } function sample(collection) { - return arraySample(isArrayLike(collection) ? collection : values(collection)); + var func = isArray(collection) ? arraySample : baseSample; + return func(collection); } function sampleSize(collection, n, guard) { if (guard ? isIterateeCall(collection, n, guard) : n === undefined) { @@ -3587,10 +3627,12 @@ } else { n = toInteger(n); } - return arraySampleSize(isArrayLike(collection) ? collection : values(collection), n); + var func = isArray(collection) ? arraySampleSize : baseSampleSize; + return func(collection, n); } function shuffle(collection) { - return shuffleSelf(isArrayLike(collection) ? copyArray(collection) : values(collection)); + var func = isArray(collection) ? arrayShuffle : baseShuffle; + return func(collection); } function size(collection) { if (collection == null) { @@ -3911,9 +3953,11 @@ var gte = createRelationalOperation(function(value, other) { return value >= other; }); - function isArguments(value) { - return isArrayLikeObject(value) && hasOwnProperty.call(value, "callee") && (!propertyIsEnumerable.call(value, "callee") || objectToString.call(value) == argsTag); - } + var isArguments = baseIsArguments(function() { + return arguments; + }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, "callee") && !propertyIsEnumerable.call(value, "callee"); + }; var isArray = Array.isArray; var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; function isArrayLike(value) { @@ -3931,7 +3975,7 @@ return value != null && value.nodeType === 1 && isObjectLike(value) && !isPlainObject(value); } function isEmpty(value) { - if (isArrayLike(value) && (isArray(value) || typeof value == "string" || typeof value.splice == "function" || isBuffer(value) || isArguments(value))) { + if (isArrayLike(value) && (isArray(value) || typeof value == "string" || typeof value.splice == "function" || isBuffer(value) || isTypedArray(value) || isArguments(value))) { return !value.length; } var tag = getTag(value); @@ -3939,7 +3983,7 @@ return !value.size; } if (isPrototype(value)) { - return !nativeKeys(value).length; + return !baseKeys(value).length; } for (var key in value) { if (hasOwnProperty.call(value, key)) { @@ -3967,7 +4011,7 @@ } function isFunction(value) { var tag = isObject(value) ? objectToString.call(value) : ""; - return tag == funcTag || tag == genTag; + return tag == funcTag || tag == genTag || tag == proxyTag; } function isInteger(value) { return typeof value == "number" && value == toInteger(value); @@ -3995,7 +4039,7 @@ } function isNative(value) { if (isMaskable(value)) { - throw new Error("This method is not supported with core-js. Try https://github.com/es-shims."); + throw new Error(CORE_ERROR_TEXT); } return baseIsNative(value); } @@ -4251,21 +4295,19 @@ var toPairs = createToPairs(keys); var toPairsIn = createToPairs(keysIn); function transform(object, iteratee, accumulator) { - var isArr = isArray(object) || isTypedArray(object); + var isArr = isArray(object), isArrLike = isArr || isBuffer(object) || isTypedArray(object); iteratee = getIteratee(iteratee, 4); if (accumulator == null) { - if (isArr || isObject(object)) { - var Ctor = object.constructor; - if (isArr) { - accumulator = isArray(object) ? new Ctor() : []; - } else { - accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; - } + var Ctor = object && object.constructor; + if (isArrLike) { + accumulator = isArr ? new Ctor() : []; + } else if (isObject(object)) { + accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; } else { accumulator = {}; } } - (isArr ? arrayEach : baseForOwn)(object, function(value, index, object) { + (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { return iteratee(accumulator, value, index, object); }); return accumulator; @@ -4411,7 +4453,7 @@ } else if (radix) { radix = +radix; } - return nativeParseInt(toString(string), radix || 0); + return nativeParseInt(toString(string).replace(reTrimStart, ""), radix || 0); } function repeat(string, n, guard) { if (guard ? isIterateeCall(string, n, guard) : n === undefined) { @@ -5286,7 +5328,7 @@ lodash.prototype[iteratorSymbol] = wrapperToIterator; } return lodash; - } + }; var _ = runInContext(); if (typeof define == "function" && typeof define.amd == "object" && define.amd) { root._ = _; @@ -5301,6 +5343,8 @@ } }).call(this); +"use strict"; + var UsergridAuthMode = Object.freeze({ NONE: "none", USER: "user", @@ -6329,24 +6373,13 @@ UsergridEntity.prototype = { var client = UsergridHelpers.validateAndRetrieveClient(args); var callback = UsergridHelpers.callback(args); var currentAsset = self.asset; - var uuid = self.uuid; - if (uuid === undefined) { - client.POST(self, function(usergridResponse) { - UsergridHelpers.updateEntityFromRemote(self, usergridResponse); - if (self.hasAsset) { - self.asset = currentAsset; - } - callback(usergridResponse, self); - }.bind(self)); - } else { - client.PUT(self, function(usergridResponse) { - UsergridHelpers.updateEntityFromRemote(self, usergridResponse); - if (self.hasAsset) { - self.asset = currentAsset; - } - callback(usergridResponse, self); - }.bind(self)); - } + client.PUT(self, function(usergridResponse) { + UsergridHelpers.updateEntityFromRemote(self, usergridResponse); + if (self.hasAsset) { + self.asset = currentAsset; + } + callback(usergridResponse, self); + }.bind(self)); }, remove: function() { var self = this; diff --git a/usergrid.min.js b/usergrid.min.js index d5c4a64..1b3cd71 100644 --- a/usergrid.min.js +++ b/usergrid.min.js @@ -19,9 +19,9 @@ * * usergrid@2.0.0 2016-10-13 */ -"use strict";!function(global){function Promise(){this.complete=!1,this.result=null,this.callbacks=[]}var name="Promise",overwrittenName=global[name];return Promise.prototype.then=function(callback,context){var f=function(){return callback.apply(context,arguments)};this.complete?f(this.result):this.callbacks.push(f)},Promise.prototype.done=function(result){this.complete=!0,this.result=result,this.callbacks&&(_.forEach(this.callbacks,function(callback){callback(result)}),this.callbacks.length=0)},Promise.join=function(promises){function notifier(i){return function(result){completed+=1,results[i]=result,completed===total&&p.done(results)}}for(var p=new Promise,total=promises.length,completed=0,results=[],i=0;total>i;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,result){var p=new Promise;return null===promises||0===promises.length?p.done(result):promises[0](result).then(function(res){promises.splice(0,1),promises?Promise.chain(promises,res).then(function(r){p.done(r)}):p.done(res)}),p},global[name]=Promise,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Promise},global[name]}(this),function(){function addMapEntry(map,pair){return map.set(pair[0],pair[1]),map}function addSetEntry(set,value){return set.add(value),set}function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}function arrayAggregator(array,setter,iteratee,accumulator){for(var index=-1,length=array?array.length:0;++index-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1;);return index}function charsEndIndex(strSymbols,chrSymbols){for(var index=strSymbols.length;index--&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1;);return index}function countHolders(array,placeholder){for(var length=array.length,result=0;length--;)array[length]===placeholder&&++result;return result}function escapeStringChar(chr){return"\\"+stringEscapes[chr]}function getValue(object,key){return null==object?undefined:object[key]}function hasUnicode(string){return reHasUnicode.test(string)}function hasUnicodeWord(string){return reHasUnicodeWord.test(string)}function iteratorToArray(iterator){for(var data,result=[];!(data=iterator.next()).done;)result.push(data.value);return result}function mapToArray(map){var index=-1,result=Array(map.size);return map.forEach(function(value,key){result[++index]=[key,value]}),result}function overArg(func,transform){return function(arg){return func(transform(arg))}}function replaceHolders(array,placeholder){for(var index=-1,length=array.length,resIndex=0,result=[];++indexdir,arrLength=isArr?array.length:0,view=getView(0,arrLength,this.__views__),start=view.start,end=view.end,length=end-start,index=isRight?end:start-1,iteratees=this.__iteratees__,iterLength=iteratees.length,resIndex=0,takeCount=nativeMin(length,this.__takeCount__);if(!isArr||LARGE_ARRAY_SIZE>arrLength||arrLength==length&&takeCount==length)return baseWrapperValue(array,this.__actions__);var result=[];outer:for(;length--&&takeCount>resIndex;){index+=dir;for(var iterIndex=-1,value=array[index];++iterIndexindex)return!1;var lastIndex=data.length-1;return index==lastIndex?data.pop():splice.call(data,index,1),--this.size,!0}function listCacheGet(key){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?undefined:data[index][1]}function listCacheHas(key){return assocIndexOf(this.__data__,key)>-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?(++this.size,data.push([key,value])):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index=number?number:upper),lower!==undefined&&(number=number>=lower?number:lower)),number}function baseClone(value,isDeep,isFull,customizer,key,object,stack){var result;if(customizer&&(result=object?customizer(value,key,object,stack):customizer(value)),result!==undefined)return result;if(!isObject(value))return value;var isArr=isArray(value);if(isArr){if(result=initCloneArray(value),!isDeep)return copyArray(value,result)}else{var tag=getTag(value),isFunc=tag==funcTag||tag==genTag;if(isBuffer(value))return cloneBuffer(value,isDeep);if(tag==objectTag||tag==argsTag||isFunc&&!object){if(result=initCloneObject(isFunc?{}:value),!isDeep)return copySymbols(value,baseAssign(result,value))}else{if(!cloneableTags[tag])return object?value:{};result=initCloneByTag(value,tag,baseClone,isDeep)}}stack||(stack=new Stack);var stacked=stack.get(value);if(stacked)return stacked;if(stack.set(value,result),!isArr)var props=isFull?getAllKeys(value):keys(value);return arrayEach(props||value,function(subValue,key){props&&(key=subValue,subValue=value[key]),assignValue(result,key,baseClone(subValue,isDeep,isFull,customizer,key,value,stack))}),result}function baseConforms(source){var props=keys(source);return function(object){return baseConformsTo(object,source,props)}}function baseConformsTo(object,source,props){var length=props.length;if(null==object)return!length;for(object=Object(object);length--;){var key=props[length],predicate=source[key],value=object[key];if(value===undefined&&!(key in object)||!predicate(value))return!1}return!0}function baseCreate(proto){return isObject(proto)?objectCreate(proto):{}}function baseDelay(func,wait,args){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return setTimeout(function(){func.apply(undefined,args)},wait)}function baseDifference(array,values,iteratee,comparator){var index=-1,includes=arrayIncludes,isCommon=!0,length=array.length,result=[],valuesLength=values.length;if(!length)return result;iteratee&&(values=arrayMap(values,baseUnary(iteratee))),comparator?(includes=arrayIncludesWith,isCommon=!1):values.length>=LARGE_ARRAY_SIZE&&(includes=cacheHas,isCommon=!1,values=new SetCache(values));outer:for(;++indexstart&&(start=-start>length?0:length+start),end=end===undefined||end>length?length:toInteger(end),0>end&&(end+=length),end=start>end?0:toLength(end);end>start;)array[start++]=value;return array}function baseFilter(collection,predicate){var result=[];return baseEach(collection,function(value,index,collection){predicate(value,index,collection)&&result.push(value)}),result}function baseFlatten(array,depth,predicate,isStrict,result){var index=-1,length=array.length;for(predicate||(predicate=isFlattenable),result||(result=[]);++index0&&predicate(value)?depth>1?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}function baseForOwn(object,iteratee){return object&&baseFor(object,iteratee,keys)}function baseForOwnRight(object,iteratee){return object&&baseForRight(object,iteratee,keys)}function baseFunctions(object,props){return arrayFilter(props,function(key){return isFunction(object[key])})}function baseGet(object,path){path=isKey(path,object)?[path]:castPath(path);for(var index=0,length=path.length;null!=object&&length>index;)object=object[toKey(path[index++])];return index&&index==length?object:undefined}function baseGetAllKeys(object,keysFunc,symbolsFunc){var result=keysFunc(object);return isArray(object)?result:arrayPush(result,symbolsFunc(object))}function baseGetTag(value){return objectToString.call(value)}function baseGt(value,other){return value>other}function baseHas(object,key){return null!=object&&hasOwnProperty.call(object,key)}function baseHasIn(object,key){return null!=object&&key in Object(object)}function baseInRange(number,start,end){return number>=nativeMin(start,end)&&number=120&&array.length>=120)?new SetCache(othIndex&&array):undefined}array=arrays[0];var index=-1,seen=caches[0];outer:for(;++indexvalue}function baseMap(collection,iteratee){var index=-1,result=isArrayLike(collection)?Array(collection.length):[];return baseEach(collection,function(value,key,collection){result[++index]=iteratee(value,key,collection)}),result}function baseMatches(source){var matchData=getMatchData(source);return 1==matchData.length&&matchData[0][2]?matchesStrictComparable(matchData[0][0],matchData[0][1]):function(object){return object===source||baseIsMatch(object,source,matchData)}}function baseMatchesProperty(path,srcValue){return isKey(path)&&isStrictComparable(srcValue)?matchesStrictComparable(toKey(path),srcValue):function(object){var objValue=get(object,path);return objValue===undefined&&objValue===srcValue?hasIn(object,path):baseIsEqual(srcValue,objValue,undefined,UNORDERED_COMPARE_FLAG|PARTIAL_COMPARE_FLAG)}}function baseMerge(object,source,srcIndex,customizer,stack){if(object!==source){if(!isArray(source)&&!isTypedArray(source))var props=baseKeysIn(source);arrayEach(props||source,function(srcValue,key){if(props&&(key=srcValue,srcValue=source[key]),isObject(srcValue))stack||(stack=new Stack),baseMergeDeep(object,source,key,srcIndex,baseMerge,customizer,stack);else{var newValue=customizer?customizer(object[key],srcValue,key+"",object,source,stack):undefined;newValue===undefined&&(newValue=srcValue),assignMergeValue(object,key,newValue)}})}}function baseMergeDeep(object,source,key,srcIndex,mergeFunc,customizer,stack){var objValue=object[key],srcValue=source[key],stacked=stack.get(srcValue);if(stacked)return void assignMergeValue(object,key,stacked);var newValue=customizer?customizer(objValue,srcValue,key+"",object,source,stack):undefined,isCommon=newValue===undefined;isCommon&&(newValue=srcValue,isArray(srcValue)||isTypedArray(srcValue)?isArray(objValue)?newValue=objValue:isArrayLikeObject(objValue)?newValue=copyArray(objValue):(isCommon=!1,newValue=baseClone(srcValue,!0)):isPlainObject(srcValue)||isArguments(srcValue)?isArguments(objValue)?newValue=toPlainObject(objValue):!isObject(objValue)||srcIndex&&isFunction(objValue)?(isCommon=!1,newValue=baseClone(srcValue,!0)):newValue=objValue:isCommon=!1),isCommon&&(stack.set(srcValue,newValue),mergeFunc(newValue,srcValue,srcIndex,customizer,stack),stack["delete"](srcValue)),assignMergeValue(object,key,newValue)}function baseNth(array,n){var length=array.length;if(length)return n+=0>n?length:0,isIndex(n,length)?array[n]:undefined}function baseOrderBy(collection,iteratees,orders){var index=-1;iteratees=arrayMap(iteratees.length?iteratees:[identity],baseUnary(getIteratee()));var result=baseMap(collection,function(value,key,collection){var criteria=arrayMap(iteratees,function(iteratee){return iteratee(value)});return{criteria:criteria,index:++index,value:value}});return baseSortBy(result,function(object,other){return compareMultiple(object,other,orders)})}function basePick(object,props){return object=Object(object),basePickBy(object,props,function(value,key){return key in object})}function basePickBy(object,props,predicate){for(var index=-1,length=props.length,result={};++index-1;)seen!==array&&splice.call(seen,fromIndex,1),splice.call(array,fromIndex,1);return array}function basePullAt(array,indexes){for(var length=array?indexes.length:0,lastIndex=length-1;length--;){var index=indexes[length];if(length==lastIndex||index!==previous){var previous=index;if(isIndex(index))splice.call(array,index,1);else if(isKey(index,array))delete array[toKey(index)];else{var path=castPath(index),object=parent(array,path);null!=object&&delete object[toKey(last(path))]}}}return array}function baseRandom(lower,upper){return lower+nativeFloor(nativeRandom()*(upper-lower+1))}function baseRange(start,end,step,fromRight){for(var index=-1,length=nativeMax(nativeCeil((end-start)/(step||1)),0),result=Array(length);length--;)result[fromRight?length:++index]=start,start+=step;return result}function baseRepeat(string,n){var result="";if(!string||1>n||n>MAX_SAFE_INTEGER)return result;do n%2&&(result+=string),n=nativeFloor(n/2),n&&(string+=string);while(n);return result}function baseRest(func,start){return setToString(overRest(func,start,identity),func+"")}function baseSet(object,path,value,customizer){if(!isObject(object))return object;path=isKey(path,object)?[path]:castPath(path);for(var index=-1,length=path.length,lastIndex=length-1,nested=object;null!=nested&&++indexstart&&(start=-start>length?0:length+start),end=end>length?length:end,0>end&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index=high){for(;high>low;){var mid=low+high>>>1,computed=array[mid];null!==computed&&!isSymbol(computed)&&(retHighest?value>=computed:value>computed)?low=mid+1:high=mid}return high}return baseSortedIndexBy(array,value,identity,retHighest)}function baseSortedIndexBy(array,value,iteratee,retHighest){value=iteratee(value);for(var low=0,high=array?array.length:0,valIsNaN=value!==value,valIsNull=null===value,valIsSymbol=isSymbol(value),valIsUndefined=value===undefined;high>low;){var mid=nativeFloor((low+high)/2),computed=iteratee(array[mid]),othIsDefined=computed!==undefined,othIsNull=null===computed,othIsReflexive=computed===computed,othIsSymbol=isSymbol(computed);if(valIsNaN)var setLow=retHighest||othIsReflexive;else setLow=valIsUndefined?othIsReflexive&&(retHighest||othIsDefined):valIsNull?othIsReflexive&&othIsDefined&&(retHighest||!othIsNull):valIsSymbol?othIsReflexive&&othIsDefined&&!othIsNull&&(retHighest||!othIsSymbol):othIsNull||othIsSymbol?!1:retHighest?value>=computed:value>computed;setLow?low=mid+1:high=mid; -}return nativeMin(high,MAX_ARRAY_INDEX)}function baseSortedUniq(array,iteratee){for(var index=-1,length=array.length,resIndex=0,result=[];++index=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++indexindex?values[index]:undefined;assignFunc(result,props[index],value)}return result}function castArrayLikeObject(value){return isArrayLikeObject(value)?value:[]}function castFunction(value){return"function"==typeof value?value:identity}function castPath(value){return isArray(value)?value:stringToPath(value)}function castSlice(array,start,end){var length=array.length;return end=end===undefined?length:end,!start&&end>=length?array:baseSlice(array,start,end)}function cloneBuffer(buffer,isDeep){if(isDeep)return buffer.slice();var result=new buffer.constructor(buffer.length);return buffer.copy(result),result}function cloneArrayBuffer(arrayBuffer){var result=new arrayBuffer.constructor(arrayBuffer.byteLength);return new Uint8Array(result).set(new Uint8Array(arrayBuffer)),result}function cloneDataView(dataView,isDeep){var buffer=isDeep?cloneArrayBuffer(dataView.buffer):dataView.buffer;return new dataView.constructor(buffer,dataView.byteOffset,dataView.byteLength)}function cloneMap(map,isDeep,cloneFunc){var array=isDeep?cloneFunc(mapToArray(map),!0):mapToArray(map);return arrayReduce(array,addMapEntry,new map.constructor)}function cloneRegExp(regexp){var result=new regexp.constructor(regexp.source,reFlags.exec(regexp));return result.lastIndex=regexp.lastIndex,result}function cloneSet(set,isDeep,cloneFunc){var array=isDeep?cloneFunc(setToArray(set),!0):setToArray(set);return arrayReduce(array,addSetEntry,new set.constructor)}function cloneSymbol(symbol){return symbolValueOf?Object(symbolValueOf.call(symbol)):{}}function cloneTypedArray(typedArray,isDeep){var buffer=isDeep?cloneArrayBuffer(typedArray.buffer):typedArray.buffer;return new typedArray.constructor(buffer,typedArray.byteOffset,typedArray.length)}function compareAscending(value,other){if(value!==other){var valIsDefined=value!==undefined,valIsNull=null===value,valIsReflexive=value===value,valIsSymbol=isSymbol(value),othIsDefined=other!==undefined,othIsNull=null===other,othIsReflexive=other===other,othIsSymbol=isSymbol(other);if(!othIsNull&&!othIsSymbol&&!valIsSymbol&&value>other||valIsSymbol&&othIsDefined&&othIsReflexive&&!othIsNull&&!othIsSymbol||valIsNull&&othIsDefined&&othIsReflexive||!valIsDefined&&othIsReflexive||!valIsReflexive)return 1;if(!valIsNull&&!valIsSymbol&&!othIsSymbol&&other>value||othIsSymbol&&valIsDefined&&valIsReflexive&&!valIsNull&&!valIsSymbol||othIsNull&&valIsDefined&&valIsReflexive||!othIsDefined&&valIsReflexive||!othIsReflexive)return-1}return 0}function compareMultiple(object,other,orders){for(var index=-1,objCriteria=object.criteria,othCriteria=other.criteria,length=objCriteria.length,ordersLength=orders.length;++index=ordersLength)return result;var order=orders[index];return result*("desc"==order?-1:1)}}return object.index-other.index}function composeArgs(args,partials,holders,isCurried){for(var argsIndex=-1,argsLength=args.length,holdersLength=holders.length,leftIndex=-1,leftLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(leftLength+rangeLength),isUncurried=!isCurried;++leftIndexargsIndex)&&(result[holders[argsIndex]]=args[argsIndex]);for(;rangeLength--;)result[leftIndex++]=args[argsIndex++];return result}function composeArgsRight(args,partials,holders,isCurried){for(var argsIndex=-1,argsLength=args.length,holdersIndex=-1,holdersLength=holders.length,rightIndex=-1,rightLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(rangeLength+rightLength),isUncurried=!isCurried;++argsIndexargsIndex)&&(result[offset+holders[holdersIndex]]=args[argsIndex++]);return result}function copyArray(source,array){var index=-1,length=source.length;for(array||(array=Array(length));++index1?sources[length-1]:undefined,guard=length>2?sources[2]:undefined;for(customizer=assigner.length>3&&"function"==typeof customizer?(length--,customizer):undefined,guard&&isIterateeCall(sources[0],sources[1],guard)&&(customizer=3>length?undefined:customizer,length=1),object=Object(object);++indexlength&&args[0]!==placeholder&&args[length-1]!==placeholder?[]:replaceHolders(args,placeholder);if(length-=holders.length,arity>length)return createRecurry(func,bitmask,createHybrid,wrapper.placeholder,undefined,args,holders,undefined,undefined,arity-length);var fn=this&&this!==root&&this instanceof wrapper?Ctor:func;return apply(fn,this,args)}var Ctor=createCtor(func);return wrapper}function createFind(findIndexFunc){return function(collection,predicate,fromIndex){var iterable=Object(collection);if(!isArrayLike(collection)){var iteratee=getIteratee(predicate,3);collection=keys(collection),predicate=function(key){return iteratee(iterable[key],key,iterable)}}var index=findIndexFunc(collection,predicate,fromIndex);return index>-1?iterable[iteratee?collection[index]:index]:undefined}}function createFlow(fromRight){return flatRest(function(funcs){var length=funcs.length,index=length,prereq=LodashWrapper.prototype.thru;for(fromRight&&funcs.reverse();index--;){var func=funcs[index];if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);if(prereq&&!wrapper&&"wrapper"==getFuncName(func))var wrapper=new LodashWrapper([],!0)}for(index=wrapper?index:length;++index=LARGE_ARRAY_SIZE)return wrapper.plant(value).value();for(var index=0,result=length?funcs[index].apply(this,args):value;++indexlength){var newHolders=replaceHolders(args,placeholder);return createRecurry(func,bitmask,createHybrid,wrapper.placeholder,thisArg,args,newHolders,argPos,ary,arity-length)}var thisBinding=isBind?thisArg:this,fn=isBindKey?thisBinding[func]:func;return length=args.length,argPos?args=reorder(args,argPos):isFlip&&length>1&&args.reverse(),isAry&&length>ary&&(args.length=ary),this&&this!==root&&this instanceof wrapper&&(fn=Ctor||createCtor(fn)),fn.apply(thisBinding,args)}var isAry=bitmask&ARY_FLAG,isBind=bitmask&BIND_FLAG,isBindKey=bitmask&BIND_KEY_FLAG,isCurried=bitmask&(CURRY_FLAG|CURRY_RIGHT_FLAG),isFlip=bitmask&FLIP_FLAG,Ctor=isBindKey?undefined:createCtor(func);return wrapper}function createInverter(setter,toIteratee){return function(object,iteratee){return baseInverter(object,setter,toIteratee(iteratee),{})}}function createMathOperation(operator,defaultValue){return function(value,other){var result;if(value===undefined&&other===undefined)return defaultValue;if(value!==undefined&&(result=value),other!==undefined){if(result===undefined)return other;"string"==typeof value||"string"==typeof other?(value=baseToString(value),other=baseToString(other)):(value=baseToNumber(value),other=baseToNumber(other)),result=operator(value,other)}return result}}function createOver(arrayFunc){return flatRest(function(iteratees){return iteratees=arrayMap(iteratees,baseUnary(getIteratee())),baseRest(function(args){var thisArg=this;return arrayFunc(iteratees,function(iteratee){return apply(iteratee,thisArg,args)})})})}function createPadding(length,chars){chars=chars===undefined?" ":baseToString(chars);var charsLength=chars.length;if(2>charsLength)return charsLength?baseRepeat(chars,length):chars;var result=baseRepeat(chars,nativeCeil(length/stringSize(chars)));return hasUnicode(chars)?castSlice(stringToArray(result),0,length).join(""):result.slice(0,length)}function createPartial(func,bitmask,thisArg,partials){function wrapper(){for(var argsIndex=-1,argsLength=arguments.length,leftIndex=-1,leftLength=partials.length,args=Array(leftLength+argsLength),fn=this&&this!==root&&this instanceof wrapper?Ctor:func;++leftIndexstart?1:-1:toFinite(step),baseRange(start,end,step,fromRight)}}function createRelationalOperation(operator){return function(value,other){return("string"!=typeof value||"string"!=typeof other)&&(value=toNumber(value),other=toNumber(other)),operator(value,other)}}function createRecurry(func,bitmask,wrapFunc,placeholder,thisArg,partials,holders,argPos,ary,arity){var isCurry=bitmask&CURRY_FLAG,newHolders=isCurry?holders:undefined,newHoldersRight=isCurry?undefined:holders,newPartials=isCurry?partials:undefined,newPartialsRight=isCurry?undefined:partials;bitmask|=isCurry?PARTIAL_FLAG:PARTIAL_RIGHT_FLAG,bitmask&=~(isCurry?PARTIAL_RIGHT_FLAG:PARTIAL_FLAG),bitmask&CURRY_BOUND_FLAG||(bitmask&=~(BIND_FLAG|BIND_KEY_FLAG));var newData=[func,bitmask,thisArg,newPartials,newHolders,newPartialsRight,newHoldersRight,argPos,ary,arity],result=wrapFunc.apply(undefined,newData);return isLaziable(func)&&setData(result,newData),result.placeholder=placeholder,setWrapToString(result,func,bitmask)}function createRound(methodName){var func=Math[methodName];return function(number,precision){if(number=toNumber(number),precision=nativeMin(toInteger(precision),292)){var pair=(toString(number)+"e").split("e"),value=func(pair[0]+"e"+(+pair[1]+precision));return pair=(toString(value)+"e").split("e"),+(pair[0]+"e"+(+pair[1]-precision))}return func(number)}}function createToPairs(keysFunc){return function(object){var tag=getTag(object);return tag==mapTag?mapToArray(object):tag==setTag?setToPairs(object):baseToPairs(object,keysFunc(object))}}function createWrap(func,bitmask,thisArg,partials,holders,argPos,ary,arity){var isBindKey=bitmask&BIND_KEY_FLAG;if(!isBindKey&&"function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);var length=partials?partials.length:0;if(length||(bitmask&=~(PARTIAL_FLAG|PARTIAL_RIGHT_FLAG),partials=holders=undefined),ary=ary===undefined?ary:nativeMax(toInteger(ary),0),arity=arity===undefined?arity:toInteger(arity),length-=holders?holders.length:0,bitmask&PARTIAL_RIGHT_FLAG){var partialsRight=partials,holdersRight=holders;partials=holders=undefined}var data=isBindKey?undefined:getData(func),newData=[func,bitmask,thisArg,partials,holders,partialsRight,holdersRight,argPos,ary,arity];if(data&&mergeData(newData,data),func=newData[0],bitmask=newData[1],thisArg=newData[2],partials=newData[3],holders=newData[4],arity=newData[9]=null==newData[9]?isBindKey?0:func.length:nativeMax(newData[9]-length,0),!arity&&bitmask&(CURRY_FLAG|CURRY_RIGHT_FLAG)&&(bitmask&=~(CURRY_FLAG|CURRY_RIGHT_FLAG)),bitmask&&bitmask!=BIND_FLAG)result=bitmask==CURRY_FLAG||bitmask==CURRY_RIGHT_FLAG?createCurry(func,bitmask,arity):bitmask!=PARTIAL_FLAG&&bitmask!=(BIND_FLAG|PARTIAL_FLAG)||holders.length?createHybrid.apply(undefined,newData):createPartial(func,bitmask,thisArg,partials);else var result=createBind(func,bitmask,thisArg);var setter=data?baseSetData:setData;return setWrapToString(setter(result,newData),func,bitmask)}function equalArrays(array,other,equalFunc,customizer,bitmask,stack){var isPartial=bitmask&PARTIAL_COMPARE_FLAG,arrLength=array.length,othLength=other.length;if(arrLength!=othLength&&!(isPartial&&othLength>arrLength))return!1;var stacked=stack.get(array);if(stacked&&stack.get(other))return stacked==other;var index=-1,result=!0,seen=bitmask&UNORDERED_COMPARE_FLAG?new SetCache:undefined;for(stack.set(array,other),stack.set(other,array);++index1?"& ":"")+details[lastIndex],details=details.join(length>2?", ":" "),source.replace(reWrapComment,"{\n/* [wrapped with "+details+"] */\n")}function isFlattenable(value){return isArray(value)||isArguments(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol])}function isIndex(value,length){return length=null==length?MAX_SAFE_INTEGER:length,!!length&&("number"==typeof value||reIsUint.test(value))&&value>-1&&value%1==0&&length>value}function isIterateeCall(value,index,object){if(!isObject(object))return!1;var type=typeof index;return("number"==type?isArrayLike(object)&&isIndex(index,object.length):"string"==type&&index in object)?eq(object[index],value):!1}function isKey(value,object){if(isArray(value))return!1;var type=typeof value;return"number"==type||"symbol"==type||"boolean"==type||null==value||isSymbol(value)?!0:reIsPlainProp.test(value)||!reIsDeepProp.test(value)||null!=object&&value in Object(object)}function isKeyable(value){var type=typeof value;return"string"==type||"number"==type||"symbol"==type||"boolean"==type?"__proto__"!==value:null===value}function isLaziable(func){var funcName=getFuncName(func),other=lodash[funcName];if("function"!=typeof other||!(funcName in LazyWrapper.prototype))return!1;if(func===other)return!0;var data=getData(other);return!!data&&func===data[0]}function isMasked(func){return!!maskSrcKey&&maskSrcKey in func}function isPrototype(value){var Ctor=value&&value.constructor,proto="function"==typeof Ctor&&Ctor.prototype||objectProto;return value===proto}function isStrictComparable(value){return value===value&&!isObject(value)}function matchesStrictComparable(key,srcValue){return function(object){return null==object?!1:object[key]===srcValue&&(srcValue!==undefined||key in Object(object))}}function memoizeCapped(func){var result=memoize(func,function(key){return cache.size===MAX_MEMOIZE_SIZE&&cache.clear(),key}),cache=result.cache;return result}function mergeData(data,source){var bitmask=data[1],srcBitmask=source[1],newBitmask=bitmask|srcBitmask,isCommon=(BIND_FLAG|BIND_KEY_FLAG|ARY_FLAG)>newBitmask,isCombo=srcBitmask==ARY_FLAG&&bitmask==CURRY_FLAG||srcBitmask==ARY_FLAG&&bitmask==REARG_FLAG&&data[7].length<=source[8]||srcBitmask==(ARY_FLAG|REARG_FLAG)&&source[7].length<=source[8]&&bitmask==CURRY_FLAG;if(!isCommon&&!isCombo)return data;srcBitmask&BIND_FLAG&&(data[2]=source[2],newBitmask|=bitmask&BIND_FLAG?0:CURRY_BOUND_FLAG);var value=source[3];if(value){var partials=data[3];data[3]=partials?composeArgs(partials,value,source[4]):value,data[4]=partials?replaceHolders(data[3],PLACEHOLDER):source[4]}return value=source[5],value&&(partials=data[5],data[5]=partials?composeArgsRight(partials,value,source[6]):value,data[6]=partials?replaceHolders(data[5],PLACEHOLDER):source[6]),value=source[7],value&&(data[7]=value),srcBitmask&ARY_FLAG&&(data[8]=null==data[8]?source[8]:nativeMin(data[8],source[8])),null==data[9]&&(data[9]=source[9]),data[0]=source[0],data[1]=newBitmask,data}function mergeDefaults(objValue,srcValue,key,object,source,stack){return isObject(objValue)&&isObject(srcValue)&&(stack.set(srcValue,objValue),baseMerge(objValue,srcValue,undefined,mergeDefaults,stack),stack["delete"](srcValue)),objValue}function nativeKeysIn(object){var result=[];if(null!=object)for(var key in Object(object))result.push(key);return result}function overRest(func,start,transform){return start=nativeMax(start===undefined?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index0){if(++count>=HOT_COUNT)return arguments[0]}else count=0;return func.apply(undefined,arguments)}}function shuffleSelf(array){for(var index=-1,length=array.length,lastIndex=length-1;++indexsize)return[];for(var index=0,resIndex=0,result=Array(nativeCeil(length/size));length>index;)result[resIndex++]=baseSlice(array,index,index+=size);return result}function compact(array){for(var index=-1,length=array?array.length:0,resIndex=0,result=[];++indexn?0:n,length)):[]}function dropRight(array,n,guard){var length=array?array.length:0;return length?(n=guard||n===undefined?1:toInteger(n),n=length-n,baseSlice(array,0,0>n?0:n)):[]}function dropRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!0,!0):[]}function dropWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!0):[]}function fill(array,value,start,end){var length=array?array.length:0;return length?(start&&"number"!=typeof start&&isIterateeCall(array,value,start)&&(start=0,end=length),baseFill(array,value,start,end)):[]}function findIndex(array,predicate,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=null==fromIndex?0:toInteger(fromIndex);return 0>index&&(index=nativeMax(length+index,0)), -baseFindIndex(array,getIteratee(predicate,3),index)}function findLastIndex(array,predicate,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=length-1;return fromIndex!==undefined&&(index=toInteger(fromIndex),index=0>fromIndex?nativeMax(length+index,0):nativeMin(index,length-1)),baseFindIndex(array,getIteratee(predicate,3),index,!0)}function flatten(array){var length=array?array.length:0;return length?baseFlatten(array,1):[]}function flattenDeep(array){var length=array?array.length:0;return length?baseFlatten(array,INFINITY):[]}function flattenDepth(array,depth){var length=array?array.length:0;return length?(depth=depth===undefined?1:toInteger(depth),baseFlatten(array,depth)):[]}function fromPairs(pairs){for(var index=-1,length=pairs?pairs.length:0,result={};++indexindex&&(index=nativeMax(length+index,0)),baseIndexOf(array,value,index)}function initial(array){var length=array?array.length:0;return length?baseSlice(array,0,-1):[]}function join(array,separator){return array?nativeJoin.call(array,separator):""}function last(array){var length=array?array.length:0;return length?array[length-1]:undefined}function lastIndexOf(array,value,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=length;return fromIndex!==undefined&&(index=toInteger(fromIndex),index=0>index?nativeMax(length+index,0):nativeMin(index,length-1)),value===value?strictLastIndexOf(array,value,index):baseFindIndex(array,baseIsNaN,index,!0)}function nth(array,n){return array&&array.length?baseNth(array,toInteger(n)):undefined}function pullAll(array,values){return array&&array.length&&values&&values.length?basePullAll(array,values):array}function pullAllBy(array,values,iteratee){return array&&array.length&&values&&values.length?basePullAll(array,values,getIteratee(iteratee,2)):array}function pullAllWith(array,values,comparator){return array&&array.length&&values&&values.length?basePullAll(array,values,undefined,comparator):array}function remove(array,predicate){var result=[];if(!array||!array.length)return result;var index=-1,indexes=[],length=array.length;for(predicate=getIteratee(predicate,3);++indexindex&&eq(array[index],value))return index}return-1}function sortedLastIndex(array,value){return baseSortedIndex(array,value,!0)}function sortedLastIndexBy(array,value,iteratee){return baseSortedIndexBy(array,value,getIteratee(iteratee,2),!0)}function sortedLastIndexOf(array,value){var length=array?array.length:0;if(length){var index=baseSortedIndex(array,value,!0)-1;if(eq(array[index],value))return index}return-1}function sortedUniq(array){return array&&array.length?baseSortedUniq(array):[]}function sortedUniqBy(array,iteratee){return array&&array.length?baseSortedUniq(array,getIteratee(iteratee,2)):[]}function tail(array){var length=array?array.length:0;return length?baseSlice(array,1,length):[]}function take(array,n,guard){return array&&array.length?(n=guard||n===undefined?1:toInteger(n),baseSlice(array,0,0>n?0:n)):[]}function takeRight(array,n,guard){var length=array?array.length:0;return length?(n=guard||n===undefined?1:toInteger(n),n=length-n,baseSlice(array,0>n?0:n,length)):[]}function takeRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!1,!0):[]}function takeWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3)):[]}function uniq(array){return array&&array.length?baseUniq(array):[]}function uniqBy(array,iteratee){return array&&array.length?baseUniq(array,getIteratee(iteratee,2)):[]}function uniqWith(array,comparator){return array&&array.length?baseUniq(array,undefined,comparator):[]}function unzip(array){if(!array||!array.length)return[];var length=0;return array=arrayFilter(array,function(group){return isArrayLikeObject(group)?(length=nativeMax(group.length,length),!0):void 0}),baseTimes(length,function(index){return arrayMap(array,baseProperty(index))})}function unzipWith(array,iteratee){if(!array||!array.length)return[];var result=unzip(array);return null==iteratee?result:arrayMap(result,function(group){return apply(iteratee,undefined,group)})}function zipObject(props,values){return baseZipObject(props||[],values||[],assignValue)}function zipObjectDeep(props,values){return baseZipObject(props||[],values||[],baseSet)}function chain(value){var result=lodash(value);return result.__chain__=!0,result}function tap(value,interceptor){return interceptor(value),value}function thru(value,interceptor){return interceptor(value)}function wrapperChain(){return chain(this)}function wrapperCommit(){return new LodashWrapper(this.value(),this.__chain__)}function wrapperNext(){this.__values__===undefined&&(this.__values__=toArray(this.value()));var done=this.__index__>=this.__values__.length,value=done?undefined:this.__values__[this.__index__++];return{done:done,value:value}}function wrapperToIterator(){return this}function wrapperPlant(value){for(var result,parent=this;parent instanceof baseLodash;){var clone=wrapperClone(parent);clone.__index__=0,clone.__values__=undefined,result?previous.__wrapped__=clone:result=clone;var previous=clone;parent=parent.__wrapped__}return previous.__wrapped__=value,result}function wrapperReverse(){var value=this.__wrapped__;if(value instanceof LazyWrapper){var wrapped=value;return this.__actions__.length&&(wrapped=new LazyWrapper(this)),wrapped=wrapped.reverse(),wrapped.__actions__.push({func:thru,args:[reverse],thisArg:undefined}),new LodashWrapper(wrapped,this.__chain__)}return this.thru(reverse)}function wrapperValue(){return baseWrapperValue(this.__wrapped__,this.__actions__)}function every(collection,predicate,guard){var func=isArray(collection)?arrayEvery:baseEvery;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=undefined),func(collection,getIteratee(predicate,3))}function filter(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,getIteratee(predicate,3))}function flatMap(collection,iteratee){return baseFlatten(map(collection,iteratee),1)}function flatMapDeep(collection,iteratee){return baseFlatten(map(collection,iteratee),INFINITY)}function flatMapDepth(collection,iteratee,depth){return depth=depth===undefined?1:toInteger(depth),baseFlatten(map(collection,iteratee),depth)}function forEach(collection,iteratee){var func=isArray(collection)?arrayEach:baseEach;return func(collection,getIteratee(iteratee,3))}function forEachRight(collection,iteratee){var func=isArray(collection)?arrayEachRight:baseEachRight;return func(collection,getIteratee(iteratee,3))}function includes(collection,value,fromIndex,guard){collection=isArrayLike(collection)?collection:values(collection),fromIndex=fromIndex&&!guard?toInteger(fromIndex):0;var length=collection.length;return 0>fromIndex&&(fromIndex=nativeMax(length+fromIndex,0)),isString(collection)?length>=fromIndex&&collection.indexOf(value,fromIndex)>-1:!!length&&baseIndexOf(collection,value,fromIndex)>-1}function map(collection,iteratee){var func=isArray(collection)?arrayMap:baseMap;return func(collection,getIteratee(iteratee,3))}function orderBy(collection,iteratees,orders,guard){return null==collection?[]:(isArray(iteratees)||(iteratees=null==iteratees?[]:[iteratees]),orders=guard?undefined:orders,isArray(orders)||(orders=null==orders?[]:[orders]),baseOrderBy(collection,iteratees,orders))}function reduce(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduce:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEach)}function reduceRight(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduceRight:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEachRight)}function reject(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,negate(getIteratee(predicate,3)))}function sample(collection){return arraySample(isArrayLike(collection)?collection:values(collection))}function sampleSize(collection,n,guard){return n=(guard?isIterateeCall(collection,n,guard):n===undefined)?1:toInteger(n),arraySampleSize(isArrayLike(collection)?collection:values(collection),n)}function shuffle(collection){return shuffleSelf(isArrayLike(collection)?copyArray(collection):values(collection))}function size(collection){if(null==collection)return 0;if(isArrayLike(collection))return isString(collection)?stringSize(collection):collection.length;var tag=getTag(collection);return tag==mapTag||tag==setTag?collection.size:baseKeys(collection).length}function some(collection,predicate,guard){var func=isArray(collection)?arraySome:baseSome;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=undefined),func(collection,getIteratee(predicate,3))}function after(n,func){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return n=toInteger(n),function(){return--n<1?func.apply(this,arguments):void 0}}function ary(func,n,guard){return n=guard?undefined:n,n=func&&null==n?func.length:n,createWrap(func,ARY_FLAG,undefined,undefined,undefined,undefined,n)}function before(n,func){var result;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return n=toInteger(n),function(){return--n>0&&(result=func.apply(this,arguments)),1>=n&&(func=undefined),result}}function curry(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,CURRY_FLAG,undefined,undefined,undefined,undefined,undefined,arity);return result.placeholder=curry.placeholder,result}function curryRight(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,CURRY_RIGHT_FLAG,undefined,undefined,undefined,undefined,undefined,arity);return result.placeholder=curryRight.placeholder,result}function debounce(func,wait,options){function invokeFunc(time){var args=lastArgs,thisArg=lastThis;return lastArgs=lastThis=undefined,lastInvokeTime=time,result=func.apply(thisArg,args)}function leadingEdge(time){return lastInvokeTime=time,timerId=setTimeout(timerExpired,wait),leading?invokeFunc(time):result}function remainingWait(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime,result=wait-timeSinceLastCall;return maxing?nativeMin(result,maxWait-timeSinceLastInvoke):result}function shouldInvoke(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime;return lastCallTime===undefined||timeSinceLastCall>=wait||0>timeSinceLastCall||maxing&&timeSinceLastInvoke>=maxWait}function timerExpired(){var time=now();return shouldInvoke(time)?trailingEdge(time):void(timerId=setTimeout(timerExpired,remainingWait(time)))}function trailingEdge(time){return timerId=undefined,trailing&&lastArgs?invokeFunc(time):(lastArgs=lastThis=undefined,result)}function cancel(){timerId!==undefined&&clearTimeout(timerId),lastInvokeTime=0,lastArgs=lastCallTime=lastThis=timerId=undefined}function flush(){return timerId===undefined?result:trailingEdge(now())}function debounced(){var time=now(),isInvoking=shouldInvoke(time);if(lastArgs=arguments,lastThis=this,lastCallTime=time,isInvoking){if(timerId===undefined)return leadingEdge(lastCallTime);if(maxing)return timerId=setTimeout(timerExpired,wait),invokeFunc(lastCallTime)}return timerId===undefined&&(timerId=setTimeout(timerExpired,wait)),result}var lastArgs,lastThis,maxWait,result,timerId,lastCallTime,lastInvokeTime=0,leading=!1,maxing=!1,trailing=!0;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return wait=toNumber(wait)||0,isObject(options)&&(leading=!!options.leading,maxing="maxWait"in options,maxWait=maxing?nativeMax(toNumber(options.maxWait)||0,wait):maxWait,trailing="trailing"in options?!!options.trailing:trailing),debounced.cancel=cancel,debounced.flush=flush,debounced}function flip(func){return createWrap(func,FLIP_FLAG)}function memoize(func,resolver){if("function"!=typeof func||resolver&&"function"!=typeof resolver)throw new TypeError(FUNC_ERROR_TEXT);var memoized=function(){var args=arguments,key=resolver?resolver.apply(this,args):args[0],cache=memoized.cache;if(cache.has(key))return cache.get(key);var result=func.apply(this,args);return memoized.cache=cache.set(key,result)||cache,result};return memoized.cache=new(memoize.Cache||MapCache),memoized}function negate(predicate){if("function"!=typeof predicate)throw new TypeError(FUNC_ERROR_TEXT);return function(){var args=arguments;switch(args.length){case 0:return!predicate.call(this);case 1:return!predicate.call(this,args[0]);case 2:return!predicate.call(this,args[0],args[1]);case 3:return!predicate.call(this,args[0],args[1],args[2])}return!predicate.apply(this,args)}}function once(func){return before(2,func)}function rest(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=start===undefined?start:toInteger(start),baseRest(func,start)}function spread(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=start===undefined?0:nativeMax(toInteger(start),0),baseRest(function(args){var array=args[start],otherArgs=castSlice(args,0,start);return array&&arrayPush(otherArgs,array),apply(func,this,otherArgs)})}function throttle(func,wait,options){var leading=!0,trailing=!0;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return isObject(options)&&(leading="leading"in options?!!options.leading:leading,trailing="trailing"in options?!!options.trailing:trailing),debounce(func,wait,{leading:leading,maxWait:wait,trailing:trailing})}function unary(func){return ary(func,1)}function wrap(value,wrapper){return wrapper=null==wrapper?identity:wrapper,partial(wrapper,value)}function castArray(){if(!arguments.length)return[];var value=arguments[0];return isArray(value)?value:[value]}function clone(value){return baseClone(value,!1,!0)}function cloneWith(value,customizer){return baseClone(value,!1,!0,customizer)}function cloneDeep(value){return baseClone(value,!0,!0)}function cloneDeepWith(value,customizer){return baseClone(value,!0,!0,customizer)}function conformsTo(object,source){return null==source||baseConformsTo(object,source,keys(source))}function eq(value,other){return value===other||value!==value&&other!==other}function isArguments(value){return isArrayLikeObject(value)&&hasOwnProperty.call(value,"callee")&&(!propertyIsEnumerable.call(value,"callee")||objectToString.call(value)==argsTag)}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value)}function isBoolean(value){return value===!0||value===!1||isObjectLike(value)&&objectToString.call(value)==boolTag}function isElement(value){return null!=value&&1===value.nodeType&&isObjectLike(value)&&!isPlainObject(value)}function isEmpty(value){if(isArrayLike(value)&&(isArray(value)||"string"==typeof value||"function"==typeof value.splice||isBuffer(value)||isArguments(value)))return!value.length;var tag=getTag(value);if(tag==mapTag||tag==setTag)return!value.size;if(isPrototype(value))return!nativeKeys(value).length;for(var key in value)if(hasOwnProperty.call(value,key))return!1;return!0}function isEqual(value,other){return baseIsEqual(value,other)}function isEqualWith(value,other,customizer){customizer="function"==typeof customizer?customizer:undefined;var result=customizer?customizer(value,other):undefined;return result===undefined?baseIsEqual(value,other,customizer):!!result}function isError(value){return isObjectLike(value)?objectToString.call(value)==errorTag||"string"==typeof value.message&&"string"==typeof value.name:!1}function isFinite(value){return"number"==typeof value&&nativeIsFinite(value)}function isFunction(value){var tag=isObject(value)?objectToString.call(value):"";return tag==funcTag||tag==genTag}function isInteger(value){return"number"==typeof value&&value==toInteger(value)}function isLength(value){return"number"==typeof value&&value>-1&&value%1==0&&MAX_SAFE_INTEGER>=value}function isObject(value){var type=typeof value;return null!=value&&("object"==type||"function"==type)}function isObjectLike(value){return null!=value&&"object"==typeof value}function isMatch(object,source){return object===source||baseIsMatch(object,source,getMatchData(source))}function isMatchWith(object,source,customizer){return customizer="function"==typeof customizer?customizer:undefined,baseIsMatch(object,source,getMatchData(source),customizer)}function isNaN(value){return isNumber(value)&&value!=+value}function isNative(value){if(isMaskable(value))throw new Error("This method is not supported with core-js. Try https://github.com/es-shims.");return baseIsNative(value)}function isNull(value){return null===value}function isNil(value){return null==value}function isNumber(value){return"number"==typeof value||isObjectLike(value)&&objectToString.call(value)==numberTag}function isPlainObject(value){if(!isObjectLike(value)||objectToString.call(value)!=objectTag)return!1;var proto=getPrototype(value);if(null===proto)return!0;var Ctor=hasOwnProperty.call(proto,"constructor")&&proto.constructor;return"function"==typeof Ctor&&Ctor instanceof Ctor&&funcToString.call(Ctor)==objectCtorString}function isSafeInteger(value){return isInteger(value)&&value>=-MAX_SAFE_INTEGER&&MAX_SAFE_INTEGER>=value}function isString(value){return"string"==typeof value||!isArray(value)&&isObjectLike(value)&&objectToString.call(value)==stringTag}function isSymbol(value){return"symbol"==typeof value||isObjectLike(value)&&objectToString.call(value)==symbolTag}function isUndefined(value){return value===undefined}function isWeakMap(value){return isObjectLike(value)&&getTag(value)==weakMapTag}function isWeakSet(value){return isObjectLike(value)&&objectToString.call(value)==weakSetTag}function toArray(value){if(!value)return[];if(isArrayLike(value))return isString(value)?stringToArray(value):copyArray(value);if(iteratorSymbol&&value[iteratorSymbol])return iteratorToArray(value[iteratorSymbol]());var tag=getTag(value),func=tag==mapTag?mapToArray:tag==setTag?setToArray:values;return func(value)}function toFinite(value){if(!value)return 0===value?value:0;if(value=toNumber(value),value===INFINITY||value===-INFINITY){var sign=0>value?-1:1;return sign*MAX_INTEGER}return value===value?value:0}function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0}function toLength(value){return value?baseClamp(toInteger(value),0,MAX_ARRAY_LENGTH):0}function toNumber(value){if("number"==typeof value)return value;if(isSymbol(value))return NAN;if(isObject(value)){var other="function"==typeof value.valueOf?value.valueOf():value;value=isObject(other)?other+"":other}if("string"!=typeof value)return 0===value?value:+value;value=value.replace(reTrim,"");var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value}function toPlainObject(value){return copyObject(value,keysIn(value))}function toSafeInteger(value){return baseClamp(toInteger(value),-MAX_SAFE_INTEGER,MAX_SAFE_INTEGER)}function toString(value){return null==value?"":baseToString(value)}function create(prototype,properties){var result=baseCreate(prototype);return properties?baseAssign(result,properties):result}function findKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwn)}function findLastKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwnRight)}function forIn(object,iteratee){return null==object?object:baseFor(object,getIteratee(iteratee,3),keysIn)}function forInRight(object,iteratee){return null==object?object:baseForRight(object,getIteratee(iteratee,3),keysIn)}function forOwn(object,iteratee){return object&&baseForOwn(object,getIteratee(iteratee,3))}function forOwnRight(object,iteratee){return object&&baseForOwnRight(object,getIteratee(iteratee,3))}function functions(object){return null==object?[]:baseFunctions(object,keys(object))}function functionsIn(object){return null==object?[]:baseFunctions(object,keysIn(object))}function get(object,path,defaultValue){var result=null==object?undefined:baseGet(object,path);return result===undefined?defaultValue:result}function has(object,path){return null!=object&&hasPath(object,path,baseHas)}function hasIn(object,path){return null!=object&&hasPath(object,path,baseHasIn)}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function keysIn(object){return isArrayLike(object)?arrayLikeKeys(object,!0):baseKeysIn(object)}function mapKeys(object,iteratee){var result={};return iteratee=getIteratee(iteratee,3),baseForOwn(object,function(value,key,object){baseAssignValue(result,iteratee(value,key,object),value)}),result}function mapValues(object,iteratee){var result={};return iteratee=getIteratee(iteratee,3),baseForOwn(object,function(value,key,object){baseAssignValue(result,key,iteratee(value,key,object))}),result}function omitBy(object,predicate){return pickBy(object,negate(getIteratee(predicate)))}function pickBy(object,predicate){return null==object?{}:basePickBy(object,getAllKeysIn(object),getIteratee(predicate))}function result(object,path,defaultValue){path=isKey(path,object)?[path]:castPath(path);var index=-1,length=path.length;for(length||(object=undefined,length=1);++indexupper){var temp=lower;lower=upper,upper=temp}if(floating||lower%1||upper%1){var rand=nativeRandom();return nativeMin(lower+rand*(upper-lower+freeParseFloat("1e-"+((rand+"").length-1))),upper)}return baseRandom(lower,upper)}function capitalize(string){return upperFirst(toString(string).toLowerCase())}function deburr(string){return string=toString(string),string&&string.replace(reLatin,deburrLetter).replace(reComboMark,"")}function endsWith(string,target,position){string=toString(string),target=baseToString(target);var length=string.length;position=position===undefined?length:baseClamp(toInteger(position),0,length);var end=position;return position-=target.length,position>=0&&string.slice(position,end)==target}function escape(string){return string=toString(string),string&&reHasUnescapedHtml.test(string)?string.replace(reUnescapedHtml,escapeHtmlChar):string}function escapeRegExp(string){return string=toString(string),string&&reHasRegExpChar.test(string)?string.replace(reRegExpChar,"\\$&"):string}function pad(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;if(!length||strLength>=length)return string;var mid=(length-strLength)/2;return createPadding(nativeFloor(mid),chars)+string+createPadding(nativeCeil(mid),chars)}function padEnd(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;return length&&length>strLength?string+createPadding(length-strLength,chars):string}function padStart(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;return length&&length>strLength?createPadding(length-strLength,chars)+string:string}function parseInt(string,radix,guard){return guard||null==radix?radix=0:radix&&(radix=+radix),nativeParseInt(toString(string),radix||0)}function repeat(string,n,guard){return n=(guard?isIterateeCall(string,n,guard):n===undefined)?1:toInteger(n),baseRepeat(toString(string),n)}function replace(){var args=arguments,string=toString(args[0]);return args.length<3?string:string.replace(args[1],args[2])}function split(string,separator,limit){return limit&&"number"!=typeof limit&&isIterateeCall(string,separator,limit)&&(separator=limit=undefined),(limit=limit===undefined?MAX_ARRAY_LENGTH:limit>>>0)?(string=toString(string),string&&("string"==typeof separator||null!=separator&&!isRegExp(separator))&&(separator=baseToString(separator),!separator&&hasUnicode(string))?castSlice(stringToArray(string),0,limit):string.split(separator,limit)):[]}function startsWith(string,target,position){return string=toString(string),position=baseClamp(toInteger(position),0,string.length),target=baseToString(target),string.slice(position,position+target.length)==target}function template(string,options,guard){var settings=lodash.templateSettings;guard&&isIterateeCall(string,options,guard)&&(options=undefined),string=toString(string),options=assignInWith({},options,settings,assignInDefaults);var isEscaping,isEvaluating,imports=assignInWith({},options.imports,settings.imports,assignInDefaults),importsKeys=keys(imports),importsValues=baseValues(imports,importsKeys),index=0,interpolate=options.interpolate||reNoMatch,source="__p += '",reDelimiters=RegExp((options.escape||reNoMatch).source+"|"+interpolate.source+"|"+(interpolate===reInterpolate?reEsTemplate:reNoMatch).source+"|"+(options.evaluate||reNoMatch).source+"|$","g"),sourceURL="//# sourceURL="+("sourceURL"in options?options.sourceURL:"lodash.templateSources["+ ++templateCounter+"]")+"\n";string.replace(reDelimiters,function(match,escapeValue,interpolateValue,esTemplateValue,evaluateValue,offset){return interpolateValue||(interpolateValue=esTemplateValue),source+=string.slice(index,offset).replace(reUnescapedString,escapeStringChar),escapeValue&&(isEscaping=!0,source+="' +\n__e("+escapeValue+") +\n'"),evaluateValue&&(isEvaluating=!0,source+="';\n"+evaluateValue+";\n__p += '"),interpolateValue&&(source+="' +\n((__t = ("+interpolateValue+")) == null ? '' : __t) +\n'"),index=offset+match.length,match}),source+="';\n";var variable=options.variable;variable||(source="with (obj) {\n"+source+"\n}\n"),source=(isEvaluating?source.replace(reEmptyStringLeading,""):source).replace(reEmptyStringMiddle,"$1").replace(reEmptyStringTrailing,"$1;"),source="function("+(variable||"obj")+") {\n"+(variable?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(isEscaping?", __e = _.escape":"")+(isEvaluating?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+source+"return __p\n}";var result=attempt(function(){return Function(importsKeys,sourceURL+"return "+source).apply(undefined,importsValues)});if(result.source=source,isError(result))throw result;return result}function toLower(value){return toString(value).toLowerCase()}function toUpper(value){return toString(value).toUpperCase()}function trim(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrim,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),chrSymbols=stringToArray(chars),start=charsStartIndex(strSymbols,chrSymbols),end=charsEndIndex(strSymbols,chrSymbols)+1;return castSlice(strSymbols,start,end).join("")}function trimEnd(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrimEnd,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),end=charsEndIndex(strSymbols,stringToArray(chars))+1;return castSlice(strSymbols,0,end).join("")}function trimStart(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrimStart,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),start=charsStartIndex(strSymbols,stringToArray(chars));return castSlice(strSymbols,start).join("")}function truncate(string,options){var length=DEFAULT_TRUNC_LENGTH,omission=DEFAULT_TRUNC_OMISSION;if(isObject(options)){var separator="separator"in options?options.separator:separator;length="length"in options?toInteger(options.length):length,omission="omission"in options?baseToString(options.omission):omission}string=toString(string);var strLength=string.length;if(hasUnicode(string)){var strSymbols=stringToArray(string);strLength=strSymbols.length}if(length>=strLength)return string;var end=length-stringSize(omission);if(1>end)return omission;var result=strSymbols?castSlice(strSymbols,0,end).join(""):string.slice(0,end);if(separator===undefined)return result+omission;if(strSymbols&&(end+=result.length-end),isRegExp(separator)){if(string.slice(end).search(separator)){var match,substring=result;for(separator.global||(separator=RegExp(separator.source,toString(reFlags.exec(separator))+"g")),separator.lastIndex=0;match=separator.exec(substring);)var newEnd=match.index;result=result.slice(0,newEnd===undefined?end:newEnd)}}else if(string.indexOf(baseToString(separator),end)!=end){var index=result.lastIndexOf(separator);index>-1&&(result=result.slice(0,index))}return result+omission}function unescape(string){return string=toString(string),string&&reHasEscapedHtml.test(string)?string.replace(reEscapedHtml,unescapeHtmlChar):string}function words(string,pattern,guard){ -return string=toString(string),pattern=guard?undefined:pattern,pattern===undefined?hasUnicodeWord(string)?unicodeWords(string):asciiWords(string):string.match(pattern)||[]}function cond(pairs){var length=pairs?pairs.length:0,toIteratee=getIteratee();return pairs=length?arrayMap(pairs,function(pair){if("function"!=typeof pair[1])throw new TypeError(FUNC_ERROR_TEXT);return[toIteratee(pair[0]),pair[1]]}):[],baseRest(function(args){for(var index=-1;++indexn||n>MAX_SAFE_INTEGER)return[];var index=MAX_ARRAY_LENGTH,length=nativeMin(n,MAX_ARRAY_LENGTH);iteratee=getIteratee(iteratee),n-=MAX_ARRAY_LENGTH;for(var result=baseTimes(length,iteratee);++index1?arrays[length-1]:undefined;return iteratee="function"==typeof iteratee?(arrays.pop(),iteratee):undefined,unzipWith(arrays,iteratee)}),wrapperAt=flatRest(function(paths){var length=paths.length,start=length?paths[0]:0,value=this.__wrapped__,interceptor=function(object){return baseAt(object,paths)};return!(length>1||this.__actions__.length)&&value instanceof LazyWrapper&&isIndex(start)?(value=value.slice(start,+start+(length?1:0)),value.__actions__.push({func:thru,args:[interceptor],thisArg:undefined}),new LodashWrapper(value,this.__chain__).thru(function(array){return length&&!array.length&&array.push(undefined),array})):this.thru(interceptor)}),countBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?++result[key]:baseAssignValue(result,key,1)}),find=createFind(findIndex),findLast=createFind(findLastIndex),groupBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?result[key].push(value):baseAssignValue(result,key,[value])}),invokeMap=baseRest(function(collection,path,args){var index=-1,isFunc="function"==typeof path,isProp=isKey(path),result=isArrayLike(collection)?Array(collection.length):[];return baseEach(collection,function(value){var func=isFunc?path:isProp&&null!=value?value[path]:undefined;result[++index]=func?apply(func,value,args):baseInvoke(value,path,args)}),result}),keyBy=createAggregator(function(result,value,key){baseAssignValue(result,key,value)}),partition=createAggregator(function(result,value,key){result[key?0:1].push(value)},function(){return[[],[]]}),sortBy=baseRest(function(collection,iteratees){if(null==collection)return[];var length=iteratees.length;return length>1&&isIterateeCall(collection,iteratees[0],iteratees[1])?iteratees=[]:length>2&&isIterateeCall(iteratees[0],iteratees[1],iteratees[2])&&(iteratees=[iteratees[0]]),baseOrderBy(collection,baseFlatten(iteratees,1),[])}),now=ctxNow||function(){return root.Date.now()},bind=baseRest(function(func,thisArg,partials){var bitmask=BIND_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bind));bitmask|=PARTIAL_FLAG}return createWrap(func,bitmask,thisArg,partials,holders)}),bindKey=baseRest(function(object,key,partials){var bitmask=BIND_FLAG|BIND_KEY_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bindKey));bitmask|=PARTIAL_FLAG}return createWrap(key,bitmask,object,partials,holders)}),defer=baseRest(function(func,args){return baseDelay(func,1,args)}),delay=baseRest(function(func,wait,args){return baseDelay(func,toNumber(wait)||0,args)});memoize.Cache=MapCache;var overArgs=castRest(function(func,transforms){transforms=1==transforms.length&&isArray(transforms[0])?arrayMap(transforms[0],baseUnary(getIteratee())):arrayMap(baseFlatten(transforms,1),baseUnary(getIteratee()));var funcsLength=transforms.length;return baseRest(function(args){for(var index=-1,length=nativeMin(args.length,funcsLength);++index=other}),isArray=Array.isArray,isArrayBuffer=nodeIsArrayBuffer?baseUnary(nodeIsArrayBuffer):baseIsArrayBuffer,isBuffer=nativeIsBuffer||stubFalse,isDate=nodeIsDate?baseUnary(nodeIsDate):baseIsDate,isMap=nodeIsMap?baseUnary(nodeIsMap):baseIsMap,isRegExp=nodeIsRegExp?baseUnary(nodeIsRegExp):baseIsRegExp,isSet=nodeIsSet?baseUnary(nodeIsSet):baseIsSet,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray,lt=createRelationalOperation(baseLt),lte=createRelationalOperation(function(value,other){return other>=value}),assign=createAssigner(function(object,source){if(isPrototype(source)||isArrayLike(source))return void copyObject(source,keys(source),object);for(var key in source)hasOwnProperty.call(source,key)&&assignValue(object,key,source[key])}),assignIn=createAssigner(function(object,source){copyObject(source,keysIn(source),object)}),assignInWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keysIn(source),object,customizer)}),assignWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keys(source),object,customizer)}),at=flatRest(baseAt),defaults=baseRest(function(args){return args.push(undefined,assignInDefaults),apply(assignInWith,undefined,args)}),defaultsDeep=baseRest(function(args){return args.push(undefined,mergeDefaults),apply(mergeWith,undefined,args)}),invert=createInverter(function(result,value,key){result[value]=key},constant(identity)),invertBy=createInverter(function(result,value,key){hasOwnProperty.call(result,value)?result[value].push(key):result[value]=[key]},getIteratee),invoke=baseRest(baseInvoke),merge=createAssigner(function(object,source,srcIndex){baseMerge(object,source,srcIndex)}),mergeWith=createAssigner(function(object,source,srcIndex,customizer){baseMerge(object,source,srcIndex,customizer)}),omit=flatRest(function(object,props){return null==object?{}:(props=arrayMap(props,toKey),basePick(object,baseDifference(getAllKeysIn(object),props)))}),pick=flatRest(function(object,props){return null==object?{}:basePick(object,arrayMap(props,toKey))}),toPairs=createToPairs(keys),toPairsIn=createToPairs(keysIn),camelCase=createCompounder(function(result,word,index){return word=word.toLowerCase(),result+(index?capitalize(word):word)}),kebabCase=createCompounder(function(result,word,index){return result+(index?"-":"")+word.toLowerCase()}),lowerCase=createCompounder(function(result,word,index){return result+(index?" ":"")+word.toLowerCase()}),lowerFirst=createCaseFirst("toLowerCase"),snakeCase=createCompounder(function(result,word,index){return result+(index?"_":"")+word.toLowerCase()}),startCase=createCompounder(function(result,word,index){return result+(index?" ":"")+upperFirst(word)}),upperCase=createCompounder(function(result,word,index){return result+(index?" ":"")+word.toUpperCase()}),upperFirst=createCaseFirst("toUpperCase"),attempt=baseRest(function(func,args){try{return apply(func,undefined,args)}catch(e){return isError(e)?e:new Error(e)}}),bindAll=flatRest(function(object,methodNames){return arrayEach(methodNames,function(key){key=toKey(key),baseAssignValue(object,key,bind(object[key],object))}),object}),flow=createFlow(),flowRight=createFlow(!0),method=baseRest(function(path,args){return function(object){return baseInvoke(object,path,args)}}),methodOf=baseRest(function(object,args){return function(path){return baseInvoke(object,path,args)}}),over=createOver(arrayMap),overEvery=createOver(arrayEvery),overSome=createOver(arraySome),range=createRange(),rangeRight=createRange(!0),add=createMathOperation(function(augend,addend){return augend+addend},0),ceil=createRound("ceil"),divide=createMathOperation(function(dividend,divisor){return dividend/divisor},1),floor=createRound("floor"),multiply=createMathOperation(function(multiplier,multiplicand){return multiplier*multiplicand},1),round=createRound("round"),subtract=createMathOperation(function(minuend,subtrahend){return minuend-subtrahend},0);return lodash.after=after,lodash.ary=ary,lodash.assign=assign,lodash.assignIn=assignIn,lodash.assignInWith=assignInWith,lodash.assignWith=assignWith,lodash.at=at,lodash.before=before,lodash.bind=bind,lodash.bindAll=bindAll,lodash.bindKey=bindKey,lodash.castArray=castArray,lodash.chain=chain,lodash.chunk=chunk,lodash.compact=compact,lodash.concat=concat,lodash.cond=cond,lodash.conforms=conforms,lodash.constant=constant,lodash.countBy=countBy,lodash.create=create,lodash.curry=curry,lodash.curryRight=curryRight,lodash.debounce=debounce,lodash.defaults=defaults,lodash.defaultsDeep=defaultsDeep,lodash.defer=defer,lodash.delay=delay,lodash.difference=difference,lodash.differenceBy=differenceBy,lodash.differenceWith=differenceWith,lodash.drop=drop,lodash.dropRight=dropRight,lodash.dropRightWhile=dropRightWhile,lodash.dropWhile=dropWhile,lodash.fill=fill,lodash.filter=filter,lodash.flatMap=flatMap,lodash.flatMapDeep=flatMapDeep,lodash.flatMapDepth=flatMapDepth,lodash.flatten=flatten,lodash.flattenDeep=flattenDeep,lodash.flattenDepth=flattenDepth,lodash.flip=flip,lodash.flow=flow,lodash.flowRight=flowRight,lodash.fromPairs=fromPairs,lodash.functions=functions,lodash.functionsIn=functionsIn,lodash.groupBy=groupBy,lodash.initial=initial,lodash.intersection=intersection,lodash.intersectionBy=intersectionBy,lodash.intersectionWith=intersectionWith,lodash.invert=invert,lodash.invertBy=invertBy,lodash.invokeMap=invokeMap,lodash.iteratee=iteratee,lodash.keyBy=keyBy,lodash.keys=keys,lodash.keysIn=keysIn,lodash.map=map,lodash.mapKeys=mapKeys,lodash.mapValues=mapValues,lodash.matches=matches,lodash.matchesProperty=matchesProperty,lodash.memoize=memoize,lodash.merge=merge,lodash.mergeWith=mergeWith,lodash.method=method,lodash.methodOf=methodOf,lodash.mixin=mixin,lodash.negate=negate,lodash.nthArg=nthArg,lodash.omit=omit,lodash.omitBy=omitBy,lodash.once=once,lodash.orderBy=orderBy,lodash.over=over,lodash.overArgs=overArgs,lodash.overEvery=overEvery,lodash.overSome=overSome,lodash.partial=partial,lodash.partialRight=partialRight,lodash.partition=partition,lodash.pick=pick,lodash.pickBy=pickBy,lodash.property=property,lodash.propertyOf=propertyOf,lodash.pull=pull,lodash.pullAll=pullAll,lodash.pullAllBy=pullAllBy,lodash.pullAllWith=pullAllWith,lodash.pullAt=pullAt,lodash.range=range,lodash.rangeRight=rangeRight,lodash.rearg=rearg,lodash.reject=reject,lodash.remove=remove,lodash.rest=rest,lodash.reverse=reverse,lodash.sampleSize=sampleSize,lodash.set=set,lodash.setWith=setWith,lodash.shuffle=shuffle,lodash.slice=slice,lodash.sortBy=sortBy,lodash.sortedUniq=sortedUniq,lodash.sortedUniqBy=sortedUniqBy,lodash.split=split,lodash.spread=spread,lodash.tail=tail,lodash.take=take,lodash.takeRight=takeRight,lodash.takeRightWhile=takeRightWhile,lodash.takeWhile=takeWhile,lodash.tap=tap,lodash.throttle=throttle,lodash.thru=thru,lodash.toArray=toArray,lodash.toPairs=toPairs,lodash.toPairsIn=toPairsIn,lodash.toPath=toPath,lodash.toPlainObject=toPlainObject,lodash.transform=transform,lodash.unary=unary,lodash.union=union,lodash.unionBy=unionBy,lodash.unionWith=unionWith,lodash.uniq=uniq,lodash.uniqBy=uniqBy,lodash.uniqWith=uniqWith,lodash.unset=unset,lodash.unzip=unzip,lodash.unzipWith=unzipWith,lodash.update=update,lodash.updateWith=updateWith,lodash.values=values,lodash.valuesIn=valuesIn,lodash.without=without,lodash.words=words,lodash.wrap=wrap,lodash.xor=xor,lodash.xorBy=xorBy,lodash.xorWith=xorWith,lodash.zip=zip,lodash.zipObject=zipObject,lodash.zipObjectDeep=zipObjectDeep,lodash.zipWith=zipWith,lodash.entries=toPairs,lodash.entriesIn=toPairsIn,lodash.extend=assignIn,lodash.extendWith=assignInWith,mixin(lodash,lodash),lodash.add=add,lodash.attempt=attempt,lodash.camelCase=camelCase,lodash.capitalize=capitalize,lodash.ceil=ceil,lodash.clamp=clamp,lodash.clone=clone,lodash.cloneDeep=cloneDeep,lodash.cloneDeepWith=cloneDeepWith,lodash.cloneWith=cloneWith,lodash.conformsTo=conformsTo,lodash.deburr=deburr,lodash.defaultTo=defaultTo,lodash.divide=divide,lodash.endsWith=endsWith,lodash.eq=eq,lodash.escape=escape,lodash.escapeRegExp=escapeRegExp,lodash.every=every,lodash.find=find,lodash.findIndex=findIndex,lodash.findKey=findKey,lodash.findLast=findLast,lodash.findLastIndex=findLastIndex,lodash.findLastKey=findLastKey,lodash.floor=floor,lodash.forEach=forEach,lodash.forEachRight=forEachRight,lodash.forIn=forIn,lodash.forInRight=forInRight,lodash.forOwn=forOwn,lodash.forOwnRight=forOwnRight,lodash.get=get,lodash.gt=gt,lodash.gte=gte,lodash.has=has,lodash.hasIn=hasIn,lodash.head=head,lodash.identity=identity,lodash.includes=includes,lodash.indexOf=indexOf,lodash.inRange=inRange,lodash.invoke=invoke,lodash.isArguments=isArguments,lodash.isArray=isArray,lodash.isArrayBuffer=isArrayBuffer,lodash.isArrayLike=isArrayLike,lodash.isArrayLikeObject=isArrayLikeObject,lodash.isBoolean=isBoolean,lodash.isBuffer=isBuffer,lodash.isDate=isDate,lodash.isElement=isElement,lodash.isEmpty=isEmpty,lodash.isEqual=isEqual,lodash.isEqualWith=isEqualWith,lodash.isError=isError,lodash.isFinite=isFinite,lodash.isFunction=isFunction,lodash.isInteger=isInteger,lodash.isLength=isLength,lodash.isMap=isMap,lodash.isMatch=isMatch,lodash.isMatchWith=isMatchWith,lodash.isNaN=isNaN,lodash.isNative=isNative,lodash.isNil=isNil,lodash.isNull=isNull,lodash.isNumber=isNumber,lodash.isObject=isObject,lodash.isObjectLike=isObjectLike,lodash.isPlainObject=isPlainObject,lodash.isRegExp=isRegExp,lodash.isSafeInteger=isSafeInteger,lodash.isSet=isSet,lodash.isString=isString,lodash.isSymbol=isSymbol,lodash.isTypedArray=isTypedArray,lodash.isUndefined=isUndefined,lodash.isWeakMap=isWeakMap,lodash.isWeakSet=isWeakSet,lodash.join=join,lodash.kebabCase=kebabCase,lodash.last=last,lodash.lastIndexOf=lastIndexOf,lodash.lowerCase=lowerCase,lodash.lowerFirst=lowerFirst,lodash.lt=lt,lodash.lte=lte,lodash.max=max,lodash.maxBy=maxBy,lodash.mean=mean,lodash.meanBy=meanBy,lodash.min=min,lodash.minBy=minBy,lodash.stubArray=stubArray,lodash.stubFalse=stubFalse,lodash.stubObject=stubObject,lodash.stubString=stubString,lodash.stubTrue=stubTrue,lodash.multiply=multiply,lodash.nth=nth,lodash.noConflict=noConflict,lodash.noop=noop,lodash.now=now,lodash.pad=pad,lodash.padEnd=padEnd,lodash.padStart=padStart,lodash.parseInt=parseInt,lodash.random=random,lodash.reduce=reduce,lodash.reduceRight=reduceRight,lodash.repeat=repeat,lodash.replace=replace,lodash.result=result,lodash.round=round,lodash.runInContext=runInContext,lodash.sample=sample,lodash.size=size,lodash.snakeCase=snakeCase,lodash.some=some,lodash.sortedIndex=sortedIndex,lodash.sortedIndexBy=sortedIndexBy,lodash.sortedIndexOf=sortedIndexOf,lodash.sortedLastIndex=sortedLastIndex,lodash.sortedLastIndexBy=sortedLastIndexBy,lodash.sortedLastIndexOf=sortedLastIndexOf,lodash.startCase=startCase,lodash.startsWith=startsWith,lodash.subtract=subtract,lodash.sum=sum,lodash.sumBy=sumBy,lodash.template=template,lodash.times=times,lodash.toFinite=toFinite,lodash.toInteger=toInteger,lodash.toLength=toLength,lodash.toLower=toLower,lodash.toNumber=toNumber,lodash.toSafeInteger=toSafeInteger,lodash.toString=toString,lodash.toUpper=toUpper,lodash.trim=trim,lodash.trimEnd=trimEnd,lodash.trimStart=trimStart,lodash.truncate=truncate,lodash.unescape=unescape,lodash.uniqueId=uniqueId,lodash.upperCase=upperCase,lodash.upperFirst=upperFirst,lodash.each=forEach,lodash.eachRight=forEachRight,lodash.first=head,mixin(lodash,function(){var source={};return baseForOwn(lodash,function(func,methodName){hasOwnProperty.call(lodash.prototype,methodName)||(source[methodName]=func)}),source}(),{chain:!1}),lodash.VERSION=VERSION,arrayEach(["bind","bindKey","curry","curryRight","partial","partialRight"],function(methodName){lodash[methodName].placeholder=lodash}),arrayEach(["drop","take"],function(methodName,index){LazyWrapper.prototype[methodName]=function(n){var filtered=this.__filtered__;if(filtered&&!index)return new LazyWrapper(this);n=n===undefined?1:nativeMax(toInteger(n),0);var result=this.clone();return filtered?result.__takeCount__=nativeMin(n,result.__takeCount__):result.__views__.push({size:nativeMin(n,MAX_ARRAY_LENGTH),type:methodName+(result.__dir__<0?"Right":"")}),result},LazyWrapper.prototype[methodName+"Right"]=function(n){return this.reverse()[methodName](n).reverse()}}),arrayEach(["filter","map","takeWhile"],function(methodName,index){var type=index+1,isFilter=type==LAZY_FILTER_FLAG||type==LAZY_WHILE_FLAG;LazyWrapper.prototype[methodName]=function(iteratee){var result=this.clone();return result.__iteratees__.push({iteratee:getIteratee(iteratee,3),type:type}),result.__filtered__=result.__filtered__||isFilter,result}}),arrayEach(["head","last"],function(methodName,index){var takeName="take"+(index?"Right":"");LazyWrapper.prototype[methodName]=function(){return this[takeName](1).value()[0]}}),arrayEach(["initial","tail"],function(methodName,index){var dropName="drop"+(index?"":"Right");LazyWrapper.prototype[methodName]=function(){return this.__filtered__?new LazyWrapper(this):this[dropName](1)}}),LazyWrapper.prototype.compact=function(){return this.filter(identity)},LazyWrapper.prototype.find=function(predicate){return this.filter(predicate).head()},LazyWrapper.prototype.findLast=function(predicate){return this.reverse().find(predicate)},LazyWrapper.prototype.invokeMap=baseRest(function(path,args){return"function"==typeof path?new LazyWrapper(this):this.map(function(value){return baseInvoke(value,path,args)})}),LazyWrapper.prototype.reject=function(predicate){return this.filter(negate(getIteratee(predicate)))},LazyWrapper.prototype.slice=function(start,end){start=toInteger(start);var result=this;return result.__filtered__&&(start>0||0>end)?new LazyWrapper(result):(0>start?result=result.takeRight(-start):start&&(result=result.drop(start)),end!==undefined&&(end=toInteger(end),result=0>end?result.dropRight(-end):result.take(end-start)),result)},LazyWrapper.prototype.takeRightWhile=function(predicate){return this.reverse().takeWhile(predicate).reverse()},LazyWrapper.prototype.toArray=function(){return this.take(MAX_ARRAY_LENGTH)},baseForOwn(LazyWrapper.prototype,function(func,methodName){var checkIteratee=/^(?:filter|find|map|reject)|While$/.test(methodName),isTaker=/^(?:head|last)$/.test(methodName),lodashFunc=lodash[isTaker?"take"+("last"==methodName?"Right":""):methodName],retUnwrapped=isTaker||/^find/.test(methodName);lodashFunc&&(lodash.prototype[methodName]=function(){var value=this.__wrapped__,args=isTaker?[1]:arguments,isLazy=value instanceof LazyWrapper,iteratee=args[0],useLazy=isLazy||isArray(value),interceptor=function(value){var result=lodashFunc.apply(lodash,arrayPush([value],args));return isTaker&&chainAll?result[0]:result};useLazy&&checkIteratee&&"function"==typeof iteratee&&1!=iteratee.length&&(isLazy=useLazy=!1);var chainAll=this.__chain__,isHybrid=!!this.__actions__.length,isUnwrapped=retUnwrapped&&!chainAll,onlyLazy=isLazy&&!isHybrid;if(!retUnwrapped&&useLazy){value=onlyLazy?value:new LazyWrapper(this);var result=func.apply(value,args);return result.__actions__.push({func:thru,args:[interceptor],thisArg:undefined}),new LodashWrapper(result,chainAll)}return isUnwrapped&&onlyLazy?func.apply(this,args):(result=this.thru(interceptor),isUnwrapped?isTaker?result.value()[0]:result.value():result)})}),arrayEach(["pop","push","shift","sort","splice","unshift"],function(methodName){var func=arrayProto[methodName],chainName=/^(?:push|sort|unshift)$/.test(methodName)?"tap":"thru",retUnwrapped=/^(?:pop|shift)$/.test(methodName);lodash.prototype[methodName]=function(){var args=arguments;if(retUnwrapped&&!this.__chain__){var value=this.value();return func.apply(isArray(value)?value:[],args)}return this[chainName](function(value){return func.apply(isArray(value)?value:[],args)})}}),baseForOwn(LazyWrapper.prototype,function(func,methodName){var lodashFunc=lodash[methodName];if(lodashFunc){var key=lodashFunc.name+"",names=realNames[key]||(realNames[key]=[]);names.push({name:methodName,func:lodashFunc})}}),realNames[createHybrid(undefined,BIND_KEY_FLAG).name]=[{name:"wrapper",func:undefined}],LazyWrapper.prototype.clone=lazyClone,LazyWrapper.prototype.reverse=lazyReverse,LazyWrapper.prototype.value=lazyValue,lodash.prototype.at=wrapperAt,lodash.prototype.chain=wrapperChain,lodash.prototype.commit=wrapperCommit,lodash.prototype.next=wrapperNext,lodash.prototype.plant=wrapperPlant,lodash.prototype.reverse=wrapperReverse,lodash.prototype.toJSON=lodash.prototype.valueOf=lodash.prototype.value=wrapperValue, -lodash.prototype.first=lodash.prototype.head,iteratorSymbol&&(lodash.prototype[iteratorSymbol]=wrapperToIterator),lodash}var undefined,VERSION="4.16.0",LARGE_ARRAY_SIZE=200,FUNC_ERROR_TEXT="Expected a function",HASH_UNDEFINED="__lodash_hash_undefined__",MAX_MEMOIZE_SIZE=500,PLACEHOLDER="__lodash_placeholder__",BIND_FLAG=1,BIND_KEY_FLAG=2,CURRY_BOUND_FLAG=4,CURRY_FLAG=8,CURRY_RIGHT_FLAG=16,PARTIAL_FLAG=32,PARTIAL_RIGHT_FLAG=64,ARY_FLAG=128,REARG_FLAG=256,FLIP_FLAG=512,UNORDERED_COMPARE_FLAG=1,PARTIAL_COMPARE_FLAG=2,DEFAULT_TRUNC_LENGTH=30,DEFAULT_TRUNC_OMISSION="...",HOT_COUNT=500,HOT_SPAN=16,LAZY_FILTER_FLAG=1,LAZY_MAP_FLAG=2,LAZY_WHILE_FLAG=3,INFINITY=1/0,MAX_SAFE_INTEGER=9007199254740991,MAX_INTEGER=1.7976931348623157e308,NAN=NaN,MAX_ARRAY_LENGTH=4294967295,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH-1,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH>>>1,wrapFlags=[["ary",ARY_FLAG],["bind",BIND_FLAG],["bindKey",BIND_KEY_FLAG],["curry",CURRY_FLAG],["curryRight",CURRY_RIGHT_FLAG],["flip",FLIP_FLAG],["partial",PARTIAL_FLAG],["partialRight",PARTIAL_RIGHT_FLAG],["rearg",REARG_FLAG]],argsTag="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",genTag="[object GeneratorFunction]",mapTag="[object Map]",numberTag="[object Number]",objectTag="[object Object]",promiseTag="[object Promise]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]",weakMapTag="[object WeakMap]",weakSetTag="[object WeakSet]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]",reEmptyStringLeading=/\b__p \+= '';/g,reEmptyStringMiddle=/\b(__p \+=) '' \+/g,reEmptyStringTrailing=/(__e\(.*?\)|\b__t\)) \+\n'';/g,reEscapedHtml=/&(?:amp|lt|gt|quot|#39|#96);/g,reUnescapedHtml=/[&<>"'`]/g,reHasEscapedHtml=RegExp(reEscapedHtml.source),reHasUnescapedHtml=RegExp(reUnescapedHtml.source),reEscape=/<%-([\s\S]+?)%>/g,reEvaluate=/<%([\s\S]+?)%>/g,reInterpolate=/<%=([\s\S]+?)%>/g,reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/,reLeadingDot=/^\./,rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reHasRegExpChar=RegExp(reRegExpChar.source),reTrim=/^\s+|\s+$/g,reTrimStart=/^\s+/,reTrimEnd=/\s+$/,reWrapComment=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,reWrapDetails=/\{\n\/\* \[wrapped with (.+)\] \*/,reSplitDetails=/,? & /,reAsciiWord=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,reEscapeChar=/\\(\\)?/g,reEsTemplate=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,reFlags=/\w*$/,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsHostCtor=/^\[object .+?Constructor\]$/,reIsOctal=/^0o[0-7]+$/i,reIsUint=/^(?:0|[1-9]\d*)$/,reLatin=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,reNoMatch=/($^)/,reUnescapedString=/['\n\r\u2028\u2029\\]/g,rsAstralRange="\\ud800-\\udfff",rsComboMarksRange="\\u0300-\\u036f\\ufe20-\\ufe23",rsComboSymbolsRange="\\u20d0-\\u20f0",rsDingbatRange="\\u2700-\\u27bf",rsLowerRange="a-z\\xdf-\\xf6\\xf8-\\xff",rsMathOpRange="\\xac\\xb1\\xd7\\xf7",rsNonCharRange="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",rsPunctuationRange="\\u2000-\\u206f",rsSpaceRange=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",rsUpperRange="A-Z\\xc0-\\xd6\\xd8-\\xde",rsVarRange="\\ufe0e\\ufe0f",rsBreakRange=rsMathOpRange+rsNonCharRange+rsPunctuationRange+rsSpaceRange,rsApos="['’]",rsAstral="["+rsAstralRange+"]",rsBreak="["+rsBreakRange+"]",rsCombo="["+rsComboMarksRange+rsComboSymbolsRange+"]",rsDigits="\\d+",rsDingbat="["+rsDingbatRange+"]",rsLower="["+rsLowerRange+"]",rsMisc="[^"+rsAstralRange+rsBreakRange+rsDigits+rsDingbatRange+rsLowerRange+rsUpperRange+"]",rsFitz="\\ud83c[\\udffb-\\udfff]",rsModifier="(?:"+rsCombo+"|"+rsFitz+")",rsNonAstral="[^"+rsAstralRange+"]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",rsUpper="["+rsUpperRange+"]",rsZWJ="\\u200d",rsLowerMisc="(?:"+rsLower+"|"+rsMisc+")",rsUpperMisc="(?:"+rsUpper+"|"+rsMisc+")",rsOptLowerContr="(?:"+rsApos+"(?:d|ll|m|re|s|t|ve))?",rsOptUpperContr="(?:"+rsApos+"(?:D|LL|M|RE|S|T|VE))?",reOptMod=rsModifier+"?",rsOptVar="["+rsVarRange+"]?",rsOptJoin="(?:"+rsZWJ+"(?:"+[rsNonAstral,rsRegional,rsSurrPair].join("|")+")"+rsOptVar+reOptMod+")*",rsSeq=rsOptVar+reOptMod+rsOptJoin,rsEmoji="(?:"+[rsDingbat,rsRegional,rsSurrPair].join("|")+")"+rsSeq,rsSymbol="(?:"+[rsNonAstral+rsCombo+"?",rsCombo,rsRegional,rsSurrPair,rsAstral].join("|")+")",reApos=RegExp(rsApos,"g"),reComboMark=RegExp(rsCombo,"g"),reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g"),reUnicodeWord=RegExp([rsUpper+"?"+rsLower+"+"+rsOptLowerContr+"(?="+[rsBreak,rsUpper,"$"].join("|")+")",rsUpperMisc+"+"+rsOptUpperContr+"(?="+[rsBreak,rsUpper+rsLowerMisc,"$"].join("|")+")",rsUpper+"?"+rsLowerMisc+"+"+rsOptLowerContr,rsUpper+"+"+rsOptUpperContr,rsDigits,rsEmoji].join("|"),"g"),reHasUnicode=RegExp("["+rsZWJ+rsAstralRange+rsComboMarksRange+rsComboSymbolsRange+rsVarRange+"]"),reHasUnicodeWord=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,contextProps=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],templateCounter=-1,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[dataViewTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[mapTag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[setTag]=cloneableTags[stringTag]=cloneableTags[symbolTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=!0,cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[weakMapTag]=!1;var deburredLetters={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"},htmlEscapes={"&":"&","<":"<",">":">",'"':""","'":"'"},htmlUnescapes={"&":"&","<":"<",">":">",""":'"',"'":"'"},stringEscapes={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},freeParseFloat=parseFloat,freeParseInt=parseInt,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,freeProcess=moduleExports&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding("util")}catch(e){}}(),nodeIsArrayBuffer=nodeUtil&&nodeUtil.isArrayBuffer,nodeIsDate=nodeUtil&&nodeUtil.isDate,nodeIsMap=nodeUtil&&nodeUtil.isMap,nodeIsRegExp=nodeUtil&&nodeUtil.isRegExp,nodeIsSet=nodeUtil&&nodeUtil.isSet,nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,asciiSize=baseProperty("length"),deburrLetter=basePropertyOf(deburredLetters),escapeHtmlChar=basePropertyOf(htmlEscapes),unescapeHtmlChar=basePropertyOf(htmlUnescapes),_=runInContext();"function"==typeof define&&"object"==typeof define.amd&&define.amd?(root._=_,define(function(){return _})):freeModule?((freeModule.exports=_)._=_,freeExports._=_):root._=_}.call(this);var UsergridAuthMode=Object.freeze({NONE:"none",USER:"user",APP:"app"}),UsergridDirection=Object.freeze({IN:"connecting",OUT:"connections"}),UsergridHttpMethod=Object.freeze({GET:"GET",PUT:"PUT",POST:"POST",DELETE:"DELETE"}),UsergridQueryOperator=Object.freeze({EQUAL:"=",GREATER_THAN:">",GREATER_THAN_EQUAL_TO:">=",LESS_THAN:"<",LESS_THAN_EQUAL_TO:"<="}),UsergridQuerySortOrder=Object.freeze({ASC:"asc",DESC:"desc"}),UsergridApplicationJSONHeaderValue="application/json";!function(global){function UsergridHelpers(){}var name="UsergridHelpers",overwrittenName=global[name];UsergridHelpers.DefaultHeaders=Object.freeze({"Content-Type":UsergridApplicationJSONHeaderValue,Accept:UsergridApplicationJSONHeaderValue}),UsergridHelpers.validateAndRetrieveClient=function(args){var client=void 0;if(args instanceof UsergridClient)client=args;else if(args[0]instanceof UsergridClient)client=args[0];else if(_.get(args,"client"))client=args.client;else{if(!Usergrid.isInitialized)throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument");client=Usergrid}return client},UsergridHelpers.inherits=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})},UsergridHelpers.flattenArgs=function(args){return _.flattenDeep(Array.prototype.slice.call(args))},UsergridHelpers.callback=function(){var args=UsergridHelpers.flattenArgs(arguments).reverse(),emptyFunc=function(){};return _.first(_.flattenDeep([args,_.get(args,"0.callback"),emptyFunc]).filter(_.isFunction))},UsergridHelpers.authForRequests=function(client){var authForRequests=void 0;return _.get(client,"tempAuth.isValid")?(authForRequests=client.tempAuth,client.tempAuth=void 0):_.get(client,"currentUser.auth.isValid")&&client.authMode===UsergridAuthMode.USER?authForRequests=client.currentUser.auth:_.get(client,"appAuth.isValid")&&client.authMode===UsergridAuthMode.APP&&(authForRequests=client.appAuth),authForRequests},UsergridHelpers.userLoginBody=function(options){var body={grant_type:"password",password:options.password};return options.tokenTtl&&(body.ttl=options.tokenTtl),body[options.username?"username":"email"]=options.username?options.username:options.email,body},UsergridHelpers.appLoginBody=function(options){var body={grant_type:"client_credentials",client_id:options.clientId,client_secret:options.clientSecret};return options.tokenTtl&&(body.ttl=options.tokenTtl),body},UsergridHelpers.calculateExpiry=function(expires_in){return Date.now()+1e3*(expires_in?expires_in-5:0)};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;return UsergridHelpers.isUUID=function(uuid){return uuid?uuidValueRegex.test(uuid):!1},UsergridHelpers.useQuotesIfRequired=function(value){return _.isFinite(value)||UsergridHelpers.isUUID(value)||_.isBoolean(value)||_.isObject(value)&&!_.isFunction(value)||_.isArray(value)?value:"'"+value+"'"},UsergridHelpers.setReadOnly=function(obj,key){return _.isArray(key)?key.forEach(function(k){UsergridHelpers.setReadOnly(obj,k)}):_.isPlainObject(obj[key])?Object.freeze(obj[key]):_.isPlainObject(obj)&&void 0===key?Object.freeze(obj):_.has(obj,key)?Object.defineProperty(obj,key,{writable:!1}):obj},UsergridHelpers.setWritable=function(obj,key){return _.isArray(key)?key.forEach(function(k){UsergridHelpers.setWritable(obj,k)}):_.isPlainObject(obj[key])?_.clone(obj[key]):_.isPlainObject(obj)&&void 0===key?_.clone(obj):_.has(obj,key)?Object.defineProperty(obj,key,{writable:!0}):obj},UsergridHelpers.assignPrefabOptions=function(args){return _.isObject(args[0])&&!_.isFunction(args[0])&&_.has(args,"method")&&_.assign(this,args[0]),this},UsergridHelpers.normalize=function(str){return str=str.replace(/\/+/g,"/"),str=str.replace(/:\//g,"://"),str=str.replace(/\/(\?|&|#[^!])/g,"$1"),str=str.replace(/(\?.+)\?/g,"$1&")},UsergridHelpers.urljoin=function(){var input=arguments,options={};"object"==typeof arguments[0]&&(input=arguments[0],options=arguments[1]||{});var joined=[].slice.call(input,0).join("/");return UsergridHelpers.normalize(joined,options)},UsergridHelpers.parseResponseHeaders=function(headerStr){var headers={};if(headerStr)for(var headerPairs=headerStr.split("\r\n"),i=0;i0){var key=headerPair.substring(0,index).toLowerCase();headers[key]=headerPair.substring(index+2)}}return headers},UsergridHelpers.uri=function(client,options){var path="";path=options instanceof UsergridEntity?options.type:options instanceof UsergridQuery?options._type:_.isString(options)?options:_.isArray(options)?_.get(options,"0.type")||_.get(options,"0.path"):options.path||options.type||_.get(options,"entity.type")||_.get(options,"query._type")||_.get(options,"body.type")||_.get(options,"body.path");var uuidOrName="";return options.method!==UsergridHttpMethod.POST&&(uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,_.get(options,"entity.uuid"),_.get(options,"entity.name"),_.get(options,"body.uuid"),_.get(options,"body.name"),""].filter(_.isString))),UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,path,uuidOrName)},UsergridHelpers.updateEntityFromRemote=function(entity,usergridResponse){UsergridHelpers.setWritable(entity,["uuid","name","type","created"]),_.assign(entity,usergridResponse.entity),UsergridHelpers.setReadOnly(entity,["uuid","name","type","created"])},UsergridHelpers.headers=function(client,options,defaultHeaders){var returnHeaders={};_.defaults(returnHeaders,options.headers,defaultHeaders),_.assign(returnHeaders,{"User-Agent":"usergrid-js/v"+UsergridSDKVersion});var authForRequests=UsergridHelpers.authForRequests(client);return authForRequests&&_.assign(returnHeaders,{authorization:"Bearer "+authForRequests.token}),returnHeaders},UsergridHelpers.setEntity=function(options,args){return options.entity=_.first([options.entity,args[0]].filter(function(property){return property instanceof UsergridEntity})),void 0!==options.entity&&(options.type=options.entity.type),options},UsergridHelpers.setAsset=function(options,args){return options.asset=_.first([options.asset,_.get(options,"entity.asset"),args[1],args[0]].filter(function(property){return property instanceof UsergridAsset})),options},UsergridHelpers.setUuidOrName=function(options,args){return options.uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,_.get(options,"entity.uuid"),_.get(options,"body.uuid"),_.get(options,"entity.name"),_.get(options,"body.name"),_.get(args,"0.uuid"),_.get(args,"0.name"),_.get(args,"2"),_.get(args,"1")].filter(_.isString)),options},UsergridHelpers.setPathOrType=function(options,args){var pathOrType=_.first([args.type,_.get(args,"0.type"),_.get(options,"entity.type"),_.get(args,"body.type"),_.get(options,"body.0.type"),_.isArray(args)?args[0]:void 0].filter(_.isString));return options[/\//.test(pathOrType)?"path":"type"]=pathOrType,options},UsergridHelpers.setQs=function(options,args){return options.path&&(options.qs=_.first([options.qs,args[2],args[1],args[0]].filter(_.isPlainObject))),options},UsergridHelpers.setQuery=function(options,args){return options.query=_.first([options,options.query,args[0]].filter(function(property){return property instanceof UsergridQuery})),options},UsergridHelpers.setAsset=function(options,args){return options.asset=_.first([options.asset,_.get(options,"entity.asset"),args[1],args[0]].filter(function(property){return property instanceof UsergridAsset})),options},UsergridHelpers.setBody=function(options,args){if(options.body=_.first([args.entity,args.body,args[0].entity,args[0].body,args[2],args[1],args[0]].filter(function(property){return _.isObject(property)&&!_.isFunction(property)&&!(property instanceof UsergridQuery)&&!(property instanceof UsergridAsset)})),void 0===options.body&&void 0===options.asset)throw new Error('"body" is required when making a '+options.method+" request");return options.body instanceof UsergridEntity?options.body=options.body.jsonValue():options.body instanceof Array&&options.body[0]instanceof UsergridEntity&&(options.body=_.map(options.body,function(entity){return entity.jsonValue()})),options},UsergridHelpers.buildReqest=function(client,method,args){var options={client:client,method:method,queryParams:args.queryParams||_.get(args,"0.queryParams"),callback:UsergridHelpers.callback(args)};return UsergridHelpers.assignPrefabOptions(options,args),UsergridHelpers.setEntity(options,args),(method===UsergridHttpMethod.POST||method===UsergridHttpMethod.PUT)&&(UsergridHelpers.setAsset(options,args),void 0===options.asset&&UsergridHelpers.setBody(options,args)),UsergridHelpers.setUuidOrName(options,args),UsergridHelpers.setPathOrType(options,args),UsergridHelpers.setQs(options,args),UsergridHelpers.setQuery(options,args),options.uri=UsergridHelpers.uri(client,options),new UsergridRequest(options)},UsergridHelpers.buildAppAuthRequest=function(client,auth,callback){var requestOptions={client:client,method:UsergridHttpMethod.POST,uri:UsergridHelpers.uri(client,{path:"token"}),body:UsergridHelpers.appLoginBody(auth),callback:callback};return new UsergridRequest(requestOptions)},UsergridHelpers.buildConnectionRequest=function(client,method,args){var options={client:client,method:method,entity:{},to:{},callback:UsergridHelpers.callback(args)};if(UsergridHelpers.assignPrefabOptions.call(options,args),_.isObject(options.from)&&(options.to=options.from),_.isObject(args[0])&&_.has(args[0],"entity")&&_.has(args[0],"to")&&(_.assign(options.entity,args[0].entity),options.relationship=_.get(args,"0.relationship"),_.assign(options.to,args[0].to)),_.isObject(args[0])&&!_.isFunction(args[0])&&_.isString(args[1])&&(_.assign(options.entity,args[0]),options.relationship=_.first([options.relationship,args[1]].filter(_.isString))),_.isObject(args[2])&&!_.isFunction(args[2])&&_.assign(options.to,args[2]),options.entity.uuidOrName=_.first([options.entity.uuidOrName,options.entity.uuid,options.entity.name,args[1]].filter(_.isString)),options.entity.type||(options.entity.type=_.first([options.entity.type,args[0]].filter(_.isString))),options.relationship=_.first([options.relationship,args[2]].filter(_.isString)),_.isString(args[3])&&!UsergridHelpers.isUUID(args[3])&&_.isString(args[4])?options.to.type=args[3]:_.isString(args[2])&&!UsergridHelpers.isUUID(args[2])&&_.isString(args[3])&&_.isObject(args[0])&&!_.isFunction(args[0])&&(options.to.type=args[2]),options.to.uuidOrName=_.first([options.to.uuidOrName,options.to.uuid,options.to.name,args[4],args[3],args[2]].filter(function(property){return _.isString(options.to.type)&&_.isString(property)||UsergridHelpers.isUUID(property)})),!_.isString(options.entity.uuidOrName))throw new Error('source entity "uuidOrName" is required when connecting or disconnecting entities');if(!_.isString(options.to.uuidOrName))throw new Error('target entity "uuidOrName" is required when connecting or disconnecting entities');if(!_.isString(options.to.type)&&!UsergridHelpers.isUUID(options.to.uuidOrName))throw new Error('target "type" (collection name) parameter is required connecting or disconnecting entities by name');return options.uri=UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,_.isString(options.entity.type)?options.entity.type:"",_.isString(options.entity.uuidOrName)?options.entity.uuidOrName:"",options.relationship,_.isString(options.to.type)?options.to.type:"",_.isString(options.to.uuidOrName)?options.to.uuidOrName:""),new UsergridRequest(options)},UsergridHelpers.buildGetConnectionRequest=function(client,args){var options={client:client,method:"GET",callback:UsergridHelpers.callback(args)};if(UsergridHelpers.assignPrefabOptions.call(options,args),_.isObject(args[1])&&!_.isFunction(args[1])&&_.assign(options,args[1]),options.direction=_.first([options.direction,args[0]].filter(function(property){return property===UsergridDirection.IN||property===UsergridDirection.OUT})),options.relationship=_.first([options.relationship,args[3],args[2]].filter(_.isString)),options.uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,args[2]].filter(_.isString)),options.type=_.first([options.type,args[1]].filter(_.isString)),!_.isString(options.type))throw new Error('"type" (collection name) parameter is required when retrieving connections');if(!_.isString(options.uuidOrName))throw new Error('target entity "uuidOrName" is required when retrieving connections');return options.uri=UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,_.isString(options.type)?options.type:"",_.isString(options.uuidOrName)?options.uuidOrName:"",options.direction,options.relationship),new UsergridRequest(options)},global[name]=UsergridHelpers,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),UsergridHelpers},global[name]}(this);var UsergridClientDefaultOptions={baseUrl:"https://api.usergrid.com",authMode:UsergridAuthMode.USER},UsergridClient=function(options){var __appAuth,self=this;if(self.tempAuth=void 0,self.isSharedInstance=!1,2===arguments.length&&(self.orgId=arguments[0],self.appId=arguments[1]),_.defaults(self,options,UsergridClientDefaultOptions),!self.orgId||!self.appId)throw new Error('"orgId" and "appId" parameters are required when instantiating UsergridClient');return Object.defineProperty(self,"clientId",{enumerable:!1}),Object.defineProperty(self,"clientSecret",{enumerable:!1}),Object.defineProperty(self,"appAuth",{get:function(){return __appAuth},set:function(options){options instanceof UsergridAppAuth?__appAuth=options:"undefined"!=typeof options&&(__appAuth=new UsergridAppAuth(options))}}),self.clientId&&self.clientSecret&&self.setAppAuth(self.clientId,self.clientSecret),self};UsergridClient.prototype={sendRequest:function(usergridRequest){return usergridRequest.sendRequest()},GET:function(){var usergridRequest=UsergridHelpers.buildReqest(this,UsergridHttpMethod.GET,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},PUT:function(){var usergridRequest=UsergridHelpers.buildReqest(this,UsergridHttpMethod.PUT,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},POST:function(){var usergridRequest=UsergridHelpers.buildReqest(this,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},DELETE:function(){var usergridRequest=UsergridHelpers.buildReqest(this,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},connect:function(){var usergridRequest=UsergridHelpers.buildConnectionRequest(this,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},disconnect:function(){var usergridRequest=UsergridHelpers.buildConnectionRequest(this,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},getConnections:function(){var usergridRequest=UsergridHelpers.buildGetConnectionRequest(this,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},usingAuth:function(auth){var self=this;return _.isString(auth)?self.tempAuth=new UsergridAuth(auth):auth instanceof UsergridAuth?self.tempAuth=auth:self.tempAuth=void 0,self},setAppAuth:function(){this.appAuth=new UsergridAppAuth(UsergridHelpers.flattenArgs(arguments))},authenticateApp:function(options){var self=this,authenticateAppCallback=UsergridHelpers.callback(UsergridHelpers.flattenArgs(arguments)),auth=_.first([options,self.appAuth,new UsergridAppAuth(options),new UsergridAppAuth(self.clientId,self.clientSecret)].filter(function(p){return p instanceof UsergridAppAuth}));if(!(auth instanceof UsergridAppAuth))throw new Error("App auth context was not defined when attempting to call .authenticateApp()");if(!auth.clientId||!auth.clientSecret)throw new Error("authenticateApp() failed because clientId or clientSecret are missing");var callback=function(usergridResponse){if(usergridResponse.ok){self.appAuth||(self.appAuth=auth),self.appAuth.token=_.get(usergridResponse.responseJSON,"access_token");var expiresIn=_.get(usergridResponse.responseJSON,"expires_in");self.appAuth.expiry=UsergridHelpers.calculateExpiry(expiresIn),self.appAuth.tokenTtl=expiresIn}authenticateAppCallback(usergridResponse)},usergridRequest=UsergridHelpers.buildAppAuthRequest(self,auth,callback);return self.sendRequest(usergridRequest)},authenticateUser:function(options){var self=this,args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args),setAsCurrentUser=void 0!==_.last(args.filter(_.isBoolean))?_.last(args.filter(_.isBoolean)):!0,userToAuthenticate=new UsergridUser(options);userToAuthenticate.login(self,function(auth,user,usergridResponse){usergridResponse.ok&&setAsCurrentUser&&(self.currentUser=userToAuthenticate),callback(auth,user,usergridResponse)})},downloadAsset:function(){var self=this,usergridRequest=UsergridHelpers.buildReqest(self,UsergridHttpMethod.GET,UsergridHelpers.flattenArgs(arguments)),assetContentType=_.get(usergridRequest,"entity.file-metadata.content-type");void 0!==assetContentType&&_.assign(usergridRequest.headers,{Accept:assetContentType});var realDownloadAssetCallback=usergridRequest.callback;return usergridRequest.callback=function(usergridResponse){var entity=usergridRequest.entity;entity.asset=usergridResponse.asset,realDownloadAssetCallback(entity.asset,usergridResponse,entity)},self.sendRequest(usergridRequest)},uploadAsset:function(){var self=this,usergridRequest=UsergridHelpers.buildReqest(self,UsergridHttpMethod.PUT,UsergridHelpers.flattenArgs(arguments));if(void 0===usergridRequest.asset)throw new Error("An UsergridAsset was not defined when attempting to call .uploadAsset()");var realUploadAssetCallback=usergridRequest.callback;return usergridRequest.callback=function(usergridResponse){var requestEntity=usergridRequest.entity,responseEntity=usergridResponse.entity,requestAsset=usergridRequest.asset;usergridResponse.ok&&void 0!==responseEntity&&(UsergridHelpers.updateEntityFromRemote(requestEntity,usergridResponse),requestEntity.asset=requestAsset,responseEntity&&(responseEntity.asset=requestAsset)),realUploadAssetCallback(requestAsset,usergridResponse,requestEntity)},self.sendRequest(usergridRequest)}};var UsergridSDKVersion="2.0.0",UsergridClientSharedInstance=function(){var self=this;return self.isInitialized=!1,self.isSharedInstance=!0,self};UsergridHelpers.inherits(UsergridClientSharedInstance,UsergridClient);var Usergrid=new UsergridClientSharedInstance;Usergrid.initSharedInstance=function(options){return Usergrid.isInitialized?console.log("Usergrid shared instance is already initialized"):(_.assign(Usergrid,new UsergridClient(options)),Usergrid.isInitialized=!0,Usergrid.isSharedInstance=!0),Usergrid},Usergrid.init=Usergrid.initSharedInstance;var UsergridQuery=function(type){var queryString,sort,self=this,query="",urlTerms={},__nextIsNot=!1;return self._type=type,_.assign(self,{type:function(value){return self._type=value,self},collection:function(value){return self._type=value,self},limit:function(value){return self._limit=value,self},cursor:function(value){return self._cursor=value,self},eq:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.EQUAL+" "+UsergridHelpers.useQuotesIfRequired(value)),self},equal:this.eq,gt:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.GREATER_THAN+" "+UsergridHelpers.useQuotesIfRequired(value)),self},greaterThan:this.gt,gte:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.GREATER_THAN_EQUAL_TO+" "+UsergridHelpers.useQuotesIfRequired(value)),self},greaterThanOrEqual:this.gte,lt:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.LESS_THAN+" "+UsergridHelpers.useQuotesIfRequired(value)),self},lessThan:this.lt,lte:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.LESS_THAN_EQUAL_TO+" "+UsergridHelpers.useQuotesIfRequired(value)),self},lessThanOrEqual:this.lte,contains:function(key,value){return query=self.andJoin(key+" contains "+UsergridHelpers.useQuotesIfRequired(value)),self},locationWithin:function(distanceInMeters,lat,lng){return query=self.andJoin("location within "+distanceInMeters+" of "+lat+", "+lng),self},asc:function(key){return self.sort(key,UsergridQuerySortOrder.ASC),self},desc:function(key){return self.sort(key,UsergridQuerySortOrder.DESC),self},sort:function(key,order){return sort=key&&order?" order by "+key+" "+order:"",self},fromString:function(string){return queryString=string,self},urlTerm:function(key,value){return"ql"===key?self.fromString():urlTerms[key]=value,self},andJoin:function(append){return __nextIsNot&&(append="not "+append,__nextIsNot=!1),append?0===query.length?append:_.endsWith(query,"and")||_.endsWith(query,"or")?query+" "+append:query+" and "+append:query},orJoin:function(){return query.length>0&&!_.endsWith(query,"or")?query+" or":query}}),Object.defineProperty(self,"_ql",{get:function(){var ql="select * ";return void 0!==queryString?ql=queryString:(ql+=query.length>0?"where "+(query||""):"",ql+=void 0!==sort?sort:""),ql}}),Object.defineProperty(self,"encodedStringValue",{get:function(){var self=this,limit=self._limit,cursor=self._cursor,requirementsString=self._ql,returnString=void 0;if(void 0!==limit&&(returnString="limit"+UsergridQueryOperator.EQUAL+limit),!_.isEmpty(cursor)){var cursorString="cursor"+UsergridQueryOperator.EQUAL+cursor;_.isEmpty(returnString)?returnString=cursorString:returnString+="&"+cursorString}if(_.forEach(urlTerms,function(value,key){var encodedURLTermString=encodeURIComponent(key)+UsergridQueryOperator.EQUAL+encodeURIComponent(value);_.isEmpty(returnString)?returnString=encodedURLTermString:returnString+="&"+encodedURLTermString; -}),!_.isEmpty(requirementsString)){var qLString="ql="+encodeURIComponent(requirementsString);_.isEmpty(returnString)?returnString=qLString:returnString+="&"+qLString}return _.isEmpty(returnString)||(returnString="?"+returnString),_.isEmpty(returnString)?void 0:returnString}}),Object.defineProperty(self,"and",{get:function(){return query=self.andJoin(""),self}}),Object.defineProperty(self,"or",{get:function(){return query=self.orJoin(),self}}),Object.defineProperty(self,"not",{get:function(){return __nextIsNot=!0,self}}),self},UsergridRequest=function(options){var self=this,client=UsergridHelpers.validateAndRetrieveClient(options);if(!_.isString(options.type)&&!_.isString(options.path)&&!_.isString(options.uri))throw new Error('one of "type" (collection name), "path", or "uri" parameters are required when initializing a UsergridRequest');if(!_.includes(["GET","PUT","POST","DELETE"],options.method))throw new Error('"method" parameter is required when initializing a UsergridRequest');self.method=options.method,self.callback=options.callback,self.uri=options.uri||UsergridHelpers.uri(client,options),self.entity=options.entity,self.body=options.body||void 0,self.asset=options.asset||void 0,self.query=options.query,self.queryParams=options.queryParams||options.qs;var defaultHeadersToUse=void 0===self.asset?UsergridHelpers.DefaultHeaders:{};if(self.headers=UsergridHelpers.headers(client,options,defaultHeadersToUse),void 0!==self.query&&(self.uri+=UsergridHelpers.normalize(self.query.encodedStringValue,{})),void 0!==self.queryParams&&(_.forOwn(self.queryParams,function(value,key){self.uri+="?"+encodeURIComponent(key)+UsergridQueryOperator.EQUAL+encodeURIComponent(value)}),self.uri=UsergridHelpers.normalize(self.uri,{})),void 0!==self.asset)self.body=new FormData,self.body.append(self.asset.filename,self.asset.data);else try{_.isPlainObject(self.body)?self.body=JSON.stringify(self.body):_.isArray(self.body)&&(self.body=JSON.stringify(self.body))}catch(exception){}return self};UsergridRequest.prototype.sendRequest=function(){var self=this,requestPromise=function(){var promise=new Promise,xmlHttpRequest=new XMLHttpRequest;return xmlHttpRequest.open(self.method,self.uri,!0),xmlHttpRequest.onload=function(){promise.done(xmlHttpRequest)},_.forOwn(self.headers,function(value,key){xmlHttpRequest.setRequestHeader(key,value)}),self.method===UsergridHttpMethod.GET&&_.get(self.headers,"Accept")!==UsergridApplicationJSONHeaderValue&&(xmlHttpRequest.responseType="blob"),xmlHttpRequest.send(self.body),promise},responsePromise=function(xmlRequest){var promise=new Promise,usergridResponse=new UsergridResponse(xmlRequest,self);return promise.done(usergridResponse),promise},onCompletePromise=function(response){var promise=new Promise;promise.done(response),self.callback(response)};return Promise.chain([requestPromise,responsePromise]).then(onCompletePromise),self};var UsergridAuth=function(token,expiry){var self=this;self.token=token,self.expiry=expiry||0;var usingToken=token?!0:!1;return Object.defineProperty(self,"hasToken",{get:function(){return void 0!==self.token},configurable:!0}),Object.defineProperty(self,"isExpired",{get:function(){return usingToken?!1:Date.now()>=self.expiry},configurable:!0}),Object.defineProperty(self,"isValid",{get:function(){return!self.isExpired&&self.hasToken},configurable:!0}),Object.defineProperty(self,"tokenTtl",{configurable:!0,writable:!0}),_.assign(self,{destroy:function(){self.token=void 0,self.expiry=0,self.tokenTtl=void 0}}),self},UsergridAppAuth=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments);return _.isPlainObject(args[0])?(self.clientId=args[0].clientId,self.clientSecret=args[0].clientSecret,self.tokenTtl=args[0].tokenTtl):(self.clientId=args[0],self.clientSecret=args[1],self.tokenTtl=args[2]),UsergridAuth.call(self),_.assign(self,UsergridAuth),self};UsergridHelpers.inherits(UsergridAppAuth,UsergridAuth);var UsergridUserAuth=function(options){var self=this,args=_.flattenDeep(UsergridHelpers.flattenArgs(arguments));return _.isPlainObject(args[0])&&(options=args[0]),self.username=options.username||args[0],self.email=options.email,(options.password||args[1])&&(self.password=options.password||args[1]),self.tokenTtl=options.tokenTtl||args[2],UsergridAuth.call(self),_.assign(self,UsergridAuth),self};UsergridHelpers.inherits(UsergridUserAuth,UsergridAuth);var UsergridEntity=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments);if(0===args.length)throw new Error("A UsergridEntity object cannot be initialized without passing one or more arguments");if(self.asset=void 0,_.isPlainObject(args[0])?_.assign(self,args[0]):(self.type||(self.type=_.isString(args[0])?args[0]:void 0),self.name||(self.name=_.isString(args[1])?args[1]:void 0)),!_.isString(self.type))throw new Error('"type" (or "collection") parameter is required when initializing a UsergridEntity object');return Object.defineProperty(self,"isUser",{get:function(){return"user"===self.type.toLowerCase()}}),Object.defineProperty(self,"hasAsset",{get:function(){return _.has(self,"file-metadata")}}),UsergridHelpers.setReadOnly(self,["uuid","name","type","created"]),self};UsergridEntity.prototype={jsonValue:function(){var jsonValue={};return _.forOwn(this,function(value,key){jsonValue[key]=value}),jsonValue},putProperty:function(key,value){this[key]=value},putProperties:function(obj){_.assign(this,obj)},removeProperty:function(key){this.removeProperties([key])},removeProperties:function(keys){var self=this;keys.forEach(function(key){delete self[key]})},insert:function(key,value,idx){_.isArray(this[key])||(this[key]=this[key]?[this[key]]:[]),this[key].splice.apply(this[key],[idx,0].concat(value))},append:function(key,value){this.insert(key,value,Number.MAX_VALUE)},prepend:function(key,value){this.insert(key,value,0)},pop:function(key){_.isArray(this[key])&&this[key].pop()},shift:function(key){_.isArray(this[key])&&this[key].shift()},reload:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.GET(self,function(usergridResponse){UsergridHelpers.updateEntityFromRemote(self,usergridResponse),callback(usergridResponse,self)}.bind(self))},save:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args),currentAsset=self.asset,uuid=self.uuid;void 0===uuid?client.POST(self,function(usergridResponse){UsergridHelpers.updateEntityFromRemote(self,usergridResponse),self.hasAsset&&(self.asset=currentAsset),callback(usergridResponse,self)}.bind(self)):client.PUT(self,function(usergridResponse){UsergridHelpers.updateEntityFromRemote(self,usergridResponse),self.hasAsset&&(self.asset=currentAsset),callback(usergridResponse,self)}.bind(self))},remove:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.DELETE(self,function(usergridResponse){callback(usergridResponse,self)}.bind(self))},attachAsset:function(asset){this.asset=asset},uploadAsset:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(_.has(self,"asset.contentType"))client.uploadAsset(self,callback);else{var response=new UsergridResponse.responseWithError({name:"asset_not_found",description:"The specified entity does not have a valid asset attached"});callback(null,response,self)}},downloadAsset:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(_.has(self,"asset.contentType"))client.downloadAsset(self,callback);else{var response=new UsergridResponse.responseWithError({name:"asset_not_found",description:"The specified entity does not have a valid asset attached"});callback(null,response,self)}},connect:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args[0]=this,client.connect.apply(client,args)},disconnect:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args[0]=this,client.disconnect.apply(client,args)},getConnections:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args.shift(),args.splice(1,0,this),client.getConnections.apply(client,args)}};var UsergridUser=function(obj){if(!_.has(obj,"email")&&!_.has(obj,"username"))throw new Error('"email" or "username" property is required when initializing a UsergridUser object');var self=this;return _.assign(self,obj,UsergridEntity),UsergridEntity.call(self,"user"),UsergridHelpers.setWritable(self,"name"),self};UsergridUser.CheckAvailable=function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);args[0]instanceof UsergridClient&&args.shift();var checkQuery,callback=UsergridHelpers.callback(args);if(args[0].username&&args[0].email)checkQuery=new UsergridQuery("users").eq("username",args[0].username).or.eq("email",args[0].email);else if(args[0].username)checkQuery=new UsergridQuery("users").eq("username",args[0].username);else{if(!args[0].email)throw new Error("'username' or 'email' property is required when checking for available users");checkQuery=new UsergridQuery("users").eq("email",args[0].email)}client.GET(checkQuery,function(usergridResponse){callback(usergridResponse,usergridResponse.entities.length>0)})},UsergridHelpers.inherits(UsergridUser,UsergridEntity),UsergridUser.prototype.uniqueId=function(){var self=this;return _.first([self.uuid,self.username,self.email].filter(_.isString))},UsergridUser.prototype.create=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.POST(self,function(usergridResponse){delete self.password,_.assign(self,usergridResponse.user),callback(usergridResponse,usergridResponse.user)}.bind(self))},UsergridUser.prototype.login=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.POST("token",UsergridHelpers.userLoginBody(self),function(usergridResponse){if(delete self.password,usergridResponse.ok){var responseJSON=usergridResponse.responseJSON;self.auth=new UsergridUserAuth(self),self.auth.token=_.get(responseJSON,"access_token");var expiresIn=_.get(responseJSON,"expires_in");self.auth.expiry=UsergridHelpers.calculateExpiry(expiresIn),self.auth.tokenTtl=expiresIn}callback(self.auth,self,usergridResponse)})},UsergridUser.prototype.logout=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(self.auth&&self.auth.isValid){var revokeAll=_.first(args.filter(_.isBoolean))||!1,queryParams=void 0;revokeAll||(queryParams={token:self.auth.token});var requestOptions={client:client,path:["users",self.uniqueId(),"revoketoken"+(revokeAll?"s":"")].join("/"),method:UsergridHttpMethod.PUT,queryParams:queryParams,callback:function(usergridResponse){self.auth.destroy(),callback(usergridResponse)}.bind(self)},request=new UsergridRequest(requestOptions);client.sendRequest(request)}else{var response=new UsergridResponse.responseWithError({name:"no_valid_token",description:"this user does not have a valid token"});callback(response)}},UsergridUser.prototype.logoutAllSessions=function(){var args=UsergridHelpers.flattenArgs(arguments);return args=_.concat([UsergridHelpers.validateAndRetrieveClient(args),!0],args),this.logout.apply(this,args)},UsergridUser.prototype.resetPassword=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);args[0]instanceof UsergridClient&&args.shift();var body={oldpassword:_.isPlainObject(args[0])?args[0].oldPassword:_.isString(args[0])?args[0]:void 0,newpassword:_.isPlainObject(args[0])?args[0].newPassword:_.isString(args[1])?args[1]:void 0};if(!body.oldpassword||!body.newpassword)throw new Error('"oldPassword" and "newPassword" properties are required when resetting a user password');client.PUT(["users",self.uniqueId(),"password"].join("/"),body,callback)};var UsergridResponseError=function(options){var self=this;return _.assign(self,options),self};UsergridResponseError.fromJSON=function(responseErrorObject){var usergridResponseError=void 0,error={name:_.get(responseErrorObject,"error")};return void 0!==error.name&&(_.assign(error,{exception:_.get(responseErrorObject,"exception"),description:_.get(responseErrorObject,"error_description")||_.get(responseErrorObject,"description")}),usergridResponseError=new UsergridResponseError(error)),usergridResponseError};var UsergridResponse=function(xmlRequest,usergridRequest){var self=this;if(self.ok=!1,self.request=usergridRequest,xmlRequest){self.statusCode=parseInt(xmlRequest.status),self.ok=self.statusCode<400,self.headers=UsergridHelpers.parseResponseHeaders(xmlRequest.getAllResponseHeaders());var responseContentType=_.get(self.headers,"content-type");if("application/json"===responseContentType){try{var responseJSON=JSON.parse(xmlRequest.responseText)}catch(e){responseJSON={}}self.parseResponseJSON(responseJSON),Object.defineProperty(self,"cursor",{get:function(){return _.get(self,"responseJSON.cursor")}}),Object.defineProperty(self,"hasNextPage",{get:function(){return void 0!==self.cursor}})}else self.asset=new UsergridAsset(xmlRequest.response)}return self};UsergridResponse.responseWithError=function(options){var usergridResponse=new UsergridResponse;return usergridResponse.error=new UsergridResponseError(options),usergridResponse},UsergridResponse.prototype={parseResponseJSON:function(responseJSON){var self=this;if(void 0!==responseJSON)if(_.assign(self,{responseJSON:_.cloneDeep(responseJSON)}),self.ok){var entitiesJSON=_.get(responseJSON,"entities");if(entitiesJSON){var entities=_.map(entitiesJSON,function(entityJSON){var entity=new UsergridEntity(entityJSON);return entity.isUser&&(entity=new UsergridUser(entity)),entity});_.assign(self,{entities:entities}),delete self.responseJSON.entities,self.first=_.first(entities)||void 0,self.entity=self.first,self.last=_.last(entities)||void 0,"/users"===_.get(responseJSON,"path")&&(self.user=self.first,self.users=self.entities),UsergridHelpers.setReadOnly(self.responseJSON)}}else self.error=UsergridResponseError.fromJSON(responseJSON)},loadNextPage:function(){var self=this,cursor=self.cursor;if(cursor){var args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args),client=UsergridHelpers.validateAndRetrieveClient(args),type=_.last(_.get(self,"responseJSON.path").split("/")),limit=_.first(_.get(self,"responseJSON.params.limit")),ql=_.first(_.get(self,"responseJSON.params.ql")),query=new UsergridQuery(type).fromString(ql).cursor(cursor).limit(limit);client.GET(query,callback)}else callback(UsergridResponse.responseWithError({name:"cursor_not_found",description:"Cursor must be present in order perform loadNextPage()."}))}};var UsergridAssetDefaultFileName="file",UsergridAsset=function(fileOrBlob){if(!fileOrBlob instanceof File||!fileOrBlob instanceof Blob)throw new Error("UsergridAsset must be initialized with a 'File' or 'Blob'");var self=this;return self.data=fileOrBlob,self.filename=fileOrBlob.name||UsergridAssetDefaultFileName,self.contentLength=fileOrBlob.size,self.contentType=fileOrBlob.type,self}; \ No newline at end of file +"use strict";!function(global){function Promise(){this.complete=!1,this.result=null,this.callbacks=[]}var name="Promise",overwrittenName=global[name];return Promise.prototype.then=function(callback,context){var f=function(){return callback.apply(context,arguments)};this.complete?f(this.result):this.callbacks.push(f)},Promise.prototype.done=function(result){this.complete=!0,this.result=result,this.callbacks&&(_.forEach(this.callbacks,function(callback){callback(result)}),this.callbacks.length=0)},Promise.join=function(promises){function notifier(i){return function(result){completed+=1,results[i]=result,completed===total&&p.done(results)}}for(var p=new Promise,total=promises.length,completed=0,results=[],i=0;total>i;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,result){var p=new Promise;return null===promises||0===promises.length?p.done(result):promises[0](result).then(function(res){promises.splice(0,1),promises?Promise.chain(promises,res).then(function(r){p.done(r)}):p.done(res)}),p},global[name]=Promise,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Promise},global[name]}(this),function(){function addMapEntry(map,pair){return map.set(pair[0],pair[1]),map}function addSetEntry(set,value){return set.add(value),set}function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}function arrayAggregator(array,setter,iteratee,accumulator){for(var index=-1,length=array?array.length:0;++index-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1;);return index}function charsEndIndex(strSymbols,chrSymbols){for(var index=strSymbols.length;index--&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1;);return index}function countHolders(array,placeholder){for(var length=array.length,result=0;length--;)array[length]===placeholder&&++result;return result}function escapeStringChar(chr){return"\\"+stringEscapes[chr]}function getValue(object,key){return null==object?undefined:object[key]}function hasUnicode(string){return reHasUnicode.test(string)}function hasUnicodeWord(string){return reHasUnicodeWord.test(string)}function iteratorToArray(iterator){for(var data,result=[];!(data=iterator.next()).done;)result.push(data.value);return result}function mapToArray(map){var index=-1,result=Array(map.size);return map.forEach(function(value,key){result[++index]=[key,value]}),result}function overArg(func,transform){return function(arg){return func(transform(arg))}}function replaceHolders(array,placeholder){for(var index=-1,length=array.length,resIndex=0,result=[];++index>>1,wrapFlags=[["ary",ARY_FLAG],["bind",BIND_FLAG],["bindKey",BIND_KEY_FLAG],["curry",CURRY_FLAG],["curryRight",CURRY_RIGHT_FLAG],["flip",FLIP_FLAG],["partial",PARTIAL_FLAG],["partialRight",PARTIAL_RIGHT_FLAG],["rearg",REARG_FLAG]],argsTag="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",genTag="[object GeneratorFunction]",mapTag="[object Map]",numberTag="[object Number]",objectTag="[object Object]",promiseTag="[object Promise]",proxyTag="[object Proxy]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]",weakMapTag="[object WeakMap]",weakSetTag="[object WeakSet]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]",reEmptyStringLeading=/\b__p \+= '';/g,reEmptyStringMiddle=/\b(__p \+=) '' \+/g,reEmptyStringTrailing=/(__e\(.*?\)|\b__t\)) \+\n'';/g,reEscapedHtml=/&(?:amp|lt|gt|quot|#39);/g,reUnescapedHtml=/[&<>"']/g,reHasEscapedHtml=RegExp(reEscapedHtml.source),reHasUnescapedHtml=RegExp(reUnescapedHtml.source),reEscape=/<%-([\s\S]+?)%>/g,reEvaluate=/<%([\s\S]+?)%>/g,reInterpolate=/<%=([\s\S]+?)%>/g,reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/,reLeadingDot=/^\./,rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reHasRegExpChar=RegExp(reRegExpChar.source),reTrim=/^\s+|\s+$/g,reTrimStart=/^\s+/,reTrimEnd=/\s+$/,reWrapComment=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,reWrapDetails=/\{\n\/\* \[wrapped with (.+)\] \*/,reSplitDetails=/,? & /,reAsciiWord=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,reEscapeChar=/\\(\\)?/g,reEsTemplate=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,reFlags=/\w*$/,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsHostCtor=/^\[object .+?Constructor\]$/,reIsOctal=/^0o[0-7]+$/i,reIsUint=/^(?:0|[1-9]\d*)$/,reLatin=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,reNoMatch=/($^)/,reUnescapedString=/['\n\r\u2028\u2029\\]/g,rsAstralRange="\\ud800-\\udfff",rsComboMarksRange="\\u0300-\\u036f\\ufe20-\\ufe23",rsComboSymbolsRange="\\u20d0-\\u20f0",rsDingbatRange="\\u2700-\\u27bf",rsLowerRange="a-z\\xdf-\\xf6\\xf8-\\xff",rsMathOpRange="\\xac\\xb1\\xd7\\xf7",rsNonCharRange="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",rsPunctuationRange="\\u2000-\\u206f",rsSpaceRange=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",rsUpperRange="A-Z\\xc0-\\xd6\\xd8-\\xde",rsVarRange="\\ufe0e\\ufe0f",rsBreakRange=rsMathOpRange+rsNonCharRange+rsPunctuationRange+rsSpaceRange,rsApos="['’]",rsAstral="["+rsAstralRange+"]",rsBreak="["+rsBreakRange+"]",rsCombo="["+rsComboMarksRange+rsComboSymbolsRange+"]",rsDigits="\\d+",rsDingbat="["+rsDingbatRange+"]",rsLower="["+rsLowerRange+"]",rsMisc="[^"+rsAstralRange+rsBreakRange+rsDigits+rsDingbatRange+rsLowerRange+rsUpperRange+"]",rsFitz="\\ud83c[\\udffb-\\udfff]",rsModifier="(?:"+rsCombo+"|"+rsFitz+")",rsNonAstral="[^"+rsAstralRange+"]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",rsUpper="["+rsUpperRange+"]",rsZWJ="\\u200d",rsLowerMisc="(?:"+rsLower+"|"+rsMisc+")",rsUpperMisc="(?:"+rsUpper+"|"+rsMisc+")",rsOptLowerContr="(?:"+rsApos+"(?:d|ll|m|re|s|t|ve))?",rsOptUpperContr="(?:"+rsApos+"(?:D|LL|M|RE|S|T|VE))?",reOptMod=rsModifier+"?",rsOptVar="["+rsVarRange+"]?",rsOptJoin="(?:"+rsZWJ+"(?:"+[rsNonAstral,rsRegional,rsSurrPair].join("|")+")"+rsOptVar+reOptMod+")*",rsSeq=rsOptVar+reOptMod+rsOptJoin,rsEmoji="(?:"+[rsDingbat,rsRegional,rsSurrPair].join("|")+")"+rsSeq,rsSymbol="(?:"+[rsNonAstral+rsCombo+"?",rsCombo,rsRegional,rsSurrPair,rsAstral].join("|")+")",reApos=RegExp(rsApos,"g"),reComboMark=RegExp(rsCombo,"g"),reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g"),reUnicodeWord=RegExp([rsUpper+"?"+rsLower+"+"+rsOptLowerContr+"(?="+[rsBreak,rsUpper,"$"].join("|")+")",rsUpperMisc+"+"+rsOptUpperContr+"(?="+[rsBreak,rsUpper+rsLowerMisc,"$"].join("|")+")",rsUpper+"?"+rsLowerMisc+"+"+rsOptLowerContr,rsUpper+"+"+rsOptUpperContr,rsDigits,rsEmoji].join("|"),"g"),reHasUnicode=RegExp("["+rsZWJ+rsAstralRange+rsComboMarksRange+rsComboSymbolsRange+rsVarRange+"]"),reHasUnicodeWord=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,contextProps=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],templateCounter=-1,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[dataViewTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[mapTag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[setTag]=cloneableTags[stringTag]=cloneableTags[symbolTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=!0,cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[weakMapTag]=!1;var deburredLetters={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"},htmlEscapes={"&":"&","<":"<",">":">",'"':""","'":"'"},htmlUnescapes={"&":"&","<":"<",">":">",""":'"',"'":"'"},stringEscapes={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},freeParseFloat=parseFloat,freeParseInt=parseInt,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,freeProcess=moduleExports&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding("util")}catch(e){}}(),nodeIsArrayBuffer=nodeUtil&&nodeUtil.isArrayBuffer,nodeIsDate=nodeUtil&&nodeUtil.isDate,nodeIsMap=nodeUtil&&nodeUtil.isMap,nodeIsRegExp=nodeUtil&&nodeUtil.isRegExp,nodeIsSet=nodeUtil&&nodeUtil.isSet,nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,asciiSize=baseProperty("length"),deburrLetter=basePropertyOf(deburredLetters),escapeHtmlChar=basePropertyOf(htmlEscapes),unescapeHtmlChar=basePropertyOf(htmlUnescapes),runInContext=function runInContext(context){function lodash(value){if(isObjectLike(value)&&!isArray(value)&&!(value instanceof LazyWrapper)){if(value instanceof LodashWrapper)return value;if(hasOwnProperty.call(value,"__wrapped__"))return wrapperClone(value)}return new LodashWrapper(value)}function baseLodash(){}function LodashWrapper(value,chainAll){this.__wrapped__=value,this.__actions__=[],this.__chain__=!!chainAll,this.__index__=0,this.__values__=undefined}function LazyWrapper(value){this.__wrapped__=value,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=MAX_ARRAY_LENGTH,this.__views__=[]}function lazyClone(){var result=new LazyWrapper(this.__wrapped__);return result.__actions__=copyArray(this.__actions__),result.__dir__=this.__dir__,result.__filtered__=this.__filtered__,result.__iteratees__=copyArray(this.__iteratees__),result.__takeCount__=this.__takeCount__,result.__views__=copyArray(this.__views__),result}function lazyReverse(){if(this.__filtered__){var result=new LazyWrapper(this);result.__dir__=-1,result.__filtered__=!0}else result=this.clone(),result.__dir__*=-1;return result}function lazyValue(){var array=this.__wrapped__.value(),dir=this.__dir__,isArr=isArray(array),isRight=0>dir,arrLength=isArr?array.length:0,view=getView(0,arrLength,this.__views__),start=view.start,end=view.end,length=end-start,index=isRight?end:start-1,iteratees=this.__iteratees__,iterLength=iteratees.length,resIndex=0,takeCount=nativeMin(length,this.__takeCount__);if(!isArr||LARGE_ARRAY_SIZE>arrLength||arrLength==length&&takeCount==length)return baseWrapperValue(array,this.__actions__);var result=[];outer:for(;length--&&takeCount>resIndex;){index+=dir;for(var iterIndex=-1,value=array[index];++iterIndexindex)return!1;var lastIndex=data.length-1;return index==lastIndex?data.pop():splice.call(data,index,1),--this.size,!0}function listCacheGet(key){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?undefined:data[index][1]}function listCacheHas(key){return assocIndexOf(this.__data__,key)>-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?(++this.size,data.push([key,value])):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index=number?number:upper),lower!==undefined&&(number=number>=lower?number:lower)),number}function baseClone(value,isDeep,isFull,customizer,key,object,stack){var result;if(customizer&&(result=object?customizer(value,key,object,stack):customizer(value)),result!==undefined)return result;if(!isObject(value))return value;var isArr=isArray(value);if(isArr){if(result=initCloneArray(value),!isDeep)return copyArray(value,result)}else{var tag=getTag(value),isFunc=tag==funcTag||tag==genTag;if(isBuffer(value))return cloneBuffer(value,isDeep);if(tag==objectTag||tag==argsTag||isFunc&&!object){if(result=initCloneObject(isFunc?{}:value),!isDeep)return copySymbols(value,baseAssign(result,value))}else{if(!cloneableTags[tag])return object?value:{};result=initCloneByTag(value,tag,baseClone,isDeep)}}stack||(stack=new Stack);var stacked=stack.get(value);if(stacked)return stacked;stack.set(value,result);var props=isArr?undefined:(isFull?getAllKeys:keys)(value);return arrayEach(props||value,function(subValue,key){props&&(key=subValue,subValue=value[key]),assignValue(result,key,baseClone(subValue,isDeep,isFull,customizer,key,value,stack))}),result}function baseConforms(source){var props=keys(source);return function(object){return baseConformsTo(object,source,props)}}function baseConformsTo(object,source,props){var length=props.length;if(null==object)return!length;for(object=Object(object);length--;){var key=props[length],predicate=source[key],value=object[key];if(value===undefined&&!(key in object)||!predicate(value))return!1}return!0}function baseDelay(func,wait,args){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return setTimeout(function(){func.apply(undefined,args)},wait)}function baseDifference(array,values,iteratee,comparator){var index=-1,includes=arrayIncludes,isCommon=!0,length=array.length,result=[],valuesLength=values.length;if(!length)return result;iteratee&&(values=arrayMap(values,baseUnary(iteratee))),comparator?(includes=arrayIncludesWith,isCommon=!1):values.length>=LARGE_ARRAY_SIZE&&(includes=cacheHas,isCommon=!1,values=new SetCache(values));outer:for(;++indexstart&&(start=-start>length?0:length+start),end=end===undefined||end>length?length:toInteger(end),0>end&&(end+=length),end=start>end?0:toLength(end);end>start;)array[start++]=value;return array}function baseFilter(collection,predicate){var result=[];return baseEach(collection,function(value,index,collection){predicate(value,index,collection)&&result.push(value)}),result}function baseFlatten(array,depth,predicate,isStrict,result){var index=-1,length=array.length;for(predicate||(predicate=isFlattenable),result||(result=[]);++index0&&predicate(value)?depth>1?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}function baseForOwn(object,iteratee){return object&&baseFor(object,iteratee,keys)}function baseForOwnRight(object,iteratee){return object&&baseForRight(object,iteratee,keys)}function baseFunctions(object,props){return arrayFilter(props,function(key){return isFunction(object[key])})}function baseGet(object,path){path=isKey(path,object)?[path]:castPath(path);for(var index=0,length=path.length;null!=object&&length>index;)object=object[toKey(path[index++])];return index&&index==length?object:undefined}function baseGetAllKeys(object,keysFunc,symbolsFunc){var result=keysFunc(object);return isArray(object)?result:arrayPush(result,symbolsFunc(object))}function baseGetTag(value){return objectToString.call(value)}function baseGt(value,other){return value>other}function baseHas(object,key){return null!=object&&hasOwnProperty.call(object,key)}function baseHasIn(object,key){return null!=object&&key in Object(object)}function baseInRange(number,start,end){return number>=nativeMin(start,end)&&number=120&&array.length>=120)?new SetCache(othIndex&&array):undefined}array=arrays[0];var index=-1,seen=caches[0];outer:for(;++indexvalue}function baseMap(collection,iteratee){var index=-1,result=isArrayLike(collection)?Array(collection.length):[];return baseEach(collection,function(value,key,collection){result[++index]=iteratee(value,key,collection)}),result}function baseMatches(source){var matchData=getMatchData(source);return 1==matchData.length&&matchData[0][2]?matchesStrictComparable(matchData[0][0],matchData[0][1]):function(object){return object===source||baseIsMatch(object,source,matchData)}}function baseMatchesProperty(path,srcValue){return isKey(path)&&isStrictComparable(srcValue)?matchesStrictComparable(toKey(path),srcValue):function(object){var objValue=get(object,path);return objValue===undefined&&objValue===srcValue?hasIn(object,path):baseIsEqual(srcValue,objValue,undefined,UNORDERED_COMPARE_FLAG|PARTIAL_COMPARE_FLAG)}}function baseMerge(object,source,srcIndex,customizer,stack){object!==source&&baseFor(source,function(srcValue,key){if(isObject(srcValue))stack||(stack=new Stack),baseMergeDeep(object,source,key,srcIndex,baseMerge,customizer,stack);else{var newValue=customizer?customizer(object[key],srcValue,key+"",object,source,stack):undefined;newValue===undefined&&(newValue=srcValue),assignMergeValue(object,key,newValue)}},keysIn)}function baseMergeDeep(object,source,key,srcIndex,mergeFunc,customizer,stack){var objValue=object[key],srcValue=source[key],stacked=stack.get(srcValue);if(stacked)return void assignMergeValue(object,key,stacked);var newValue=customizer?customizer(objValue,srcValue,key+"",object,source,stack):undefined,isCommon=newValue===undefined;if(isCommon){var isArr=isArray(srcValue),isBuff=!isArr&&isBuffer(srcValue),isTyped=!isArr&&!isBuff&&isTypedArray(srcValue);newValue=srcValue,isArr||isBuff||isTyped?isArray(objValue)?newValue=objValue:isArrayLikeObject(objValue)?newValue=copyArray(objValue):isBuff?(isCommon=!1,newValue=cloneBuffer(srcValue,!0)):isTyped?(isCommon=!1,newValue=cloneTypedArray(srcValue,!0)):newValue=[]:isPlainObject(srcValue)||isArguments(srcValue)?(newValue=objValue,isArguments(objValue)?newValue=toPlainObject(objValue):(!isObject(objValue)||srcIndex&&isFunction(objValue))&&(newValue=initCloneObject(srcValue))):isCommon=!1}isCommon&&(stack.set(srcValue,newValue),mergeFunc(newValue,srcValue,srcIndex,customizer,stack),stack["delete"](srcValue)),assignMergeValue(object,key,newValue)}function baseNth(array,n){var length=array.length;if(length)return n+=0>n?length:0,isIndex(n,length)?array[n]:undefined}function baseOrderBy(collection,iteratees,orders){var index=-1;iteratees=arrayMap(iteratees.length?iteratees:[identity],baseUnary(getIteratee()));var result=baseMap(collection,function(value,key,collection){var criteria=arrayMap(iteratees,function(iteratee){return iteratee(value)});return{criteria:criteria,index:++index,value:value}});return baseSortBy(result,function(object,other){return compareMultiple(object,other,orders)})}function basePick(object,props){return object=Object(object),basePickBy(object,props,function(value,key){return key in object})}function basePickBy(object,props,predicate){for(var index=-1,length=props.length,result={};++index-1;)seen!==array&&splice.call(seen,fromIndex,1),splice.call(array,fromIndex,1);return array}function basePullAt(array,indexes){for(var length=array?indexes.length:0,lastIndex=length-1;length--;){var index=indexes[length];if(length==lastIndex||index!==previous){var previous=index;if(isIndex(index))splice.call(array,index,1);else if(isKey(index,array))delete array[toKey(index)];else{var path=castPath(index),object=parent(array,path);null!=object&&delete object[toKey(last(path))]}}}return array}function baseRandom(lower,upper){return lower+nativeFloor(nativeRandom()*(upper-lower+1))}function baseRange(start,end,step,fromRight){for(var index=-1,length=nativeMax(nativeCeil((end-start)/(step||1)),0),result=Array(length);length--;)result[fromRight?length:++index]=start,start+=step;return result}function baseRepeat(string,n){var result="";if(!string||1>n||n>MAX_SAFE_INTEGER)return result;do n%2&&(result+=string),n=nativeFloor(n/2),n&&(string+=string);while(n);return result}function baseRest(func,start){return setToString(overRest(func,start,identity),func+"")}function baseSample(collection){return arraySample(values(collection))}function baseSampleSize(collection,n){var array=values(collection);return shuffleSelf(array,baseClamp(n,0,array.length))}function baseSet(object,path,value,customizer){if(!isObject(object))return object;path=isKey(path,object)?[path]:castPath(path);for(var index=-1,length=path.length,lastIndex=length-1,nested=object;null!=nested&&++indexstart&&(start=-start>length?0:length+start),end=end>length?length:end,0>end&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index=high){for(;high>low;){var mid=low+high>>>1,computed=array[mid];null!==computed&&!isSymbol(computed)&&(retHighest?value>=computed:value>computed)?low=mid+1:high=mid}return high}return baseSortedIndexBy(array,value,identity,retHighest)}function baseSortedIndexBy(array,value,iteratee,retHighest){value=iteratee(value);for(var low=0,high=array?array.length:0,valIsNaN=value!==value,valIsNull=null===value,valIsSymbol=isSymbol(value),valIsUndefined=value===undefined;high>low;){var mid=nativeFloor((low+high)/2),computed=iteratee(array[mid]),othIsDefined=computed!==undefined,othIsNull=null===computed,othIsReflexive=computed===computed,othIsSymbol=isSymbol(computed);if(valIsNaN)var setLow=retHighest||othIsReflexive;else setLow=valIsUndefined?othIsReflexive&&(retHighest||othIsDefined):valIsNull?othIsReflexive&&othIsDefined&&(retHighest||!othIsNull):valIsSymbol?othIsReflexive&&othIsDefined&&!othIsNull&&(retHighest||!othIsSymbol):othIsNull||othIsSymbol?!1:retHighest?value>=computed:value>computed;setLow?low=mid+1:high=mid}return nativeMin(high,MAX_ARRAY_INDEX)}function baseSortedUniq(array,iteratee){for(var index=-1,length=array.length,resIndex=0,result=[];++index=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++indexindex?values[index]:undefined;assignFunc(result,props[index],value)}return result}function castArrayLikeObject(value){return isArrayLikeObject(value)?value:[]}function castFunction(value){return"function"==typeof value?value:identity}function castPath(value){return isArray(value)?value:stringToPath(value)}function castSlice(array,start,end){var length=array.length;return end=end===undefined?length:end,!start&&end>=length?array:baseSlice(array,start,end)}function cloneBuffer(buffer,isDeep){if(isDeep)return buffer.slice();var length=buffer.length,result=allocUnsafe?allocUnsafe(length):new buffer.constructor(length);return buffer.copy(result),result}function cloneArrayBuffer(arrayBuffer){var result=new arrayBuffer.constructor(arrayBuffer.byteLength);return new Uint8Array(result).set(new Uint8Array(arrayBuffer)),result}function cloneDataView(dataView,isDeep){var buffer=isDeep?cloneArrayBuffer(dataView.buffer):dataView.buffer;return new dataView.constructor(buffer,dataView.byteOffset,dataView.byteLength)}function cloneMap(map,isDeep,cloneFunc){var array=isDeep?cloneFunc(mapToArray(map),!0):mapToArray(map);return arrayReduce(array,addMapEntry,new map.constructor)}function cloneRegExp(regexp){var result=new regexp.constructor(regexp.source,reFlags.exec(regexp));return result.lastIndex=regexp.lastIndex,result}function cloneSet(set,isDeep,cloneFunc){var array=isDeep?cloneFunc(setToArray(set),!0):setToArray(set);return arrayReduce(array,addSetEntry,new set.constructor)}function cloneSymbol(symbol){return symbolValueOf?Object(symbolValueOf.call(symbol)):{}}function cloneTypedArray(typedArray,isDeep){var buffer=isDeep?cloneArrayBuffer(typedArray.buffer):typedArray.buffer;return new typedArray.constructor(buffer,typedArray.byteOffset,typedArray.length)}function compareAscending(value,other){if(value!==other){var valIsDefined=value!==undefined,valIsNull=null===value,valIsReflexive=value===value,valIsSymbol=isSymbol(value),othIsDefined=other!==undefined,othIsNull=null===other,othIsReflexive=other===other,othIsSymbol=isSymbol(other);if(!othIsNull&&!othIsSymbol&&!valIsSymbol&&value>other||valIsSymbol&&othIsDefined&&othIsReflexive&&!othIsNull&&!othIsSymbol||valIsNull&&othIsDefined&&othIsReflexive||!valIsDefined&&othIsReflexive||!valIsReflexive)return 1;if(!valIsNull&&!valIsSymbol&&!othIsSymbol&&other>value||othIsSymbol&&valIsDefined&&valIsReflexive&&!valIsNull&&!valIsSymbol||othIsNull&&valIsDefined&&valIsReflexive||!othIsDefined&&valIsReflexive||!othIsReflexive)return-1}return 0}function compareMultiple(object,other,orders){for(var index=-1,objCriteria=object.criteria,othCriteria=other.criteria,length=objCriteria.length,ordersLength=orders.length;++index=ordersLength)return result;var order=orders[index];return result*("desc"==order?-1:1)}}return object.index-other.index}function composeArgs(args,partials,holders,isCurried){for(var argsIndex=-1,argsLength=args.length,holdersLength=holders.length,leftIndex=-1,leftLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(leftLength+rangeLength),isUncurried=!isCurried;++leftIndexargsIndex)&&(result[holders[argsIndex]]=args[argsIndex]);for(;rangeLength--;)result[leftIndex++]=args[argsIndex++];return result}function composeArgsRight(args,partials,holders,isCurried){for(var argsIndex=-1,argsLength=args.length,holdersIndex=-1,holdersLength=holders.length,rightIndex=-1,rightLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(rangeLength+rightLength),isUncurried=!isCurried;++argsIndexargsIndex)&&(result[offset+holders[holdersIndex]]=args[argsIndex++]);return result}function copyArray(source,array){var index=-1,length=source.length;for(array||(array=Array(length));++index1?sources[length-1]:undefined,guard=length>2?sources[2]:undefined;for(customizer=assigner.length>3&&"function"==typeof customizer?(length--,customizer):undefined,guard&&isIterateeCall(sources[0],sources[1],guard)&&(customizer=3>length?undefined:customizer,length=1),object=Object(object);++indexlength&&args[0]!==placeholder&&args[length-1]!==placeholder?[]:replaceHolders(args,placeholder);if(length-=holders.length,arity>length)return createRecurry(func,bitmask,createHybrid,wrapper.placeholder,undefined,args,holders,undefined,undefined,arity-length);var fn=this&&this!==root&&this instanceof wrapper?Ctor:func;return apply(fn,this,args)}var Ctor=createCtor(func);return wrapper}function createFind(findIndexFunc){return function(collection,predicate,fromIndex){var iterable=Object(collection);if(!isArrayLike(collection)){var iteratee=getIteratee(predicate,3);collection=keys(collection),predicate=function(key){return iteratee(iterable[key],key,iterable)}}var index=findIndexFunc(collection,predicate,fromIndex);return index>-1?iterable[iteratee?collection[index]:index]:undefined}}function createFlow(fromRight){return flatRest(function(funcs){var length=funcs.length,index=length,prereq=LodashWrapper.prototype.thru;for(fromRight&&funcs.reverse();index--;){var func=funcs[index];if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);if(prereq&&!wrapper&&"wrapper"==getFuncName(func))var wrapper=new LodashWrapper([],!0)}for(index=wrapper?index:length;++index=LARGE_ARRAY_SIZE)return wrapper.plant(value).value();for(var index=0,result=length?funcs[index].apply(this,args):value;++indexlength){var newHolders=replaceHolders(args,placeholder);return createRecurry(func,bitmask,createHybrid,wrapper.placeholder,thisArg,args,newHolders,argPos,ary,arity-length)}var thisBinding=isBind?thisArg:this,fn=isBindKey?thisBinding[func]:func;return length=args.length,argPos?args=reorder(args,argPos):isFlip&&length>1&&args.reverse(),isAry&&length>ary&&(args.length=ary),this&&this!==root&&this instanceof wrapper&&(fn=Ctor||createCtor(fn)),fn.apply(thisBinding,args)}var isAry=bitmask&ARY_FLAG,isBind=bitmask&BIND_FLAG,isBindKey=bitmask&BIND_KEY_FLAG,isCurried=bitmask&(CURRY_FLAG|CURRY_RIGHT_FLAG),isFlip=bitmask&FLIP_FLAG,Ctor=isBindKey?undefined:createCtor(func);return wrapper}function createInverter(setter,toIteratee){return function(object,iteratee){return baseInverter(object,setter,toIteratee(iteratee),{})}}function createMathOperation(operator,defaultValue){return function(value,other){var result;if(value===undefined&&other===undefined)return defaultValue;if(value!==undefined&&(result=value),other!==undefined){if(result===undefined)return other;"string"==typeof value||"string"==typeof other?(value=baseToString(value),other=baseToString(other)):(value=baseToNumber(value),other=baseToNumber(other)),result=operator(value,other)}return result}}function createOver(arrayFunc){return flatRest(function(iteratees){return iteratees=arrayMap(iteratees,baseUnary(getIteratee())),baseRest(function(args){var thisArg=this;return arrayFunc(iteratees,function(iteratee){return apply(iteratee,thisArg,args)})})})}function createPadding(length,chars){chars=chars===undefined?" ":baseToString(chars);var charsLength=chars.length;if(2>charsLength)return charsLength?baseRepeat(chars,length):chars;var result=baseRepeat(chars,nativeCeil(length/stringSize(chars)));return hasUnicode(chars)?castSlice(stringToArray(result),0,length).join(""):result.slice(0,length)}function createPartial(func,bitmask,thisArg,partials){function wrapper(){for(var argsIndex=-1,argsLength=arguments.length,leftIndex=-1,leftLength=partials.length,args=Array(leftLength+argsLength),fn=this&&this!==root&&this instanceof wrapper?Ctor:func;++leftIndexstart?1:-1:toFinite(step),baseRange(start,end,step,fromRight)}}function createRelationalOperation(operator){return function(value,other){return("string"!=typeof value||"string"!=typeof other)&&(value=toNumber(value),other=toNumber(other)),operator(value,other)}}function createRecurry(func,bitmask,wrapFunc,placeholder,thisArg,partials,holders,argPos,ary,arity){var isCurry=bitmask&CURRY_FLAG,newHolders=isCurry?holders:undefined,newHoldersRight=isCurry?undefined:holders,newPartials=isCurry?partials:undefined,newPartialsRight=isCurry?undefined:partials;bitmask|=isCurry?PARTIAL_FLAG:PARTIAL_RIGHT_FLAG,bitmask&=~(isCurry?PARTIAL_RIGHT_FLAG:PARTIAL_FLAG),bitmask&CURRY_BOUND_FLAG||(bitmask&=~(BIND_FLAG|BIND_KEY_FLAG));var newData=[func,bitmask,thisArg,newPartials,newHolders,newPartialsRight,newHoldersRight,argPos,ary,arity],result=wrapFunc.apply(undefined,newData);return isLaziable(func)&&setData(result,newData),result.placeholder=placeholder,setWrapToString(result,func,bitmask)}function createRound(methodName){var func=Math[methodName];return function(number,precision){if(number=toNumber(number),precision=nativeMin(toInteger(precision),292)){var pair=(toString(number)+"e").split("e"),value=func(pair[0]+"e"+(+pair[1]+precision));return pair=(toString(value)+"e").split("e"),+(pair[0]+"e"+(+pair[1]-precision))}return func(number)}}function createToPairs(keysFunc){return function(object){var tag=getTag(object);return tag==mapTag?mapToArray(object):tag==setTag?setToPairs(object):baseToPairs(object,keysFunc(object))}}function createWrap(func,bitmask,thisArg,partials,holders,argPos,ary,arity){var isBindKey=bitmask&BIND_KEY_FLAG;if(!isBindKey&&"function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);var length=partials?partials.length:0;if(length||(bitmask&=~(PARTIAL_FLAG|PARTIAL_RIGHT_FLAG),partials=holders=undefined),ary=ary===undefined?ary:nativeMax(toInteger(ary),0),arity=arity===undefined?arity:toInteger(arity),length-=holders?holders.length:0,bitmask&PARTIAL_RIGHT_FLAG){var partialsRight=partials,holdersRight=holders;partials=holders=undefined}var data=isBindKey?undefined:getData(func),newData=[func,bitmask,thisArg,partials,holders,partialsRight,holdersRight,argPos,ary,arity];if(data&&mergeData(newData,data),func=newData[0],bitmask=newData[1],thisArg=newData[2],partials=newData[3],holders=newData[4],arity=newData[9]=null==newData[9]?isBindKey?0:func.length:nativeMax(newData[9]-length,0),!arity&&bitmask&(CURRY_FLAG|CURRY_RIGHT_FLAG)&&(bitmask&=~(CURRY_FLAG|CURRY_RIGHT_FLAG)),bitmask&&bitmask!=BIND_FLAG)result=bitmask==CURRY_FLAG||bitmask==CURRY_RIGHT_FLAG?createCurry(func,bitmask,arity):bitmask!=PARTIAL_FLAG&&bitmask!=(BIND_FLAG|PARTIAL_FLAG)||holders.length?createHybrid.apply(undefined,newData):createPartial(func,bitmask,thisArg,partials);else var result=createBind(func,bitmask,thisArg);var setter=data?baseSetData:setData;return setWrapToString(setter(result,newData),func,bitmask)}function equalArrays(array,other,equalFunc,customizer,bitmask,stack){var isPartial=bitmask&PARTIAL_COMPARE_FLAG,arrLength=array.length,othLength=other.length;if(arrLength!=othLength&&!(isPartial&&othLength>arrLength))return!1;var stacked=stack.get(array);if(stacked&&stack.get(other))return stacked==other;var index=-1,result=!0,seen=bitmask&UNORDERED_COMPARE_FLAG?new SetCache:undefined;for(stack.set(array,other),stack.set(other,array);++index1?"& ":"")+details[lastIndex],details=details.join(length>2?", ":" "),source.replace(reWrapComment,"{\n/* [wrapped with "+details+"] */\n")}function isFlattenable(value){return isArray(value)||isArguments(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol])}function isIndex(value,length){return length=null==length?MAX_SAFE_INTEGER:length,!!length&&("number"==typeof value||reIsUint.test(value))&&value>-1&&value%1==0&&length>value}function isIterateeCall(value,index,object){if(!isObject(object))return!1;var type=typeof index;return("number"==type?isArrayLike(object)&&isIndex(index,object.length):"string"==type&&index in object)?eq(object[index],value):!1}function isKey(value,object){if(isArray(value))return!1;var type=typeof value;return"number"==type||"symbol"==type||"boolean"==type||null==value||isSymbol(value)?!0:reIsPlainProp.test(value)||!reIsDeepProp.test(value)||null!=object&&value in Object(object)}function isKeyable(value){var type=typeof value;return"string"==type||"number"==type||"symbol"==type||"boolean"==type?"__proto__"!==value:null===value}function isLaziable(func){var funcName=getFuncName(func),other=lodash[funcName];if("function"!=typeof other||!(funcName in LazyWrapper.prototype))return!1;if(func===other)return!0;var data=getData(other);return!!data&&func===data[0]}function isMasked(func){return!!maskSrcKey&&maskSrcKey in func}function isPrototype(value){var Ctor=value&&value.constructor,proto="function"==typeof Ctor&&Ctor.prototype||objectProto;return value===proto}function isStrictComparable(value){return value===value&&!isObject(value)}function matchesStrictComparable(key,srcValue){return function(object){return null==object?!1:object[key]===srcValue&&(srcValue!==undefined||key in Object(object))}}function memoizeCapped(func){var result=memoize(func,function(key){return cache.size===MAX_MEMOIZE_SIZE&&cache.clear(),key}),cache=result.cache;return result}function mergeData(data,source){var bitmask=data[1],srcBitmask=source[1],newBitmask=bitmask|srcBitmask,isCommon=(BIND_FLAG|BIND_KEY_FLAG|ARY_FLAG)>newBitmask,isCombo=srcBitmask==ARY_FLAG&&bitmask==CURRY_FLAG||srcBitmask==ARY_FLAG&&bitmask==REARG_FLAG&&data[7].length<=source[8]||srcBitmask==(ARY_FLAG|REARG_FLAG)&&source[7].length<=source[8]&&bitmask==CURRY_FLAG;if(!isCommon&&!isCombo)return data;srcBitmask&BIND_FLAG&&(data[2]=source[2],newBitmask|=bitmask&BIND_FLAG?0:CURRY_BOUND_FLAG);var value=source[3];if(value){var partials=data[3];data[3]=partials?composeArgs(partials,value,source[4]):value,data[4]=partials?replaceHolders(data[3],PLACEHOLDER):source[4]}return value=source[5],value&&(partials=data[5],data[5]=partials?composeArgsRight(partials,value,source[6]):value,data[6]=partials?replaceHolders(data[5],PLACEHOLDER):source[6]),value=source[7],value&&(data[7]=value),srcBitmask&ARY_FLAG&&(data[8]=null==data[8]?source[8]:nativeMin(data[8],source[8])),null==data[9]&&(data[9]=source[9]),data[0]=source[0],data[1]=newBitmask,data}function mergeDefaults(objValue,srcValue,key,object,source,stack){return isObject(objValue)&&isObject(srcValue)&&(stack.set(srcValue,objValue),baseMerge(objValue,srcValue,undefined,mergeDefaults,stack),stack["delete"](srcValue)),objValue}function nativeKeysIn(object){var result=[];if(null!=object)for(var key in Object(object))result.push(key);return result}function overRest(func,start,transform){return start=nativeMax(start===undefined?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index0){if(++count>=HOT_COUNT)return arguments[0]}else count=0;return func.apply(undefined,arguments)}}function shuffleSelf(array,size){var index=-1,length=array.length,lastIndex=length-1;for(size=size===undefined?length:size;++indexsize)return[];for(var index=0,resIndex=0,result=Array(nativeCeil(length/size));length>index;)result[resIndex++]=baseSlice(array,index,index+=size);return result}function compact(array){for(var index=-1,length=array?array.length:0,resIndex=0,result=[];++indexn?0:n,length)):[]}function dropRight(array,n,guard){var length=array?array.length:0;return length?(n=guard||n===undefined?1:toInteger(n),n=length-n,baseSlice(array,0,0>n?0:n)):[]}function dropRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!0,!0):[]}function dropWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!0):[]}function fill(array,value,start,end){var length=array?array.length:0;return length?(start&&"number"!=typeof start&&isIterateeCall(array,value,start)&&(start=0,end=length),baseFill(array,value,start,end)):[]}function findIndex(array,predicate,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=null==fromIndex?0:toInteger(fromIndex);return 0>index&&(index=nativeMax(length+index,0)),baseFindIndex(array,getIteratee(predicate,3),index)}function findLastIndex(array,predicate,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=length-1;return fromIndex!==undefined&&(index=toInteger(fromIndex),index=0>fromIndex?nativeMax(length+index,0):nativeMin(index,length-1)),baseFindIndex(array,getIteratee(predicate,3),index,!0)}function flatten(array){var length=array?array.length:0;return length?baseFlatten(array,1):[]}function flattenDeep(array){var length=array?array.length:0;return length?baseFlatten(array,INFINITY):[]}function flattenDepth(array,depth){var length=array?array.length:0;return length?(depth=depth===undefined?1:toInteger(depth),baseFlatten(array,depth)):[]}function fromPairs(pairs){for(var index=-1,length=pairs?pairs.length:0,result={};++indexindex&&(index=nativeMax(length+index,0)),baseIndexOf(array,value,index)}function initial(array){var length=array?array.length:0;return length?baseSlice(array,0,-1):[]}function join(array,separator){return array?nativeJoin.call(array,separator):""}function last(array){var length=array?array.length:0;return length?array[length-1]:undefined}function lastIndexOf(array,value,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=length;return fromIndex!==undefined&&(index=toInteger(fromIndex),index=0>index?nativeMax(length+index,0):nativeMin(index,length-1)),value===value?strictLastIndexOf(array,value,index):baseFindIndex(array,baseIsNaN,index,!0)}function nth(array,n){return array&&array.length?baseNth(array,toInteger(n)):undefined}function pullAll(array,values){return array&&array.length&&values&&values.length?basePullAll(array,values):array}function pullAllBy(array,values,iteratee){return array&&array.length&&values&&values.length?basePullAll(array,values,getIteratee(iteratee,2)):array}function pullAllWith(array,values,comparator){return array&&array.length&&values&&values.length?basePullAll(array,values,undefined,comparator):array}function remove(array,predicate){var result=[];if(!array||!array.length)return result;var index=-1,indexes=[],length=array.length;for(predicate=getIteratee(predicate,3);++indexindex&&eq(array[index],value))return index}return-1}function sortedLastIndex(array,value){return baseSortedIndex(array,value,!0)}function sortedLastIndexBy(array,value,iteratee){return baseSortedIndexBy(array,value,getIteratee(iteratee,2),!0)}function sortedLastIndexOf(array,value){var length=array?array.length:0;if(length){var index=baseSortedIndex(array,value,!0)-1;if(eq(array[index],value))return index}return-1}function sortedUniq(array){return array&&array.length?baseSortedUniq(array):[]}function sortedUniqBy(array,iteratee){return array&&array.length?baseSortedUniq(array,getIteratee(iteratee,2)):[]}function tail(array){var length=array?array.length:0;return length?baseSlice(array,1,length):[]}function take(array,n,guard){return array&&array.length?(n=guard||n===undefined?1:toInteger(n),baseSlice(array,0,0>n?0:n)):[]}function takeRight(array,n,guard){var length=array?array.length:0;return length?(n=guard||n===undefined?1:toInteger(n),n=length-n,baseSlice(array,0>n?0:n,length)):[]}function takeRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!1,!0):[]}function takeWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3)):[]}function uniq(array){return array&&array.length?baseUniq(array):[]}function uniqBy(array,iteratee){return array&&array.length?baseUniq(array,getIteratee(iteratee,2)):[]}function uniqWith(array,comparator){return array&&array.length?baseUniq(array,undefined,comparator):[]}function unzip(array){if(!array||!array.length)return[];var length=0;return array=arrayFilter(array,function(group){return isArrayLikeObject(group)?(length=nativeMax(group.length,length),!0):void 0}),baseTimes(length,function(index){return arrayMap(array,baseProperty(index))})}function unzipWith(array,iteratee){if(!array||!array.length)return[];var result=unzip(array);return null==iteratee?result:arrayMap(result,function(group){return apply(iteratee,undefined,group)})}function zipObject(props,values){return baseZipObject(props||[],values||[],assignValue)}function zipObjectDeep(props,values){return baseZipObject(props||[],values||[],baseSet)}function chain(value){var result=lodash(value);return result.__chain__=!0,result}function tap(value,interceptor){return interceptor(value),value}function thru(value,interceptor){return interceptor(value)}function wrapperChain(){return chain(this)}function wrapperCommit(){return new LodashWrapper(this.value(),this.__chain__)}function wrapperNext(){this.__values__===undefined&&(this.__values__=toArray(this.value()));var done=this.__index__>=this.__values__.length,value=done?undefined:this.__values__[this.__index__++];return{done:done,value:value}}function wrapperToIterator(){return this}function wrapperPlant(value){for(var result,parent=this;parent instanceof baseLodash;){var clone=wrapperClone(parent);clone.__index__=0,clone.__values__=undefined,result?previous.__wrapped__=clone:result=clone;var previous=clone;parent=parent.__wrapped__}return previous.__wrapped__=value,result}function wrapperReverse(){var value=this.__wrapped__;if(value instanceof LazyWrapper){var wrapped=value;return this.__actions__.length&&(wrapped=new LazyWrapper(this)),wrapped=wrapped.reverse(),wrapped.__actions__.push({func:thru,args:[reverse],thisArg:undefined}),new LodashWrapper(wrapped,this.__chain__)}return this.thru(reverse)}function wrapperValue(){return baseWrapperValue(this.__wrapped__,this.__actions__)}function every(collection,predicate,guard){var func=isArray(collection)?arrayEvery:baseEvery;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=undefined),func(collection,getIteratee(predicate,3))}function filter(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,getIteratee(predicate,3))}function flatMap(collection,iteratee){return baseFlatten(map(collection,iteratee),1)}function flatMapDeep(collection,iteratee){return baseFlatten(map(collection,iteratee),INFINITY)}function flatMapDepth(collection,iteratee,depth){return depth=depth===undefined?1:toInteger(depth),baseFlatten(map(collection,iteratee),depth)}function forEach(collection,iteratee){var func=isArray(collection)?arrayEach:baseEach;return func(collection,getIteratee(iteratee,3))}function forEachRight(collection,iteratee){var func=isArray(collection)?arrayEachRight:baseEachRight;return func(collection,getIteratee(iteratee,3))}function includes(collection,value,fromIndex,guard){collection=isArrayLike(collection)?collection:values(collection),fromIndex=fromIndex&&!guard?toInteger(fromIndex):0;var length=collection.length;return 0>fromIndex&&(fromIndex=nativeMax(length+fromIndex,0)),isString(collection)?length>=fromIndex&&collection.indexOf(value,fromIndex)>-1:!!length&&baseIndexOf(collection,value,fromIndex)>-1}function map(collection,iteratee){var func=isArray(collection)?arrayMap:baseMap;return func(collection,getIteratee(iteratee,3))}function orderBy(collection,iteratees,orders,guard){return null==collection?[]:(isArray(iteratees)||(iteratees=null==iteratees?[]:[iteratees]),orders=guard?undefined:orders,isArray(orders)||(orders=null==orders?[]:[orders]),baseOrderBy(collection,iteratees,orders))}function reduce(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduce:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEach)}function reduceRight(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduceRight:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEachRight)}function reject(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,negate(getIteratee(predicate,3)))}function sample(collection){var func=isArray(collection)?arraySample:baseSample;return func(collection)}function sampleSize(collection,n,guard){n=(guard?isIterateeCall(collection,n,guard):n===undefined)?1:toInteger(n);var func=isArray(collection)?arraySampleSize:baseSampleSize;return func(collection,n)}function shuffle(collection){var func=isArray(collection)?arrayShuffle:baseShuffle;return func(collection)}function size(collection){if(null==collection)return 0;if(isArrayLike(collection))return isString(collection)?stringSize(collection):collection.length;var tag=getTag(collection);return tag==mapTag||tag==setTag?collection.size:baseKeys(collection).length}function some(collection,predicate,guard){var func=isArray(collection)?arraySome:baseSome;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=undefined),func(collection,getIteratee(predicate,3))}function after(n,func){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return n=toInteger(n),function(){return--n<1?func.apply(this,arguments):void 0}}function ary(func,n,guard){return n=guard?undefined:n,n=func&&null==n?func.length:n,createWrap(func,ARY_FLAG,undefined,undefined,undefined,undefined,n)}function before(n,func){var result;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return n=toInteger(n),function(){return--n>0&&(result=func.apply(this,arguments)),1>=n&&(func=undefined),result}}function curry(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,CURRY_FLAG,undefined,undefined,undefined,undefined,undefined,arity);return result.placeholder=curry.placeholder,result}function curryRight(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,CURRY_RIGHT_FLAG,undefined,undefined,undefined,undefined,undefined,arity);return result.placeholder=curryRight.placeholder,result}function debounce(func,wait,options){function invokeFunc(time){var args=lastArgs,thisArg=lastThis;return lastArgs=lastThis=undefined,lastInvokeTime=time,result=func.apply(thisArg,args)}function leadingEdge(time){return lastInvokeTime=time,timerId=setTimeout(timerExpired,wait),leading?invokeFunc(time):result}function remainingWait(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime,result=wait-timeSinceLastCall;return maxing?nativeMin(result,maxWait-timeSinceLastInvoke):result}function shouldInvoke(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime;return lastCallTime===undefined||timeSinceLastCall>=wait||0>timeSinceLastCall||maxing&&timeSinceLastInvoke>=maxWait}function timerExpired(){var time=now();return shouldInvoke(time)?trailingEdge(time):void(timerId=setTimeout(timerExpired,remainingWait(time)))}function trailingEdge(time){return timerId=undefined,trailing&&lastArgs?invokeFunc(time):(lastArgs=lastThis=undefined,result)}function cancel(){timerId!==undefined&&clearTimeout(timerId),lastInvokeTime=0,lastArgs=lastCallTime=lastThis=timerId=undefined}function flush(){return timerId===undefined?result:trailingEdge(now())}function debounced(){var time=now(),isInvoking=shouldInvoke(time);if(lastArgs=arguments,lastThis=this,lastCallTime=time,isInvoking){if(timerId===undefined)return leadingEdge(lastCallTime);if(maxing)return timerId=setTimeout(timerExpired,wait),invokeFunc(lastCallTime)}return timerId===undefined&&(timerId=setTimeout(timerExpired,wait)),result}var lastArgs,lastThis,maxWait,result,timerId,lastCallTime,lastInvokeTime=0,leading=!1,maxing=!1,trailing=!0;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return wait=toNumber(wait)||0,isObject(options)&&(leading=!!options.leading,maxing="maxWait"in options,maxWait=maxing?nativeMax(toNumber(options.maxWait)||0,wait):maxWait,trailing="trailing"in options?!!options.trailing:trailing),debounced.cancel=cancel,debounced.flush=flush,debounced}function flip(func){return createWrap(func,FLIP_FLAG)}function memoize(func,resolver){if("function"!=typeof func||resolver&&"function"!=typeof resolver)throw new TypeError(FUNC_ERROR_TEXT);var memoized=function(){var args=arguments,key=resolver?resolver.apply(this,args):args[0],cache=memoized.cache;if(cache.has(key))return cache.get(key);var result=func.apply(this,args);return memoized.cache=cache.set(key,result)||cache,result};return memoized.cache=new(memoize.Cache||MapCache),memoized}function negate(predicate){if("function"!=typeof predicate)throw new TypeError(FUNC_ERROR_TEXT);return function(){var args=arguments;switch(args.length){case 0:return!predicate.call(this);case 1:return!predicate.call(this,args[0]);case 2:return!predicate.call(this,args[0],args[1]);case 3:return!predicate.call(this,args[0],args[1],args[2])}return!predicate.apply(this,args)}}function once(func){return before(2,func)}function rest(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=start===undefined?start:toInteger(start),baseRest(func,start)}function spread(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=start===undefined?0:nativeMax(toInteger(start),0),baseRest(function(args){var array=args[start],otherArgs=castSlice(args,0,start);return array&&arrayPush(otherArgs,array),apply(func,this,otherArgs)})}function throttle(func,wait,options){var leading=!0,trailing=!0;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return isObject(options)&&(leading="leading"in options?!!options.leading:leading,trailing="trailing"in options?!!options.trailing:trailing),debounce(func,wait,{leading:leading,maxWait:wait,trailing:trailing})}function unary(func){return ary(func,1)}function wrap(value,wrapper){return wrapper=null==wrapper?identity:wrapper,partial(wrapper,value)}function castArray(){if(!arguments.length)return[];var value=arguments[0];return isArray(value)?value:[value]}function clone(value){return baseClone(value,!1,!0)}function cloneWith(value,customizer){return baseClone(value,!1,!0,customizer)}function cloneDeep(value){return baseClone(value,!0,!0)}function cloneDeepWith(value,customizer){return baseClone(value,!0,!0,customizer)}function conformsTo(object,source){return null==source||baseConformsTo(object,source,keys(source))}function eq(value,other){return value===other||value!==value&&other!==other}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value)}function isBoolean(value){return value===!0||value===!1||isObjectLike(value)&&objectToString.call(value)==boolTag}function isElement(value){return null!=value&&1===value.nodeType&&isObjectLike(value)&&!isPlainObject(value)}function isEmpty(value){if(isArrayLike(value)&&(isArray(value)||"string"==typeof value||"function"==typeof value.splice||isBuffer(value)||isTypedArray(value)||isArguments(value)))return!value.length;var tag=getTag(value);if(tag==mapTag||tag==setTag)return!value.size;if(isPrototype(value))return!baseKeys(value).length;for(var key in value)if(hasOwnProperty.call(value,key))return!1;return!0}function isEqual(value,other){return baseIsEqual(value,other)}function isEqualWith(value,other,customizer){customizer="function"==typeof customizer?customizer:undefined;var result=customizer?customizer(value,other):undefined;return result===undefined?baseIsEqual(value,other,customizer):!!result}function isError(value){return isObjectLike(value)?objectToString.call(value)==errorTag||"string"==typeof value.message&&"string"==typeof value.name:!1}function isFinite(value){return"number"==typeof value&&nativeIsFinite(value)}function isFunction(value){var tag=isObject(value)?objectToString.call(value):"";return tag==funcTag||tag==genTag||tag==proxyTag}function isInteger(value){return"number"==typeof value&&value==toInteger(value)}function isLength(value){return"number"==typeof value&&value>-1&&value%1==0&&MAX_SAFE_INTEGER>=value}function isObject(value){var type=typeof value;return null!=value&&("object"==type||"function"==type)}function isObjectLike(value){return null!=value&&"object"==typeof value}function isMatch(object,source){return object===source||baseIsMatch(object,source,getMatchData(source))}function isMatchWith(object,source,customizer){return customizer="function"==typeof customizer?customizer:undefined,baseIsMatch(object,source,getMatchData(source),customizer)}function isNaN(value){return isNumber(value)&&value!=+value}function isNative(value){if(isMaskable(value))throw new Error(CORE_ERROR_TEXT);return baseIsNative(value)}function isNull(value){return null===value}function isNil(value){return null==value}function isNumber(value){return"number"==typeof value||isObjectLike(value)&&objectToString.call(value)==numberTag}function isPlainObject(value){if(!isObjectLike(value)||objectToString.call(value)!=objectTag)return!1;var proto=getPrototype(value);if(null===proto)return!0;var Ctor=hasOwnProperty.call(proto,"constructor")&&proto.constructor;return"function"==typeof Ctor&&Ctor instanceof Ctor&&funcToString.call(Ctor)==objectCtorString}function isSafeInteger(value){return isInteger(value)&&value>=-MAX_SAFE_INTEGER&&MAX_SAFE_INTEGER>=value}function isString(value){return"string"==typeof value||!isArray(value)&&isObjectLike(value)&&objectToString.call(value)==stringTag}function isSymbol(value){return"symbol"==typeof value||isObjectLike(value)&&objectToString.call(value)==symbolTag}function isUndefined(value){return value===undefined}function isWeakMap(value){return isObjectLike(value)&&getTag(value)==weakMapTag}function isWeakSet(value){return isObjectLike(value)&&objectToString.call(value)==weakSetTag}function toArray(value){if(!value)return[];if(isArrayLike(value))return isString(value)?stringToArray(value):copyArray(value);if(iteratorSymbol&&value[iteratorSymbol])return iteratorToArray(value[iteratorSymbol]());var tag=getTag(value),func=tag==mapTag?mapToArray:tag==setTag?setToArray:values;return func(value)}function toFinite(value){if(!value)return 0===value?value:0;if(value=toNumber(value),value===INFINITY||value===-INFINITY){var sign=0>value?-1:1;return sign*MAX_INTEGER}return value===value?value:0}function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0}function toLength(value){return value?baseClamp(toInteger(value),0,MAX_ARRAY_LENGTH):0}function toNumber(value){if("number"==typeof value)return value;if(isSymbol(value))return NAN;if(isObject(value)){var other="function"==typeof value.valueOf?value.valueOf():value;value=isObject(other)?other+"":other}if("string"!=typeof value)return 0===value?value:+value;value=value.replace(reTrim,"");var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value}function toPlainObject(value){return copyObject(value,keysIn(value))}function toSafeInteger(value){return baseClamp(toInteger(value),-MAX_SAFE_INTEGER,MAX_SAFE_INTEGER)}function toString(value){return null==value?"":baseToString(value)}function create(prototype,properties){var result=baseCreate(prototype);return properties?baseAssign(result,properties):result}function findKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwn)}function findLastKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwnRight)}function forIn(object,iteratee){return null==object?object:baseFor(object,getIteratee(iteratee,3),keysIn)}function forInRight(object,iteratee){return null==object?object:baseForRight(object,getIteratee(iteratee,3),keysIn)}function forOwn(object,iteratee){return object&&baseForOwn(object,getIteratee(iteratee,3))}function forOwnRight(object,iteratee){return object&&baseForOwnRight(object,getIteratee(iteratee,3))}function functions(object){return null==object?[]:baseFunctions(object,keys(object))}function functionsIn(object){return null==object?[]:baseFunctions(object,keysIn(object))}function get(object,path,defaultValue){var result=null==object?undefined:baseGet(object,path);return result===undefined?defaultValue:result}function has(object,path){return null!=object&&hasPath(object,path,baseHas)}function hasIn(object,path){return null!=object&&hasPath(object,path,baseHasIn)}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function keysIn(object){return isArrayLike(object)?arrayLikeKeys(object,!0):baseKeysIn(object)}function mapKeys(object,iteratee){var result={};return iteratee=getIteratee(iteratee,3), +baseForOwn(object,function(value,key,object){baseAssignValue(result,iteratee(value,key,object),value)}),result}function mapValues(object,iteratee){var result={};return iteratee=getIteratee(iteratee,3),baseForOwn(object,function(value,key,object){baseAssignValue(result,key,iteratee(value,key,object))}),result}function omitBy(object,predicate){return pickBy(object,negate(getIteratee(predicate)))}function pickBy(object,predicate){return null==object?{}:basePickBy(object,getAllKeysIn(object),getIteratee(predicate))}function result(object,path,defaultValue){path=isKey(path,object)?[path]:castPath(path);var index=-1,length=path.length;for(length||(object=undefined,length=1);++indexupper){var temp=lower;lower=upper,upper=temp}if(floating||lower%1||upper%1){var rand=nativeRandom();return nativeMin(lower+rand*(upper-lower+freeParseFloat("1e-"+((rand+"").length-1))),upper)}return baseRandom(lower,upper)}function capitalize(string){return upperFirst(toString(string).toLowerCase())}function deburr(string){return string=toString(string),string&&string.replace(reLatin,deburrLetter).replace(reComboMark,"")}function endsWith(string,target,position){string=toString(string),target=baseToString(target);var length=string.length;position=position===undefined?length:baseClamp(toInteger(position),0,length);var end=position;return position-=target.length,position>=0&&string.slice(position,end)==target}function escape(string){return string=toString(string),string&&reHasUnescapedHtml.test(string)?string.replace(reUnescapedHtml,escapeHtmlChar):string}function escapeRegExp(string){return string=toString(string),string&&reHasRegExpChar.test(string)?string.replace(reRegExpChar,"\\$&"):string}function pad(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;if(!length||strLength>=length)return string;var mid=(length-strLength)/2;return createPadding(nativeFloor(mid),chars)+string+createPadding(nativeCeil(mid),chars)}function padEnd(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;return length&&length>strLength?string+createPadding(length-strLength,chars):string}function padStart(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;return length&&length>strLength?createPadding(length-strLength,chars)+string:string}function parseInt(string,radix,guard){return guard||null==radix?radix=0:radix&&(radix=+radix),nativeParseInt(toString(string).replace(reTrimStart,""),radix||0)}function repeat(string,n,guard){return n=(guard?isIterateeCall(string,n,guard):n===undefined)?1:toInteger(n),baseRepeat(toString(string),n)}function replace(){var args=arguments,string=toString(args[0]);return args.length<3?string:string.replace(args[1],args[2])}function split(string,separator,limit){return limit&&"number"!=typeof limit&&isIterateeCall(string,separator,limit)&&(separator=limit=undefined),(limit=limit===undefined?MAX_ARRAY_LENGTH:limit>>>0)?(string=toString(string),string&&("string"==typeof separator||null!=separator&&!isRegExp(separator))&&(separator=baseToString(separator),!separator&&hasUnicode(string))?castSlice(stringToArray(string),0,limit):string.split(separator,limit)):[]}function startsWith(string,target,position){return string=toString(string),position=baseClamp(toInteger(position),0,string.length),target=baseToString(target),string.slice(position,position+target.length)==target}function template(string,options,guard){var settings=lodash.templateSettings;guard&&isIterateeCall(string,options,guard)&&(options=undefined),string=toString(string),options=assignInWith({},options,settings,assignInDefaults);var isEscaping,isEvaluating,imports=assignInWith({},options.imports,settings.imports,assignInDefaults),importsKeys=keys(imports),importsValues=baseValues(imports,importsKeys),index=0,interpolate=options.interpolate||reNoMatch,source="__p += '",reDelimiters=RegExp((options.escape||reNoMatch).source+"|"+interpolate.source+"|"+(interpolate===reInterpolate?reEsTemplate:reNoMatch).source+"|"+(options.evaluate||reNoMatch).source+"|$","g"),sourceURL="//# sourceURL="+("sourceURL"in options?options.sourceURL:"lodash.templateSources["+ ++templateCounter+"]")+"\n";string.replace(reDelimiters,function(match,escapeValue,interpolateValue,esTemplateValue,evaluateValue,offset){return interpolateValue||(interpolateValue=esTemplateValue),source+=string.slice(index,offset).replace(reUnescapedString,escapeStringChar),escapeValue&&(isEscaping=!0,source+="' +\n__e("+escapeValue+") +\n'"),evaluateValue&&(isEvaluating=!0,source+="';\n"+evaluateValue+";\n__p += '"),interpolateValue&&(source+="' +\n((__t = ("+interpolateValue+")) == null ? '' : __t) +\n'"),index=offset+match.length,match}),source+="';\n";var variable=options.variable;variable||(source="with (obj) {\n"+source+"\n}\n"),source=(isEvaluating?source.replace(reEmptyStringLeading,""):source).replace(reEmptyStringMiddle,"$1").replace(reEmptyStringTrailing,"$1;"),source="function("+(variable||"obj")+") {\n"+(variable?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(isEscaping?", __e = _.escape":"")+(isEvaluating?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+source+"return __p\n}";var result=attempt(function(){return Function(importsKeys,sourceURL+"return "+source).apply(undefined,importsValues)});if(result.source=source,isError(result))throw result;return result}function toLower(value){return toString(value).toLowerCase()}function toUpper(value){return toString(value).toUpperCase()}function trim(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrim,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),chrSymbols=stringToArray(chars),start=charsStartIndex(strSymbols,chrSymbols),end=charsEndIndex(strSymbols,chrSymbols)+1;return castSlice(strSymbols,start,end).join("")}function trimEnd(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrimEnd,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),end=charsEndIndex(strSymbols,stringToArray(chars))+1;return castSlice(strSymbols,0,end).join("")}function trimStart(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrimStart,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),start=charsStartIndex(strSymbols,stringToArray(chars));return castSlice(strSymbols,start).join("")}function truncate(string,options){var length=DEFAULT_TRUNC_LENGTH,omission=DEFAULT_TRUNC_OMISSION;if(isObject(options)){var separator="separator"in options?options.separator:separator;length="length"in options?toInteger(options.length):length,omission="omission"in options?baseToString(options.omission):omission}string=toString(string);var strLength=string.length;if(hasUnicode(string)){var strSymbols=stringToArray(string);strLength=strSymbols.length}if(length>=strLength)return string;var end=length-stringSize(omission);if(1>end)return omission;var result=strSymbols?castSlice(strSymbols,0,end).join(""):string.slice(0,end);if(separator===undefined)return result+omission;if(strSymbols&&(end+=result.length-end),isRegExp(separator)){if(string.slice(end).search(separator)){var match,substring=result;for(separator.global||(separator=RegExp(separator.source,toString(reFlags.exec(separator))+"g")),separator.lastIndex=0;match=separator.exec(substring);)var newEnd=match.index;result=result.slice(0,newEnd===undefined?end:newEnd)}}else if(string.indexOf(baseToString(separator),end)!=end){var index=result.lastIndexOf(separator);index>-1&&(result=result.slice(0,index))}return result+omission}function unescape(string){return string=toString(string),string&&reHasEscapedHtml.test(string)?string.replace(reEscapedHtml,unescapeHtmlChar):string}function words(string,pattern,guard){return string=toString(string),pattern=guard?undefined:pattern,pattern===undefined?hasUnicodeWord(string)?unicodeWords(string):asciiWords(string):string.match(pattern)||[]}function cond(pairs){var length=pairs?pairs.length:0,toIteratee=getIteratee();return pairs=length?arrayMap(pairs,function(pair){if("function"!=typeof pair[1])throw new TypeError(FUNC_ERROR_TEXT);return[toIteratee(pair[0]),pair[1]]}):[],baseRest(function(args){for(var index=-1;++indexn||n>MAX_SAFE_INTEGER)return[];var index=MAX_ARRAY_LENGTH,length=nativeMin(n,MAX_ARRAY_LENGTH);iteratee=getIteratee(iteratee),n-=MAX_ARRAY_LENGTH;for(var result=baseTimes(length,iteratee);++index1?arrays[length-1]:undefined;return iteratee="function"==typeof iteratee?(arrays.pop(),iteratee):undefined,unzipWith(arrays,iteratee)}),wrapperAt=flatRest(function(paths){var length=paths.length,start=length?paths[0]:0,value=this.__wrapped__,interceptor=function(object){return baseAt(object,paths)};return!(length>1||this.__actions__.length)&&value instanceof LazyWrapper&&isIndex(start)?(value=value.slice(start,+start+(length?1:0)),value.__actions__.push({func:thru,args:[interceptor],thisArg:undefined}),new LodashWrapper(value,this.__chain__).thru(function(array){return length&&!array.length&&array.push(undefined),array})):this.thru(interceptor)}),countBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?++result[key]:baseAssignValue(result,key,1)}),find=createFind(findIndex),findLast=createFind(findLastIndex),groupBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?result[key].push(value):baseAssignValue(result,key,[value])}),invokeMap=baseRest(function(collection,path,args){var index=-1,isFunc="function"==typeof path,isProp=isKey(path),result=isArrayLike(collection)?Array(collection.length):[];return baseEach(collection,function(value){var func=isFunc?path:isProp&&null!=value?value[path]:undefined;result[++index]=func?apply(func,value,args):baseInvoke(value,path,args)}),result}),keyBy=createAggregator(function(result,value,key){baseAssignValue(result,key,value)}),partition=createAggregator(function(result,value,key){result[key?0:1].push(value)},function(){return[[],[]]}),sortBy=baseRest(function(collection,iteratees){if(null==collection)return[];var length=iteratees.length;return length>1&&isIterateeCall(collection,iteratees[0],iteratees[1])?iteratees=[]:length>2&&isIterateeCall(iteratees[0],iteratees[1],iteratees[2])&&(iteratees=[iteratees[0]]),baseOrderBy(collection,baseFlatten(iteratees,1),[])}),now=ctxNow||function(){return root.Date.now()},bind=baseRest(function(func,thisArg,partials){var bitmask=BIND_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bind));bitmask|=PARTIAL_FLAG}return createWrap(func,bitmask,thisArg,partials,holders)}),bindKey=baseRest(function(object,key,partials){var bitmask=BIND_FLAG|BIND_KEY_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bindKey));bitmask|=PARTIAL_FLAG}return createWrap(key,bitmask,object,partials,holders)}),defer=baseRest(function(func,args){return baseDelay(func,1,args)}),delay=baseRest(function(func,wait,args){return baseDelay(func,toNumber(wait)||0,args)});memoize.Cache=MapCache;var overArgs=castRest(function(func,transforms){transforms=1==transforms.length&&isArray(transforms[0])?arrayMap(transforms[0],baseUnary(getIteratee())):arrayMap(baseFlatten(transforms,1),baseUnary(getIteratee()));var funcsLength=transforms.length;return baseRest(function(args){for(var index=-1,length=nativeMin(args.length,funcsLength);++index=other}),isArguments=baseIsArguments(function(){return arguments}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty.call(value,"callee")&&!propertyIsEnumerable.call(value,"callee")},isArray=Array.isArray,isArrayBuffer=nodeIsArrayBuffer?baseUnary(nodeIsArrayBuffer):baseIsArrayBuffer,isBuffer=nativeIsBuffer||stubFalse,isDate=nodeIsDate?baseUnary(nodeIsDate):baseIsDate,isMap=nodeIsMap?baseUnary(nodeIsMap):baseIsMap,isRegExp=nodeIsRegExp?baseUnary(nodeIsRegExp):baseIsRegExp,isSet=nodeIsSet?baseUnary(nodeIsSet):baseIsSet,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray,lt=createRelationalOperation(baseLt),lte=createRelationalOperation(function(value,other){return other>=value}),assign=createAssigner(function(object,source){if(isPrototype(source)||isArrayLike(source))return void copyObject(source,keys(source),object);for(var key in source)hasOwnProperty.call(source,key)&&assignValue(object,key,source[key])}),assignIn=createAssigner(function(object,source){copyObject(source,keysIn(source),object)}),assignInWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keysIn(source),object,customizer)}),assignWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keys(source),object,customizer)}),at=flatRest(baseAt),defaults=baseRest(function(args){return args.push(undefined,assignInDefaults),apply(assignInWith,undefined,args)}),defaultsDeep=baseRest(function(args){return args.push(undefined,mergeDefaults),apply(mergeWith,undefined,args)}),invert=createInverter(function(result,value,key){result[value]=key},constant(identity)),invertBy=createInverter(function(result,value,key){hasOwnProperty.call(result,value)?result[value].push(key):result[value]=[key]},getIteratee),invoke=baseRest(baseInvoke),merge=createAssigner(function(object,source,srcIndex){baseMerge(object,source,srcIndex)}),mergeWith=createAssigner(function(object,source,srcIndex,customizer){baseMerge(object,source,srcIndex,customizer)}),omit=flatRest(function(object,props){return null==object?{}:(props=arrayMap(props,toKey),basePick(object,baseDifference(getAllKeysIn(object),props)))}),pick=flatRest(function(object,props){return null==object?{}:basePick(object,arrayMap(props,toKey))}),toPairs=createToPairs(keys),toPairsIn=createToPairs(keysIn),camelCase=createCompounder(function(result,word,index){return word=word.toLowerCase(),result+(index?capitalize(word):word)}),kebabCase=createCompounder(function(result,word,index){return result+(index?"-":"")+word.toLowerCase()}),lowerCase=createCompounder(function(result,word,index){return result+(index?" ":"")+word.toLowerCase()}),lowerFirst=createCaseFirst("toLowerCase"),snakeCase=createCompounder(function(result,word,index){return result+(index?"_":"")+word.toLowerCase()}),startCase=createCompounder(function(result,word,index){return result+(index?" ":"")+upperFirst(word)}),upperCase=createCompounder(function(result,word,index){return result+(index?" ":"")+word.toUpperCase()}),upperFirst=createCaseFirst("toUpperCase"),attempt=baseRest(function(func,args){try{return apply(func,undefined,args)}catch(e){return isError(e)?e:new Error(e)}}),bindAll=flatRest(function(object,methodNames){return arrayEach(methodNames,function(key){key=toKey(key),baseAssignValue(object,key,bind(object[key],object))}),object}),flow=createFlow(),flowRight=createFlow(!0),method=baseRest(function(path,args){return function(object){return baseInvoke(object,path,args)}}),methodOf=baseRest(function(object,args){return function(path){return baseInvoke(object,path,args)}}),over=createOver(arrayMap),overEvery=createOver(arrayEvery),overSome=createOver(arraySome),range=createRange(),rangeRight=createRange(!0),add=createMathOperation(function(augend,addend){return augend+addend},0),ceil=createRound("ceil"),divide=createMathOperation(function(dividend,divisor){return dividend/divisor},1),floor=createRound("floor"),multiply=createMathOperation(function(multiplier,multiplicand){return multiplier*multiplicand},1),round=createRound("round"),subtract=createMathOperation(function(minuend,subtrahend){return minuend-subtrahend},0);return lodash.after=after,lodash.ary=ary,lodash.assign=assign,lodash.assignIn=assignIn,lodash.assignInWith=assignInWith,lodash.assignWith=assignWith,lodash.at=at,lodash.before=before,lodash.bind=bind,lodash.bindAll=bindAll,lodash.bindKey=bindKey,lodash.castArray=castArray,lodash.chain=chain,lodash.chunk=chunk,lodash.compact=compact,lodash.concat=concat,lodash.cond=cond,lodash.conforms=conforms,lodash.constant=constant,lodash.countBy=countBy,lodash.create=create,lodash.curry=curry,lodash.curryRight=curryRight,lodash.debounce=debounce,lodash.defaults=defaults,lodash.defaultsDeep=defaultsDeep,lodash.defer=defer,lodash.delay=delay,lodash.difference=difference,lodash.differenceBy=differenceBy,lodash.differenceWith=differenceWith,lodash.drop=drop,lodash.dropRight=dropRight,lodash.dropRightWhile=dropRightWhile,lodash.dropWhile=dropWhile,lodash.fill=fill,lodash.filter=filter,lodash.flatMap=flatMap,lodash.flatMapDeep=flatMapDeep,lodash.flatMapDepth=flatMapDepth,lodash.flatten=flatten,lodash.flattenDeep=flattenDeep,lodash.flattenDepth=flattenDepth,lodash.flip=flip,lodash.flow=flow,lodash.flowRight=flowRight,lodash.fromPairs=fromPairs,lodash.functions=functions,lodash.functionsIn=functionsIn,lodash.groupBy=groupBy,lodash.initial=initial,lodash.intersection=intersection,lodash.intersectionBy=intersectionBy,lodash.intersectionWith=intersectionWith,lodash.invert=invert,lodash.invertBy=invertBy,lodash.invokeMap=invokeMap,lodash.iteratee=iteratee,lodash.keyBy=keyBy,lodash.keys=keys,lodash.keysIn=keysIn,lodash.map=map,lodash.mapKeys=mapKeys,lodash.mapValues=mapValues,lodash.matches=matches,lodash.matchesProperty=matchesProperty, +lodash.memoize=memoize,lodash.merge=merge,lodash.mergeWith=mergeWith,lodash.method=method,lodash.methodOf=methodOf,lodash.mixin=mixin,lodash.negate=negate,lodash.nthArg=nthArg,lodash.omit=omit,lodash.omitBy=omitBy,lodash.once=once,lodash.orderBy=orderBy,lodash.over=over,lodash.overArgs=overArgs,lodash.overEvery=overEvery,lodash.overSome=overSome,lodash.partial=partial,lodash.partialRight=partialRight,lodash.partition=partition,lodash.pick=pick,lodash.pickBy=pickBy,lodash.property=property,lodash.propertyOf=propertyOf,lodash.pull=pull,lodash.pullAll=pullAll,lodash.pullAllBy=pullAllBy,lodash.pullAllWith=pullAllWith,lodash.pullAt=pullAt,lodash.range=range,lodash.rangeRight=rangeRight,lodash.rearg=rearg,lodash.reject=reject,lodash.remove=remove,lodash.rest=rest,lodash.reverse=reverse,lodash.sampleSize=sampleSize,lodash.set=set,lodash.setWith=setWith,lodash.shuffle=shuffle,lodash.slice=slice,lodash.sortBy=sortBy,lodash.sortedUniq=sortedUniq,lodash.sortedUniqBy=sortedUniqBy,lodash.split=split,lodash.spread=spread,lodash.tail=tail,lodash.take=take,lodash.takeRight=takeRight,lodash.takeRightWhile=takeRightWhile,lodash.takeWhile=takeWhile,lodash.tap=tap,lodash.throttle=throttle,lodash.thru=thru,lodash.toArray=toArray,lodash.toPairs=toPairs,lodash.toPairsIn=toPairsIn,lodash.toPath=toPath,lodash.toPlainObject=toPlainObject,lodash.transform=transform,lodash.unary=unary,lodash.union=union,lodash.unionBy=unionBy,lodash.unionWith=unionWith,lodash.uniq=uniq,lodash.uniqBy=uniqBy,lodash.uniqWith=uniqWith,lodash.unset=unset,lodash.unzip=unzip,lodash.unzipWith=unzipWith,lodash.update=update,lodash.updateWith=updateWith,lodash.values=values,lodash.valuesIn=valuesIn,lodash.without=without,lodash.words=words,lodash.wrap=wrap,lodash.xor=xor,lodash.xorBy=xorBy,lodash.xorWith=xorWith,lodash.zip=zip,lodash.zipObject=zipObject,lodash.zipObjectDeep=zipObjectDeep,lodash.zipWith=zipWith,lodash.entries=toPairs,lodash.entriesIn=toPairsIn,lodash.extend=assignIn,lodash.extendWith=assignInWith,mixin(lodash,lodash),lodash.add=add,lodash.attempt=attempt,lodash.camelCase=camelCase,lodash.capitalize=capitalize,lodash.ceil=ceil,lodash.clamp=clamp,lodash.clone=clone,lodash.cloneDeep=cloneDeep,lodash.cloneDeepWith=cloneDeepWith,lodash.cloneWith=cloneWith,lodash.conformsTo=conformsTo,lodash.deburr=deburr,lodash.defaultTo=defaultTo,lodash.divide=divide,lodash.endsWith=endsWith,lodash.eq=eq,lodash.escape=escape,lodash.escapeRegExp=escapeRegExp,lodash.every=every,lodash.find=find,lodash.findIndex=findIndex,lodash.findKey=findKey,lodash.findLast=findLast,lodash.findLastIndex=findLastIndex,lodash.findLastKey=findLastKey,lodash.floor=floor,lodash.forEach=forEach,lodash.forEachRight=forEachRight,lodash.forIn=forIn,lodash.forInRight=forInRight,lodash.forOwn=forOwn,lodash.forOwnRight=forOwnRight,lodash.get=get,lodash.gt=gt,lodash.gte=gte,lodash.has=has,lodash.hasIn=hasIn,lodash.head=head,lodash.identity=identity,lodash.includes=includes,lodash.indexOf=indexOf,lodash.inRange=inRange,lodash.invoke=invoke,lodash.isArguments=isArguments,lodash.isArray=isArray,lodash.isArrayBuffer=isArrayBuffer,lodash.isArrayLike=isArrayLike,lodash.isArrayLikeObject=isArrayLikeObject,lodash.isBoolean=isBoolean,lodash.isBuffer=isBuffer,lodash.isDate=isDate,lodash.isElement=isElement,lodash.isEmpty=isEmpty,lodash.isEqual=isEqual,lodash.isEqualWith=isEqualWith,lodash.isError=isError,lodash.isFinite=isFinite,lodash.isFunction=isFunction,lodash.isInteger=isInteger,lodash.isLength=isLength,lodash.isMap=isMap,lodash.isMatch=isMatch,lodash.isMatchWith=isMatchWith,lodash.isNaN=isNaN,lodash.isNative=isNative,lodash.isNil=isNil,lodash.isNull=isNull,lodash.isNumber=isNumber,lodash.isObject=isObject,lodash.isObjectLike=isObjectLike,lodash.isPlainObject=isPlainObject,lodash.isRegExp=isRegExp,lodash.isSafeInteger=isSafeInteger,lodash.isSet=isSet,lodash.isString=isString,lodash.isSymbol=isSymbol,lodash.isTypedArray=isTypedArray,lodash.isUndefined=isUndefined,lodash.isWeakMap=isWeakMap,lodash.isWeakSet=isWeakSet,lodash.join=join,lodash.kebabCase=kebabCase,lodash.last=last,lodash.lastIndexOf=lastIndexOf,lodash.lowerCase=lowerCase,lodash.lowerFirst=lowerFirst,lodash.lt=lt,lodash.lte=lte,lodash.max=max,lodash.maxBy=maxBy,lodash.mean=mean,lodash.meanBy=meanBy,lodash.min=min,lodash.minBy=minBy,lodash.stubArray=stubArray,lodash.stubFalse=stubFalse,lodash.stubObject=stubObject,lodash.stubString=stubString,lodash.stubTrue=stubTrue,lodash.multiply=multiply,lodash.nth=nth,lodash.noConflict=noConflict,lodash.noop=noop,lodash.now=now,lodash.pad=pad,lodash.padEnd=padEnd,lodash.padStart=padStart,lodash.parseInt=parseInt,lodash.random=random,lodash.reduce=reduce,lodash.reduceRight=reduceRight,lodash.repeat=repeat,lodash.replace=replace,lodash.result=result,lodash.round=round,lodash.runInContext=runInContext,lodash.sample=sample,lodash.size=size,lodash.snakeCase=snakeCase,lodash.some=some,lodash.sortedIndex=sortedIndex,lodash.sortedIndexBy=sortedIndexBy,lodash.sortedIndexOf=sortedIndexOf,lodash.sortedLastIndex=sortedLastIndex,lodash.sortedLastIndexBy=sortedLastIndexBy,lodash.sortedLastIndexOf=sortedLastIndexOf,lodash.startCase=startCase,lodash.startsWith=startsWith,lodash.subtract=subtract,lodash.sum=sum,lodash.sumBy=sumBy,lodash.template=template,lodash.times=times,lodash.toFinite=toFinite,lodash.toInteger=toInteger,lodash.toLength=toLength,lodash.toLower=toLower,lodash.toNumber=toNumber,lodash.toSafeInteger=toSafeInteger,lodash.toString=toString,lodash.toUpper=toUpper,lodash.trim=trim,lodash.trimEnd=trimEnd,lodash.trimStart=trimStart,lodash.truncate=truncate,lodash.unescape=unescape,lodash.uniqueId=uniqueId,lodash.upperCase=upperCase,lodash.upperFirst=upperFirst,lodash.each=forEach,lodash.eachRight=forEachRight,lodash.first=head,mixin(lodash,function(){var source={};return baseForOwn(lodash,function(func,methodName){hasOwnProperty.call(lodash.prototype,methodName)||(source[methodName]=func)}),source}(),{chain:!1}),lodash.VERSION=VERSION,arrayEach(["bind","bindKey","curry","curryRight","partial","partialRight"],function(methodName){lodash[methodName].placeholder=lodash}),arrayEach(["drop","take"],function(methodName,index){LazyWrapper.prototype[methodName]=function(n){var filtered=this.__filtered__;if(filtered&&!index)return new LazyWrapper(this);n=n===undefined?1:nativeMax(toInteger(n),0);var result=this.clone();return filtered?result.__takeCount__=nativeMin(n,result.__takeCount__):result.__views__.push({size:nativeMin(n,MAX_ARRAY_LENGTH),type:methodName+(result.__dir__<0?"Right":"")}),result},LazyWrapper.prototype[methodName+"Right"]=function(n){return this.reverse()[methodName](n).reverse()}}),arrayEach(["filter","map","takeWhile"],function(methodName,index){var type=index+1,isFilter=type==LAZY_FILTER_FLAG||type==LAZY_WHILE_FLAG;LazyWrapper.prototype[methodName]=function(iteratee){var result=this.clone();return result.__iteratees__.push({iteratee:getIteratee(iteratee,3),type:type}),result.__filtered__=result.__filtered__||isFilter,result}}),arrayEach(["head","last"],function(methodName,index){var takeName="take"+(index?"Right":"");LazyWrapper.prototype[methodName]=function(){return this[takeName](1).value()[0]}}),arrayEach(["initial","tail"],function(methodName,index){var dropName="drop"+(index?"":"Right");LazyWrapper.prototype[methodName]=function(){return this.__filtered__?new LazyWrapper(this):this[dropName](1)}}),LazyWrapper.prototype.compact=function(){return this.filter(identity)},LazyWrapper.prototype.find=function(predicate){return this.filter(predicate).head()},LazyWrapper.prototype.findLast=function(predicate){return this.reverse().find(predicate)},LazyWrapper.prototype.invokeMap=baseRest(function(path,args){return"function"==typeof path?new LazyWrapper(this):this.map(function(value){return baseInvoke(value,path,args)})}),LazyWrapper.prototype.reject=function(predicate){return this.filter(negate(getIteratee(predicate)))},LazyWrapper.prototype.slice=function(start,end){start=toInteger(start);var result=this;return result.__filtered__&&(start>0||0>end)?new LazyWrapper(result):(0>start?result=result.takeRight(-start):start&&(result=result.drop(start)),end!==undefined&&(end=toInteger(end),result=0>end?result.dropRight(-end):result.take(end-start)),result)},LazyWrapper.prototype.takeRightWhile=function(predicate){return this.reverse().takeWhile(predicate).reverse()},LazyWrapper.prototype.toArray=function(){return this.take(MAX_ARRAY_LENGTH)},baseForOwn(LazyWrapper.prototype,function(func,methodName){var checkIteratee=/^(?:filter|find|map|reject)|While$/.test(methodName),isTaker=/^(?:head|last)$/.test(methodName),lodashFunc=lodash[isTaker?"take"+("last"==methodName?"Right":""):methodName],retUnwrapped=isTaker||/^find/.test(methodName);lodashFunc&&(lodash.prototype[methodName]=function(){var value=this.__wrapped__,args=isTaker?[1]:arguments,isLazy=value instanceof LazyWrapper,iteratee=args[0],useLazy=isLazy||isArray(value),interceptor=function(value){var result=lodashFunc.apply(lodash,arrayPush([value],args));return isTaker&&chainAll?result[0]:result};useLazy&&checkIteratee&&"function"==typeof iteratee&&1!=iteratee.length&&(isLazy=useLazy=!1);var chainAll=this.__chain__,isHybrid=!!this.__actions__.length,isUnwrapped=retUnwrapped&&!chainAll,onlyLazy=isLazy&&!isHybrid;if(!retUnwrapped&&useLazy){value=onlyLazy?value:new LazyWrapper(this);var result=func.apply(value,args);return result.__actions__.push({func:thru,args:[interceptor],thisArg:undefined}),new LodashWrapper(result,chainAll)}return isUnwrapped&&onlyLazy?func.apply(this,args):(result=this.thru(interceptor),isUnwrapped?isTaker?result.value()[0]:result.value():result)})}),arrayEach(["pop","push","shift","sort","splice","unshift"],function(methodName){var func=arrayProto[methodName],chainName=/^(?:push|sort|unshift)$/.test(methodName)?"tap":"thru",retUnwrapped=/^(?:pop|shift)$/.test(methodName);lodash.prototype[methodName]=function(){var args=arguments;if(retUnwrapped&&!this.__chain__){var value=this.value();return func.apply(isArray(value)?value:[],args)}return this[chainName](function(value){return func.apply(isArray(value)?value:[],args)})}}),baseForOwn(LazyWrapper.prototype,function(func,methodName){var lodashFunc=lodash[methodName];if(lodashFunc){var key=lodashFunc.name+"",names=realNames[key]||(realNames[key]=[]);names.push({name:methodName,func:lodashFunc})}}),realNames[createHybrid(undefined,BIND_KEY_FLAG).name]=[{name:"wrapper",func:undefined}],LazyWrapper.prototype.clone=lazyClone,LazyWrapper.prototype.reverse=lazyReverse,LazyWrapper.prototype.value=lazyValue,lodash.prototype.at=wrapperAt,lodash.prototype.chain=wrapperChain,lodash.prototype.commit=wrapperCommit,lodash.prototype.next=wrapperNext,lodash.prototype.plant=wrapperPlant,lodash.prototype.reverse=wrapperReverse,lodash.prototype.toJSON=lodash.prototype.valueOf=lodash.prototype.value=wrapperValue,lodash.prototype.first=lodash.prototype.head,iteratorSymbol&&(lodash.prototype[iteratorSymbol]=wrapperToIterator),lodash},_=runInContext();"function"==typeof define&&"object"==typeof define.amd&&define.amd?(root._=_,define(function(){return _})):freeModule?((freeModule.exports=_)._=_,freeExports._=_):root._=_}.call(this);var UsergridAuthMode=Object.freeze({NONE:"none",USER:"user",APP:"app"}),UsergridDirection=Object.freeze({IN:"connecting",OUT:"connections"}),UsergridHttpMethod=Object.freeze({GET:"GET",PUT:"PUT",POST:"POST",DELETE:"DELETE"}),UsergridQueryOperator=Object.freeze({EQUAL:"=",GREATER_THAN:">",GREATER_THAN_EQUAL_TO:">=",LESS_THAN:"<",LESS_THAN_EQUAL_TO:"<="}),UsergridQuerySortOrder=Object.freeze({ASC:"asc",DESC:"desc"}),UsergridApplicationJSONHeaderValue="application/json";!function(global){function UsergridHelpers(){}var name="UsergridHelpers",overwrittenName=global[name];UsergridHelpers.DefaultHeaders=Object.freeze({"Content-Type":UsergridApplicationJSONHeaderValue,Accept:UsergridApplicationJSONHeaderValue}),UsergridHelpers.validateAndRetrieveClient=function(args){var client=void 0;if(args instanceof UsergridClient)client=args;else if(args[0]instanceof UsergridClient)client=args[0];else if(_.get(args,"client"))client=args.client;else{if(!Usergrid.isInitialized)throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument");client=Usergrid}return client},UsergridHelpers.inherits=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})},UsergridHelpers.flattenArgs=function(args){return _.flattenDeep(Array.prototype.slice.call(args))},UsergridHelpers.callback=function(){var args=UsergridHelpers.flattenArgs(arguments).reverse(),emptyFunc=function(){};return _.first(_.flattenDeep([args,_.get(args,"0.callback"),emptyFunc]).filter(_.isFunction))},UsergridHelpers.authForRequests=function(client){var authForRequests=void 0;return _.get(client,"tempAuth.isValid")?(authForRequests=client.tempAuth,client.tempAuth=void 0):_.get(client,"currentUser.auth.isValid")&&client.authMode===UsergridAuthMode.USER?authForRequests=client.currentUser.auth:_.get(client,"appAuth.isValid")&&client.authMode===UsergridAuthMode.APP&&(authForRequests=client.appAuth),authForRequests},UsergridHelpers.userLoginBody=function(options){var body={grant_type:"password",password:options.password};return options.tokenTtl&&(body.ttl=options.tokenTtl),body[options.username?"username":"email"]=options.username?options.username:options.email,body},UsergridHelpers.appLoginBody=function(options){var body={grant_type:"client_credentials",client_id:options.clientId,client_secret:options.clientSecret};return options.tokenTtl&&(body.ttl=options.tokenTtl),body},UsergridHelpers.calculateExpiry=function(expires_in){return Date.now()+1e3*(expires_in?expires_in-5:0)};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;return UsergridHelpers.isUUID=function(uuid){return uuid?uuidValueRegex.test(uuid):!1},UsergridHelpers.useQuotesIfRequired=function(value){return _.isFinite(value)||UsergridHelpers.isUUID(value)||_.isBoolean(value)||_.isObject(value)&&!_.isFunction(value)||_.isArray(value)?value:"'"+value+"'"},UsergridHelpers.setReadOnly=function(obj,key){return _.isArray(key)?key.forEach(function(k){UsergridHelpers.setReadOnly(obj,k)}):_.isPlainObject(obj[key])?Object.freeze(obj[key]):_.isPlainObject(obj)&&void 0===key?Object.freeze(obj):_.has(obj,key)?Object.defineProperty(obj,key,{writable:!1}):obj},UsergridHelpers.setWritable=function(obj,key){return _.isArray(key)?key.forEach(function(k){UsergridHelpers.setWritable(obj,k)}):_.isPlainObject(obj[key])?_.clone(obj[key]):_.isPlainObject(obj)&&void 0===key?_.clone(obj):_.has(obj,key)?Object.defineProperty(obj,key,{writable:!0}):obj},UsergridHelpers.assignPrefabOptions=function(args){return _.isObject(args[0])&&!_.isFunction(args[0])&&_.has(args,"method")&&_.assign(this,args[0]),this},UsergridHelpers.normalize=function(str){return str=str.replace(/\/+/g,"/"),str=str.replace(/:\//g,"://"),str=str.replace(/\/(\?|&|#[^!])/g,"$1"),str=str.replace(/(\?.+)\?/g,"$1&")},UsergridHelpers.urljoin=function(){var input=arguments,options={};"object"==typeof arguments[0]&&(input=arguments[0],options=arguments[1]||{});var joined=[].slice.call(input,0).join("/");return UsergridHelpers.normalize(joined,options)},UsergridHelpers.parseResponseHeaders=function(headerStr){var headers={};if(headerStr)for(var headerPairs=headerStr.split("\r\n"),i=0;i0){var key=headerPair.substring(0,index).toLowerCase();headers[key]=headerPair.substring(index+2)}}return headers},UsergridHelpers.uri=function(client,options){var path="";path=options instanceof UsergridEntity?options.type:options instanceof UsergridQuery?options._type:_.isString(options)?options:_.isArray(options)?_.get(options,"0.type")||_.get(options,"0.path"):options.path||options.type||_.get(options,"entity.type")||_.get(options,"query._type")||_.get(options,"body.type")||_.get(options,"body.path");var uuidOrName="";return options.method!==UsergridHttpMethod.POST&&(uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,_.get(options,"entity.uuid"),_.get(options,"entity.name"),_.get(options,"body.uuid"),_.get(options,"body.name"),""].filter(_.isString))),UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,path,uuidOrName)},UsergridHelpers.updateEntityFromRemote=function(entity,usergridResponse){UsergridHelpers.setWritable(entity,["uuid","name","type","created"]),_.assign(entity,usergridResponse.entity),UsergridHelpers.setReadOnly(entity,["uuid","name","type","created"])},UsergridHelpers.headers=function(client,options,defaultHeaders){var returnHeaders={};_.defaults(returnHeaders,options.headers,defaultHeaders),_.assign(returnHeaders,{"User-Agent":"usergrid-js/v"+UsergridSDKVersion});var authForRequests=UsergridHelpers.authForRequests(client);return authForRequests&&_.assign(returnHeaders,{authorization:"Bearer "+authForRequests.token}),returnHeaders},UsergridHelpers.setEntity=function(options,args){return options.entity=_.first([options.entity,args[0]].filter(function(property){return property instanceof UsergridEntity})),void 0!==options.entity&&(options.type=options.entity.type),options},UsergridHelpers.setAsset=function(options,args){return options.asset=_.first([options.asset,_.get(options,"entity.asset"),args[1],args[0]].filter(function(property){return property instanceof UsergridAsset})),options},UsergridHelpers.setUuidOrName=function(options,args){return options.uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,_.get(options,"entity.uuid"),_.get(options,"body.uuid"),_.get(options,"entity.name"),_.get(options,"body.name"),_.get(args,"0.uuid"),_.get(args,"0.name"),_.get(args,"2"),_.get(args,"1")].filter(_.isString)),options},UsergridHelpers.setPathOrType=function(options,args){var pathOrType=_.first([args.type,_.get(args,"0.type"),_.get(options,"entity.type"),_.get(args,"body.type"),_.get(options,"body.0.type"),_.isArray(args)?args[0]:void 0].filter(_.isString));return options[/\//.test(pathOrType)?"path":"type"]=pathOrType,options},UsergridHelpers.setQs=function(options,args){return options.path&&(options.qs=_.first([options.qs,args[2],args[1],args[0]].filter(_.isPlainObject))),options},UsergridHelpers.setQuery=function(options,args){return options.query=_.first([options,options.query,args[0]].filter(function(property){return property instanceof UsergridQuery})),options},UsergridHelpers.setAsset=function(options,args){return options.asset=_.first([options.asset,_.get(options,"entity.asset"),args[1],args[0]].filter(function(property){return property instanceof UsergridAsset})),options},UsergridHelpers.setBody=function(options,args){if(options.body=_.first([args.entity,args.body,args[0].entity,args[0].body,args[2],args[1],args[0]].filter(function(property){return _.isObject(property)&&!_.isFunction(property)&&!(property instanceof UsergridQuery)&&!(property instanceof UsergridAsset)})),void 0===options.body&&void 0===options.asset)throw new Error('"body" is required when making a '+options.method+" request");return options.body instanceof UsergridEntity?options.body=options.body.jsonValue():options.body instanceof Array&&options.body[0]instanceof UsergridEntity&&(options.body=_.map(options.body,function(entity){return entity.jsonValue()})),options},UsergridHelpers.buildReqest=function(client,method,args){var options={client:client,method:method,queryParams:args.queryParams||_.get(args,"0.queryParams"),callback:UsergridHelpers.callback(args)};return UsergridHelpers.assignPrefabOptions(options,args),UsergridHelpers.setEntity(options,args),(method===UsergridHttpMethod.POST||method===UsergridHttpMethod.PUT)&&(UsergridHelpers.setAsset(options,args),void 0===options.asset&&UsergridHelpers.setBody(options,args)),UsergridHelpers.setUuidOrName(options,args),UsergridHelpers.setPathOrType(options,args),UsergridHelpers.setQs(options,args),UsergridHelpers.setQuery(options,args),options.uri=UsergridHelpers.uri(client,options),new UsergridRequest(options)},UsergridHelpers.buildAppAuthRequest=function(client,auth,callback){var requestOptions={client:client,method:UsergridHttpMethod.POST,uri:UsergridHelpers.uri(client,{path:"token"}),body:UsergridHelpers.appLoginBody(auth),callback:callback};return new UsergridRequest(requestOptions)},UsergridHelpers.buildConnectionRequest=function(client,method,args){var options={client:client,method:method,entity:{},to:{},callback:UsergridHelpers.callback(args)};if(UsergridHelpers.assignPrefabOptions.call(options,args),_.isObject(options.from)&&(options.to=options.from),_.isObject(args[0])&&_.has(args[0],"entity")&&_.has(args[0],"to")&&(_.assign(options.entity,args[0].entity),options.relationship=_.get(args,"0.relationship"),_.assign(options.to,args[0].to)),_.isObject(args[0])&&!_.isFunction(args[0])&&_.isString(args[1])&&(_.assign(options.entity,args[0]),options.relationship=_.first([options.relationship,args[1]].filter(_.isString))),_.isObject(args[2])&&!_.isFunction(args[2])&&_.assign(options.to,args[2]),options.entity.uuidOrName=_.first([options.entity.uuidOrName,options.entity.uuid,options.entity.name,args[1]].filter(_.isString)),options.entity.type||(options.entity.type=_.first([options.entity.type,args[0]].filter(_.isString))),options.relationship=_.first([options.relationship,args[2]].filter(_.isString)),_.isString(args[3])&&!UsergridHelpers.isUUID(args[3])&&_.isString(args[4])?options.to.type=args[3]:_.isString(args[2])&&!UsergridHelpers.isUUID(args[2])&&_.isString(args[3])&&_.isObject(args[0])&&!_.isFunction(args[0])&&(options.to.type=args[2]),options.to.uuidOrName=_.first([options.to.uuidOrName,options.to.uuid,options.to.name,args[4],args[3],args[2]].filter(function(property){return _.isString(options.to.type)&&_.isString(property)||UsergridHelpers.isUUID(property)})),!_.isString(options.entity.uuidOrName))throw new Error('source entity "uuidOrName" is required when connecting or disconnecting entities');if(!_.isString(options.to.uuidOrName))throw new Error('target entity "uuidOrName" is required when connecting or disconnecting entities');if(!_.isString(options.to.type)&&!UsergridHelpers.isUUID(options.to.uuidOrName))throw new Error('target "type" (collection name) parameter is required connecting or disconnecting entities by name');return options.uri=UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,_.isString(options.entity.type)?options.entity.type:"",_.isString(options.entity.uuidOrName)?options.entity.uuidOrName:"",options.relationship,_.isString(options.to.type)?options.to.type:"",_.isString(options.to.uuidOrName)?options.to.uuidOrName:""),new UsergridRequest(options)},UsergridHelpers.buildGetConnectionRequest=function(client,args){var options={client:client,method:"GET",callback:UsergridHelpers.callback(args)};if(UsergridHelpers.assignPrefabOptions.call(options,args),_.isObject(args[1])&&!_.isFunction(args[1])&&_.assign(options,args[1]),options.direction=_.first([options.direction,args[0]].filter(function(property){return property===UsergridDirection.IN||property===UsergridDirection.OUT})),options.relationship=_.first([options.relationship,args[3],args[2]].filter(_.isString)),options.uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,args[2]].filter(_.isString)),options.type=_.first([options.type,args[1]].filter(_.isString)),!_.isString(options.type))throw new Error('"type" (collection name) parameter is required when retrieving connections');if(!_.isString(options.uuidOrName))throw new Error('target entity "uuidOrName" is required when retrieving connections');return options.uri=UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,_.isString(options.type)?options.type:"",_.isString(options.uuidOrName)?options.uuidOrName:"",options.direction,options.relationship),new UsergridRequest(options)},global[name]=UsergridHelpers,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),UsergridHelpers},global[name]}(this);var UsergridClientDefaultOptions={baseUrl:"https://api.usergrid.com",authMode:UsergridAuthMode.USER},UsergridClient=function(options){var __appAuth,self=this;if(self.tempAuth=void 0,self.isSharedInstance=!1,2===arguments.length&&(self.orgId=arguments[0],self.appId=arguments[1]),_.defaults(self,options,UsergridClientDefaultOptions),!self.orgId||!self.appId)throw new Error('"orgId" and "appId" parameters are required when instantiating UsergridClient');return Object.defineProperty(self,"clientId",{enumerable:!1}),Object.defineProperty(self,"clientSecret",{enumerable:!1}),Object.defineProperty(self,"appAuth",{get:function(){return __appAuth},set:function(options){options instanceof UsergridAppAuth?__appAuth=options:"undefined"!=typeof options&&(__appAuth=new UsergridAppAuth(options))}}),self.clientId&&self.clientSecret&&self.setAppAuth(self.clientId,self.clientSecret),self};UsergridClient.prototype={sendRequest:function(usergridRequest){return usergridRequest.sendRequest()},GET:function(){var usergridRequest=UsergridHelpers.buildReqest(this,UsergridHttpMethod.GET,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},PUT:function(){var usergridRequest=UsergridHelpers.buildReqest(this,UsergridHttpMethod.PUT,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},POST:function(){var usergridRequest=UsergridHelpers.buildReqest(this,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},DELETE:function(){var usergridRequest=UsergridHelpers.buildReqest(this,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},connect:function(){var usergridRequest=UsergridHelpers.buildConnectionRequest(this,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},disconnect:function(){var usergridRequest=UsergridHelpers.buildConnectionRequest(this,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},getConnections:function(){var usergridRequest=UsergridHelpers.buildGetConnectionRequest(this,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},usingAuth:function(auth){var self=this;return _.isString(auth)?self.tempAuth=new UsergridAuth(auth):auth instanceof UsergridAuth?self.tempAuth=auth:self.tempAuth=void 0,self},setAppAuth:function(){this.appAuth=new UsergridAppAuth(UsergridHelpers.flattenArgs(arguments))},authenticateApp:function(options){var self=this,authenticateAppCallback=UsergridHelpers.callback(UsergridHelpers.flattenArgs(arguments)),auth=_.first([options,self.appAuth,new UsergridAppAuth(options),new UsergridAppAuth(self.clientId,self.clientSecret)].filter(function(p){return p instanceof UsergridAppAuth}));if(!(auth instanceof UsergridAppAuth))throw new Error("App auth context was not defined when attempting to call .authenticateApp()");if(!auth.clientId||!auth.clientSecret)throw new Error("authenticateApp() failed because clientId or clientSecret are missing");var callback=function(usergridResponse){if(usergridResponse.ok){self.appAuth||(self.appAuth=auth),self.appAuth.token=_.get(usergridResponse.responseJSON,"access_token");var expiresIn=_.get(usergridResponse.responseJSON,"expires_in");self.appAuth.expiry=UsergridHelpers.calculateExpiry(expiresIn),self.appAuth.tokenTtl=expiresIn}authenticateAppCallback(usergridResponse)},usergridRequest=UsergridHelpers.buildAppAuthRequest(self,auth,callback);return self.sendRequest(usergridRequest)},authenticateUser:function(options){var self=this,args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args),setAsCurrentUser=void 0!==_.last(args.filter(_.isBoolean))?_.last(args.filter(_.isBoolean)):!0,userToAuthenticate=new UsergridUser(options);userToAuthenticate.login(self,function(auth,user,usergridResponse){usergridResponse.ok&&setAsCurrentUser&&(self.currentUser=userToAuthenticate),callback(auth,user,usergridResponse)})},downloadAsset:function(){var self=this,usergridRequest=UsergridHelpers.buildReqest(self,UsergridHttpMethod.GET,UsergridHelpers.flattenArgs(arguments)),assetContentType=_.get(usergridRequest,"entity.file-metadata.content-type");void 0!==assetContentType&&_.assign(usergridRequest.headers,{Accept:assetContentType});var realDownloadAssetCallback=usergridRequest.callback;return usergridRequest.callback=function(usergridResponse){var entity=usergridRequest.entity;entity.asset=usergridResponse.asset,realDownloadAssetCallback(entity.asset,usergridResponse,entity)},self.sendRequest(usergridRequest)},uploadAsset:function(){var self=this,usergridRequest=UsergridHelpers.buildReqest(self,UsergridHttpMethod.PUT,UsergridHelpers.flattenArgs(arguments));if(void 0===usergridRequest.asset)throw new Error("An UsergridAsset was not defined when attempting to call .uploadAsset()");var realUploadAssetCallback=usergridRequest.callback;return usergridRequest.callback=function(usergridResponse){var requestEntity=usergridRequest.entity,responseEntity=usergridResponse.entity,requestAsset=usergridRequest.asset;usergridResponse.ok&&void 0!==responseEntity&&(UsergridHelpers.updateEntityFromRemote(requestEntity,usergridResponse),requestEntity.asset=requestAsset,responseEntity&&(responseEntity.asset=requestAsset)),realUploadAssetCallback(requestAsset,usergridResponse,requestEntity)},self.sendRequest(usergridRequest)}};var UsergridSDKVersion="2.0.0",UsergridClientSharedInstance=function(){var self=this;return self.isInitialized=!1,self.isSharedInstance=!0,self};UsergridHelpers.inherits(UsergridClientSharedInstance,UsergridClient);var Usergrid=new UsergridClientSharedInstance;Usergrid.initSharedInstance=function(options){return Usergrid.isInitialized?console.log("Usergrid shared instance is already initialized"):(_.assign(Usergrid,new UsergridClient(options)),Usergrid.isInitialized=!0,Usergrid.isSharedInstance=!0),Usergrid},Usergrid.init=Usergrid.initSharedInstance;var UsergridQuery=function(type){var queryString,sort,self=this,query="",urlTerms={},__nextIsNot=!1;return self._type=type,_.assign(self,{type:function(value){return self._type=value,self},collection:function(value){return self._type=value,self},limit:function(value){return self._limit=value,self},cursor:function(value){return self._cursor=value,self},eq:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.EQUAL+" "+UsergridHelpers.useQuotesIfRequired(value)),self},equal:this.eq,gt:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.GREATER_THAN+" "+UsergridHelpers.useQuotesIfRequired(value)),self},greaterThan:this.gt,gte:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.GREATER_THAN_EQUAL_TO+" "+UsergridHelpers.useQuotesIfRequired(value)),self},greaterThanOrEqual:this.gte,lt:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.LESS_THAN+" "+UsergridHelpers.useQuotesIfRequired(value)),self},lessThan:this.lt,lte:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.LESS_THAN_EQUAL_TO+" "+UsergridHelpers.useQuotesIfRequired(value)),self},lessThanOrEqual:this.lte,contains:function(key,value){return query=self.andJoin(key+" contains "+UsergridHelpers.useQuotesIfRequired(value)),self},locationWithin:function(distanceInMeters,lat,lng){return query=self.andJoin("location within "+distanceInMeters+" of "+lat+", "+lng),self},asc:function(key){return self.sort(key,UsergridQuerySortOrder.ASC),self},desc:function(key){return self.sort(key,UsergridQuerySortOrder.DESC),self},sort:function(key,order){return sort=key&&order?" order by "+key+" "+order:"",self},fromString:function(string){return queryString=string,self},urlTerm:function(key,value){return"ql"===key?self.fromString():urlTerms[key]=value,self},andJoin:function(append){return __nextIsNot&&(append="not "+append,__nextIsNot=!1), +append?0===query.length?append:_.endsWith(query,"and")||_.endsWith(query,"or")?query+" "+append:query+" and "+append:query},orJoin:function(){return query.length>0&&!_.endsWith(query,"or")?query+" or":query}}),Object.defineProperty(self,"_ql",{get:function(){var ql="select * ";return void 0!==queryString?ql=queryString:(ql+=query.length>0?"where "+(query||""):"",ql+=void 0!==sort?sort:""),ql}}),Object.defineProperty(self,"encodedStringValue",{get:function(){var self=this,limit=self._limit,cursor=self._cursor,requirementsString=self._ql,returnString=void 0;if(void 0!==limit&&(returnString="limit"+UsergridQueryOperator.EQUAL+limit),!_.isEmpty(cursor)){var cursorString="cursor"+UsergridQueryOperator.EQUAL+cursor;_.isEmpty(returnString)?returnString=cursorString:returnString+="&"+cursorString}if(_.forEach(urlTerms,function(value,key){var encodedURLTermString=encodeURIComponent(key)+UsergridQueryOperator.EQUAL+encodeURIComponent(value);_.isEmpty(returnString)?returnString=encodedURLTermString:returnString+="&"+encodedURLTermString}),!_.isEmpty(requirementsString)){var qLString="ql="+encodeURIComponent(requirementsString);_.isEmpty(returnString)?returnString=qLString:returnString+="&"+qLString}return _.isEmpty(returnString)||(returnString="?"+returnString),_.isEmpty(returnString)?void 0:returnString}}),Object.defineProperty(self,"and",{get:function(){return query=self.andJoin(""),self}}),Object.defineProperty(self,"or",{get:function(){return query=self.orJoin(),self}}),Object.defineProperty(self,"not",{get:function(){return __nextIsNot=!0,self}}),self},UsergridRequest=function(options){var self=this,client=UsergridHelpers.validateAndRetrieveClient(options);if(!_.isString(options.type)&&!_.isString(options.path)&&!_.isString(options.uri))throw new Error('one of "type" (collection name), "path", or "uri" parameters are required when initializing a UsergridRequest');if(!_.includes(["GET","PUT","POST","DELETE"],options.method))throw new Error('"method" parameter is required when initializing a UsergridRequest');self.method=options.method,self.callback=options.callback,self.uri=options.uri||UsergridHelpers.uri(client,options),self.entity=options.entity,self.body=options.body||void 0,self.asset=options.asset||void 0,self.query=options.query,self.queryParams=options.queryParams||options.qs;var defaultHeadersToUse=void 0===self.asset?UsergridHelpers.DefaultHeaders:{};if(self.headers=UsergridHelpers.headers(client,options,defaultHeadersToUse),void 0!==self.query&&(self.uri+=UsergridHelpers.normalize(self.query.encodedStringValue,{})),void 0!==self.queryParams&&(_.forOwn(self.queryParams,function(value,key){self.uri+="?"+encodeURIComponent(key)+UsergridQueryOperator.EQUAL+encodeURIComponent(value)}),self.uri=UsergridHelpers.normalize(self.uri,{})),void 0!==self.asset)self.body=new FormData,self.body.append(self.asset.filename,self.asset.data);else try{_.isPlainObject(self.body)?self.body=JSON.stringify(self.body):_.isArray(self.body)&&(self.body=JSON.stringify(self.body))}catch(exception){}return self};UsergridRequest.prototype.sendRequest=function(){var self=this,requestPromise=function(){var promise=new Promise,xmlHttpRequest=new XMLHttpRequest;return xmlHttpRequest.open(self.method,self.uri,!0),xmlHttpRequest.onload=function(){promise.done(xmlHttpRequest)},_.forOwn(self.headers,function(value,key){xmlHttpRequest.setRequestHeader(key,value)}),self.method===UsergridHttpMethod.GET&&_.get(self.headers,"Accept")!==UsergridApplicationJSONHeaderValue&&(xmlHttpRequest.responseType="blob"),xmlHttpRequest.send(self.body),promise},responsePromise=function(xmlRequest){var promise=new Promise,usergridResponse=new UsergridResponse(xmlRequest,self);return promise.done(usergridResponse),promise},onCompletePromise=function(response){var promise=new Promise;promise.done(response),self.callback(response)};return Promise.chain([requestPromise,responsePromise]).then(onCompletePromise),self};var UsergridAuth=function(token,expiry){var self=this;self.token=token,self.expiry=expiry||0;var usingToken=token?!0:!1;return Object.defineProperty(self,"hasToken",{get:function(){return void 0!==self.token},configurable:!0}),Object.defineProperty(self,"isExpired",{get:function(){return usingToken?!1:Date.now()>=self.expiry},configurable:!0}),Object.defineProperty(self,"isValid",{get:function(){return!self.isExpired&&self.hasToken},configurable:!0}),Object.defineProperty(self,"tokenTtl",{configurable:!0,writable:!0}),_.assign(self,{destroy:function(){self.token=void 0,self.expiry=0,self.tokenTtl=void 0}}),self},UsergridAppAuth=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments);return _.isPlainObject(args[0])?(self.clientId=args[0].clientId,self.clientSecret=args[0].clientSecret,self.tokenTtl=args[0].tokenTtl):(self.clientId=args[0],self.clientSecret=args[1],self.tokenTtl=args[2]),UsergridAuth.call(self),_.assign(self,UsergridAuth),self};UsergridHelpers.inherits(UsergridAppAuth,UsergridAuth);var UsergridUserAuth=function(options){var self=this,args=_.flattenDeep(UsergridHelpers.flattenArgs(arguments));return _.isPlainObject(args[0])&&(options=args[0]),self.username=options.username||args[0],self.email=options.email,(options.password||args[1])&&(self.password=options.password||args[1]),self.tokenTtl=options.tokenTtl||args[2],UsergridAuth.call(self),_.assign(self,UsergridAuth),self};UsergridHelpers.inherits(UsergridUserAuth,UsergridAuth);var UsergridEntity=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments);if(0===args.length)throw new Error("A UsergridEntity object cannot be initialized without passing one or more arguments");if(self.asset=void 0,_.isPlainObject(args[0])?_.assign(self,args[0]):(self.type||(self.type=_.isString(args[0])?args[0]:void 0),self.name||(self.name=_.isString(args[1])?args[1]:void 0)),!_.isString(self.type))throw new Error('"type" (or "collection") parameter is required when initializing a UsergridEntity object');return Object.defineProperty(self,"isUser",{get:function(){return"user"===self.type.toLowerCase()}}),Object.defineProperty(self,"hasAsset",{get:function(){return _.has(self,"file-metadata")}}),UsergridHelpers.setReadOnly(self,["uuid","name","type","created"]),self};UsergridEntity.prototype={jsonValue:function(){var jsonValue={};return _.forOwn(this,function(value,key){jsonValue[key]=value}),jsonValue},putProperty:function(key,value){this[key]=value},putProperties:function(obj){_.assign(this,obj)},removeProperty:function(key){this.removeProperties([key])},removeProperties:function(keys){var self=this;keys.forEach(function(key){delete self[key]})},insert:function(key,value,idx){_.isArray(this[key])||(this[key]=this[key]?[this[key]]:[]),this[key].splice.apply(this[key],[idx,0].concat(value))},append:function(key,value){this.insert(key,value,Number.MAX_VALUE)},prepend:function(key,value){this.insert(key,value,0)},pop:function(key){_.isArray(this[key])&&this[key].pop()},shift:function(key){_.isArray(this[key])&&this[key].shift()},reload:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.GET(self,function(usergridResponse){UsergridHelpers.updateEntityFromRemote(self,usergridResponse),callback(usergridResponse,self)}.bind(self))},save:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args),currentAsset=self.asset;client.PUT(self,function(usergridResponse){UsergridHelpers.updateEntityFromRemote(self,usergridResponse),self.hasAsset&&(self.asset=currentAsset),callback(usergridResponse,self)}.bind(self))},remove:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.DELETE(self,function(usergridResponse){callback(usergridResponse,self)}.bind(self))},attachAsset:function(asset){this.asset=asset},uploadAsset:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(_.has(self,"asset.contentType"))client.uploadAsset(self,callback);else{var response=new UsergridResponse.responseWithError({name:"asset_not_found",description:"The specified entity does not have a valid asset attached"});callback(null,response,self)}},downloadAsset:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(_.has(self,"asset.contentType"))client.downloadAsset(self,callback);else{var response=new UsergridResponse.responseWithError({name:"asset_not_found",description:"The specified entity does not have a valid asset attached"});callback(null,response,self)}},connect:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args[0]=this,client.connect.apply(client,args)},disconnect:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args[0]=this,client.disconnect.apply(client,args)},getConnections:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args.shift(),args.splice(1,0,this),client.getConnections.apply(client,args)}};var UsergridUser=function(obj){if(!_.has(obj,"email")&&!_.has(obj,"username"))throw new Error('"email" or "username" property is required when initializing a UsergridUser object');var self=this;return _.assign(self,obj,UsergridEntity),UsergridEntity.call(self,"user"),UsergridHelpers.setWritable(self,"name"),self};UsergridUser.CheckAvailable=function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);args[0]instanceof UsergridClient&&args.shift();var checkQuery,callback=UsergridHelpers.callback(args);if(args[0].username&&args[0].email)checkQuery=new UsergridQuery("users").eq("username",args[0].username).or.eq("email",args[0].email);else if(args[0].username)checkQuery=new UsergridQuery("users").eq("username",args[0].username);else{if(!args[0].email)throw new Error("'username' or 'email' property is required when checking for available users");checkQuery=new UsergridQuery("users").eq("email",args[0].email)}client.GET(checkQuery,function(usergridResponse){callback(usergridResponse,usergridResponse.entities.length>0)})},UsergridHelpers.inherits(UsergridUser,UsergridEntity),UsergridUser.prototype.uniqueId=function(){var self=this;return _.first([self.uuid,self.username,self.email].filter(_.isString))},UsergridUser.prototype.create=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.POST(self,function(usergridResponse){delete self.password,_.assign(self,usergridResponse.user),callback(usergridResponse,usergridResponse.user)}.bind(self))},UsergridUser.prototype.login=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.POST("token",UsergridHelpers.userLoginBody(self),function(usergridResponse){if(delete self.password,usergridResponse.ok){var responseJSON=usergridResponse.responseJSON;self.auth=new UsergridUserAuth(self),self.auth.token=_.get(responseJSON,"access_token");var expiresIn=_.get(responseJSON,"expires_in");self.auth.expiry=UsergridHelpers.calculateExpiry(expiresIn),self.auth.tokenTtl=expiresIn}callback(self.auth,self,usergridResponse)})},UsergridUser.prototype.logout=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(self.auth&&self.auth.isValid){var revokeAll=_.first(args.filter(_.isBoolean))||!1,queryParams=void 0;revokeAll||(queryParams={token:self.auth.token});var requestOptions={client:client,path:["users",self.uniqueId(),"revoketoken"+(revokeAll?"s":"")].join("/"),method:UsergridHttpMethod.PUT,queryParams:queryParams,callback:function(usergridResponse){self.auth.destroy(),callback(usergridResponse)}.bind(self)},request=new UsergridRequest(requestOptions);client.sendRequest(request)}else{var response=new UsergridResponse.responseWithError({name:"no_valid_token",description:"this user does not have a valid token"});callback(response)}},UsergridUser.prototype.logoutAllSessions=function(){var args=UsergridHelpers.flattenArgs(arguments);return args=_.concat([UsergridHelpers.validateAndRetrieveClient(args),!0],args),this.logout.apply(this,args)},UsergridUser.prototype.resetPassword=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);args[0]instanceof UsergridClient&&args.shift();var body={oldpassword:_.isPlainObject(args[0])?args[0].oldPassword:_.isString(args[0])?args[0]:void 0,newpassword:_.isPlainObject(args[0])?args[0].newPassword:_.isString(args[1])?args[1]:void 0};if(!body.oldpassword||!body.newpassword)throw new Error('"oldPassword" and "newPassword" properties are required when resetting a user password');client.PUT(["users",self.uniqueId(),"password"].join("/"),body,callback)};var UsergridResponseError=function(options){var self=this;return _.assign(self,options),self};UsergridResponseError.fromJSON=function(responseErrorObject){var usergridResponseError=void 0,error={name:_.get(responseErrorObject,"error")};return void 0!==error.name&&(_.assign(error,{exception:_.get(responseErrorObject,"exception"),description:_.get(responseErrorObject,"error_description")||_.get(responseErrorObject,"description")}),usergridResponseError=new UsergridResponseError(error)),usergridResponseError};var UsergridResponse=function(xmlRequest,usergridRequest){var self=this;if(self.ok=!1,self.request=usergridRequest,xmlRequest){self.statusCode=parseInt(xmlRequest.status),self.ok=self.statusCode<400,self.headers=UsergridHelpers.parseResponseHeaders(xmlRequest.getAllResponseHeaders());var responseContentType=_.get(self.headers,"content-type");if("application/json"===responseContentType){try{var responseJSON=JSON.parse(xmlRequest.responseText)}catch(e){responseJSON={}}self.parseResponseJSON(responseJSON),Object.defineProperty(self,"cursor",{get:function(){return _.get(self,"responseJSON.cursor")}}),Object.defineProperty(self,"hasNextPage",{get:function(){return void 0!==self.cursor}})}else self.asset=new UsergridAsset(xmlRequest.response)}return self};UsergridResponse.responseWithError=function(options){var usergridResponse=new UsergridResponse;return usergridResponse.error=new UsergridResponseError(options),usergridResponse},UsergridResponse.prototype={parseResponseJSON:function(responseJSON){var self=this;if(void 0!==responseJSON)if(_.assign(self,{responseJSON:_.cloneDeep(responseJSON)}),self.ok){var entitiesJSON=_.get(responseJSON,"entities");if(entitiesJSON){var entities=_.map(entitiesJSON,function(entityJSON){var entity=new UsergridEntity(entityJSON);return entity.isUser&&(entity=new UsergridUser(entity)),entity});_.assign(self,{entities:entities}),delete self.responseJSON.entities,self.first=_.first(entities)||void 0,self.entity=self.first,self.last=_.last(entities)||void 0,"/users"===_.get(responseJSON,"path")&&(self.user=self.first,self.users=self.entities),UsergridHelpers.setReadOnly(self.responseJSON)}}else self.error=UsergridResponseError.fromJSON(responseJSON)},loadNextPage:function(){var self=this,cursor=self.cursor;if(cursor){var args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args),client=UsergridHelpers.validateAndRetrieveClient(args),type=_.last(_.get(self,"responseJSON.path").split("/")),limit=_.first(_.get(self,"responseJSON.params.limit")),ql=_.first(_.get(self,"responseJSON.params.ql")),query=new UsergridQuery(type).fromString(ql).cursor(cursor).limit(limit);client.GET(query,callback)}else callback(UsergridResponse.responseWithError({name:"cursor_not_found",description:"Cursor must be present in order perform loadNextPage()."}))}};var UsergridAssetDefaultFileName="file",UsergridAsset=function(fileOrBlob){if(!fileOrBlob instanceof File||!fileOrBlob instanceof Blob)throw new Error("UsergridAsset must be initialized with a 'File' or 'Blob'");var self=this;return self.data=fileOrBlob,self.filename=fileOrBlob.name||UsergridAssetDefaultFileName,self.contentLength=fileOrBlob.size,self.contentType=fileOrBlob.type,self}; \ No newline at end of file From 729d0649092cc45817cd0abe26f78fed9fa0c15a Mon Sep 17 00:00:00 2001 From: Robert Walsh Date: Thu, 13 Oct 2016 18:13:30 -0500 Subject: [PATCH 29/36] Updated all callbacks. All callback now match the NodeJS SDK callbacks. The biggest change was that the callback functions all begin with the first parameter being the error of the call (if one exists). --- lib/modules/UsergridClient.js | 21 +++---- lib/modules/UsergridEntity.js | 16 +++--- lib/modules/UsergridRequest.js | 6 +- lib/modules/UsergridUser.js | 27 +++++---- tests/mocha/test_asset.js | 16 +++--- tests/mocha/test_client_auth.js | 48 ++++++++-------- tests/mocha/test_client_connections.js | 42 +++++++------- tests/mocha/test_client_rest.js | 76 +++++++++++++------------- tests/mocha/test_entity.js | 52 +++++++++--------- tests/mocha/test_response.js | 22 ++++---- tests/mocha/test_response_error.js | 4 +- tests/mocha/test_user.js | 40 +++++++------- usergrid.js | 68 +++++++++++------------ usergrid.min.js | 4 +- 14 files changed, 222 insertions(+), 220 deletions(-) diff --git a/lib/modules/UsergridClient.js b/lib/modules/UsergridClient.js index 870d8d2..c29eeac 100644 --- a/lib/modules/UsergridClient.js +++ b/lib/modules/UsergridClient.js @@ -120,17 +120,18 @@ UsergridClient.prototype = { throw new Error('authenticateApp() failed because clientId or clientSecret are missing'); } - var callback = function(usergridResponse) { + var callback = function(error,usergridResponse) { + var token = _.get(usergridResponse.responseJSON,'access_token'); + var expiresIn = _.get(usergridResponse.responseJSON,'expires_in'); if (usergridResponse.ok) { if (!self.appAuth) { self.appAuth = auth; } - self.appAuth.token = _.get(usergridResponse.responseJSON,'access_token'); - var expiresIn = _.get(usergridResponse.responseJSON,'expires_in'); + self.appAuth.token = token; self.appAuth.expiry = UsergridHelpers.calculateExpiry(expiresIn); self.appAuth.tokenTtl = expiresIn; } - authenticateAppCallback(usergridResponse); + authenticateAppCallback(error,usergridResponse,token); }; var usergridRequest = UsergridHelpers.buildAppAuthRequest(self,auth,callback); @@ -143,11 +144,11 @@ UsergridClient.prototype = { var setAsCurrentUser = (_.last(args.filter(_.isBoolean))) !== undefined ? _.last(args.filter(_.isBoolean)) : true; var userToAuthenticate = new UsergridUser(options); - userToAuthenticate.login(self, function(auth, user, usergridResponse) { + userToAuthenticate.login(self, function(error, usergridResponse, token) { if (usergridResponse.ok && setAsCurrentUser) { self.currentUser = userToAuthenticate; } - callback(auth,user,usergridResponse); + callback(usergridResponse.error,usergridResponse,token); }) }, downloadAsset: function() { @@ -158,10 +159,10 @@ UsergridClient.prototype = { _.assign(usergridRequest.headers,{"Accept":assetContentType}); } var realDownloadAssetCallback = usergridRequest.callback; - usergridRequest.callback = function (usergridResponse) { + usergridRequest.callback = function (error,usergridResponse) { var entity = usergridRequest.entity; entity.asset = usergridResponse.asset; - realDownloadAssetCallback(entity.asset,usergridResponse,entity); + realDownloadAssetCallback(error,usergridResponse,entity); }; return self.sendRequest(usergridRequest); }, @@ -173,7 +174,7 @@ UsergridClient.prototype = { } var realUploadAssetCallback = usergridRequest.callback; - usergridRequest.callback = function (usergridResponse) { + usergridRequest.callback = function (error,usergridResponse) { var requestEntity = usergridRequest.entity; var responseEntity = usergridResponse.entity; var requestAsset = usergridRequest.asset; @@ -185,7 +186,7 @@ UsergridClient.prototype = { responseEntity.asset = requestAsset; } } - realUploadAssetCallback(requestAsset,usergridResponse,requestEntity); + realUploadAssetCallback(error,usergridResponse,requestEntity); }; return self.sendRequest(usergridRequest); } diff --git a/lib/modules/UsergridEntity.js b/lib/modules/UsergridEntity.js index c99e8ae..7777803 100644 --- a/lib/modules/UsergridEntity.js +++ b/lib/modules/UsergridEntity.js @@ -107,9 +107,9 @@ UsergridEntity.prototype = { var client = UsergridHelpers.validateAndRetrieveClient(args); var callback = UsergridHelpers.callback(args); - client.GET(self, function(usergridResponse) { + client.GET(self, function(error,usergridResponse) { UsergridHelpers.updateEntityFromRemote(self, usergridResponse); - callback(usergridResponse,self); + callback(error,usergridResponse,self); }.bind(self)); }, save: function() { @@ -118,12 +118,12 @@ UsergridEntity.prototype = { var client = UsergridHelpers.validateAndRetrieveClient(args); var callback = UsergridHelpers.callback(args); var currentAsset = self.asset; - client.PUT(self, function(usergridResponse) { + client.PUT(self, function(error,usergridResponse) { UsergridHelpers.updateEntityFromRemote(self, usergridResponse); if( self.hasAsset ) { self.asset = currentAsset; } - callback(usergridResponse,self); + callback(error,usergridResponse,self); }.bind(self)); }, remove: function() { @@ -132,8 +132,8 @@ UsergridEntity.prototype = { var client = UsergridHelpers.validateAndRetrieveClient(args); var callback = UsergridHelpers.callback(args); - client.DELETE(self, function(usergridResponse) { - callback(usergridResponse,self); + client.DELETE(self, function(error,usergridResponse) { + callback(error,usergridResponse,self); }.bind(self)); }, attachAsset: function(asset) { @@ -153,7 +153,7 @@ UsergridEntity.prototype = { name: 'asset_not_found', description: 'The specified entity does not have a valid asset attached' }); - callback(null,response,self); + callback(response.error,response,self); } }, downloadAsset: function() { @@ -170,7 +170,7 @@ UsergridEntity.prototype = { name: 'asset_not_found', description: 'The specified entity does not have a valid asset attached' }); - callback(null,response,self); + callback(response.error,response,self); } }, connect: function() { diff --git a/lib/modules/UsergridRequest.js b/lib/modules/UsergridRequest.js index 1cae541..09723d0 100644 --- a/lib/modules/UsergridRequest.js +++ b/lib/modules/UsergridRequest.js @@ -96,10 +96,8 @@ UsergridRequest.prototype.sendRequest = function() { return promise; }; - var onCompletePromise = function(response) { - var promise = new Promise(); - promise.done(response); - self.callback(response); + var onCompletePromise = function(usergridResponse) { + self.callback(usergridResponse.error,usergridResponse); }; Promise.chain([requestPromise, responsePromise]).then(onCompletePromise); diff --git a/lib/modules/UsergridUser.js b/lib/modules/UsergridUser.js index 13f5ee3..468cd17 100644 --- a/lib/modules/UsergridUser.js +++ b/lib/modules/UsergridUser.js @@ -49,8 +49,8 @@ UsergridUser.CheckAvailable = function() { throw new Error("'username' or 'email' property is required when checking for available users"); } - client.GET(checkQuery, function(usergridResponse) { - callback(usergridResponse, usergridResponse.entities.length > 0); + client.GET(checkQuery, function(error,usergridResponse) { + callback(error, usergridResponse, usergridResponse.entities.length > 0); }) }; UsergridHelpers.inherits(UsergridUser, UsergridEntity); @@ -66,10 +66,10 @@ UsergridUser.prototype.create = function() { var client = UsergridHelpers.validateAndRetrieveClient(args); var callback = UsergridHelpers.callback(args); - client.POST(self, function(usergridResponse) { + client.POST(self, function(error,usergridResponse) { delete self.password; _.assign(self, usergridResponse.user); - callback(usergridResponse, usergridResponse.user); + callback(error, usergridResponse, self); }.bind(self)); }; @@ -79,17 +79,20 @@ UsergridUser.prototype.login = function() { var client = UsergridHelpers.validateAndRetrieveClient(args); var callback = UsergridHelpers.callback(args); - client.POST('token', UsergridHelpers.userLoginBody(self), function (usergridResponse) { + client.POST('token', UsergridHelpers.userLoginBody(self), function (error,usergridResponse) { delete self.password; + + var responseJSON = usergridResponse.responseJSON; + var token = _.get(responseJSON,'access_token'); + var expiresIn = _.get(responseJSON,'expires_in'); + if (usergridResponse.ok) { - var responseJSON = usergridResponse.responseJSON; self.auth = new UsergridUserAuth(self); - self.auth.token = _.get(responseJSON,'access_token'); - var expiresIn = _.get(responseJSON,'expires_in'); + self.auth.token = token; self.auth.expiry = UsergridHelpers.calculateExpiry(expiresIn); self.auth.tokenTtl = expiresIn; } - callback(self.auth,self,usergridResponse); + callback(error,usergridResponse,token); }); }; @@ -104,7 +107,7 @@ UsergridUser.prototype.logout = function() { name: 'no_valid_token', description: 'this user does not have a valid token' }); - callback(response); + callback(response.error,response); } else { var revokeAll = _.first(args.filter(_.isBoolean)) || false; var queryParams = undefined; @@ -117,9 +120,9 @@ UsergridUser.prototype.logout = function() { path: ['users', self.uniqueId(), ('revoketoken' + ((revokeAll) ? "s" : ""))].join('/'), method: UsergridHttpMethod.PUT, queryParams: queryParams, - callback: function (usergridResponse) { + callback: function (error,usergridResponse) { self.auth.destroy(); - callback(usergridResponse); + callback(error,usergridResponse,usergridResponse.ok); }.bind(self) }; var request = new UsergridRequest(requestOptions); diff --git a/tests/mocha/test_asset.js b/tests/mocha/test_asset.js index a8b4bea..80c7507 100644 --- a/tests/mocha/test_asset.js +++ b/tests/mocha/test_asset.js @@ -47,14 +47,14 @@ configs.forEach(function(config) { }); before(function (done) { - entity.save(client, function (response) { + entity.save(client, function (error,response) { response.ok.should.be.true(); entity.should.have.property('uuid'); done() }) }); after(function (done) { - entity.remove(client, function (response) { + entity.remove(client, function (error,response) { response.ok.should.be.true(); entity.uuid.should.be.equal(response.entity.uuid); entity.name.should.be.equal(response.entity.name); @@ -62,7 +62,7 @@ configs.forEach(function(config) { }) }); it('should upload a binary asset to an entity', function (done) { - client.uploadAsset(entity, asset, function (asset, assetResponse, entityWithAsset) { + client.uploadAsset(entity, asset, function (error, assetResponse, entityWithAsset) { assetResponse.statusCode.should.equal(200); entityWithAsset.uuid.should.be.equal(entity.uuid); entityWithAsset.name.should.be.equal(entity.name); @@ -81,7 +81,7 @@ configs.forEach(function(config) { }); before(function (done) { - entity.save(client, function (response) { + entity.save(client, function (error,response) { response.ok.should.be.true(); entity.should.have.property('uuid'); done() @@ -90,7 +90,7 @@ configs.forEach(function(config) { after(function (done) { - entity.remove(client, function (response) { + entity.remove(client, function (error,response) { response.ok.should.be.true(); entity.uuid.should.be.equal(response.entity.uuid); entity.name.should.be.equal(response.entity.name); @@ -101,8 +101,8 @@ configs.forEach(function(config) { it('should upload a binary asset to an existing entity', function (done) { entity.attachAsset(asset); - entity.save(client, function (response) { - entity.uploadAsset(client, function (asset, assetResponse, entityWithAsset) { + entity.save(client, function () { + entity.uploadAsset(client, function (error, assetResponse, entityWithAsset) { assetResponse.statusCode.should.equal(200); entityWithAsset.uuid.should.be.equal(entity.uuid); entityWithAsset.name.should.be.equal(entity.name); @@ -114,7 +114,7 @@ configs.forEach(function(config) { }) }); it('should download a binary asset to an existing entity', function (done) { - entity.downloadAsset(client, function (asset, assetResponse, entityWithAsset) { + entity.downloadAsset(client, function (error, assetResponse, entityWithAsset) { assetResponse.statusCode.should.equal(200); entityWithAsset.uuid.should.be.equal(entity.uuid); entityWithAsset.name.should.be.equal(entity.name); diff --git a/tests/mocha/test_client_auth.js b/tests/mocha/test_client_auth.js index f883b71..6c2689f 100644 --- a/tests/mocha/test_client_auth.js +++ b/tests/mocha/test_client_auth.js @@ -17,10 +17,10 @@ configs.forEach(function(config) { before(function (done) { // authenticate app and remove sandbox permissions client.setAppAuth(config.clientId, config.clientSecret); - client.authenticateApp(function (response) { + client.authenticateApp(function () { token = client.appAuth.token; var permissionsQuery = new UsergridQuery('roles/guest/permissions').urlTerm('permission', 'get,post,put,delete:/**'); - client.usingAuth(client.appAuth).DELETE(permissionsQuery, function (response) { + client.usingAuth(client.appAuth).DELETE(permissionsQuery, function () { done() }) }) @@ -28,7 +28,7 @@ configs.forEach(function(config) { it('should fall back to using no authentication when currentUser is not authenticated and authFallback is set to NONE', function (done) { client.authMode = UsergridAuthMode.NONE; - client.GET('users', function (usergridResponse) { + client.GET('users', function (error,usergridResponse) { should(client.currentUser).be.undefined(); usergridResponse.request.headers.should.not.have.property('authorization'); usergridResponse.error.name.should.equal('unauthorized'); @@ -39,7 +39,7 @@ configs.forEach(function(config) { it('should fall back to using the app token when currentUser is not authenticated and authFallback is set to APP', function (done) { client.authMode = UsergridAuthMode.APP; - client.GET('users', function (usergridResponse) { + client.GET('users', function (error,usergridResponse) { should(client.currentUser).be.undefined(); usergridResponse.request.headers.should.have.property('authorization').equal('Bearer ' + token); usergridResponse.ok.should.be.true(); @@ -50,7 +50,7 @@ configs.forEach(function(config) { after(function (done) { client.authMode = UsergridAuthMode.NONE; - client.usingAuth(client.appAuth).POST('roles/guest/permissions', {'permission': 'get,post,put,delete:/**'}, function (usergridResponse) { + client.usingAuth(client.appAuth).POST('roles/guest/permissions', {'permission': 'get,post,put,delete:/**'}, function () { done() }) }) @@ -61,7 +61,7 @@ configs.forEach(function(config) { var response, token, client = getClient(); before(function (done) { client.setAppAuth(config.clientId, config.clientSecret); - client.authenticateApp(function (usergridResponse) { + client.authenticateApp(function (error,usergridResponse) { response = usergridResponse; token = client.appAuth.token; done() @@ -106,7 +106,7 @@ configs.forEach(function(config) { isolatedClient.authenticateApp({ clientId: config.clientId, clientSecret: config.clientSecret - }, function (reponse) { + }, function () { isolatedClient.appAuth.should.have.property('token'); done() }) @@ -120,7 +120,7 @@ configs.forEach(function(config) { }); var ttlInMilliseconds = 500000; var appAuth = new UsergridAppAuth(config.clientId, config.clientSecret, ttlInMilliseconds); - isolatedClient.authenticateApp(appAuth, function (response) { + isolatedClient.authenticateApp(appAuth, function (error,response) { isolatedClient.appAuth.should.have.property('token'); response.responseJSON.expires_in.should.equal(ttlInMilliseconds / 1000); done() @@ -132,8 +132,8 @@ configs.forEach(function(config) { failClient.authenticateApp({ clientId: 'BADCLIENTID', clientSecret: 'BADCLIENTSECRET' - }, function (response) { - response.error.should.containDeep({ + }, function (error,response) { + error.should.containDeep({ name: 'invalid_grant', description: 'invalid username or password' }); @@ -147,8 +147,8 @@ configs.forEach(function(config) { failClient.authenticateApp(new UsergridAppAuth({ clientId: 'BADCLIENTID', clientSecret: 'BADCLIENTSECRET' - }), function (response) { - response.error.should.containDeep({ + }), function (error,response) { + error.should.containDeep({ name: 'invalid_grant', description: 'invalid username or password' }); @@ -160,8 +160,8 @@ configs.forEach(function(config) { it('should not set client.appAuth when authenticating with a bad UsergridAppAuth instance (using arguments)', function (done) { var failClient = new UsergridClient({orgId: config.orgId, appId: config.appId, baseUrl: config.baseUrl}); - failClient.authenticateApp(new UsergridAppAuth('BADCLIENTID', 'BADCLIENTSECRET'), function (response) { - response.error.should.containDeep({ + failClient.authenticateApp(new UsergridAppAuth('BADCLIENTID', 'BADCLIENTSECRET'), function (error,response) { + error.should.containDeep({ name: 'invalid_grant', description: 'invalid username or password' }); @@ -180,9 +180,9 @@ configs.forEach(function(config) { username: config.test.username, password: config.test.password, email: email - }, function (auth, user, usergridResponse) { + }, function (error, usergridResponse, authToken) { response = usergridResponse; - token = auth.token; + token = authToken done() }) }); @@ -239,7 +239,7 @@ configs.forEach(function(config) { username: config.test.username, password: config.test.password, email: config.test.email - }, false, function (response) { + }, false, function (error,response) { should(noCurrentUserClient.currentUser).be.undefined(); done() }) @@ -249,9 +249,9 @@ configs.forEach(function(config) { var newClient = new UsergridClient({orgId: config.orgId, appId: config.appId, baseUrl: config.baseUrl}); var ttlInMilliseconds = 500000; var userAuth = new UsergridUserAuth(config.test.username, config.test.password, ttlInMilliseconds); - newClient.authenticateUser(userAuth, function (auth, user, usergridResponse) { + newClient.authenticateUser(userAuth, function (error, usergridResponse, authToken) { usergridResponse.ok.should.be.true(); - newClient.currentUser.auth.token.should.equal(auth.token); + newClient.currentUser.auth.token.should.equal(authToken); usergridResponse.responseJSON.expires_in.should.equal(ttlInMilliseconds / 1000); done() }) @@ -299,8 +299,8 @@ configs.forEach(function(config) { client.authenticateUser({ username: config.test.username, password: config.test.password - }, function (auth, user, response) { - authFromToken = new UsergridAuth(auth.token); + }, function (error, response, token) { + authFromToken = new UsergridAuth(token); done() }) }); @@ -308,7 +308,7 @@ configs.forEach(function(config) { it('should authenticate using an ad-hoc token', function (done) { authFromToken.isValid.should.be.true(); authFromToken.should.have.property('token'); - client.usingAuth(authFromToken).GET('/users/me', function (usergridResponse) { + client.usingAuth(authFromToken).GET('/users/me', function (error,usergridResponse) { usergridResponse.ok.should.be.true(); usergridResponse.should.have.property('user').which.is.an.instanceof(UsergridUser); usergridResponse.user.should.have.property('uuid'); @@ -323,7 +323,7 @@ configs.forEach(function(config) { it('should send an unauthenticated request when UsergridAuth.NO_AUTH is passed to .usingAuth()', function (done) { client.authMode = UsergridAuthMode.NONE; - client.GET('/users/me', function (usergridResponse) { + client.GET('/users/me', function (error,usergridResponse) { usergridResponse.ok.should.be.false(); usergridResponse.request.headers.should.not.have.property('authentication'); usergridResponse.should.not.have.property('user'); @@ -332,7 +332,7 @@ configs.forEach(function(config) { }); it('should send an unauthenticated request when no arguments are passed to .usingAuth()', function (done) { - client.usingAuth().GET('/users/me', function (usergridResponse) { + client.usingAuth().GET('/users/me', function (error,usergridResponse) { usergridResponse.ok.should.be.false(); usergridResponse.request.headers.should.not.have.property('authentication'); usergridResponse.should.not.have.property('user'); diff --git a/tests/mocha/test_client_connections.js b/tests/mocha/test_client_connections.js index 8901179..2a450ed 100644 --- a/tests/mocha/test_client_connections.js +++ b/tests/mocha/test_client_connections.js @@ -17,7 +17,7 @@ configs.forEach(function(config) { client.POST({ type: config.test.collection, body: [{"name": "testClientConnectOne"}, {"name": "testClientConnectTwo"}] - }, function (postResponse) { + }, function (error,postResponse) { response = postResponse; entity1 = response.first; entity2 = response.last; @@ -38,9 +38,9 @@ configs.forEach(function(config) { it('should connect entities by passing UsergridEntity objects as parameters', function (done) { var relationship = "foos"; - client.connect(entity1, relationship, entity2, function (usergridResponse) { + client.connect(entity1, relationship, entity2, function (error,usergridResponse) { usergridResponse.ok.should.be.true(); - client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (error,usergridResponse) { usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( "/", config.test.collection, @@ -58,9 +58,9 @@ configs.forEach(function(config) { it('should connect entities by passing a source UsergridEntity object and a target uuid', function (done) { var relationship = "bars"; - client.connect(entity1, relationship, entity2.uuid, function (usergridResponse) { + client.connect(entity1, relationship, entity2.uuid, function (error,usergridResponse) { usergridResponse.ok.should.be.true(); - client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (error,usergridResponse) { usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( "/", config.test.collection, @@ -78,9 +78,9 @@ configs.forEach(function(config) { it('should connect entities by passing source type, source uuid, and target uuid as parameters', function (done) { var relationship = "bazzes"; - client.connect(entity1.type, entity1.uuid, relationship, entity2.uuid, function (usergridResponse) { + client.connect(entity1.type, entity1.uuid, relationship, entity2.uuid, function (error,usergridResponse) { usergridResponse.ok.should.be.true(); - client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (error,usergridResponse) { usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( "/", config.test.collection, @@ -98,9 +98,9 @@ configs.forEach(function(config) { it('should connect entities by passing source type, source name, target type, and target name as parameters', function (done) { var relationship = "quxes"; - client.connect(entity1.type, entity1.name, relationship, entity2.type, entity2.name, function (usergridResponse) { + client.connect(entity1.type, entity1.name, relationship, entity2.type, entity2.name, function (error,usergridResponse) { usergridResponse.ok.should.be.true(); - client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (error,usergridResponse) { usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( "/", config.test.collection, @@ -122,9 +122,9 @@ configs.forEach(function(config) { to: entity2 }; - client.connect(options, function (usergridResponse) { + client.connect(options, function (error,usergridResponse) { usergridResponse.ok.should.be.true(); - client.getConnections(UsergridDirection.OUT, entity1, options.relationship, function (usergridResponse) { + client.getConnections(UsergridDirection.OUT, entity1, options.relationship, function (error,usergridResponse) { usergridResponse.first.metadata.connecting[options.relationship].should.equal(UsergridHelpers.urljoin( "/", config.test.collection, @@ -153,7 +153,7 @@ configs.forEach(function(config) { var relationship = "foos"; - client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (error,usergridResponse) { usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( "/", config.test.collection, @@ -171,7 +171,7 @@ configs.forEach(function(config) { var relationship = "foos"; - client.getConnections(UsergridDirection.IN, entity2, relationship, function (usergridResponse) { + client.getConnections(UsergridDirection.IN, entity2, relationship, function (error,usergridResponse) { usergridResponse.first.metadata.connections[relationship].should.equal(UsergridHelpers.urljoin( "/", config.test.collection, @@ -191,9 +191,9 @@ configs.forEach(function(config) { var relationship = "foos"; - client.disconnect(entity1, relationship, entity2, function (usergridResponse) { + client.disconnect(entity1, relationship, entity2, function (error,usergridResponse) { usergridResponse.ok.should.be.true(); - client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (error,usergridResponse) { usergridResponse.entities.should.be.an.Array().with.lengthOf(0); done() }) @@ -204,9 +204,9 @@ configs.forEach(function(config) { var relationship = "bars"; - client.disconnect(entity1.type, entity1.uuid, relationship, entity2.uuid, function (usergridResponse) { + client.disconnect(entity1.type, entity1.uuid, relationship, entity2.uuid, function (error,usergridResponse) { usergridResponse.ok.should.be.true(); - client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (error,usergridResponse) { usergridResponse.entities.should.be.an.Array().with.lengthOf(0); done() }) @@ -217,9 +217,9 @@ configs.forEach(function(config) { var relationship = "bazzes"; - client.disconnect(entity1.type, entity1.name, relationship, entity2.type, entity2.name, function (usergridResponse) { + client.disconnect(entity1.type, entity1.name, relationship, entity2.type, entity2.name, function (error,usergridResponse) { usergridResponse.ok.should.be.true(); - client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (error,usergridResponse) { usergridResponse.entities.should.be.an.Array().with.lengthOf(0); done() }) @@ -234,9 +234,9 @@ configs.forEach(function(config) { to: entity2 }; - client.disconnect(options, function (usergridResponse) { + client.disconnect(options, function (error,usergridResponse) { usergridResponse.ok.should.be.true(); - client.getConnections(UsergridDirection.OUT, entity1, options.relationship, function (usergridResponse) { + client.getConnections(UsergridDirection.OUT, entity1, options.relationship, function (error,usergridResponse) { usergridResponse.entities.should.be.an.Array().with.lengthOf(0); done() }) diff --git a/tests/mocha/test_client_rest.js b/tests/mocha/test_client_rest.js index 49b16e6..a4696ab 100644 --- a/tests/mocha/test_client_rest.js +++ b/tests/mocha/test_client_rest.js @@ -18,7 +18,7 @@ configs.forEach(function(config) { type: config.test.collection, body: { author: 'Sir Arthur Conan Doyle' } - }, function (usergridResponse) { + }, function (error,usergridResponse) { response = usergridResponse; _uuid = usergridResponse.entity.uuid; done() @@ -54,10 +54,10 @@ configs.forEach(function(config) { cuisine: "pizza" }); - client.POST(entity, function (usergridResponse) { + client.POST(entity, function (error,usergridResponse) { usergridResponse.entity.should.be.an.Object().with.property('restaurant').equal(entity.restaurant); sleepFor(config.defaultSleepTime); - client.DELETE(usergridResponse.entity, function (delResponse) { + client.DELETE(usergridResponse.entity, function (error,delResponse) { delResponse.entity.should.have.property('uuid').equal(usergridResponse.entity.uuid); done() }) @@ -69,10 +69,10 @@ configs.forEach(function(config) { type: config.test.collection, name: randomWord() }); - client.POST(entity, function (usergridResponse) { + client.POST(entity, function (error,usergridResponse) { usergridResponse.entity.should.be.an.Object().with.property('name').equal(entity.name); sleepFor(config.defaultSleepTime); - client.DELETE(usergridResponse.entity, function (delResponse) { + client.DELETE(usergridResponse.entity, function (error,delResponse) { delResponse.entity.should.have.property('uuid').equal(usergridResponse.entity.uuid); done() }) @@ -87,10 +87,10 @@ configs.forEach(function(config) { cuisine: "pizza" } }; - client.POST(options, function (usergridResponse) { + client.POST(options, function (error,usergridResponse) { usergridResponse.entity.should.be.an.Object().with.property('restaurant').equal("Dino's Deep Dish"); sleepFor(config.defaultSleepTime); - client.DELETE(usergridResponse.entity, function (delResponse) { + client.DELETE(usergridResponse.entity, function (error,delResponse) { delResponse.entity.should.have.property('uuid').equal(usergridResponse.entity.uuid); done() }) @@ -105,10 +105,10 @@ configs.forEach(function(config) { cuisine: "pizza" } }; - client.POST(options, function (usergridResponse) { + client.POST(options, function (error,usergridResponse) { usergridResponse.entity.should.be.an.Object().with.property('restaurant').equal("Dino's Deep Dish"); sleepFor(config.defaultSleepTime); - client.DELETE(usergridResponse.entity, function (delResponse) { + client.DELETE(usergridResponse.entity, function (error,delResponse) { delResponse.entity.should.have.property('uuid').equal(usergridResponse.entity.uuid); done() }) @@ -129,7 +129,7 @@ configs.forEach(function(config) { ]; client.POST({ - body: entities, callback: function (usergridResponse) { + body: entities, callback: function (error,usergridResponse) { usergridResponse.entities.should.be.an.Array().with.lengthOf(2); _.forEach(usergridResponse.entities, function (entity) { entity.should.be.an.Object().with.property('restaurant').equal(entity.restaurant) @@ -148,9 +148,9 @@ configs.forEach(function(config) { } }; - client.POST(options, function (usergridResponse) { + client.POST(options, function (error,usergridResponse) { usergridResponse.entity.should.be.an.Object().with.property('restaurant').equal(usergridResponse.entity.restaurant); - usergridResponse.entity.remove(client, function (delResponse) { + usergridResponse.entity.remove(client, function (error,delResponse) { delResponse.entity.should.have.property('uuid').equal(usergridResponse.entity.uuid); done() }) @@ -162,7 +162,7 @@ configs.forEach(function(config) { var response; before(function (done) { - client.GET({type: config.test.collection}, function (usergridResponse) { + client.GET({type: config.test.collection}, function (error,usergridResponse) { response = usergridResponse; done() }) @@ -195,7 +195,7 @@ configs.forEach(function(config) { it('each entity should match the search criteria when passing a UsergridQuery object', function (done) { var query = new UsergridQuery(config.test.collection).eq('author', 'Sir Arthur Conan Doyle'); - client.GET(query, function (usergridResponse) { + client.GET(query, function (error,usergridResponse) { usergridResponse.entities.should.be.an.Array().with.lengthOf(1); usergridResponse.entities.forEach(function (entity) { entity.should.be.an.Object().with.property('author').equal('Sir Arthur Conan Doyle') @@ -205,7 +205,7 @@ configs.forEach(function(config) { }); it('a single entity should be retrieved when specifying a uuid', function (done) { - client.GET(config.test.collection, response.entity.uuid, function (usergridResponse) { + client.GET(config.test.collection, response.entity.uuid, function (error,usergridResponse) { usergridResponse.should.have.property('entity').which.is.an.instanceof(UsergridEntity); usergridResponse.entities.should.be.an.Array().with.a.lengthOf(1); done() @@ -218,13 +218,13 @@ configs.forEach(function(config) { var response; before(function (done) { - client.PUT(config.test.collection, _uuid, {narrator: 'Peter Doyle'}, function (usergridResponse) { + client.PUT(config.test.collection, _uuid, {narrator: 'Peter Doyle'}, function (error,usergridResponse) { response = usergridResponse; done() }) }); after(function (done) { - client.DELETE(response.entity, function (delResponse) { + client.DELETE(response.entity, function (error,delResponse) { delResponse.entity.should.have.property('uuid').equal(response.entity.uuid); done() }) @@ -257,13 +257,13 @@ configs.forEach(function(config) { author: 'Frank Mills' }); - client.PUT(newEntity, function (usergridResponse) { + client.PUT(newEntity, function (error,usergridResponse) { usergridResponse.entity.should.be.an.Object(); usergridResponse.entity.should.be.an.instanceof(UsergridEntity).with.property('uuid')//.which.is.a.uuid() usergridResponse.entity.should.have.property('author').equal('Frank Mills'); usergridResponse.entity.created.should.equal(usergridResponse.entity.modified); sleepFor(config.defaultSleepTime); - client.DELETE(usergridResponse.entity, function (delResponse) { + client.DELETE(usergridResponse.entity, function (error,delResponse) { delResponse.entity.should.be.an.Object(); delResponse.entity.should.have.property('uuid').equal(usergridResponse.entity.uuid); done() @@ -281,7 +281,7 @@ configs.forEach(function(config) { } }); - client.PUT(updateEntity, function (usergridResponse) { + client.PUT(updateEntity, function (error,usergridResponse) { usergridResponse.entity.should.be.an.Object().with.property('publisher').deepEqual(updateEntity.publisher); done() }) @@ -296,7 +296,7 @@ configs.forEach(function(config) { updateByPassingTypeAndBody: true } }; - client.PUT(options, function (usergridResponse) { + client.PUT(options, function (error,usergridResponse) { usergridResponse.entity.should.be.an.Object().with.property('updateByPassingTypeAndBody').equal(true); done() }) @@ -312,7 +312,7 @@ configs.forEach(function(config) { updateByPassingBodyIncludingType: true } }; - client.PUT(options, function (usergridResponse) { + client.PUT(options, function (error,usergridResponse) { usergridResponse.entity.should.be.an.Object().with.property('updateByPassingBodyIncludingType').equal(true); done() }) @@ -325,13 +325,13 @@ configs.forEach(function(config) { }; sleepFor(config.defaultSleepTime); - client.PUT(query, body, function (usergridResponse) { + client.PUT(query, body, function (error,usergridResponse) { usergridResponse.entities.should.be.an.Array().with.lengthOf(2); usergridResponse.entities.forEach(function (entity) { entity.should.be.an.Object().with.property('testUuid').equal(body.testUuid) }); sleepFor(config.defaultLongSleepTime + config.defaultSleepTime); - client.DELETE(query, function (delResponse) { + client.DELETE(query, function (error,delResponse) { delResponse.entities.should.be.an.Array().with.lengthOf(usergridResponse.entities.length); done() }) @@ -348,7 +348,7 @@ configs.forEach(function(config) { } }; - client.PUT(options, function (usergridResponse) { + client.PUT(options, function (error,usergridResponse) { usergridResponse.entity.should.be.an.Object().with.property('relatedUuid').equal(options.body.relatedUuid); done() }) @@ -360,7 +360,7 @@ configs.forEach(function(config) { var response; before(function (done) { client.DELETE(config.test.collection, _uuid, function () { - client.GET(config.test.collection, _uuid, function (usergridResponse) { + client.GET(config.test.collection, _uuid, function (error,usergridResponse) { response = usergridResponse; done() }) @@ -386,14 +386,14 @@ configs.forEach(function(config) { command: "CTRL+ALT+DEL" }); - client.POST(entity, function (postResponse) { + client.POST(entity, function (error,postResponse) { postResponse.entity.should.have.property('uuid'); postResponse.entity.should.have.property('command').equal('CTRL+ALT+DEL'); sleepFor(config.defaultSleepTime); - client.DELETE(postResponse.entity, function (delResponse) { + client.DELETE(postResponse.entity, function (error,delResponse) { delResponse.entity.should.have.property('uuid').equal(postResponse.entity.uuid); sleepFor(config.defaultSleepTime); - client.GET(config.test.collection, postResponse.entity.uuid, function (getResponse) { + client.GET(config.test.collection, postResponse.entity.uuid, function (error,getResponse) { getResponse.ok.should.be.false(); getResponse.error.name.should.equal((config.target === '1.0') ? 'service_resource_not_found' : 'entity_not_found'); done() @@ -407,14 +407,14 @@ configs.forEach(function(config) { command: "CTRL+ALT+DEL" }; - client.POST(config.test.collection, body, function (postResponse) { + client.POST(config.test.collection, body, function (error,postResponse) { postResponse.entity.should.have.property('uuid'); postResponse.entity.should.have.property('command').equal('CTRL+ALT+DEL'); sleepFor(config.defaultSleepTime); - client.DELETE(config.test.collection, postResponse.entity.uuid, function (delResponse) { + client.DELETE(config.test.collection, postResponse.entity.uuid, function (error,delResponse) { delResponse.entity.should.have.property('uuid').equal(postResponse.entity.uuid); sleepFor(config.defaultSleepTime); - client.GET(config.test.collection, postResponse.entity.uuid, function (getResponse) { + client.GET(config.test.collection, postResponse.entity.uuid, function (error,getResponse) { getResponse.error.name.should.equal((config.target === '1.0') ? 'service_resource_not_found' : 'entity_not_found'); done() }) @@ -431,13 +431,13 @@ configs.forEach(function(config) { var query = new UsergridQuery(config.test.collection).eq('command', 'CMD'); client.POST({ - body: [entity, entity, entity, entity], callback: function (postResponse) { + body: [entity, entity, entity, entity], callback: function (error,postResponse) { postResponse.entities.should.be.an.Array().with.lengthOf(4); sleepFor(config.defaultLongSleepTime); - client.DELETE(query, function (delResponse) { + client.DELETE(query, function (error,delResponse) { delResponse.entities.should.be.an.Array().with.lengthOf(4); sleepFor(config.defaultLongSleepTime); - client.GET(query, function (getResponse) { + client.GET(query, function (error,getResponse) { getResponse.entities.should.be.an.Array().with.lengthOf(0); done() }) @@ -455,15 +455,15 @@ configs.forEach(function(config) { } }; - client.POST(options, function (postResponse) { + client.POST(options, function (error,postResponse) { postResponse.entity.should.have.property('uuid'); postResponse.entity.should.have.property('restaurant').equal('IHOP'); postResponse.entity.should.have.property('cuisine').equal('breakfast'); sleepFor(config.defaultSleepTime); - client.DELETE(config.test.collection, postResponse.entity.uuid, function (delResponse) { + client.DELETE(config.test.collection, postResponse.entity.uuid, function (error,delResponse) { delResponse.entity.should.have.property('uuid').equal(postResponse.entity.uuid); sleepFor(config.defaultSleepTime); - client.GET(config.test.collection, postResponse.entity.uuid, function (delResponse) { + client.GET(config.test.collection, postResponse.entity.uuid, function (error,delResponse) { delResponse.error.name.should.equal((config.target === '1.0') ? 'service_resource_not_found' : 'entity_not_found'); done() }) diff --git a/tests/mocha/test_entity.js b/tests/mocha/test_entity.js index d5569ed..1e27da6 100644 --- a/tests/mocha/test_entity.js +++ b/tests/mocha/test_entity.js @@ -278,14 +278,14 @@ configs.forEach(function(config) { describe('save()', function () { it('should POST an entity without a uuid', function (done) { - entity.save(client, function (response) { + entity.save(client, function (error,response) { response.entity.should.have.property('uuid'); done() }) }); it('should PUT an entity without a uuid', function (done) { entity.putProperty('saveTest', now); - entity.save(client, function (response) { + entity.save(client, function (error,response) { response.entity.should.have.property('saveTest').equal(now); done() }) @@ -297,9 +297,9 @@ configs.forEach(function(config) { it('should refresh an entity with the latest server copy of itself', function (done) { var modified = entity.modified; entity.putProperty('reloadTest', now); - client.PUT(entity, function (putResponse) { + client.PUT(entity, function (error,putResponse) { entity.modified.should.equal(modified); - entity.reload(client, function (reloadResponse) { + entity.reload(client, function (error,reloadResponse) { entity.reloadTest.should.equal(now); entity.modified.should.not.equal(modified); done() @@ -311,7 +311,7 @@ configs.forEach(function(config) { describe('remove()', function () { it('should remove an entity from the server', function (done) { - entity.remove(client, function (deleteResponse) { + entity.remove(client, function (error,deleteResponse) { deleteResponse.ok.should.be.true(); // best practice is to destroy the 'entity' instance here, because it no longer exists on the server entity = null; @@ -333,7 +333,7 @@ configs.forEach(function(config) { "name": "testEntityConnectOne" }, { "name": "testEntityConnectTwo" - }], callback: function (postResponse) { + }], callback: function (error,postResponse) { response = postResponse; entity1 = response.first; entity2 = response.last; @@ -344,10 +344,10 @@ configs.forEach(function(config) { it('should connect entities by passing a target UsergridEntity object as a parameter', function (done) { var relationship = "foos"; - entity1.connect(client, relationship, entity2, function (usergridResponse) { + entity1.connect(client, relationship, entity2, function (error,usergridResponse) { sleepFor(config.defaultSleepTime); usergridResponse.ok.should.be.true(); - client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (error,usergridResponse) { usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( "", config.test.collection, @@ -365,10 +365,10 @@ configs.forEach(function(config) { it('should connect entities by passing target uuid as a parameter', function (done) { var relationship = "bars"; - entity1.connect(client, relationship, entity2.uuid, function (usergridResponse) { + entity1.connect(client, relationship, entity2.uuid, function (error,usergridResponse) { usergridResponse.ok.should.be.true(); sleepFor(config.defaultSleepTime); - client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (error,usergridResponse) { usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( "", config.test.collection, @@ -386,10 +386,10 @@ configs.forEach(function(config) { it('should connect entities by passing target type and name as parameters', function (done) { var relationship = "bazzes"; - entity1.connect(client, relationship, entity2.type, entity2.name, function (usergridResponse) { + entity1.connect(client, relationship, entity2.type, entity2.name, function (error,usergridResponse) { usergridResponse.ok.should.be.true(); sleepFor(config.defaultSleepTime); - client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (error,usergridResponse) { usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( "", config.test.collection, @@ -419,7 +419,7 @@ configs.forEach(function(config) { before(function (done) { sleepFor(config.defaultLongSleepTime); - client.GET(query, function (usergridResponse) { + client.GET(query, function (error,usergridResponse) { response = usergridResponse; done() }) @@ -431,7 +431,7 @@ configs.forEach(function(config) { var relationship = "foos"; - entity1.getConnections(client, UsergridDirection.OUT, relationship, function (usergridResponse) { + entity1.getConnections(client, UsergridDirection.OUT, relationship, function (error,usergridResponse) { usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( "", config.test.collection, @@ -451,7 +451,7 @@ configs.forEach(function(config) { var relationship = "foos"; - entity2.getConnections(client, UsergridDirection.IN, relationship, function (usergridResponse) { + entity2.getConnections(client, UsergridDirection.IN, relationship, function (error,usergridResponse) { usergridResponse.first.metadata.connections[relationship].should.equal(UsergridHelpers.urljoin( "", config.test.collection, @@ -473,7 +473,7 @@ configs.forEach(function(config) { query = new UsergridQuery(config.test.collection).eq('name', 'testEntityConnectOne').or.eq('name', 'testEntityConnectTwo').asc('name'); before(function (done) { - client.GET(query, function (usergridResponse) { + client.GET(query, function (error,usergridResponse) { response = usergridResponse; entity1 = response.first; entity2 = response.last; @@ -482,7 +482,7 @@ configs.forEach(function(config) { }); after(function (done) { var deleteQuery = new UsergridQuery(config.test.collection).eq('uuid', entity1.uuid).or.eq('uuid', entity2.uuid); - client.DELETE(deleteQuery, function (delResponse) { + client.DELETE(deleteQuery, function (error,delResponse) { delResponse.entities.should.be.an.Array().with.lengthOf(2); done() }) @@ -490,9 +490,9 @@ configs.forEach(function(config) { it('should disconnect entities by passing a target UsergridEntity object as a parameter', function (done) { var relationship = "foos"; - entity1.disconnect(client, relationship, entity2, function (usergridResponse) { + entity1.disconnect(client, relationship, entity2, function (error,usergridResponse) { usergridResponse.ok.should.be.true(); - client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (error,usergridResponse) { usergridResponse.entities.should.be.an.Array().with.lengthOf(0); done() }) @@ -501,9 +501,9 @@ configs.forEach(function(config) { it('should disconnect entities by passing target uuid as a parameter', function (done) { var relationship = "bars"; - entity1.disconnect(client, relationship, entity2.uuid, function (usergridResponse) { + entity1.disconnect(client, relationship, entity2.uuid, function (error,usergridResponse) { usergridResponse.ok.should.be.true(); - client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (error,usergridResponse) { usergridResponse.entities.should.be.an.Array().with.lengthOf(0); done() }) @@ -512,9 +512,9 @@ configs.forEach(function(config) { it('should disconnect entities by passing target type and name as parameters', function (done) { var relationship = "bazzes"; - entity1.disconnect(client, relationship, entity2.type, entity2.name, function (usergridResponse) { + entity1.disconnect(client, relationship, entity2.type, entity2.name, function (error,usergridResponse) { usergridResponse.ok.should.be.true(); - client.getConnections(UsergridDirection.OUT, entity1, relationship, function (usergridResponse) { + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (error,usergridResponse) { usergridResponse.entities.should.be.an.Array().with.lengthOf(0); done() }) @@ -536,7 +536,7 @@ configs.forEach(function(config) { var asset; before(function (done) { - assetEntity.save(client, function (response) { + assetEntity.save(client, function (error,response) { response.ok.should.be.true(); assetEntity.should.have.property('uuid'); done() @@ -565,7 +565,7 @@ configs.forEach(function(config) { }); it('should upload an image asset to the remote entity', function (done) { - assetEntity.uploadAsset(client, function (asset, usergridResponse, entity) { + assetEntity.uploadAsset(client, function (error, usergridResponse, entity) { entity.should.have.property('file-metadata'); entity['file-metadata'].should.have.property('content-type').equal(testFile.contentType); entity['file-metadata'].should.have.property('content-length').equal(testFile.contentLength); @@ -582,7 +582,7 @@ configs.forEach(function(config) { }); it('should download a an image from the remote entity', function (done) { - assetEntity.downloadAsset(client, function (asset, usergridResponse, entityWithAsset) { + assetEntity.downloadAsset(client, function (error, usergridResponse, entityWithAsset) { entityWithAsset.should.have.property('asset').which.is.an.instanceof(UsergridAsset); entityWithAsset.asset.should.have.property('contentType').equal(assetEntity['file-metadata']['content-type']); entityWithAsset.asset.should.have.property('contentLength').equal(assetEntity['file-metadata']['content-length']); diff --git a/tests/mocha/test_response.js b/tests/mocha/test_response.js index ce442a7..6d2db05 100644 --- a/tests/mocha/test_response.js +++ b/tests/mocha/test_response.js @@ -19,7 +19,7 @@ configs.forEach(function(config) { entitiesArray.push(entity) } client.POST({ - body: entitiesArray, callback: function (postResponse) { + body: entitiesArray, callback: function (error,postResponse) { postResponse.entities.should.be.an.Array().with.lengthOf(entitiesArray.length); entitiesArray = postResponse.entities; done() @@ -28,7 +28,7 @@ configs.forEach(function(config) { }); before(function (done) { - client.GET(config.test.collection, function (usergridResponse) { + client.GET(config.test.collection, function (error,usergridResponse) { _response = usergridResponse; done() }) @@ -69,7 +69,7 @@ configs.forEach(function(config) { describe('error', function () { it('should be a UsergridResponseError object', function (done) { - client.GET(config.test.collection, 'BADNAMEORUUID', function (usergridResponse) { + client.GET(config.test.collection, 'BADNAMEORUUID', function (error,usergridResponse) { usergridResponse.error.should.be.an.instanceof(UsergridResponseError); done() }) @@ -79,9 +79,9 @@ configs.forEach(function(config) { describe('users', function () { it('response.users should be an array of UsergridUser objects', function (done) { client.setAppAuth(config.clientId, config.clientSecret, config.tokenTtl); - client.authenticateApp(function (response) { + client.authenticateApp(function (error,response) { should(response.error).be.undefined(); - client.GET('users', function (usergridResponse) { + client.GET('users', function (error,usergridResponse) { usergridResponse.ok.should.be.true(); usergridResponse.users.should.be.an.Array(); usergridResponse.users.forEach(function (user) { @@ -98,9 +98,9 @@ configs.forEach(function(config) { it('response.user should be a UsergridUser object and have a valid uuid matching the first object in response.users', function (done) { client.setAppAuth(config.clientId, config.clientSecret, config.tokenTtl); - client.authenticateApp(function (response) { + client.authenticateApp(function (error,response) { should(response.error).be.undefined(); - client.GET('users', function (usergridResponse) { + client.GET('users', function (error,usergridResponse) { user = usergridResponse.user; user.should.be.an.instanceof(UsergridUser).with.property('uuid').equal(_.first(usergridResponse.entities).uuid); done() @@ -142,14 +142,14 @@ configs.forEach(function(config) { describe('hasNextPage', function () { it('should be true when more entities exist', function (done) { - client.GET({type: config.test.collection}, function (usergridResponse) { + client.GET({type: config.test.collection}, function (error,usergridResponse) { usergridResponse.hasNextPage.should.be.true(); done() }) }); it('should be false when no more entities exist', function (done) { - client.GET({type: 'users'}, function (usergridResponse) { + client.GET({type: 'users'}, function (error,usergridResponse) { usergridResponse.responseJSON.count.should.be.lessThan(10); usergridResponse.hasNextPage.should.not.be.true(); done() @@ -161,14 +161,14 @@ configs.forEach(function(config) { var firstResponse; before(function (done) { - client.GET({type: config.test.collection}, function (usergridResponse) { + client.GET({type: config.test.collection}, function (error,usergridResponse) { firstResponse = usergridResponse; done() }) }); it('should load a new page of entities by passing an instance of UsergridClient', function (done) { - firstResponse.loadNextPage(client, function (usergridResponse) { + firstResponse.loadNextPage(client, function (error,usergridResponse) { usergridResponse.first.uuid.should.not.equal(firstResponse.first.uuid); usergridResponse.entities.length.should.equal(10); done() diff --git a/tests/mocha/test_response_error.js b/tests/mocha/test_response_error.js index 31f29c2..9b2cbe8 100644 --- a/tests/mocha/test_response_error.js +++ b/tests/mocha/test_response_error.js @@ -13,7 +13,7 @@ configs.forEach(function(config) { describe('name, description, exception', function () { before(function (done) { - client.GET(config.test.collection, 'BADNAMEORUUID', function (usergridResponse) { + client.GET(config.test.collection, 'BADNAMEORUUID', function (error,usergridResponse) { _response = usergridResponse; done() }) @@ -31,7 +31,7 @@ configs.forEach(function(config) { describe('undefined check', function () { it('response.error should be undefined on a successful response', function (done) { - client.GET(config.test.collection, function (usergridResponse) { + client.GET(config.test.collection, function (error,usergridResponse) { usergridResponse.ok.should.be.true(); should(usergridResponse.error).be.undefined(); done() diff --git a/tests/mocha/test_user.js b/tests/mocha/test_user.js index 2bf4870..fbba543 100644 --- a/tests/mocha/test_user.js +++ b/tests/mocha/test_user.js @@ -52,7 +52,7 @@ configs.forEach(function(config) { username: _username1, password: config.test.password }); - user.create(client, function (usergridResponse) { + user.create(client, function (error,usergridResponse) { usergridResponse.error.should.not.be.null(); usergridResponse.error.should.containDeep({ name: 'duplicate_unique_property_exists' @@ -68,14 +68,14 @@ configs.forEach(function(config) { username: username, password: config.test.password }); - user.create(client, function (usergridResponse) { + user.create(client, function (error,usergridResponse) { user.username.should.equal(username); user.should.have.property('uuid')//.which.is.a.uuid() user.should.have.property('created'); user.should.have.property('activated').true(); user.should.not.have.property('password'); // cleanup - user.remove(client, function (response) { + user.remove(client, function (error,response) { done() }) }); @@ -85,8 +85,8 @@ configs.forEach(function(config) { describe('login()', function () { it("it should log in the user '" + _username1 + "' and receive a token", function (done) { _user1.password = config.test.password; - _user1.login(client, function (auth, user, response) { - _user1.auth.should.have.property('token').equal(auth.token); + _user1.login(client, function (error, response, token) { + _user1.auth.should.have.property('token').equal(token); _user1.should.not.have.property('password'); _user1.auth.should.not.have.property('password'); done() @@ -97,7 +97,7 @@ configs.forEach(function(config) { describe('logout()', function () { it("it should log out " + _username1 + " and destroy the saved UsergridUserAuth instance", function (done) { - _user1.logout(client, function (response) { + _user1.logout(client, function (error,response) { response.ok.should.be.true(); response.responseJSON.action.should.equal("revoked user token"); _user1.auth.isValid.should.be.false(); @@ -106,7 +106,7 @@ configs.forEach(function(config) { }); it("it should return an error when attempting to log out a user that does not have a valid token", function (done) { - _user1.logout(client, function (response) { + _user1.logout(client, function (error,response) { response.error.name.should.equal('no_valid_token'); done() }) @@ -116,8 +116,8 @@ configs.forEach(function(config) { describe('logoutAllSessions()', function () { it("it should log out all tokens for the user " + _username1 + " destroy the saved UsergridUserAuth instance", function (done) { _user1.password = config.test.password; - _user1.login(client, function (auth, user, response) { - _user1.logoutAllSessions(client, function (response) { + _user1.login(client, function (error, response, token) { + _user1.logoutAllSessions(client, function (error,response) { response.ok.should.be.true(); response.responseJSON.action.should.equal("revoked user tokens"); _user1.auth.isValid.should.be.false(); @@ -130,7 +130,7 @@ configs.forEach(function(config) { describe('resetPassword()', function () { it("it should reset the password for " + _username1 + " by passing parameters", function (done) { - _user1.resetPassword(client, config.test.password, '2cool4u', function (response) { + _user1.resetPassword(client, config.test.password, '2cool4u', function (error,response) { response.ok.should.be.true(); response.responseJSON.action.should.equal("set user password"); done() @@ -141,7 +141,7 @@ configs.forEach(function(config) { _user1.resetPassword(client, { oldPassword: '2cool4u', newPassword: config.test.password - }, function (response) { + }, function (error,response) { response.ok.should.be.true(); response.responseJSON.action.should.equal("set user password"); done() @@ -152,7 +152,7 @@ configs.forEach(function(config) { _user1.resetPassword(client, { oldPassword: 'BADOLDPASSWORD', newPassword: config.test.password - }, function (response) { + }, function (error,response) { response.ok.should.be.false(); response.error.name.should.equal('auth_invalid_username_or_password'); _user1.remove(client, function () { @@ -177,7 +177,7 @@ configs.forEach(function(config) { it("it should return true for username " + config.test.username, function (done) { UsergridUser.CheckAvailable(client, { username: config.test.username - }, function (response, exists) { + }, function (error,response, exists) { exists.should.be.true(); done() }) @@ -186,7 +186,7 @@ configs.forEach(function(config) { it("it should return true for email " + config.test.email, function (done) { UsergridUser.CheckAvailable(client, { email: config.test.email - }, function (response, exists) { + }, function (error,response, exists) { exists.should.be.true(); done() }) @@ -196,7 +196,7 @@ configs.forEach(function(config) { UsergridUser.CheckAvailable(client, { email: config.test.email, username: nonExistentUsername - }, function (response, exists) { + }, function (error,response, exists) { exists.should.be.true(); done() }) @@ -206,7 +206,7 @@ configs.forEach(function(config) { UsergridUser.CheckAvailable(client, { email: nonExistentEmail, username: config.test.username - }, function (response, exists) { + }, function (error,response, exists) { exists.should.be.true(); done() }) @@ -216,7 +216,7 @@ configs.forEach(function(config) { UsergridUser.CheckAvailable(client, { email: config.test.email, username: config.test.useranme - }, function (response, exists) { + }, function (error,response, exists) { exists.should.be.true(); done() }) @@ -225,7 +225,7 @@ configs.forEach(function(config) { it("it should return false for non-existent email " + nonExistentEmail, function (done) { UsergridUser.CheckAvailable(client, { email: nonExistentEmail - }, function (response, exists) { + }, function (error,response, exists) { exists.should.be.false(); done() }) @@ -234,7 +234,7 @@ configs.forEach(function(config) { it("it should return false for non-existent username " + nonExistentUsername, function (done) { UsergridUser.CheckAvailable(client, { username: nonExistentUsername - }, function (response, exists) { + }, function (error,response, exists) { exists.should.be.false(); done() }) @@ -244,7 +244,7 @@ configs.forEach(function(config) { UsergridUser.CheckAvailable(client, { email: nonExistentEmail, username: nonExistentUsername - }, function (response, exists) { + }, function (error,response, exists) { exists.should.be.false(); done() }) diff --git a/usergrid.js b/usergrid.js index 3c0a560..a37ae44 100644 --- a/usergrid.js +++ b/usergrid.js @@ -5854,17 +5854,18 @@ UsergridClient.prototype = { } else if (!auth.clientId || !auth.clientSecret) { throw new Error("authenticateApp() failed because clientId or clientSecret are missing"); } - var callback = function(usergridResponse) { + var callback = function(error, usergridResponse) { + var token = _.get(usergridResponse.responseJSON, "access_token"); + var expiresIn = _.get(usergridResponse.responseJSON, "expires_in"); if (usergridResponse.ok) { if (!self.appAuth) { self.appAuth = auth; } - self.appAuth.token = _.get(usergridResponse.responseJSON, "access_token"); - var expiresIn = _.get(usergridResponse.responseJSON, "expires_in"); + self.appAuth.token = token; self.appAuth.expiry = UsergridHelpers.calculateExpiry(expiresIn); self.appAuth.tokenTtl = expiresIn; } - authenticateAppCallback(usergridResponse); + authenticateAppCallback(error, usergridResponse, token); }; var usergridRequest = UsergridHelpers.buildAppAuthRequest(self, auth, callback); return self.sendRequest(usergridRequest); @@ -5875,11 +5876,11 @@ UsergridClient.prototype = { var callback = UsergridHelpers.callback(args); var setAsCurrentUser = _.last(args.filter(_.isBoolean)) !== undefined ? _.last(args.filter(_.isBoolean)) : true; var userToAuthenticate = new UsergridUser(options); - userToAuthenticate.login(self, function(auth, user, usergridResponse) { + userToAuthenticate.login(self, function(error, usergridResponse, token) { if (usergridResponse.ok && setAsCurrentUser) { self.currentUser = userToAuthenticate; } - callback(auth, user, usergridResponse); + callback(usergridResponse.error, usergridResponse, token); }); }, downloadAsset: function() { @@ -5892,10 +5893,10 @@ UsergridClient.prototype = { }); } var realDownloadAssetCallback = usergridRequest.callback; - usergridRequest.callback = function(usergridResponse) { + usergridRequest.callback = function(error, usergridResponse) { var entity = usergridRequest.entity; entity.asset = usergridResponse.asset; - realDownloadAssetCallback(entity.asset, usergridResponse, entity); + realDownloadAssetCallback(error, usergridResponse, entity); }; return self.sendRequest(usergridRequest); }, @@ -5906,7 +5907,7 @@ UsergridClient.prototype = { throw new Error("An UsergridAsset was not defined when attempting to call .uploadAsset()"); } var realUploadAssetCallback = usergridRequest.callback; - usergridRequest.callback = function(usergridResponse) { + usergridRequest.callback = function(error, usergridResponse) { var requestEntity = usergridRequest.entity; var responseEntity = usergridResponse.entity; var requestAsset = usergridRequest.asset; @@ -5917,7 +5918,7 @@ UsergridClient.prototype = { responseEntity.asset = requestAsset; } } - realUploadAssetCallback(requestAsset, usergridResponse, requestEntity); + realUploadAssetCallback(error, usergridResponse, requestEntity); }; return self.sendRequest(usergridRequest); } @@ -6190,10 +6191,8 @@ UsergridRequest.prototype.sendRequest = function() { promise.done(usergridResponse); return promise; }; - var onCompletePromise = function(response) { - var promise = new Promise(); - promise.done(response); - self.callback(response); + var onCompletePromise = function(usergridResponse) { + self.callback(usergridResponse.error, usergridResponse); }; Promise.chain([ requestPromise, responsePromise ]).then(onCompletePromise); return self; @@ -6362,9 +6361,9 @@ UsergridEntity.prototype = { var args = UsergridHelpers.flattenArgs(arguments); var client = UsergridHelpers.validateAndRetrieveClient(args); var callback = UsergridHelpers.callback(args); - client.GET(self, function(usergridResponse) { + client.GET(self, function(error, usergridResponse) { UsergridHelpers.updateEntityFromRemote(self, usergridResponse); - callback(usergridResponse, self); + callback(error, usergridResponse, self); }.bind(self)); }, save: function() { @@ -6373,12 +6372,12 @@ UsergridEntity.prototype = { var client = UsergridHelpers.validateAndRetrieveClient(args); var callback = UsergridHelpers.callback(args); var currentAsset = self.asset; - client.PUT(self, function(usergridResponse) { + client.PUT(self, function(error, usergridResponse) { UsergridHelpers.updateEntityFromRemote(self, usergridResponse); if (self.hasAsset) { self.asset = currentAsset; } - callback(usergridResponse, self); + callback(error, usergridResponse, self); }.bind(self)); }, remove: function() { @@ -6386,8 +6385,8 @@ UsergridEntity.prototype = { var args = UsergridHelpers.flattenArgs(arguments); var client = UsergridHelpers.validateAndRetrieveClient(args); var callback = UsergridHelpers.callback(args); - client.DELETE(self, function(usergridResponse) { - callback(usergridResponse, self); + client.DELETE(self, function(error, usergridResponse) { + callback(error, usergridResponse, self); }.bind(self)); }, attachAsset: function(asset) { @@ -6405,7 +6404,7 @@ UsergridEntity.prototype = { name: "asset_not_found", description: "The specified entity does not have a valid asset attached" }); - callback(null, response, self); + callback(response.error, response, self); } }, downloadAsset: function() { @@ -6420,7 +6419,7 @@ UsergridEntity.prototype = { name: "asset_not_found", description: "The specified entity does not have a valid asset attached" }); - callback(null, response, self); + callback(response.error, response, self); } }, connect: function() { @@ -6474,8 +6473,8 @@ UsergridUser.CheckAvailable = function() { } else { throw new Error("'username' or 'email' property is required when checking for available users"); } - client.GET(checkQuery, function(usergridResponse) { - callback(usergridResponse, usergridResponse.entities.length > 0); + client.GET(checkQuery, function(error, usergridResponse) { + callback(error, usergridResponse, usergridResponse.entities.length > 0); }); }; @@ -6491,10 +6490,10 @@ UsergridUser.prototype.create = function() { var args = UsergridHelpers.flattenArgs(arguments); var client = UsergridHelpers.validateAndRetrieveClient(args); var callback = UsergridHelpers.callback(args); - client.POST(self, function(usergridResponse) { + client.POST(self, function(error, usergridResponse) { delete self.password; _.assign(self, usergridResponse.user); - callback(usergridResponse, usergridResponse.user); + callback(error, usergridResponse, self); }.bind(self)); }; @@ -6503,17 +6502,18 @@ UsergridUser.prototype.login = function() { var args = UsergridHelpers.flattenArgs(arguments); var client = UsergridHelpers.validateAndRetrieveClient(args); var callback = UsergridHelpers.callback(args); - client.POST("token", UsergridHelpers.userLoginBody(self), function(usergridResponse) { + client.POST("token", UsergridHelpers.userLoginBody(self), function(error, usergridResponse) { delete self.password; + var responseJSON = usergridResponse.responseJSON; + var token = _.get(responseJSON, "access_token"); + var expiresIn = _.get(responseJSON, "expires_in"); if (usergridResponse.ok) { - var responseJSON = usergridResponse.responseJSON; self.auth = new UsergridUserAuth(self); - self.auth.token = _.get(responseJSON, "access_token"); - var expiresIn = _.get(responseJSON, "expires_in"); + self.auth.token = token; self.auth.expiry = UsergridHelpers.calculateExpiry(expiresIn); self.auth.tokenTtl = expiresIn; } - callback(self.auth, self, usergridResponse); + callback(error, usergridResponse, token); }); }; @@ -6527,7 +6527,7 @@ UsergridUser.prototype.logout = function() { name: "no_valid_token", description: "this user does not have a valid token" }); - callback(response); + callback(response.error, response); } else { var revokeAll = _.first(args.filter(_.isBoolean)) || false; var queryParams = undefined; @@ -6541,9 +6541,9 @@ UsergridUser.prototype.logout = function() { path: [ "users", self.uniqueId(), "revoketoken" + (revokeAll ? "s" : "") ].join("/"), method: UsergridHttpMethod.PUT, queryParams: queryParams, - callback: function(usergridResponse) { + callback: function(error, usergridResponse) { self.auth.destroy(); - callback(usergridResponse); + callback(error, usergridResponse, usergridResponse.ok); }.bind(self) }; var request = new UsergridRequest(requestOptions); diff --git a/usergrid.min.js b/usergrid.min.js index 1b3cd71..fc4abc4 100644 --- a/usergrid.min.js +++ b/usergrid.min.js @@ -23,5 +23,5 @@ return value===other?!0:null==value||null==other||!isObject(value)&&!isObjectLike(other)?value!==value&&other!==other:baseIsEqualDeep(value,other,baseIsEqual,customizer,bitmask,stack)}function baseIsEqualDeep(object,other,equalFunc,customizer,bitmask,stack){var objIsArr=isArray(object),othIsArr=isArray(other),objTag=arrayTag,othTag=arrayTag;objIsArr||(objTag=getTag(object),objTag=objTag==argsTag?objectTag:objTag),othIsArr||(othTag=getTag(other),othTag=othTag==argsTag?objectTag:othTag);var objIsObj=objTag==objectTag,othIsObj=othTag==objectTag,isSameTag=objTag==othTag;if(isSameTag&&isBuffer(object)){if(!isBuffer(other))return!1;objIsArr=!0,objIsObj=!1}if(isSameTag&&!objIsObj)return stack||(stack=new Stack),objIsArr||isTypedArray(object)?equalArrays(object,other,equalFunc,customizer,bitmask,stack):equalByTag(object,other,objTag,equalFunc,customizer,bitmask,stack);if(!(bitmask&PARTIAL_COMPARE_FLAG)){var objIsWrapped=objIsObj&&hasOwnProperty.call(object,"__wrapped__"),othIsWrapped=othIsObj&&hasOwnProperty.call(other,"__wrapped__");if(objIsWrapped||othIsWrapped){var objUnwrapped=objIsWrapped?object.value():object,othUnwrapped=othIsWrapped?other.value():other;return stack||(stack=new Stack),equalFunc(objUnwrapped,othUnwrapped,customizer,bitmask,stack)}}return isSameTag?(stack||(stack=new Stack),equalObjects(object,other,equalFunc,customizer,bitmask,stack)):!1}function baseIsMap(value){return isObjectLike(value)&&getTag(value)==mapTag}function baseIsMatch(object,source,matchData,customizer){var index=matchData.length,length=index,noCustomizer=!customizer;if(null==object)return!length;for(object=Object(object);index--;){var data=matchData[index];if(noCustomizer&&data[2]?data[1]!==object[data[0]]:!(data[0]in object))return!1}for(;++indexvalue}function baseMap(collection,iteratee){var index=-1,result=isArrayLike(collection)?Array(collection.length):[];return baseEach(collection,function(value,key,collection){result[++index]=iteratee(value,key,collection)}),result}function baseMatches(source){var matchData=getMatchData(source);return 1==matchData.length&&matchData[0][2]?matchesStrictComparable(matchData[0][0],matchData[0][1]):function(object){return object===source||baseIsMatch(object,source,matchData)}}function baseMatchesProperty(path,srcValue){return isKey(path)&&isStrictComparable(srcValue)?matchesStrictComparable(toKey(path),srcValue):function(object){var objValue=get(object,path);return objValue===undefined&&objValue===srcValue?hasIn(object,path):baseIsEqual(srcValue,objValue,undefined,UNORDERED_COMPARE_FLAG|PARTIAL_COMPARE_FLAG)}}function baseMerge(object,source,srcIndex,customizer,stack){object!==source&&baseFor(source,function(srcValue,key){if(isObject(srcValue))stack||(stack=new Stack),baseMergeDeep(object,source,key,srcIndex,baseMerge,customizer,stack);else{var newValue=customizer?customizer(object[key],srcValue,key+"",object,source,stack):undefined;newValue===undefined&&(newValue=srcValue),assignMergeValue(object,key,newValue)}},keysIn)}function baseMergeDeep(object,source,key,srcIndex,mergeFunc,customizer,stack){var objValue=object[key],srcValue=source[key],stacked=stack.get(srcValue);if(stacked)return void assignMergeValue(object,key,stacked);var newValue=customizer?customizer(objValue,srcValue,key+"",object,source,stack):undefined,isCommon=newValue===undefined;if(isCommon){var isArr=isArray(srcValue),isBuff=!isArr&&isBuffer(srcValue),isTyped=!isArr&&!isBuff&&isTypedArray(srcValue);newValue=srcValue,isArr||isBuff||isTyped?isArray(objValue)?newValue=objValue:isArrayLikeObject(objValue)?newValue=copyArray(objValue):isBuff?(isCommon=!1,newValue=cloneBuffer(srcValue,!0)):isTyped?(isCommon=!1,newValue=cloneTypedArray(srcValue,!0)):newValue=[]:isPlainObject(srcValue)||isArguments(srcValue)?(newValue=objValue,isArguments(objValue)?newValue=toPlainObject(objValue):(!isObject(objValue)||srcIndex&&isFunction(objValue))&&(newValue=initCloneObject(srcValue))):isCommon=!1}isCommon&&(stack.set(srcValue,newValue),mergeFunc(newValue,srcValue,srcIndex,customizer,stack),stack["delete"](srcValue)),assignMergeValue(object,key,newValue)}function baseNth(array,n){var length=array.length;if(length)return n+=0>n?length:0,isIndex(n,length)?array[n]:undefined}function baseOrderBy(collection,iteratees,orders){var index=-1;iteratees=arrayMap(iteratees.length?iteratees:[identity],baseUnary(getIteratee()));var result=baseMap(collection,function(value,key,collection){var criteria=arrayMap(iteratees,function(iteratee){return iteratee(value)});return{criteria:criteria,index:++index,value:value}});return baseSortBy(result,function(object,other){return compareMultiple(object,other,orders)})}function basePick(object,props){return object=Object(object),basePickBy(object,props,function(value,key){return key in object})}function basePickBy(object,props,predicate){for(var index=-1,length=props.length,result={};++index-1;)seen!==array&&splice.call(seen,fromIndex,1),splice.call(array,fromIndex,1);return array}function basePullAt(array,indexes){for(var length=array?indexes.length:0,lastIndex=length-1;length--;){var index=indexes[length];if(length==lastIndex||index!==previous){var previous=index;if(isIndex(index))splice.call(array,index,1);else if(isKey(index,array))delete array[toKey(index)];else{var path=castPath(index),object=parent(array,path);null!=object&&delete object[toKey(last(path))]}}}return array}function baseRandom(lower,upper){return lower+nativeFloor(nativeRandom()*(upper-lower+1))}function baseRange(start,end,step,fromRight){for(var index=-1,length=nativeMax(nativeCeil((end-start)/(step||1)),0),result=Array(length);length--;)result[fromRight?length:++index]=start,start+=step;return result}function baseRepeat(string,n){var result="";if(!string||1>n||n>MAX_SAFE_INTEGER)return result;do n%2&&(result+=string),n=nativeFloor(n/2),n&&(string+=string);while(n);return result}function baseRest(func,start){return setToString(overRest(func,start,identity),func+"")}function baseSample(collection){return arraySample(values(collection))}function baseSampleSize(collection,n){var array=values(collection);return shuffleSelf(array,baseClamp(n,0,array.length))}function baseSet(object,path,value,customizer){if(!isObject(object))return object;path=isKey(path,object)?[path]:castPath(path);for(var index=-1,length=path.length,lastIndex=length-1,nested=object;null!=nested&&++indexstart&&(start=-start>length?0:length+start),end=end>length?length:end,0>end&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index=high){for(;high>low;){var mid=low+high>>>1,computed=array[mid];null!==computed&&!isSymbol(computed)&&(retHighest?value>=computed:value>computed)?low=mid+1:high=mid}return high}return baseSortedIndexBy(array,value,identity,retHighest)}function baseSortedIndexBy(array,value,iteratee,retHighest){value=iteratee(value);for(var low=0,high=array?array.length:0,valIsNaN=value!==value,valIsNull=null===value,valIsSymbol=isSymbol(value),valIsUndefined=value===undefined;high>low;){var mid=nativeFloor((low+high)/2),computed=iteratee(array[mid]),othIsDefined=computed!==undefined,othIsNull=null===computed,othIsReflexive=computed===computed,othIsSymbol=isSymbol(computed);if(valIsNaN)var setLow=retHighest||othIsReflexive;else setLow=valIsUndefined?othIsReflexive&&(retHighest||othIsDefined):valIsNull?othIsReflexive&&othIsDefined&&(retHighest||!othIsNull):valIsSymbol?othIsReflexive&&othIsDefined&&!othIsNull&&(retHighest||!othIsSymbol):othIsNull||othIsSymbol?!1:retHighest?value>=computed:value>computed;setLow?low=mid+1:high=mid}return nativeMin(high,MAX_ARRAY_INDEX)}function baseSortedUniq(array,iteratee){for(var index=-1,length=array.length,resIndex=0,result=[];++index=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++indexindex?values[index]:undefined;assignFunc(result,props[index],value)}return result}function castArrayLikeObject(value){return isArrayLikeObject(value)?value:[]}function castFunction(value){return"function"==typeof value?value:identity}function castPath(value){return isArray(value)?value:stringToPath(value)}function castSlice(array,start,end){var length=array.length;return end=end===undefined?length:end,!start&&end>=length?array:baseSlice(array,start,end)}function cloneBuffer(buffer,isDeep){if(isDeep)return buffer.slice();var length=buffer.length,result=allocUnsafe?allocUnsafe(length):new buffer.constructor(length);return buffer.copy(result),result}function cloneArrayBuffer(arrayBuffer){var result=new arrayBuffer.constructor(arrayBuffer.byteLength);return new Uint8Array(result).set(new Uint8Array(arrayBuffer)),result}function cloneDataView(dataView,isDeep){var buffer=isDeep?cloneArrayBuffer(dataView.buffer):dataView.buffer;return new dataView.constructor(buffer,dataView.byteOffset,dataView.byteLength)}function cloneMap(map,isDeep,cloneFunc){var array=isDeep?cloneFunc(mapToArray(map),!0):mapToArray(map);return arrayReduce(array,addMapEntry,new map.constructor)}function cloneRegExp(regexp){var result=new regexp.constructor(regexp.source,reFlags.exec(regexp));return result.lastIndex=regexp.lastIndex,result}function cloneSet(set,isDeep,cloneFunc){var array=isDeep?cloneFunc(setToArray(set),!0):setToArray(set);return arrayReduce(array,addSetEntry,new set.constructor)}function cloneSymbol(symbol){return symbolValueOf?Object(symbolValueOf.call(symbol)):{}}function cloneTypedArray(typedArray,isDeep){var buffer=isDeep?cloneArrayBuffer(typedArray.buffer):typedArray.buffer;return new typedArray.constructor(buffer,typedArray.byteOffset,typedArray.length)}function compareAscending(value,other){if(value!==other){var valIsDefined=value!==undefined,valIsNull=null===value,valIsReflexive=value===value,valIsSymbol=isSymbol(value),othIsDefined=other!==undefined,othIsNull=null===other,othIsReflexive=other===other,othIsSymbol=isSymbol(other);if(!othIsNull&&!othIsSymbol&&!valIsSymbol&&value>other||valIsSymbol&&othIsDefined&&othIsReflexive&&!othIsNull&&!othIsSymbol||valIsNull&&othIsDefined&&othIsReflexive||!valIsDefined&&othIsReflexive||!valIsReflexive)return 1;if(!valIsNull&&!valIsSymbol&&!othIsSymbol&&other>value||othIsSymbol&&valIsDefined&&valIsReflexive&&!valIsNull&&!valIsSymbol||othIsNull&&valIsDefined&&valIsReflexive||!othIsDefined&&valIsReflexive||!othIsReflexive)return-1}return 0}function compareMultiple(object,other,orders){for(var index=-1,objCriteria=object.criteria,othCriteria=other.criteria,length=objCriteria.length,ordersLength=orders.length;++index=ordersLength)return result;var order=orders[index];return result*("desc"==order?-1:1)}}return object.index-other.index}function composeArgs(args,partials,holders,isCurried){for(var argsIndex=-1,argsLength=args.length,holdersLength=holders.length,leftIndex=-1,leftLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(leftLength+rangeLength),isUncurried=!isCurried;++leftIndexargsIndex)&&(result[holders[argsIndex]]=args[argsIndex]);for(;rangeLength--;)result[leftIndex++]=args[argsIndex++];return result}function composeArgsRight(args,partials,holders,isCurried){for(var argsIndex=-1,argsLength=args.length,holdersIndex=-1,holdersLength=holders.length,rightIndex=-1,rightLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(rangeLength+rightLength),isUncurried=!isCurried;++argsIndexargsIndex)&&(result[offset+holders[holdersIndex]]=args[argsIndex++]);return result}function copyArray(source,array){var index=-1,length=source.length;for(array||(array=Array(length));++index1?sources[length-1]:undefined,guard=length>2?sources[2]:undefined;for(customizer=assigner.length>3&&"function"==typeof customizer?(length--,customizer):undefined,guard&&isIterateeCall(sources[0],sources[1],guard)&&(customizer=3>length?undefined:customizer,length=1),object=Object(object);++indexlength&&args[0]!==placeholder&&args[length-1]!==placeholder?[]:replaceHolders(args,placeholder);if(length-=holders.length,arity>length)return createRecurry(func,bitmask,createHybrid,wrapper.placeholder,undefined,args,holders,undefined,undefined,arity-length);var fn=this&&this!==root&&this instanceof wrapper?Ctor:func;return apply(fn,this,args)}var Ctor=createCtor(func);return wrapper}function createFind(findIndexFunc){return function(collection,predicate,fromIndex){var iterable=Object(collection);if(!isArrayLike(collection)){var iteratee=getIteratee(predicate,3);collection=keys(collection),predicate=function(key){return iteratee(iterable[key],key,iterable)}}var index=findIndexFunc(collection,predicate,fromIndex);return index>-1?iterable[iteratee?collection[index]:index]:undefined}}function createFlow(fromRight){return flatRest(function(funcs){var length=funcs.length,index=length,prereq=LodashWrapper.prototype.thru;for(fromRight&&funcs.reverse();index--;){var func=funcs[index];if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);if(prereq&&!wrapper&&"wrapper"==getFuncName(func))var wrapper=new LodashWrapper([],!0)}for(index=wrapper?index:length;++index=LARGE_ARRAY_SIZE)return wrapper.plant(value).value();for(var index=0,result=length?funcs[index].apply(this,args):value;++indexlength){var newHolders=replaceHolders(args,placeholder);return createRecurry(func,bitmask,createHybrid,wrapper.placeholder,thisArg,args,newHolders,argPos,ary,arity-length)}var thisBinding=isBind?thisArg:this,fn=isBindKey?thisBinding[func]:func;return length=args.length,argPos?args=reorder(args,argPos):isFlip&&length>1&&args.reverse(),isAry&&length>ary&&(args.length=ary),this&&this!==root&&this instanceof wrapper&&(fn=Ctor||createCtor(fn)),fn.apply(thisBinding,args)}var isAry=bitmask&ARY_FLAG,isBind=bitmask&BIND_FLAG,isBindKey=bitmask&BIND_KEY_FLAG,isCurried=bitmask&(CURRY_FLAG|CURRY_RIGHT_FLAG),isFlip=bitmask&FLIP_FLAG,Ctor=isBindKey?undefined:createCtor(func);return wrapper}function createInverter(setter,toIteratee){return function(object,iteratee){return baseInverter(object,setter,toIteratee(iteratee),{})}}function createMathOperation(operator,defaultValue){return function(value,other){var result;if(value===undefined&&other===undefined)return defaultValue;if(value!==undefined&&(result=value),other!==undefined){if(result===undefined)return other;"string"==typeof value||"string"==typeof other?(value=baseToString(value),other=baseToString(other)):(value=baseToNumber(value),other=baseToNumber(other)),result=operator(value,other)}return result}}function createOver(arrayFunc){return flatRest(function(iteratees){return iteratees=arrayMap(iteratees,baseUnary(getIteratee())),baseRest(function(args){var thisArg=this;return arrayFunc(iteratees,function(iteratee){return apply(iteratee,thisArg,args)})})})}function createPadding(length,chars){chars=chars===undefined?" ":baseToString(chars);var charsLength=chars.length;if(2>charsLength)return charsLength?baseRepeat(chars,length):chars;var result=baseRepeat(chars,nativeCeil(length/stringSize(chars)));return hasUnicode(chars)?castSlice(stringToArray(result),0,length).join(""):result.slice(0,length)}function createPartial(func,bitmask,thisArg,partials){function wrapper(){for(var argsIndex=-1,argsLength=arguments.length,leftIndex=-1,leftLength=partials.length,args=Array(leftLength+argsLength),fn=this&&this!==root&&this instanceof wrapper?Ctor:func;++leftIndexstart?1:-1:toFinite(step),baseRange(start,end,step,fromRight)}}function createRelationalOperation(operator){return function(value,other){return("string"!=typeof value||"string"!=typeof other)&&(value=toNumber(value),other=toNumber(other)),operator(value,other)}}function createRecurry(func,bitmask,wrapFunc,placeholder,thisArg,partials,holders,argPos,ary,arity){var isCurry=bitmask&CURRY_FLAG,newHolders=isCurry?holders:undefined,newHoldersRight=isCurry?undefined:holders,newPartials=isCurry?partials:undefined,newPartialsRight=isCurry?undefined:partials;bitmask|=isCurry?PARTIAL_FLAG:PARTIAL_RIGHT_FLAG,bitmask&=~(isCurry?PARTIAL_RIGHT_FLAG:PARTIAL_FLAG),bitmask&CURRY_BOUND_FLAG||(bitmask&=~(BIND_FLAG|BIND_KEY_FLAG));var newData=[func,bitmask,thisArg,newPartials,newHolders,newPartialsRight,newHoldersRight,argPos,ary,arity],result=wrapFunc.apply(undefined,newData);return isLaziable(func)&&setData(result,newData),result.placeholder=placeholder,setWrapToString(result,func,bitmask)}function createRound(methodName){var func=Math[methodName];return function(number,precision){if(number=toNumber(number),precision=nativeMin(toInteger(precision),292)){var pair=(toString(number)+"e").split("e"),value=func(pair[0]+"e"+(+pair[1]+precision));return pair=(toString(value)+"e").split("e"),+(pair[0]+"e"+(+pair[1]-precision))}return func(number)}}function createToPairs(keysFunc){return function(object){var tag=getTag(object);return tag==mapTag?mapToArray(object):tag==setTag?setToPairs(object):baseToPairs(object,keysFunc(object))}}function createWrap(func,bitmask,thisArg,partials,holders,argPos,ary,arity){var isBindKey=bitmask&BIND_KEY_FLAG;if(!isBindKey&&"function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);var length=partials?partials.length:0;if(length||(bitmask&=~(PARTIAL_FLAG|PARTIAL_RIGHT_FLAG),partials=holders=undefined),ary=ary===undefined?ary:nativeMax(toInteger(ary),0),arity=arity===undefined?arity:toInteger(arity),length-=holders?holders.length:0,bitmask&PARTIAL_RIGHT_FLAG){var partialsRight=partials,holdersRight=holders;partials=holders=undefined}var data=isBindKey?undefined:getData(func),newData=[func,bitmask,thisArg,partials,holders,partialsRight,holdersRight,argPos,ary,arity];if(data&&mergeData(newData,data),func=newData[0],bitmask=newData[1],thisArg=newData[2],partials=newData[3],holders=newData[4],arity=newData[9]=null==newData[9]?isBindKey?0:func.length:nativeMax(newData[9]-length,0),!arity&&bitmask&(CURRY_FLAG|CURRY_RIGHT_FLAG)&&(bitmask&=~(CURRY_FLAG|CURRY_RIGHT_FLAG)),bitmask&&bitmask!=BIND_FLAG)result=bitmask==CURRY_FLAG||bitmask==CURRY_RIGHT_FLAG?createCurry(func,bitmask,arity):bitmask!=PARTIAL_FLAG&&bitmask!=(BIND_FLAG|PARTIAL_FLAG)||holders.length?createHybrid.apply(undefined,newData):createPartial(func,bitmask,thisArg,partials);else var result=createBind(func,bitmask,thisArg);var setter=data?baseSetData:setData;return setWrapToString(setter(result,newData),func,bitmask)}function equalArrays(array,other,equalFunc,customizer,bitmask,stack){var isPartial=bitmask&PARTIAL_COMPARE_FLAG,arrLength=array.length,othLength=other.length;if(arrLength!=othLength&&!(isPartial&&othLength>arrLength))return!1;var stacked=stack.get(array);if(stacked&&stack.get(other))return stacked==other;var index=-1,result=!0,seen=bitmask&UNORDERED_COMPARE_FLAG?new SetCache:undefined;for(stack.set(array,other),stack.set(other,array);++index1?"& ":"")+details[lastIndex],details=details.join(length>2?", ":" "),source.replace(reWrapComment,"{\n/* [wrapped with "+details+"] */\n")}function isFlattenable(value){return isArray(value)||isArguments(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol])}function isIndex(value,length){return length=null==length?MAX_SAFE_INTEGER:length,!!length&&("number"==typeof value||reIsUint.test(value))&&value>-1&&value%1==0&&length>value}function isIterateeCall(value,index,object){if(!isObject(object))return!1;var type=typeof index;return("number"==type?isArrayLike(object)&&isIndex(index,object.length):"string"==type&&index in object)?eq(object[index],value):!1}function isKey(value,object){if(isArray(value))return!1;var type=typeof value;return"number"==type||"symbol"==type||"boolean"==type||null==value||isSymbol(value)?!0:reIsPlainProp.test(value)||!reIsDeepProp.test(value)||null!=object&&value in Object(object)}function isKeyable(value){var type=typeof value;return"string"==type||"number"==type||"symbol"==type||"boolean"==type?"__proto__"!==value:null===value}function isLaziable(func){var funcName=getFuncName(func),other=lodash[funcName];if("function"!=typeof other||!(funcName in LazyWrapper.prototype))return!1;if(func===other)return!0;var data=getData(other);return!!data&&func===data[0]}function isMasked(func){return!!maskSrcKey&&maskSrcKey in func}function isPrototype(value){var Ctor=value&&value.constructor,proto="function"==typeof Ctor&&Ctor.prototype||objectProto;return value===proto}function isStrictComparable(value){return value===value&&!isObject(value)}function matchesStrictComparable(key,srcValue){return function(object){return null==object?!1:object[key]===srcValue&&(srcValue!==undefined||key in Object(object))}}function memoizeCapped(func){var result=memoize(func,function(key){return cache.size===MAX_MEMOIZE_SIZE&&cache.clear(),key}),cache=result.cache;return result}function mergeData(data,source){var bitmask=data[1],srcBitmask=source[1],newBitmask=bitmask|srcBitmask,isCommon=(BIND_FLAG|BIND_KEY_FLAG|ARY_FLAG)>newBitmask,isCombo=srcBitmask==ARY_FLAG&&bitmask==CURRY_FLAG||srcBitmask==ARY_FLAG&&bitmask==REARG_FLAG&&data[7].length<=source[8]||srcBitmask==(ARY_FLAG|REARG_FLAG)&&source[7].length<=source[8]&&bitmask==CURRY_FLAG;if(!isCommon&&!isCombo)return data;srcBitmask&BIND_FLAG&&(data[2]=source[2],newBitmask|=bitmask&BIND_FLAG?0:CURRY_BOUND_FLAG);var value=source[3];if(value){var partials=data[3];data[3]=partials?composeArgs(partials,value,source[4]):value,data[4]=partials?replaceHolders(data[3],PLACEHOLDER):source[4]}return value=source[5],value&&(partials=data[5],data[5]=partials?composeArgsRight(partials,value,source[6]):value,data[6]=partials?replaceHolders(data[5],PLACEHOLDER):source[6]),value=source[7],value&&(data[7]=value),srcBitmask&ARY_FLAG&&(data[8]=null==data[8]?source[8]:nativeMin(data[8],source[8])),null==data[9]&&(data[9]=source[9]),data[0]=source[0],data[1]=newBitmask,data}function mergeDefaults(objValue,srcValue,key,object,source,stack){return isObject(objValue)&&isObject(srcValue)&&(stack.set(srcValue,objValue),baseMerge(objValue,srcValue,undefined,mergeDefaults,stack),stack["delete"](srcValue)),objValue}function nativeKeysIn(object){var result=[];if(null!=object)for(var key in Object(object))result.push(key);return result}function overRest(func,start,transform){return start=nativeMax(start===undefined?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index0){if(++count>=HOT_COUNT)return arguments[0]}else count=0;return func.apply(undefined,arguments)}}function shuffleSelf(array,size){var index=-1,length=array.length,lastIndex=length-1;for(size=size===undefined?length:size;++indexsize)return[];for(var index=0,resIndex=0,result=Array(nativeCeil(length/size));length>index;)result[resIndex++]=baseSlice(array,index,index+=size);return result}function compact(array){for(var index=-1,length=array?array.length:0,resIndex=0,result=[];++indexn?0:n,length)):[]}function dropRight(array,n,guard){var length=array?array.length:0;return length?(n=guard||n===undefined?1:toInteger(n),n=length-n,baseSlice(array,0,0>n?0:n)):[]}function dropRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!0,!0):[]}function dropWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!0):[]}function fill(array,value,start,end){var length=array?array.length:0;return length?(start&&"number"!=typeof start&&isIterateeCall(array,value,start)&&(start=0,end=length),baseFill(array,value,start,end)):[]}function findIndex(array,predicate,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=null==fromIndex?0:toInteger(fromIndex);return 0>index&&(index=nativeMax(length+index,0)),baseFindIndex(array,getIteratee(predicate,3),index)}function findLastIndex(array,predicate,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=length-1;return fromIndex!==undefined&&(index=toInteger(fromIndex),index=0>fromIndex?nativeMax(length+index,0):nativeMin(index,length-1)),baseFindIndex(array,getIteratee(predicate,3),index,!0)}function flatten(array){var length=array?array.length:0;return length?baseFlatten(array,1):[]}function flattenDeep(array){var length=array?array.length:0;return length?baseFlatten(array,INFINITY):[]}function flattenDepth(array,depth){var length=array?array.length:0;return length?(depth=depth===undefined?1:toInteger(depth),baseFlatten(array,depth)):[]}function fromPairs(pairs){for(var index=-1,length=pairs?pairs.length:0,result={};++indexindex&&(index=nativeMax(length+index,0)),baseIndexOf(array,value,index)}function initial(array){var length=array?array.length:0;return length?baseSlice(array,0,-1):[]}function join(array,separator){return array?nativeJoin.call(array,separator):""}function last(array){var length=array?array.length:0;return length?array[length-1]:undefined}function lastIndexOf(array,value,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=length;return fromIndex!==undefined&&(index=toInteger(fromIndex),index=0>index?nativeMax(length+index,0):nativeMin(index,length-1)),value===value?strictLastIndexOf(array,value,index):baseFindIndex(array,baseIsNaN,index,!0)}function nth(array,n){return array&&array.length?baseNth(array,toInteger(n)):undefined}function pullAll(array,values){return array&&array.length&&values&&values.length?basePullAll(array,values):array}function pullAllBy(array,values,iteratee){return array&&array.length&&values&&values.length?basePullAll(array,values,getIteratee(iteratee,2)):array}function pullAllWith(array,values,comparator){return array&&array.length&&values&&values.length?basePullAll(array,values,undefined,comparator):array}function remove(array,predicate){var result=[];if(!array||!array.length)return result;var index=-1,indexes=[],length=array.length;for(predicate=getIteratee(predicate,3);++indexindex&&eq(array[index],value))return index}return-1}function sortedLastIndex(array,value){return baseSortedIndex(array,value,!0)}function sortedLastIndexBy(array,value,iteratee){return baseSortedIndexBy(array,value,getIteratee(iteratee,2),!0)}function sortedLastIndexOf(array,value){var length=array?array.length:0;if(length){var index=baseSortedIndex(array,value,!0)-1;if(eq(array[index],value))return index}return-1}function sortedUniq(array){return array&&array.length?baseSortedUniq(array):[]}function sortedUniqBy(array,iteratee){return array&&array.length?baseSortedUniq(array,getIteratee(iteratee,2)):[]}function tail(array){var length=array?array.length:0;return length?baseSlice(array,1,length):[]}function take(array,n,guard){return array&&array.length?(n=guard||n===undefined?1:toInteger(n),baseSlice(array,0,0>n?0:n)):[]}function takeRight(array,n,guard){var length=array?array.length:0;return length?(n=guard||n===undefined?1:toInteger(n),n=length-n,baseSlice(array,0>n?0:n,length)):[]}function takeRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!1,!0):[]}function takeWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3)):[]}function uniq(array){return array&&array.length?baseUniq(array):[]}function uniqBy(array,iteratee){return array&&array.length?baseUniq(array,getIteratee(iteratee,2)):[]}function uniqWith(array,comparator){return array&&array.length?baseUniq(array,undefined,comparator):[]}function unzip(array){if(!array||!array.length)return[];var length=0;return array=arrayFilter(array,function(group){return isArrayLikeObject(group)?(length=nativeMax(group.length,length),!0):void 0}),baseTimes(length,function(index){return arrayMap(array,baseProperty(index))})}function unzipWith(array,iteratee){if(!array||!array.length)return[];var result=unzip(array);return null==iteratee?result:arrayMap(result,function(group){return apply(iteratee,undefined,group)})}function zipObject(props,values){return baseZipObject(props||[],values||[],assignValue)}function zipObjectDeep(props,values){return baseZipObject(props||[],values||[],baseSet)}function chain(value){var result=lodash(value);return result.__chain__=!0,result}function tap(value,interceptor){return interceptor(value),value}function thru(value,interceptor){return interceptor(value)}function wrapperChain(){return chain(this)}function wrapperCommit(){return new LodashWrapper(this.value(),this.__chain__)}function wrapperNext(){this.__values__===undefined&&(this.__values__=toArray(this.value()));var done=this.__index__>=this.__values__.length,value=done?undefined:this.__values__[this.__index__++];return{done:done,value:value}}function wrapperToIterator(){return this}function wrapperPlant(value){for(var result,parent=this;parent instanceof baseLodash;){var clone=wrapperClone(parent);clone.__index__=0,clone.__values__=undefined,result?previous.__wrapped__=clone:result=clone;var previous=clone;parent=parent.__wrapped__}return previous.__wrapped__=value,result}function wrapperReverse(){var value=this.__wrapped__;if(value instanceof LazyWrapper){var wrapped=value;return this.__actions__.length&&(wrapped=new LazyWrapper(this)),wrapped=wrapped.reverse(),wrapped.__actions__.push({func:thru,args:[reverse],thisArg:undefined}),new LodashWrapper(wrapped,this.__chain__)}return this.thru(reverse)}function wrapperValue(){return baseWrapperValue(this.__wrapped__,this.__actions__)}function every(collection,predicate,guard){var func=isArray(collection)?arrayEvery:baseEvery;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=undefined),func(collection,getIteratee(predicate,3))}function filter(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,getIteratee(predicate,3))}function flatMap(collection,iteratee){return baseFlatten(map(collection,iteratee),1)}function flatMapDeep(collection,iteratee){return baseFlatten(map(collection,iteratee),INFINITY)}function flatMapDepth(collection,iteratee,depth){return depth=depth===undefined?1:toInteger(depth),baseFlatten(map(collection,iteratee),depth)}function forEach(collection,iteratee){var func=isArray(collection)?arrayEach:baseEach;return func(collection,getIteratee(iteratee,3))}function forEachRight(collection,iteratee){var func=isArray(collection)?arrayEachRight:baseEachRight;return func(collection,getIteratee(iteratee,3))}function includes(collection,value,fromIndex,guard){collection=isArrayLike(collection)?collection:values(collection),fromIndex=fromIndex&&!guard?toInteger(fromIndex):0;var length=collection.length;return 0>fromIndex&&(fromIndex=nativeMax(length+fromIndex,0)),isString(collection)?length>=fromIndex&&collection.indexOf(value,fromIndex)>-1:!!length&&baseIndexOf(collection,value,fromIndex)>-1}function map(collection,iteratee){var func=isArray(collection)?arrayMap:baseMap;return func(collection,getIteratee(iteratee,3))}function orderBy(collection,iteratees,orders,guard){return null==collection?[]:(isArray(iteratees)||(iteratees=null==iteratees?[]:[iteratees]),orders=guard?undefined:orders,isArray(orders)||(orders=null==orders?[]:[orders]),baseOrderBy(collection,iteratees,orders))}function reduce(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduce:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEach)}function reduceRight(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduceRight:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEachRight)}function reject(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,negate(getIteratee(predicate,3)))}function sample(collection){var func=isArray(collection)?arraySample:baseSample;return func(collection)}function sampleSize(collection,n,guard){n=(guard?isIterateeCall(collection,n,guard):n===undefined)?1:toInteger(n);var func=isArray(collection)?arraySampleSize:baseSampleSize;return func(collection,n)}function shuffle(collection){var func=isArray(collection)?arrayShuffle:baseShuffle;return func(collection)}function size(collection){if(null==collection)return 0;if(isArrayLike(collection))return isString(collection)?stringSize(collection):collection.length;var tag=getTag(collection);return tag==mapTag||tag==setTag?collection.size:baseKeys(collection).length}function some(collection,predicate,guard){var func=isArray(collection)?arraySome:baseSome;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=undefined),func(collection,getIteratee(predicate,3))}function after(n,func){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return n=toInteger(n),function(){return--n<1?func.apply(this,arguments):void 0}}function ary(func,n,guard){return n=guard?undefined:n,n=func&&null==n?func.length:n,createWrap(func,ARY_FLAG,undefined,undefined,undefined,undefined,n)}function before(n,func){var result;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return n=toInteger(n),function(){return--n>0&&(result=func.apply(this,arguments)),1>=n&&(func=undefined),result}}function curry(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,CURRY_FLAG,undefined,undefined,undefined,undefined,undefined,arity);return result.placeholder=curry.placeholder,result}function curryRight(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,CURRY_RIGHT_FLAG,undefined,undefined,undefined,undefined,undefined,arity);return result.placeholder=curryRight.placeholder,result}function debounce(func,wait,options){function invokeFunc(time){var args=lastArgs,thisArg=lastThis;return lastArgs=lastThis=undefined,lastInvokeTime=time,result=func.apply(thisArg,args)}function leadingEdge(time){return lastInvokeTime=time,timerId=setTimeout(timerExpired,wait),leading?invokeFunc(time):result}function remainingWait(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime,result=wait-timeSinceLastCall;return maxing?nativeMin(result,maxWait-timeSinceLastInvoke):result}function shouldInvoke(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime;return lastCallTime===undefined||timeSinceLastCall>=wait||0>timeSinceLastCall||maxing&&timeSinceLastInvoke>=maxWait}function timerExpired(){var time=now();return shouldInvoke(time)?trailingEdge(time):void(timerId=setTimeout(timerExpired,remainingWait(time)))}function trailingEdge(time){return timerId=undefined,trailing&&lastArgs?invokeFunc(time):(lastArgs=lastThis=undefined,result)}function cancel(){timerId!==undefined&&clearTimeout(timerId),lastInvokeTime=0,lastArgs=lastCallTime=lastThis=timerId=undefined}function flush(){return timerId===undefined?result:trailingEdge(now())}function debounced(){var time=now(),isInvoking=shouldInvoke(time);if(lastArgs=arguments,lastThis=this,lastCallTime=time,isInvoking){if(timerId===undefined)return leadingEdge(lastCallTime);if(maxing)return timerId=setTimeout(timerExpired,wait),invokeFunc(lastCallTime)}return timerId===undefined&&(timerId=setTimeout(timerExpired,wait)),result}var lastArgs,lastThis,maxWait,result,timerId,lastCallTime,lastInvokeTime=0,leading=!1,maxing=!1,trailing=!0;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return wait=toNumber(wait)||0,isObject(options)&&(leading=!!options.leading,maxing="maxWait"in options,maxWait=maxing?nativeMax(toNumber(options.maxWait)||0,wait):maxWait,trailing="trailing"in options?!!options.trailing:trailing),debounced.cancel=cancel,debounced.flush=flush,debounced}function flip(func){return createWrap(func,FLIP_FLAG)}function memoize(func,resolver){if("function"!=typeof func||resolver&&"function"!=typeof resolver)throw new TypeError(FUNC_ERROR_TEXT);var memoized=function(){var args=arguments,key=resolver?resolver.apply(this,args):args[0],cache=memoized.cache;if(cache.has(key))return cache.get(key);var result=func.apply(this,args);return memoized.cache=cache.set(key,result)||cache,result};return memoized.cache=new(memoize.Cache||MapCache),memoized}function negate(predicate){if("function"!=typeof predicate)throw new TypeError(FUNC_ERROR_TEXT);return function(){var args=arguments;switch(args.length){case 0:return!predicate.call(this);case 1:return!predicate.call(this,args[0]);case 2:return!predicate.call(this,args[0],args[1]);case 3:return!predicate.call(this,args[0],args[1],args[2])}return!predicate.apply(this,args)}}function once(func){return before(2,func)}function rest(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=start===undefined?start:toInteger(start),baseRest(func,start)}function spread(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=start===undefined?0:nativeMax(toInteger(start),0),baseRest(function(args){var array=args[start],otherArgs=castSlice(args,0,start);return array&&arrayPush(otherArgs,array),apply(func,this,otherArgs)})}function throttle(func,wait,options){var leading=!0,trailing=!0;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return isObject(options)&&(leading="leading"in options?!!options.leading:leading,trailing="trailing"in options?!!options.trailing:trailing),debounce(func,wait,{leading:leading,maxWait:wait,trailing:trailing})}function unary(func){return ary(func,1)}function wrap(value,wrapper){return wrapper=null==wrapper?identity:wrapper,partial(wrapper,value)}function castArray(){if(!arguments.length)return[];var value=arguments[0];return isArray(value)?value:[value]}function clone(value){return baseClone(value,!1,!0)}function cloneWith(value,customizer){return baseClone(value,!1,!0,customizer)}function cloneDeep(value){return baseClone(value,!0,!0)}function cloneDeepWith(value,customizer){return baseClone(value,!0,!0,customizer)}function conformsTo(object,source){return null==source||baseConformsTo(object,source,keys(source))}function eq(value,other){return value===other||value!==value&&other!==other}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value)}function isBoolean(value){return value===!0||value===!1||isObjectLike(value)&&objectToString.call(value)==boolTag}function isElement(value){return null!=value&&1===value.nodeType&&isObjectLike(value)&&!isPlainObject(value)}function isEmpty(value){if(isArrayLike(value)&&(isArray(value)||"string"==typeof value||"function"==typeof value.splice||isBuffer(value)||isTypedArray(value)||isArguments(value)))return!value.length;var tag=getTag(value);if(tag==mapTag||tag==setTag)return!value.size;if(isPrototype(value))return!baseKeys(value).length;for(var key in value)if(hasOwnProperty.call(value,key))return!1;return!0}function isEqual(value,other){return baseIsEqual(value,other)}function isEqualWith(value,other,customizer){customizer="function"==typeof customizer?customizer:undefined;var result=customizer?customizer(value,other):undefined;return result===undefined?baseIsEqual(value,other,customizer):!!result}function isError(value){return isObjectLike(value)?objectToString.call(value)==errorTag||"string"==typeof value.message&&"string"==typeof value.name:!1}function isFinite(value){return"number"==typeof value&&nativeIsFinite(value)}function isFunction(value){var tag=isObject(value)?objectToString.call(value):"";return tag==funcTag||tag==genTag||tag==proxyTag}function isInteger(value){return"number"==typeof value&&value==toInteger(value)}function isLength(value){return"number"==typeof value&&value>-1&&value%1==0&&MAX_SAFE_INTEGER>=value}function isObject(value){var type=typeof value;return null!=value&&("object"==type||"function"==type)}function isObjectLike(value){return null!=value&&"object"==typeof value}function isMatch(object,source){return object===source||baseIsMatch(object,source,getMatchData(source))}function isMatchWith(object,source,customizer){return customizer="function"==typeof customizer?customizer:undefined,baseIsMatch(object,source,getMatchData(source),customizer)}function isNaN(value){return isNumber(value)&&value!=+value}function isNative(value){if(isMaskable(value))throw new Error(CORE_ERROR_TEXT);return baseIsNative(value)}function isNull(value){return null===value}function isNil(value){return null==value}function isNumber(value){return"number"==typeof value||isObjectLike(value)&&objectToString.call(value)==numberTag}function isPlainObject(value){if(!isObjectLike(value)||objectToString.call(value)!=objectTag)return!1;var proto=getPrototype(value);if(null===proto)return!0;var Ctor=hasOwnProperty.call(proto,"constructor")&&proto.constructor;return"function"==typeof Ctor&&Ctor instanceof Ctor&&funcToString.call(Ctor)==objectCtorString}function isSafeInteger(value){return isInteger(value)&&value>=-MAX_SAFE_INTEGER&&MAX_SAFE_INTEGER>=value}function isString(value){return"string"==typeof value||!isArray(value)&&isObjectLike(value)&&objectToString.call(value)==stringTag}function isSymbol(value){return"symbol"==typeof value||isObjectLike(value)&&objectToString.call(value)==symbolTag}function isUndefined(value){return value===undefined}function isWeakMap(value){return isObjectLike(value)&&getTag(value)==weakMapTag}function isWeakSet(value){return isObjectLike(value)&&objectToString.call(value)==weakSetTag}function toArray(value){if(!value)return[];if(isArrayLike(value))return isString(value)?stringToArray(value):copyArray(value);if(iteratorSymbol&&value[iteratorSymbol])return iteratorToArray(value[iteratorSymbol]());var tag=getTag(value),func=tag==mapTag?mapToArray:tag==setTag?setToArray:values;return func(value)}function toFinite(value){if(!value)return 0===value?value:0;if(value=toNumber(value),value===INFINITY||value===-INFINITY){var sign=0>value?-1:1;return sign*MAX_INTEGER}return value===value?value:0}function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0}function toLength(value){return value?baseClamp(toInteger(value),0,MAX_ARRAY_LENGTH):0}function toNumber(value){if("number"==typeof value)return value;if(isSymbol(value))return NAN;if(isObject(value)){var other="function"==typeof value.valueOf?value.valueOf():value;value=isObject(other)?other+"":other}if("string"!=typeof value)return 0===value?value:+value;value=value.replace(reTrim,"");var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value}function toPlainObject(value){return copyObject(value,keysIn(value))}function toSafeInteger(value){return baseClamp(toInteger(value),-MAX_SAFE_INTEGER,MAX_SAFE_INTEGER)}function toString(value){return null==value?"":baseToString(value)}function create(prototype,properties){var result=baseCreate(prototype);return properties?baseAssign(result,properties):result}function findKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwn)}function findLastKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwnRight)}function forIn(object,iteratee){return null==object?object:baseFor(object,getIteratee(iteratee,3),keysIn)}function forInRight(object,iteratee){return null==object?object:baseForRight(object,getIteratee(iteratee,3),keysIn)}function forOwn(object,iteratee){return object&&baseForOwn(object,getIteratee(iteratee,3))}function forOwnRight(object,iteratee){return object&&baseForOwnRight(object,getIteratee(iteratee,3))}function functions(object){return null==object?[]:baseFunctions(object,keys(object))}function functionsIn(object){return null==object?[]:baseFunctions(object,keysIn(object))}function get(object,path,defaultValue){var result=null==object?undefined:baseGet(object,path);return result===undefined?defaultValue:result}function has(object,path){return null!=object&&hasPath(object,path,baseHas)}function hasIn(object,path){return null!=object&&hasPath(object,path,baseHasIn)}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function keysIn(object){return isArrayLike(object)?arrayLikeKeys(object,!0):baseKeysIn(object)}function mapKeys(object,iteratee){var result={};return iteratee=getIteratee(iteratee,3), baseForOwn(object,function(value,key,object){baseAssignValue(result,iteratee(value,key,object),value)}),result}function mapValues(object,iteratee){var result={};return iteratee=getIteratee(iteratee,3),baseForOwn(object,function(value,key,object){baseAssignValue(result,key,iteratee(value,key,object))}),result}function omitBy(object,predicate){return pickBy(object,negate(getIteratee(predicate)))}function pickBy(object,predicate){return null==object?{}:basePickBy(object,getAllKeysIn(object),getIteratee(predicate))}function result(object,path,defaultValue){path=isKey(path,object)?[path]:castPath(path);var index=-1,length=path.length;for(length||(object=undefined,length=1);++indexupper){var temp=lower;lower=upper,upper=temp}if(floating||lower%1||upper%1){var rand=nativeRandom();return nativeMin(lower+rand*(upper-lower+freeParseFloat("1e-"+((rand+"").length-1))),upper)}return baseRandom(lower,upper)}function capitalize(string){return upperFirst(toString(string).toLowerCase())}function deburr(string){return string=toString(string),string&&string.replace(reLatin,deburrLetter).replace(reComboMark,"")}function endsWith(string,target,position){string=toString(string),target=baseToString(target);var length=string.length;position=position===undefined?length:baseClamp(toInteger(position),0,length);var end=position;return position-=target.length,position>=0&&string.slice(position,end)==target}function escape(string){return string=toString(string),string&&reHasUnescapedHtml.test(string)?string.replace(reUnescapedHtml,escapeHtmlChar):string}function escapeRegExp(string){return string=toString(string),string&&reHasRegExpChar.test(string)?string.replace(reRegExpChar,"\\$&"):string}function pad(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;if(!length||strLength>=length)return string;var mid=(length-strLength)/2;return createPadding(nativeFloor(mid),chars)+string+createPadding(nativeCeil(mid),chars)}function padEnd(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;return length&&length>strLength?string+createPadding(length-strLength,chars):string}function padStart(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;return length&&length>strLength?createPadding(length-strLength,chars)+string:string}function parseInt(string,radix,guard){return guard||null==radix?radix=0:radix&&(radix=+radix),nativeParseInt(toString(string).replace(reTrimStart,""),radix||0)}function repeat(string,n,guard){return n=(guard?isIterateeCall(string,n,guard):n===undefined)?1:toInteger(n),baseRepeat(toString(string),n)}function replace(){var args=arguments,string=toString(args[0]);return args.length<3?string:string.replace(args[1],args[2])}function split(string,separator,limit){return limit&&"number"!=typeof limit&&isIterateeCall(string,separator,limit)&&(separator=limit=undefined),(limit=limit===undefined?MAX_ARRAY_LENGTH:limit>>>0)?(string=toString(string),string&&("string"==typeof separator||null!=separator&&!isRegExp(separator))&&(separator=baseToString(separator),!separator&&hasUnicode(string))?castSlice(stringToArray(string),0,limit):string.split(separator,limit)):[]}function startsWith(string,target,position){return string=toString(string),position=baseClamp(toInteger(position),0,string.length),target=baseToString(target),string.slice(position,position+target.length)==target}function template(string,options,guard){var settings=lodash.templateSettings;guard&&isIterateeCall(string,options,guard)&&(options=undefined),string=toString(string),options=assignInWith({},options,settings,assignInDefaults);var isEscaping,isEvaluating,imports=assignInWith({},options.imports,settings.imports,assignInDefaults),importsKeys=keys(imports),importsValues=baseValues(imports,importsKeys),index=0,interpolate=options.interpolate||reNoMatch,source="__p += '",reDelimiters=RegExp((options.escape||reNoMatch).source+"|"+interpolate.source+"|"+(interpolate===reInterpolate?reEsTemplate:reNoMatch).source+"|"+(options.evaluate||reNoMatch).source+"|$","g"),sourceURL="//# sourceURL="+("sourceURL"in options?options.sourceURL:"lodash.templateSources["+ ++templateCounter+"]")+"\n";string.replace(reDelimiters,function(match,escapeValue,interpolateValue,esTemplateValue,evaluateValue,offset){return interpolateValue||(interpolateValue=esTemplateValue),source+=string.slice(index,offset).replace(reUnescapedString,escapeStringChar),escapeValue&&(isEscaping=!0,source+="' +\n__e("+escapeValue+") +\n'"),evaluateValue&&(isEvaluating=!0,source+="';\n"+evaluateValue+";\n__p += '"),interpolateValue&&(source+="' +\n((__t = ("+interpolateValue+")) == null ? '' : __t) +\n'"),index=offset+match.length,match}),source+="';\n";var variable=options.variable;variable||(source="with (obj) {\n"+source+"\n}\n"),source=(isEvaluating?source.replace(reEmptyStringLeading,""):source).replace(reEmptyStringMiddle,"$1").replace(reEmptyStringTrailing,"$1;"),source="function("+(variable||"obj")+") {\n"+(variable?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(isEscaping?", __e = _.escape":"")+(isEvaluating?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+source+"return __p\n}";var result=attempt(function(){return Function(importsKeys,sourceURL+"return "+source).apply(undefined,importsValues)});if(result.source=source,isError(result))throw result;return result}function toLower(value){return toString(value).toLowerCase()}function toUpper(value){return toString(value).toUpperCase()}function trim(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrim,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),chrSymbols=stringToArray(chars),start=charsStartIndex(strSymbols,chrSymbols),end=charsEndIndex(strSymbols,chrSymbols)+1;return castSlice(strSymbols,start,end).join("")}function trimEnd(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrimEnd,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),end=charsEndIndex(strSymbols,stringToArray(chars))+1;return castSlice(strSymbols,0,end).join("")}function trimStart(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrimStart,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),start=charsStartIndex(strSymbols,stringToArray(chars));return castSlice(strSymbols,start).join("")}function truncate(string,options){var length=DEFAULT_TRUNC_LENGTH,omission=DEFAULT_TRUNC_OMISSION;if(isObject(options)){var separator="separator"in options?options.separator:separator;length="length"in options?toInteger(options.length):length,omission="omission"in options?baseToString(options.omission):omission}string=toString(string);var strLength=string.length;if(hasUnicode(string)){var strSymbols=stringToArray(string);strLength=strSymbols.length}if(length>=strLength)return string;var end=length-stringSize(omission);if(1>end)return omission;var result=strSymbols?castSlice(strSymbols,0,end).join(""):string.slice(0,end);if(separator===undefined)return result+omission;if(strSymbols&&(end+=result.length-end),isRegExp(separator)){if(string.slice(end).search(separator)){var match,substring=result;for(separator.global||(separator=RegExp(separator.source,toString(reFlags.exec(separator))+"g")),separator.lastIndex=0;match=separator.exec(substring);)var newEnd=match.index;result=result.slice(0,newEnd===undefined?end:newEnd)}}else if(string.indexOf(baseToString(separator),end)!=end){var index=result.lastIndexOf(separator);index>-1&&(result=result.slice(0,index))}return result+omission}function unescape(string){return string=toString(string),string&&reHasEscapedHtml.test(string)?string.replace(reEscapedHtml,unescapeHtmlChar):string}function words(string,pattern,guard){return string=toString(string),pattern=guard?undefined:pattern,pattern===undefined?hasUnicodeWord(string)?unicodeWords(string):asciiWords(string):string.match(pattern)||[]}function cond(pairs){var length=pairs?pairs.length:0,toIteratee=getIteratee();return pairs=length?arrayMap(pairs,function(pair){if("function"!=typeof pair[1])throw new TypeError(FUNC_ERROR_TEXT);return[toIteratee(pair[0]),pair[1]]}):[],baseRest(function(args){for(var index=-1;++indexn||n>MAX_SAFE_INTEGER)return[];var index=MAX_ARRAY_LENGTH,length=nativeMin(n,MAX_ARRAY_LENGTH);iteratee=getIteratee(iteratee),n-=MAX_ARRAY_LENGTH;for(var result=baseTimes(length,iteratee);++index1?arrays[length-1]:undefined;return iteratee="function"==typeof iteratee?(arrays.pop(),iteratee):undefined,unzipWith(arrays,iteratee)}),wrapperAt=flatRest(function(paths){var length=paths.length,start=length?paths[0]:0,value=this.__wrapped__,interceptor=function(object){return baseAt(object,paths)};return!(length>1||this.__actions__.length)&&value instanceof LazyWrapper&&isIndex(start)?(value=value.slice(start,+start+(length?1:0)),value.__actions__.push({func:thru,args:[interceptor],thisArg:undefined}),new LodashWrapper(value,this.__chain__).thru(function(array){return length&&!array.length&&array.push(undefined),array})):this.thru(interceptor)}),countBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?++result[key]:baseAssignValue(result,key,1)}),find=createFind(findIndex),findLast=createFind(findLastIndex),groupBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?result[key].push(value):baseAssignValue(result,key,[value])}),invokeMap=baseRest(function(collection,path,args){var index=-1,isFunc="function"==typeof path,isProp=isKey(path),result=isArrayLike(collection)?Array(collection.length):[];return baseEach(collection,function(value){var func=isFunc?path:isProp&&null!=value?value[path]:undefined;result[++index]=func?apply(func,value,args):baseInvoke(value,path,args)}),result}),keyBy=createAggregator(function(result,value,key){baseAssignValue(result,key,value)}),partition=createAggregator(function(result,value,key){result[key?0:1].push(value)},function(){return[[],[]]}),sortBy=baseRest(function(collection,iteratees){if(null==collection)return[];var length=iteratees.length;return length>1&&isIterateeCall(collection,iteratees[0],iteratees[1])?iteratees=[]:length>2&&isIterateeCall(iteratees[0],iteratees[1],iteratees[2])&&(iteratees=[iteratees[0]]),baseOrderBy(collection,baseFlatten(iteratees,1),[])}),now=ctxNow||function(){return root.Date.now()},bind=baseRest(function(func,thisArg,partials){var bitmask=BIND_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bind));bitmask|=PARTIAL_FLAG}return createWrap(func,bitmask,thisArg,partials,holders)}),bindKey=baseRest(function(object,key,partials){var bitmask=BIND_FLAG|BIND_KEY_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bindKey));bitmask|=PARTIAL_FLAG}return createWrap(key,bitmask,object,partials,holders)}),defer=baseRest(function(func,args){return baseDelay(func,1,args)}),delay=baseRest(function(func,wait,args){return baseDelay(func,toNumber(wait)||0,args)});memoize.Cache=MapCache;var overArgs=castRest(function(func,transforms){transforms=1==transforms.length&&isArray(transforms[0])?arrayMap(transforms[0],baseUnary(getIteratee())):arrayMap(baseFlatten(transforms,1),baseUnary(getIteratee()));var funcsLength=transforms.length;return baseRest(function(args){for(var index=-1,length=nativeMin(args.length,funcsLength);++index=other}),isArguments=baseIsArguments(function(){return arguments}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty.call(value,"callee")&&!propertyIsEnumerable.call(value,"callee")},isArray=Array.isArray,isArrayBuffer=nodeIsArrayBuffer?baseUnary(nodeIsArrayBuffer):baseIsArrayBuffer,isBuffer=nativeIsBuffer||stubFalse,isDate=nodeIsDate?baseUnary(nodeIsDate):baseIsDate,isMap=nodeIsMap?baseUnary(nodeIsMap):baseIsMap,isRegExp=nodeIsRegExp?baseUnary(nodeIsRegExp):baseIsRegExp,isSet=nodeIsSet?baseUnary(nodeIsSet):baseIsSet,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray,lt=createRelationalOperation(baseLt),lte=createRelationalOperation(function(value,other){return other>=value}),assign=createAssigner(function(object,source){if(isPrototype(source)||isArrayLike(source))return void copyObject(source,keys(source),object);for(var key in source)hasOwnProperty.call(source,key)&&assignValue(object,key,source[key])}),assignIn=createAssigner(function(object,source){copyObject(source,keysIn(source),object)}),assignInWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keysIn(source),object,customizer)}),assignWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keys(source),object,customizer)}),at=flatRest(baseAt),defaults=baseRest(function(args){return args.push(undefined,assignInDefaults),apply(assignInWith,undefined,args)}),defaultsDeep=baseRest(function(args){return args.push(undefined,mergeDefaults),apply(mergeWith,undefined,args)}),invert=createInverter(function(result,value,key){result[value]=key},constant(identity)),invertBy=createInverter(function(result,value,key){hasOwnProperty.call(result,value)?result[value].push(key):result[value]=[key]},getIteratee),invoke=baseRest(baseInvoke),merge=createAssigner(function(object,source,srcIndex){baseMerge(object,source,srcIndex)}),mergeWith=createAssigner(function(object,source,srcIndex,customizer){baseMerge(object,source,srcIndex,customizer)}),omit=flatRest(function(object,props){return null==object?{}:(props=arrayMap(props,toKey),basePick(object,baseDifference(getAllKeysIn(object),props)))}),pick=flatRest(function(object,props){return null==object?{}:basePick(object,arrayMap(props,toKey))}),toPairs=createToPairs(keys),toPairsIn=createToPairs(keysIn),camelCase=createCompounder(function(result,word,index){return word=word.toLowerCase(),result+(index?capitalize(word):word)}),kebabCase=createCompounder(function(result,word,index){return result+(index?"-":"")+word.toLowerCase()}),lowerCase=createCompounder(function(result,word,index){return result+(index?" ":"")+word.toLowerCase()}),lowerFirst=createCaseFirst("toLowerCase"),snakeCase=createCompounder(function(result,word,index){return result+(index?"_":"")+word.toLowerCase()}),startCase=createCompounder(function(result,word,index){return result+(index?" ":"")+upperFirst(word)}),upperCase=createCompounder(function(result,word,index){return result+(index?" ":"")+word.toUpperCase()}),upperFirst=createCaseFirst("toUpperCase"),attempt=baseRest(function(func,args){try{return apply(func,undefined,args)}catch(e){return isError(e)?e:new Error(e)}}),bindAll=flatRest(function(object,methodNames){return arrayEach(methodNames,function(key){key=toKey(key),baseAssignValue(object,key,bind(object[key],object))}),object}),flow=createFlow(),flowRight=createFlow(!0),method=baseRest(function(path,args){return function(object){return baseInvoke(object,path,args)}}),methodOf=baseRest(function(object,args){return function(path){return baseInvoke(object,path,args)}}),over=createOver(arrayMap),overEvery=createOver(arrayEvery),overSome=createOver(arraySome),range=createRange(),rangeRight=createRange(!0),add=createMathOperation(function(augend,addend){return augend+addend},0),ceil=createRound("ceil"),divide=createMathOperation(function(dividend,divisor){return dividend/divisor},1),floor=createRound("floor"),multiply=createMathOperation(function(multiplier,multiplicand){return multiplier*multiplicand},1),round=createRound("round"),subtract=createMathOperation(function(minuend,subtrahend){return minuend-subtrahend},0);return lodash.after=after,lodash.ary=ary,lodash.assign=assign,lodash.assignIn=assignIn,lodash.assignInWith=assignInWith,lodash.assignWith=assignWith,lodash.at=at,lodash.before=before,lodash.bind=bind,lodash.bindAll=bindAll,lodash.bindKey=bindKey,lodash.castArray=castArray,lodash.chain=chain,lodash.chunk=chunk,lodash.compact=compact,lodash.concat=concat,lodash.cond=cond,lodash.conforms=conforms,lodash.constant=constant,lodash.countBy=countBy,lodash.create=create,lodash.curry=curry,lodash.curryRight=curryRight,lodash.debounce=debounce,lodash.defaults=defaults,lodash.defaultsDeep=defaultsDeep,lodash.defer=defer,lodash.delay=delay,lodash.difference=difference,lodash.differenceBy=differenceBy,lodash.differenceWith=differenceWith,lodash.drop=drop,lodash.dropRight=dropRight,lodash.dropRightWhile=dropRightWhile,lodash.dropWhile=dropWhile,lodash.fill=fill,lodash.filter=filter,lodash.flatMap=flatMap,lodash.flatMapDeep=flatMapDeep,lodash.flatMapDepth=flatMapDepth,lodash.flatten=flatten,lodash.flattenDeep=flattenDeep,lodash.flattenDepth=flattenDepth,lodash.flip=flip,lodash.flow=flow,lodash.flowRight=flowRight,lodash.fromPairs=fromPairs,lodash.functions=functions,lodash.functionsIn=functionsIn,lodash.groupBy=groupBy,lodash.initial=initial,lodash.intersection=intersection,lodash.intersectionBy=intersectionBy,lodash.intersectionWith=intersectionWith,lodash.invert=invert,lodash.invertBy=invertBy,lodash.invokeMap=invokeMap,lodash.iteratee=iteratee,lodash.keyBy=keyBy,lodash.keys=keys,lodash.keysIn=keysIn,lodash.map=map,lodash.mapKeys=mapKeys,lodash.mapValues=mapValues,lodash.matches=matches,lodash.matchesProperty=matchesProperty, -lodash.memoize=memoize,lodash.merge=merge,lodash.mergeWith=mergeWith,lodash.method=method,lodash.methodOf=methodOf,lodash.mixin=mixin,lodash.negate=negate,lodash.nthArg=nthArg,lodash.omit=omit,lodash.omitBy=omitBy,lodash.once=once,lodash.orderBy=orderBy,lodash.over=over,lodash.overArgs=overArgs,lodash.overEvery=overEvery,lodash.overSome=overSome,lodash.partial=partial,lodash.partialRight=partialRight,lodash.partition=partition,lodash.pick=pick,lodash.pickBy=pickBy,lodash.property=property,lodash.propertyOf=propertyOf,lodash.pull=pull,lodash.pullAll=pullAll,lodash.pullAllBy=pullAllBy,lodash.pullAllWith=pullAllWith,lodash.pullAt=pullAt,lodash.range=range,lodash.rangeRight=rangeRight,lodash.rearg=rearg,lodash.reject=reject,lodash.remove=remove,lodash.rest=rest,lodash.reverse=reverse,lodash.sampleSize=sampleSize,lodash.set=set,lodash.setWith=setWith,lodash.shuffle=shuffle,lodash.slice=slice,lodash.sortBy=sortBy,lodash.sortedUniq=sortedUniq,lodash.sortedUniqBy=sortedUniqBy,lodash.split=split,lodash.spread=spread,lodash.tail=tail,lodash.take=take,lodash.takeRight=takeRight,lodash.takeRightWhile=takeRightWhile,lodash.takeWhile=takeWhile,lodash.tap=tap,lodash.throttle=throttle,lodash.thru=thru,lodash.toArray=toArray,lodash.toPairs=toPairs,lodash.toPairsIn=toPairsIn,lodash.toPath=toPath,lodash.toPlainObject=toPlainObject,lodash.transform=transform,lodash.unary=unary,lodash.union=union,lodash.unionBy=unionBy,lodash.unionWith=unionWith,lodash.uniq=uniq,lodash.uniqBy=uniqBy,lodash.uniqWith=uniqWith,lodash.unset=unset,lodash.unzip=unzip,lodash.unzipWith=unzipWith,lodash.update=update,lodash.updateWith=updateWith,lodash.values=values,lodash.valuesIn=valuesIn,lodash.without=without,lodash.words=words,lodash.wrap=wrap,lodash.xor=xor,lodash.xorBy=xorBy,lodash.xorWith=xorWith,lodash.zip=zip,lodash.zipObject=zipObject,lodash.zipObjectDeep=zipObjectDeep,lodash.zipWith=zipWith,lodash.entries=toPairs,lodash.entriesIn=toPairsIn,lodash.extend=assignIn,lodash.extendWith=assignInWith,mixin(lodash,lodash),lodash.add=add,lodash.attempt=attempt,lodash.camelCase=camelCase,lodash.capitalize=capitalize,lodash.ceil=ceil,lodash.clamp=clamp,lodash.clone=clone,lodash.cloneDeep=cloneDeep,lodash.cloneDeepWith=cloneDeepWith,lodash.cloneWith=cloneWith,lodash.conformsTo=conformsTo,lodash.deburr=deburr,lodash.defaultTo=defaultTo,lodash.divide=divide,lodash.endsWith=endsWith,lodash.eq=eq,lodash.escape=escape,lodash.escapeRegExp=escapeRegExp,lodash.every=every,lodash.find=find,lodash.findIndex=findIndex,lodash.findKey=findKey,lodash.findLast=findLast,lodash.findLastIndex=findLastIndex,lodash.findLastKey=findLastKey,lodash.floor=floor,lodash.forEach=forEach,lodash.forEachRight=forEachRight,lodash.forIn=forIn,lodash.forInRight=forInRight,lodash.forOwn=forOwn,lodash.forOwnRight=forOwnRight,lodash.get=get,lodash.gt=gt,lodash.gte=gte,lodash.has=has,lodash.hasIn=hasIn,lodash.head=head,lodash.identity=identity,lodash.includes=includes,lodash.indexOf=indexOf,lodash.inRange=inRange,lodash.invoke=invoke,lodash.isArguments=isArguments,lodash.isArray=isArray,lodash.isArrayBuffer=isArrayBuffer,lodash.isArrayLike=isArrayLike,lodash.isArrayLikeObject=isArrayLikeObject,lodash.isBoolean=isBoolean,lodash.isBuffer=isBuffer,lodash.isDate=isDate,lodash.isElement=isElement,lodash.isEmpty=isEmpty,lodash.isEqual=isEqual,lodash.isEqualWith=isEqualWith,lodash.isError=isError,lodash.isFinite=isFinite,lodash.isFunction=isFunction,lodash.isInteger=isInteger,lodash.isLength=isLength,lodash.isMap=isMap,lodash.isMatch=isMatch,lodash.isMatchWith=isMatchWith,lodash.isNaN=isNaN,lodash.isNative=isNative,lodash.isNil=isNil,lodash.isNull=isNull,lodash.isNumber=isNumber,lodash.isObject=isObject,lodash.isObjectLike=isObjectLike,lodash.isPlainObject=isPlainObject,lodash.isRegExp=isRegExp,lodash.isSafeInteger=isSafeInteger,lodash.isSet=isSet,lodash.isString=isString,lodash.isSymbol=isSymbol,lodash.isTypedArray=isTypedArray,lodash.isUndefined=isUndefined,lodash.isWeakMap=isWeakMap,lodash.isWeakSet=isWeakSet,lodash.join=join,lodash.kebabCase=kebabCase,lodash.last=last,lodash.lastIndexOf=lastIndexOf,lodash.lowerCase=lowerCase,lodash.lowerFirst=lowerFirst,lodash.lt=lt,lodash.lte=lte,lodash.max=max,lodash.maxBy=maxBy,lodash.mean=mean,lodash.meanBy=meanBy,lodash.min=min,lodash.minBy=minBy,lodash.stubArray=stubArray,lodash.stubFalse=stubFalse,lodash.stubObject=stubObject,lodash.stubString=stubString,lodash.stubTrue=stubTrue,lodash.multiply=multiply,lodash.nth=nth,lodash.noConflict=noConflict,lodash.noop=noop,lodash.now=now,lodash.pad=pad,lodash.padEnd=padEnd,lodash.padStart=padStart,lodash.parseInt=parseInt,lodash.random=random,lodash.reduce=reduce,lodash.reduceRight=reduceRight,lodash.repeat=repeat,lodash.replace=replace,lodash.result=result,lodash.round=round,lodash.runInContext=runInContext,lodash.sample=sample,lodash.size=size,lodash.snakeCase=snakeCase,lodash.some=some,lodash.sortedIndex=sortedIndex,lodash.sortedIndexBy=sortedIndexBy,lodash.sortedIndexOf=sortedIndexOf,lodash.sortedLastIndex=sortedLastIndex,lodash.sortedLastIndexBy=sortedLastIndexBy,lodash.sortedLastIndexOf=sortedLastIndexOf,lodash.startCase=startCase,lodash.startsWith=startsWith,lodash.subtract=subtract,lodash.sum=sum,lodash.sumBy=sumBy,lodash.template=template,lodash.times=times,lodash.toFinite=toFinite,lodash.toInteger=toInteger,lodash.toLength=toLength,lodash.toLower=toLower,lodash.toNumber=toNumber,lodash.toSafeInteger=toSafeInteger,lodash.toString=toString,lodash.toUpper=toUpper,lodash.trim=trim,lodash.trimEnd=trimEnd,lodash.trimStart=trimStart,lodash.truncate=truncate,lodash.unescape=unescape,lodash.uniqueId=uniqueId,lodash.upperCase=upperCase,lodash.upperFirst=upperFirst,lodash.each=forEach,lodash.eachRight=forEachRight,lodash.first=head,mixin(lodash,function(){var source={};return baseForOwn(lodash,function(func,methodName){hasOwnProperty.call(lodash.prototype,methodName)||(source[methodName]=func)}),source}(),{chain:!1}),lodash.VERSION=VERSION,arrayEach(["bind","bindKey","curry","curryRight","partial","partialRight"],function(methodName){lodash[methodName].placeholder=lodash}),arrayEach(["drop","take"],function(methodName,index){LazyWrapper.prototype[methodName]=function(n){var filtered=this.__filtered__;if(filtered&&!index)return new LazyWrapper(this);n=n===undefined?1:nativeMax(toInteger(n),0);var result=this.clone();return filtered?result.__takeCount__=nativeMin(n,result.__takeCount__):result.__views__.push({size:nativeMin(n,MAX_ARRAY_LENGTH),type:methodName+(result.__dir__<0?"Right":"")}),result},LazyWrapper.prototype[methodName+"Right"]=function(n){return this.reverse()[methodName](n).reverse()}}),arrayEach(["filter","map","takeWhile"],function(methodName,index){var type=index+1,isFilter=type==LAZY_FILTER_FLAG||type==LAZY_WHILE_FLAG;LazyWrapper.prototype[methodName]=function(iteratee){var result=this.clone();return result.__iteratees__.push({iteratee:getIteratee(iteratee,3),type:type}),result.__filtered__=result.__filtered__||isFilter,result}}),arrayEach(["head","last"],function(methodName,index){var takeName="take"+(index?"Right":"");LazyWrapper.prototype[methodName]=function(){return this[takeName](1).value()[0]}}),arrayEach(["initial","tail"],function(methodName,index){var dropName="drop"+(index?"":"Right");LazyWrapper.prototype[methodName]=function(){return this.__filtered__?new LazyWrapper(this):this[dropName](1)}}),LazyWrapper.prototype.compact=function(){return this.filter(identity)},LazyWrapper.prototype.find=function(predicate){return this.filter(predicate).head()},LazyWrapper.prototype.findLast=function(predicate){return this.reverse().find(predicate)},LazyWrapper.prototype.invokeMap=baseRest(function(path,args){return"function"==typeof path?new LazyWrapper(this):this.map(function(value){return baseInvoke(value,path,args)})}),LazyWrapper.prototype.reject=function(predicate){return this.filter(negate(getIteratee(predicate)))},LazyWrapper.prototype.slice=function(start,end){start=toInteger(start);var result=this;return result.__filtered__&&(start>0||0>end)?new LazyWrapper(result):(0>start?result=result.takeRight(-start):start&&(result=result.drop(start)),end!==undefined&&(end=toInteger(end),result=0>end?result.dropRight(-end):result.take(end-start)),result)},LazyWrapper.prototype.takeRightWhile=function(predicate){return this.reverse().takeWhile(predicate).reverse()},LazyWrapper.prototype.toArray=function(){return this.take(MAX_ARRAY_LENGTH)},baseForOwn(LazyWrapper.prototype,function(func,methodName){var checkIteratee=/^(?:filter|find|map|reject)|While$/.test(methodName),isTaker=/^(?:head|last)$/.test(methodName),lodashFunc=lodash[isTaker?"take"+("last"==methodName?"Right":""):methodName],retUnwrapped=isTaker||/^find/.test(methodName);lodashFunc&&(lodash.prototype[methodName]=function(){var value=this.__wrapped__,args=isTaker?[1]:arguments,isLazy=value instanceof LazyWrapper,iteratee=args[0],useLazy=isLazy||isArray(value),interceptor=function(value){var result=lodashFunc.apply(lodash,arrayPush([value],args));return isTaker&&chainAll?result[0]:result};useLazy&&checkIteratee&&"function"==typeof iteratee&&1!=iteratee.length&&(isLazy=useLazy=!1);var chainAll=this.__chain__,isHybrid=!!this.__actions__.length,isUnwrapped=retUnwrapped&&!chainAll,onlyLazy=isLazy&&!isHybrid;if(!retUnwrapped&&useLazy){value=onlyLazy?value:new LazyWrapper(this);var result=func.apply(value,args);return result.__actions__.push({func:thru,args:[interceptor],thisArg:undefined}),new LodashWrapper(result,chainAll)}return isUnwrapped&&onlyLazy?func.apply(this,args):(result=this.thru(interceptor),isUnwrapped?isTaker?result.value()[0]:result.value():result)})}),arrayEach(["pop","push","shift","sort","splice","unshift"],function(methodName){var func=arrayProto[methodName],chainName=/^(?:push|sort|unshift)$/.test(methodName)?"tap":"thru",retUnwrapped=/^(?:pop|shift)$/.test(methodName);lodash.prototype[methodName]=function(){var args=arguments;if(retUnwrapped&&!this.__chain__){var value=this.value();return func.apply(isArray(value)?value:[],args)}return this[chainName](function(value){return func.apply(isArray(value)?value:[],args)})}}),baseForOwn(LazyWrapper.prototype,function(func,methodName){var lodashFunc=lodash[methodName];if(lodashFunc){var key=lodashFunc.name+"",names=realNames[key]||(realNames[key]=[]);names.push({name:methodName,func:lodashFunc})}}),realNames[createHybrid(undefined,BIND_KEY_FLAG).name]=[{name:"wrapper",func:undefined}],LazyWrapper.prototype.clone=lazyClone,LazyWrapper.prototype.reverse=lazyReverse,LazyWrapper.prototype.value=lazyValue,lodash.prototype.at=wrapperAt,lodash.prototype.chain=wrapperChain,lodash.prototype.commit=wrapperCommit,lodash.prototype.next=wrapperNext,lodash.prototype.plant=wrapperPlant,lodash.prototype.reverse=wrapperReverse,lodash.prototype.toJSON=lodash.prototype.valueOf=lodash.prototype.value=wrapperValue,lodash.prototype.first=lodash.prototype.head,iteratorSymbol&&(lodash.prototype[iteratorSymbol]=wrapperToIterator),lodash},_=runInContext();"function"==typeof define&&"object"==typeof define.amd&&define.amd?(root._=_,define(function(){return _})):freeModule?((freeModule.exports=_)._=_,freeExports._=_):root._=_}.call(this);var UsergridAuthMode=Object.freeze({NONE:"none",USER:"user",APP:"app"}),UsergridDirection=Object.freeze({IN:"connecting",OUT:"connections"}),UsergridHttpMethod=Object.freeze({GET:"GET",PUT:"PUT",POST:"POST",DELETE:"DELETE"}),UsergridQueryOperator=Object.freeze({EQUAL:"=",GREATER_THAN:">",GREATER_THAN_EQUAL_TO:">=",LESS_THAN:"<",LESS_THAN_EQUAL_TO:"<="}),UsergridQuerySortOrder=Object.freeze({ASC:"asc",DESC:"desc"}),UsergridApplicationJSONHeaderValue="application/json";!function(global){function UsergridHelpers(){}var name="UsergridHelpers",overwrittenName=global[name];UsergridHelpers.DefaultHeaders=Object.freeze({"Content-Type":UsergridApplicationJSONHeaderValue,Accept:UsergridApplicationJSONHeaderValue}),UsergridHelpers.validateAndRetrieveClient=function(args){var client=void 0;if(args instanceof UsergridClient)client=args;else if(args[0]instanceof UsergridClient)client=args[0];else if(_.get(args,"client"))client=args.client;else{if(!Usergrid.isInitialized)throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument");client=Usergrid}return client},UsergridHelpers.inherits=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})},UsergridHelpers.flattenArgs=function(args){return _.flattenDeep(Array.prototype.slice.call(args))},UsergridHelpers.callback=function(){var args=UsergridHelpers.flattenArgs(arguments).reverse(),emptyFunc=function(){};return _.first(_.flattenDeep([args,_.get(args,"0.callback"),emptyFunc]).filter(_.isFunction))},UsergridHelpers.authForRequests=function(client){var authForRequests=void 0;return _.get(client,"tempAuth.isValid")?(authForRequests=client.tempAuth,client.tempAuth=void 0):_.get(client,"currentUser.auth.isValid")&&client.authMode===UsergridAuthMode.USER?authForRequests=client.currentUser.auth:_.get(client,"appAuth.isValid")&&client.authMode===UsergridAuthMode.APP&&(authForRequests=client.appAuth),authForRequests},UsergridHelpers.userLoginBody=function(options){var body={grant_type:"password",password:options.password};return options.tokenTtl&&(body.ttl=options.tokenTtl),body[options.username?"username":"email"]=options.username?options.username:options.email,body},UsergridHelpers.appLoginBody=function(options){var body={grant_type:"client_credentials",client_id:options.clientId,client_secret:options.clientSecret};return options.tokenTtl&&(body.ttl=options.tokenTtl),body},UsergridHelpers.calculateExpiry=function(expires_in){return Date.now()+1e3*(expires_in?expires_in-5:0)};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;return UsergridHelpers.isUUID=function(uuid){return uuid?uuidValueRegex.test(uuid):!1},UsergridHelpers.useQuotesIfRequired=function(value){return _.isFinite(value)||UsergridHelpers.isUUID(value)||_.isBoolean(value)||_.isObject(value)&&!_.isFunction(value)||_.isArray(value)?value:"'"+value+"'"},UsergridHelpers.setReadOnly=function(obj,key){return _.isArray(key)?key.forEach(function(k){UsergridHelpers.setReadOnly(obj,k)}):_.isPlainObject(obj[key])?Object.freeze(obj[key]):_.isPlainObject(obj)&&void 0===key?Object.freeze(obj):_.has(obj,key)?Object.defineProperty(obj,key,{writable:!1}):obj},UsergridHelpers.setWritable=function(obj,key){return _.isArray(key)?key.forEach(function(k){UsergridHelpers.setWritable(obj,k)}):_.isPlainObject(obj[key])?_.clone(obj[key]):_.isPlainObject(obj)&&void 0===key?_.clone(obj):_.has(obj,key)?Object.defineProperty(obj,key,{writable:!0}):obj},UsergridHelpers.assignPrefabOptions=function(args){return _.isObject(args[0])&&!_.isFunction(args[0])&&_.has(args,"method")&&_.assign(this,args[0]),this},UsergridHelpers.normalize=function(str){return str=str.replace(/\/+/g,"/"),str=str.replace(/:\//g,"://"),str=str.replace(/\/(\?|&|#[^!])/g,"$1"),str=str.replace(/(\?.+)\?/g,"$1&")},UsergridHelpers.urljoin=function(){var input=arguments,options={};"object"==typeof arguments[0]&&(input=arguments[0],options=arguments[1]||{});var joined=[].slice.call(input,0).join("/");return UsergridHelpers.normalize(joined,options)},UsergridHelpers.parseResponseHeaders=function(headerStr){var headers={};if(headerStr)for(var headerPairs=headerStr.split("\r\n"),i=0;i0){var key=headerPair.substring(0,index).toLowerCase();headers[key]=headerPair.substring(index+2)}}return headers},UsergridHelpers.uri=function(client,options){var path="";path=options instanceof UsergridEntity?options.type:options instanceof UsergridQuery?options._type:_.isString(options)?options:_.isArray(options)?_.get(options,"0.type")||_.get(options,"0.path"):options.path||options.type||_.get(options,"entity.type")||_.get(options,"query._type")||_.get(options,"body.type")||_.get(options,"body.path");var uuidOrName="";return options.method!==UsergridHttpMethod.POST&&(uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,_.get(options,"entity.uuid"),_.get(options,"entity.name"),_.get(options,"body.uuid"),_.get(options,"body.name"),""].filter(_.isString))),UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,path,uuidOrName)},UsergridHelpers.updateEntityFromRemote=function(entity,usergridResponse){UsergridHelpers.setWritable(entity,["uuid","name","type","created"]),_.assign(entity,usergridResponse.entity),UsergridHelpers.setReadOnly(entity,["uuid","name","type","created"])},UsergridHelpers.headers=function(client,options,defaultHeaders){var returnHeaders={};_.defaults(returnHeaders,options.headers,defaultHeaders),_.assign(returnHeaders,{"User-Agent":"usergrid-js/v"+UsergridSDKVersion});var authForRequests=UsergridHelpers.authForRequests(client);return authForRequests&&_.assign(returnHeaders,{authorization:"Bearer "+authForRequests.token}),returnHeaders},UsergridHelpers.setEntity=function(options,args){return options.entity=_.first([options.entity,args[0]].filter(function(property){return property instanceof UsergridEntity})),void 0!==options.entity&&(options.type=options.entity.type),options},UsergridHelpers.setAsset=function(options,args){return options.asset=_.first([options.asset,_.get(options,"entity.asset"),args[1],args[0]].filter(function(property){return property instanceof UsergridAsset})),options},UsergridHelpers.setUuidOrName=function(options,args){return options.uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,_.get(options,"entity.uuid"),_.get(options,"body.uuid"),_.get(options,"entity.name"),_.get(options,"body.name"),_.get(args,"0.uuid"),_.get(args,"0.name"),_.get(args,"2"),_.get(args,"1")].filter(_.isString)),options},UsergridHelpers.setPathOrType=function(options,args){var pathOrType=_.first([args.type,_.get(args,"0.type"),_.get(options,"entity.type"),_.get(args,"body.type"),_.get(options,"body.0.type"),_.isArray(args)?args[0]:void 0].filter(_.isString));return options[/\//.test(pathOrType)?"path":"type"]=pathOrType,options},UsergridHelpers.setQs=function(options,args){return options.path&&(options.qs=_.first([options.qs,args[2],args[1],args[0]].filter(_.isPlainObject))),options},UsergridHelpers.setQuery=function(options,args){return options.query=_.first([options,options.query,args[0]].filter(function(property){return property instanceof UsergridQuery})),options},UsergridHelpers.setAsset=function(options,args){return options.asset=_.first([options.asset,_.get(options,"entity.asset"),args[1],args[0]].filter(function(property){return property instanceof UsergridAsset})),options},UsergridHelpers.setBody=function(options,args){if(options.body=_.first([args.entity,args.body,args[0].entity,args[0].body,args[2],args[1],args[0]].filter(function(property){return _.isObject(property)&&!_.isFunction(property)&&!(property instanceof UsergridQuery)&&!(property instanceof UsergridAsset)})),void 0===options.body&&void 0===options.asset)throw new Error('"body" is required when making a '+options.method+" request");return options.body instanceof UsergridEntity?options.body=options.body.jsonValue():options.body instanceof Array&&options.body[0]instanceof UsergridEntity&&(options.body=_.map(options.body,function(entity){return entity.jsonValue()})),options},UsergridHelpers.buildReqest=function(client,method,args){var options={client:client,method:method,queryParams:args.queryParams||_.get(args,"0.queryParams"),callback:UsergridHelpers.callback(args)};return UsergridHelpers.assignPrefabOptions(options,args),UsergridHelpers.setEntity(options,args),(method===UsergridHttpMethod.POST||method===UsergridHttpMethod.PUT)&&(UsergridHelpers.setAsset(options,args),void 0===options.asset&&UsergridHelpers.setBody(options,args)),UsergridHelpers.setUuidOrName(options,args),UsergridHelpers.setPathOrType(options,args),UsergridHelpers.setQs(options,args),UsergridHelpers.setQuery(options,args),options.uri=UsergridHelpers.uri(client,options),new UsergridRequest(options)},UsergridHelpers.buildAppAuthRequest=function(client,auth,callback){var requestOptions={client:client,method:UsergridHttpMethod.POST,uri:UsergridHelpers.uri(client,{path:"token"}),body:UsergridHelpers.appLoginBody(auth),callback:callback};return new UsergridRequest(requestOptions)},UsergridHelpers.buildConnectionRequest=function(client,method,args){var options={client:client,method:method,entity:{},to:{},callback:UsergridHelpers.callback(args)};if(UsergridHelpers.assignPrefabOptions.call(options,args),_.isObject(options.from)&&(options.to=options.from),_.isObject(args[0])&&_.has(args[0],"entity")&&_.has(args[0],"to")&&(_.assign(options.entity,args[0].entity),options.relationship=_.get(args,"0.relationship"),_.assign(options.to,args[0].to)),_.isObject(args[0])&&!_.isFunction(args[0])&&_.isString(args[1])&&(_.assign(options.entity,args[0]),options.relationship=_.first([options.relationship,args[1]].filter(_.isString))),_.isObject(args[2])&&!_.isFunction(args[2])&&_.assign(options.to,args[2]),options.entity.uuidOrName=_.first([options.entity.uuidOrName,options.entity.uuid,options.entity.name,args[1]].filter(_.isString)),options.entity.type||(options.entity.type=_.first([options.entity.type,args[0]].filter(_.isString))),options.relationship=_.first([options.relationship,args[2]].filter(_.isString)),_.isString(args[3])&&!UsergridHelpers.isUUID(args[3])&&_.isString(args[4])?options.to.type=args[3]:_.isString(args[2])&&!UsergridHelpers.isUUID(args[2])&&_.isString(args[3])&&_.isObject(args[0])&&!_.isFunction(args[0])&&(options.to.type=args[2]),options.to.uuidOrName=_.first([options.to.uuidOrName,options.to.uuid,options.to.name,args[4],args[3],args[2]].filter(function(property){return _.isString(options.to.type)&&_.isString(property)||UsergridHelpers.isUUID(property)})),!_.isString(options.entity.uuidOrName))throw new Error('source entity "uuidOrName" is required when connecting or disconnecting entities');if(!_.isString(options.to.uuidOrName))throw new Error('target entity "uuidOrName" is required when connecting or disconnecting entities');if(!_.isString(options.to.type)&&!UsergridHelpers.isUUID(options.to.uuidOrName))throw new Error('target "type" (collection name) parameter is required connecting or disconnecting entities by name');return options.uri=UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,_.isString(options.entity.type)?options.entity.type:"",_.isString(options.entity.uuidOrName)?options.entity.uuidOrName:"",options.relationship,_.isString(options.to.type)?options.to.type:"",_.isString(options.to.uuidOrName)?options.to.uuidOrName:""),new UsergridRequest(options)},UsergridHelpers.buildGetConnectionRequest=function(client,args){var options={client:client,method:"GET",callback:UsergridHelpers.callback(args)};if(UsergridHelpers.assignPrefabOptions.call(options,args),_.isObject(args[1])&&!_.isFunction(args[1])&&_.assign(options,args[1]),options.direction=_.first([options.direction,args[0]].filter(function(property){return property===UsergridDirection.IN||property===UsergridDirection.OUT})),options.relationship=_.first([options.relationship,args[3],args[2]].filter(_.isString)),options.uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,args[2]].filter(_.isString)),options.type=_.first([options.type,args[1]].filter(_.isString)),!_.isString(options.type))throw new Error('"type" (collection name) parameter is required when retrieving connections');if(!_.isString(options.uuidOrName))throw new Error('target entity "uuidOrName" is required when retrieving connections');return options.uri=UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,_.isString(options.type)?options.type:"",_.isString(options.uuidOrName)?options.uuidOrName:"",options.direction,options.relationship),new UsergridRequest(options)},global[name]=UsergridHelpers,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),UsergridHelpers},global[name]}(this);var UsergridClientDefaultOptions={baseUrl:"https://api.usergrid.com",authMode:UsergridAuthMode.USER},UsergridClient=function(options){var __appAuth,self=this;if(self.tempAuth=void 0,self.isSharedInstance=!1,2===arguments.length&&(self.orgId=arguments[0],self.appId=arguments[1]),_.defaults(self,options,UsergridClientDefaultOptions),!self.orgId||!self.appId)throw new Error('"orgId" and "appId" parameters are required when instantiating UsergridClient');return Object.defineProperty(self,"clientId",{enumerable:!1}),Object.defineProperty(self,"clientSecret",{enumerable:!1}),Object.defineProperty(self,"appAuth",{get:function(){return __appAuth},set:function(options){options instanceof UsergridAppAuth?__appAuth=options:"undefined"!=typeof options&&(__appAuth=new UsergridAppAuth(options))}}),self.clientId&&self.clientSecret&&self.setAppAuth(self.clientId,self.clientSecret),self};UsergridClient.prototype={sendRequest:function(usergridRequest){return usergridRequest.sendRequest()},GET:function(){var usergridRequest=UsergridHelpers.buildReqest(this,UsergridHttpMethod.GET,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},PUT:function(){var usergridRequest=UsergridHelpers.buildReqest(this,UsergridHttpMethod.PUT,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},POST:function(){var usergridRequest=UsergridHelpers.buildReqest(this,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},DELETE:function(){var usergridRequest=UsergridHelpers.buildReqest(this,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},connect:function(){var usergridRequest=UsergridHelpers.buildConnectionRequest(this,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},disconnect:function(){var usergridRequest=UsergridHelpers.buildConnectionRequest(this,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},getConnections:function(){var usergridRequest=UsergridHelpers.buildGetConnectionRequest(this,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},usingAuth:function(auth){var self=this;return _.isString(auth)?self.tempAuth=new UsergridAuth(auth):auth instanceof UsergridAuth?self.tempAuth=auth:self.tempAuth=void 0,self},setAppAuth:function(){this.appAuth=new UsergridAppAuth(UsergridHelpers.flattenArgs(arguments))},authenticateApp:function(options){var self=this,authenticateAppCallback=UsergridHelpers.callback(UsergridHelpers.flattenArgs(arguments)),auth=_.first([options,self.appAuth,new UsergridAppAuth(options),new UsergridAppAuth(self.clientId,self.clientSecret)].filter(function(p){return p instanceof UsergridAppAuth}));if(!(auth instanceof UsergridAppAuth))throw new Error("App auth context was not defined when attempting to call .authenticateApp()");if(!auth.clientId||!auth.clientSecret)throw new Error("authenticateApp() failed because clientId or clientSecret are missing");var callback=function(usergridResponse){if(usergridResponse.ok){self.appAuth||(self.appAuth=auth),self.appAuth.token=_.get(usergridResponse.responseJSON,"access_token");var expiresIn=_.get(usergridResponse.responseJSON,"expires_in");self.appAuth.expiry=UsergridHelpers.calculateExpiry(expiresIn),self.appAuth.tokenTtl=expiresIn}authenticateAppCallback(usergridResponse)},usergridRequest=UsergridHelpers.buildAppAuthRequest(self,auth,callback);return self.sendRequest(usergridRequest)},authenticateUser:function(options){var self=this,args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args),setAsCurrentUser=void 0!==_.last(args.filter(_.isBoolean))?_.last(args.filter(_.isBoolean)):!0,userToAuthenticate=new UsergridUser(options);userToAuthenticate.login(self,function(auth,user,usergridResponse){usergridResponse.ok&&setAsCurrentUser&&(self.currentUser=userToAuthenticate),callback(auth,user,usergridResponse)})},downloadAsset:function(){var self=this,usergridRequest=UsergridHelpers.buildReqest(self,UsergridHttpMethod.GET,UsergridHelpers.flattenArgs(arguments)),assetContentType=_.get(usergridRequest,"entity.file-metadata.content-type");void 0!==assetContentType&&_.assign(usergridRequest.headers,{Accept:assetContentType});var realDownloadAssetCallback=usergridRequest.callback;return usergridRequest.callback=function(usergridResponse){var entity=usergridRequest.entity;entity.asset=usergridResponse.asset,realDownloadAssetCallback(entity.asset,usergridResponse,entity)},self.sendRequest(usergridRequest)},uploadAsset:function(){var self=this,usergridRequest=UsergridHelpers.buildReqest(self,UsergridHttpMethod.PUT,UsergridHelpers.flattenArgs(arguments));if(void 0===usergridRequest.asset)throw new Error("An UsergridAsset was not defined when attempting to call .uploadAsset()");var realUploadAssetCallback=usergridRequest.callback;return usergridRequest.callback=function(usergridResponse){var requestEntity=usergridRequest.entity,responseEntity=usergridResponse.entity,requestAsset=usergridRequest.asset;usergridResponse.ok&&void 0!==responseEntity&&(UsergridHelpers.updateEntityFromRemote(requestEntity,usergridResponse),requestEntity.asset=requestAsset,responseEntity&&(responseEntity.asset=requestAsset)),realUploadAssetCallback(requestAsset,usergridResponse,requestEntity)},self.sendRequest(usergridRequest)}};var UsergridSDKVersion="2.0.0",UsergridClientSharedInstance=function(){var self=this;return self.isInitialized=!1,self.isSharedInstance=!0,self};UsergridHelpers.inherits(UsergridClientSharedInstance,UsergridClient);var Usergrid=new UsergridClientSharedInstance;Usergrid.initSharedInstance=function(options){return Usergrid.isInitialized?console.log("Usergrid shared instance is already initialized"):(_.assign(Usergrid,new UsergridClient(options)),Usergrid.isInitialized=!0,Usergrid.isSharedInstance=!0),Usergrid},Usergrid.init=Usergrid.initSharedInstance;var UsergridQuery=function(type){var queryString,sort,self=this,query="",urlTerms={},__nextIsNot=!1;return self._type=type,_.assign(self,{type:function(value){return self._type=value,self},collection:function(value){return self._type=value,self},limit:function(value){return self._limit=value,self},cursor:function(value){return self._cursor=value,self},eq:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.EQUAL+" "+UsergridHelpers.useQuotesIfRequired(value)),self},equal:this.eq,gt:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.GREATER_THAN+" "+UsergridHelpers.useQuotesIfRequired(value)),self},greaterThan:this.gt,gte:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.GREATER_THAN_EQUAL_TO+" "+UsergridHelpers.useQuotesIfRequired(value)),self},greaterThanOrEqual:this.gte,lt:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.LESS_THAN+" "+UsergridHelpers.useQuotesIfRequired(value)),self},lessThan:this.lt,lte:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.LESS_THAN_EQUAL_TO+" "+UsergridHelpers.useQuotesIfRequired(value)),self},lessThanOrEqual:this.lte,contains:function(key,value){return query=self.andJoin(key+" contains "+UsergridHelpers.useQuotesIfRequired(value)),self},locationWithin:function(distanceInMeters,lat,lng){return query=self.andJoin("location within "+distanceInMeters+" of "+lat+", "+lng),self},asc:function(key){return self.sort(key,UsergridQuerySortOrder.ASC),self},desc:function(key){return self.sort(key,UsergridQuerySortOrder.DESC),self},sort:function(key,order){return sort=key&&order?" order by "+key+" "+order:"",self},fromString:function(string){return queryString=string,self},urlTerm:function(key,value){return"ql"===key?self.fromString():urlTerms[key]=value,self},andJoin:function(append){return __nextIsNot&&(append="not "+append,__nextIsNot=!1), -append?0===query.length?append:_.endsWith(query,"and")||_.endsWith(query,"or")?query+" "+append:query+" and "+append:query},orJoin:function(){return query.length>0&&!_.endsWith(query,"or")?query+" or":query}}),Object.defineProperty(self,"_ql",{get:function(){var ql="select * ";return void 0!==queryString?ql=queryString:(ql+=query.length>0?"where "+(query||""):"",ql+=void 0!==sort?sort:""),ql}}),Object.defineProperty(self,"encodedStringValue",{get:function(){var self=this,limit=self._limit,cursor=self._cursor,requirementsString=self._ql,returnString=void 0;if(void 0!==limit&&(returnString="limit"+UsergridQueryOperator.EQUAL+limit),!_.isEmpty(cursor)){var cursorString="cursor"+UsergridQueryOperator.EQUAL+cursor;_.isEmpty(returnString)?returnString=cursorString:returnString+="&"+cursorString}if(_.forEach(urlTerms,function(value,key){var encodedURLTermString=encodeURIComponent(key)+UsergridQueryOperator.EQUAL+encodeURIComponent(value);_.isEmpty(returnString)?returnString=encodedURLTermString:returnString+="&"+encodedURLTermString}),!_.isEmpty(requirementsString)){var qLString="ql="+encodeURIComponent(requirementsString);_.isEmpty(returnString)?returnString=qLString:returnString+="&"+qLString}return _.isEmpty(returnString)||(returnString="?"+returnString),_.isEmpty(returnString)?void 0:returnString}}),Object.defineProperty(self,"and",{get:function(){return query=self.andJoin(""),self}}),Object.defineProperty(self,"or",{get:function(){return query=self.orJoin(),self}}),Object.defineProperty(self,"not",{get:function(){return __nextIsNot=!0,self}}),self},UsergridRequest=function(options){var self=this,client=UsergridHelpers.validateAndRetrieveClient(options);if(!_.isString(options.type)&&!_.isString(options.path)&&!_.isString(options.uri))throw new Error('one of "type" (collection name), "path", or "uri" parameters are required when initializing a UsergridRequest');if(!_.includes(["GET","PUT","POST","DELETE"],options.method))throw new Error('"method" parameter is required when initializing a UsergridRequest');self.method=options.method,self.callback=options.callback,self.uri=options.uri||UsergridHelpers.uri(client,options),self.entity=options.entity,self.body=options.body||void 0,self.asset=options.asset||void 0,self.query=options.query,self.queryParams=options.queryParams||options.qs;var defaultHeadersToUse=void 0===self.asset?UsergridHelpers.DefaultHeaders:{};if(self.headers=UsergridHelpers.headers(client,options,defaultHeadersToUse),void 0!==self.query&&(self.uri+=UsergridHelpers.normalize(self.query.encodedStringValue,{})),void 0!==self.queryParams&&(_.forOwn(self.queryParams,function(value,key){self.uri+="?"+encodeURIComponent(key)+UsergridQueryOperator.EQUAL+encodeURIComponent(value)}),self.uri=UsergridHelpers.normalize(self.uri,{})),void 0!==self.asset)self.body=new FormData,self.body.append(self.asset.filename,self.asset.data);else try{_.isPlainObject(self.body)?self.body=JSON.stringify(self.body):_.isArray(self.body)&&(self.body=JSON.stringify(self.body))}catch(exception){}return self};UsergridRequest.prototype.sendRequest=function(){var self=this,requestPromise=function(){var promise=new Promise,xmlHttpRequest=new XMLHttpRequest;return xmlHttpRequest.open(self.method,self.uri,!0),xmlHttpRequest.onload=function(){promise.done(xmlHttpRequest)},_.forOwn(self.headers,function(value,key){xmlHttpRequest.setRequestHeader(key,value)}),self.method===UsergridHttpMethod.GET&&_.get(self.headers,"Accept")!==UsergridApplicationJSONHeaderValue&&(xmlHttpRequest.responseType="blob"),xmlHttpRequest.send(self.body),promise},responsePromise=function(xmlRequest){var promise=new Promise,usergridResponse=new UsergridResponse(xmlRequest,self);return promise.done(usergridResponse),promise},onCompletePromise=function(response){var promise=new Promise;promise.done(response),self.callback(response)};return Promise.chain([requestPromise,responsePromise]).then(onCompletePromise),self};var UsergridAuth=function(token,expiry){var self=this;self.token=token,self.expiry=expiry||0;var usingToken=token?!0:!1;return Object.defineProperty(self,"hasToken",{get:function(){return void 0!==self.token},configurable:!0}),Object.defineProperty(self,"isExpired",{get:function(){return usingToken?!1:Date.now()>=self.expiry},configurable:!0}),Object.defineProperty(self,"isValid",{get:function(){return!self.isExpired&&self.hasToken},configurable:!0}),Object.defineProperty(self,"tokenTtl",{configurable:!0,writable:!0}),_.assign(self,{destroy:function(){self.token=void 0,self.expiry=0,self.tokenTtl=void 0}}),self},UsergridAppAuth=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments);return _.isPlainObject(args[0])?(self.clientId=args[0].clientId,self.clientSecret=args[0].clientSecret,self.tokenTtl=args[0].tokenTtl):(self.clientId=args[0],self.clientSecret=args[1],self.tokenTtl=args[2]),UsergridAuth.call(self),_.assign(self,UsergridAuth),self};UsergridHelpers.inherits(UsergridAppAuth,UsergridAuth);var UsergridUserAuth=function(options){var self=this,args=_.flattenDeep(UsergridHelpers.flattenArgs(arguments));return _.isPlainObject(args[0])&&(options=args[0]),self.username=options.username||args[0],self.email=options.email,(options.password||args[1])&&(self.password=options.password||args[1]),self.tokenTtl=options.tokenTtl||args[2],UsergridAuth.call(self),_.assign(self,UsergridAuth),self};UsergridHelpers.inherits(UsergridUserAuth,UsergridAuth);var UsergridEntity=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments);if(0===args.length)throw new Error("A UsergridEntity object cannot be initialized without passing one or more arguments");if(self.asset=void 0,_.isPlainObject(args[0])?_.assign(self,args[0]):(self.type||(self.type=_.isString(args[0])?args[0]:void 0),self.name||(self.name=_.isString(args[1])?args[1]:void 0)),!_.isString(self.type))throw new Error('"type" (or "collection") parameter is required when initializing a UsergridEntity object');return Object.defineProperty(self,"isUser",{get:function(){return"user"===self.type.toLowerCase()}}),Object.defineProperty(self,"hasAsset",{get:function(){return _.has(self,"file-metadata")}}),UsergridHelpers.setReadOnly(self,["uuid","name","type","created"]),self};UsergridEntity.prototype={jsonValue:function(){var jsonValue={};return _.forOwn(this,function(value,key){jsonValue[key]=value}),jsonValue},putProperty:function(key,value){this[key]=value},putProperties:function(obj){_.assign(this,obj)},removeProperty:function(key){this.removeProperties([key])},removeProperties:function(keys){var self=this;keys.forEach(function(key){delete self[key]})},insert:function(key,value,idx){_.isArray(this[key])||(this[key]=this[key]?[this[key]]:[]),this[key].splice.apply(this[key],[idx,0].concat(value))},append:function(key,value){this.insert(key,value,Number.MAX_VALUE)},prepend:function(key,value){this.insert(key,value,0)},pop:function(key){_.isArray(this[key])&&this[key].pop()},shift:function(key){_.isArray(this[key])&&this[key].shift()},reload:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.GET(self,function(usergridResponse){UsergridHelpers.updateEntityFromRemote(self,usergridResponse),callback(usergridResponse,self)}.bind(self))},save:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args),currentAsset=self.asset;client.PUT(self,function(usergridResponse){UsergridHelpers.updateEntityFromRemote(self,usergridResponse),self.hasAsset&&(self.asset=currentAsset),callback(usergridResponse,self)}.bind(self))},remove:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.DELETE(self,function(usergridResponse){callback(usergridResponse,self)}.bind(self))},attachAsset:function(asset){this.asset=asset},uploadAsset:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(_.has(self,"asset.contentType"))client.uploadAsset(self,callback);else{var response=new UsergridResponse.responseWithError({name:"asset_not_found",description:"The specified entity does not have a valid asset attached"});callback(null,response,self)}},downloadAsset:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(_.has(self,"asset.contentType"))client.downloadAsset(self,callback);else{var response=new UsergridResponse.responseWithError({name:"asset_not_found",description:"The specified entity does not have a valid asset attached"});callback(null,response,self)}},connect:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args[0]=this,client.connect.apply(client,args)},disconnect:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args[0]=this,client.disconnect.apply(client,args)},getConnections:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args.shift(),args.splice(1,0,this),client.getConnections.apply(client,args)}};var UsergridUser=function(obj){if(!_.has(obj,"email")&&!_.has(obj,"username"))throw new Error('"email" or "username" property is required when initializing a UsergridUser object');var self=this;return _.assign(self,obj,UsergridEntity),UsergridEntity.call(self,"user"),UsergridHelpers.setWritable(self,"name"),self};UsergridUser.CheckAvailable=function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);args[0]instanceof UsergridClient&&args.shift();var checkQuery,callback=UsergridHelpers.callback(args);if(args[0].username&&args[0].email)checkQuery=new UsergridQuery("users").eq("username",args[0].username).or.eq("email",args[0].email);else if(args[0].username)checkQuery=new UsergridQuery("users").eq("username",args[0].username);else{if(!args[0].email)throw new Error("'username' or 'email' property is required when checking for available users");checkQuery=new UsergridQuery("users").eq("email",args[0].email)}client.GET(checkQuery,function(usergridResponse){callback(usergridResponse,usergridResponse.entities.length>0)})},UsergridHelpers.inherits(UsergridUser,UsergridEntity),UsergridUser.prototype.uniqueId=function(){var self=this;return _.first([self.uuid,self.username,self.email].filter(_.isString))},UsergridUser.prototype.create=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.POST(self,function(usergridResponse){delete self.password,_.assign(self,usergridResponse.user),callback(usergridResponse,usergridResponse.user)}.bind(self))},UsergridUser.prototype.login=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.POST("token",UsergridHelpers.userLoginBody(self),function(usergridResponse){if(delete self.password,usergridResponse.ok){var responseJSON=usergridResponse.responseJSON;self.auth=new UsergridUserAuth(self),self.auth.token=_.get(responseJSON,"access_token");var expiresIn=_.get(responseJSON,"expires_in");self.auth.expiry=UsergridHelpers.calculateExpiry(expiresIn),self.auth.tokenTtl=expiresIn}callback(self.auth,self,usergridResponse)})},UsergridUser.prototype.logout=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(self.auth&&self.auth.isValid){var revokeAll=_.first(args.filter(_.isBoolean))||!1,queryParams=void 0;revokeAll||(queryParams={token:self.auth.token});var requestOptions={client:client,path:["users",self.uniqueId(),"revoketoken"+(revokeAll?"s":"")].join("/"),method:UsergridHttpMethod.PUT,queryParams:queryParams,callback:function(usergridResponse){self.auth.destroy(),callback(usergridResponse)}.bind(self)},request=new UsergridRequest(requestOptions);client.sendRequest(request)}else{var response=new UsergridResponse.responseWithError({name:"no_valid_token",description:"this user does not have a valid token"});callback(response)}},UsergridUser.prototype.logoutAllSessions=function(){var args=UsergridHelpers.flattenArgs(arguments);return args=_.concat([UsergridHelpers.validateAndRetrieveClient(args),!0],args),this.logout.apply(this,args)},UsergridUser.prototype.resetPassword=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);args[0]instanceof UsergridClient&&args.shift();var body={oldpassword:_.isPlainObject(args[0])?args[0].oldPassword:_.isString(args[0])?args[0]:void 0,newpassword:_.isPlainObject(args[0])?args[0].newPassword:_.isString(args[1])?args[1]:void 0};if(!body.oldpassword||!body.newpassword)throw new Error('"oldPassword" and "newPassword" properties are required when resetting a user password');client.PUT(["users",self.uniqueId(),"password"].join("/"),body,callback)};var UsergridResponseError=function(options){var self=this;return _.assign(self,options),self};UsergridResponseError.fromJSON=function(responseErrorObject){var usergridResponseError=void 0,error={name:_.get(responseErrorObject,"error")};return void 0!==error.name&&(_.assign(error,{exception:_.get(responseErrorObject,"exception"),description:_.get(responseErrorObject,"error_description")||_.get(responseErrorObject,"description")}),usergridResponseError=new UsergridResponseError(error)),usergridResponseError};var UsergridResponse=function(xmlRequest,usergridRequest){var self=this;if(self.ok=!1,self.request=usergridRequest,xmlRequest){self.statusCode=parseInt(xmlRequest.status),self.ok=self.statusCode<400,self.headers=UsergridHelpers.parseResponseHeaders(xmlRequest.getAllResponseHeaders());var responseContentType=_.get(self.headers,"content-type");if("application/json"===responseContentType){try{var responseJSON=JSON.parse(xmlRequest.responseText)}catch(e){responseJSON={}}self.parseResponseJSON(responseJSON),Object.defineProperty(self,"cursor",{get:function(){return _.get(self,"responseJSON.cursor")}}),Object.defineProperty(self,"hasNextPage",{get:function(){return void 0!==self.cursor}})}else self.asset=new UsergridAsset(xmlRequest.response)}return self};UsergridResponse.responseWithError=function(options){var usergridResponse=new UsergridResponse;return usergridResponse.error=new UsergridResponseError(options),usergridResponse},UsergridResponse.prototype={parseResponseJSON:function(responseJSON){var self=this;if(void 0!==responseJSON)if(_.assign(self,{responseJSON:_.cloneDeep(responseJSON)}),self.ok){var entitiesJSON=_.get(responseJSON,"entities");if(entitiesJSON){var entities=_.map(entitiesJSON,function(entityJSON){var entity=new UsergridEntity(entityJSON);return entity.isUser&&(entity=new UsergridUser(entity)),entity});_.assign(self,{entities:entities}),delete self.responseJSON.entities,self.first=_.first(entities)||void 0,self.entity=self.first,self.last=_.last(entities)||void 0,"/users"===_.get(responseJSON,"path")&&(self.user=self.first,self.users=self.entities),UsergridHelpers.setReadOnly(self.responseJSON)}}else self.error=UsergridResponseError.fromJSON(responseJSON)},loadNextPage:function(){var self=this,cursor=self.cursor;if(cursor){var args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args),client=UsergridHelpers.validateAndRetrieveClient(args),type=_.last(_.get(self,"responseJSON.path").split("/")),limit=_.first(_.get(self,"responseJSON.params.limit")),ql=_.first(_.get(self,"responseJSON.params.ql")),query=new UsergridQuery(type).fromString(ql).cursor(cursor).limit(limit);client.GET(query,callback)}else callback(UsergridResponse.responseWithError({name:"cursor_not_found",description:"Cursor must be present in order perform loadNextPage()."}))}};var UsergridAssetDefaultFileName="file",UsergridAsset=function(fileOrBlob){if(!fileOrBlob instanceof File||!fileOrBlob instanceof Blob)throw new Error("UsergridAsset must be initialized with a 'File' or 'Blob'");var self=this;return self.data=fileOrBlob,self.filename=fileOrBlob.name||UsergridAssetDefaultFileName,self.contentLength=fileOrBlob.size,self.contentType=fileOrBlob.type,self}; \ No newline at end of file +lodash.memoize=memoize,lodash.merge=merge,lodash.mergeWith=mergeWith,lodash.method=method,lodash.methodOf=methodOf,lodash.mixin=mixin,lodash.negate=negate,lodash.nthArg=nthArg,lodash.omit=omit,lodash.omitBy=omitBy,lodash.once=once,lodash.orderBy=orderBy,lodash.over=over,lodash.overArgs=overArgs,lodash.overEvery=overEvery,lodash.overSome=overSome,lodash.partial=partial,lodash.partialRight=partialRight,lodash.partition=partition,lodash.pick=pick,lodash.pickBy=pickBy,lodash.property=property,lodash.propertyOf=propertyOf,lodash.pull=pull,lodash.pullAll=pullAll,lodash.pullAllBy=pullAllBy,lodash.pullAllWith=pullAllWith,lodash.pullAt=pullAt,lodash.range=range,lodash.rangeRight=rangeRight,lodash.rearg=rearg,lodash.reject=reject,lodash.remove=remove,lodash.rest=rest,lodash.reverse=reverse,lodash.sampleSize=sampleSize,lodash.set=set,lodash.setWith=setWith,lodash.shuffle=shuffle,lodash.slice=slice,lodash.sortBy=sortBy,lodash.sortedUniq=sortedUniq,lodash.sortedUniqBy=sortedUniqBy,lodash.split=split,lodash.spread=spread,lodash.tail=tail,lodash.take=take,lodash.takeRight=takeRight,lodash.takeRightWhile=takeRightWhile,lodash.takeWhile=takeWhile,lodash.tap=tap,lodash.throttle=throttle,lodash.thru=thru,lodash.toArray=toArray,lodash.toPairs=toPairs,lodash.toPairsIn=toPairsIn,lodash.toPath=toPath,lodash.toPlainObject=toPlainObject,lodash.transform=transform,lodash.unary=unary,lodash.union=union,lodash.unionBy=unionBy,lodash.unionWith=unionWith,lodash.uniq=uniq,lodash.uniqBy=uniqBy,lodash.uniqWith=uniqWith,lodash.unset=unset,lodash.unzip=unzip,lodash.unzipWith=unzipWith,lodash.update=update,lodash.updateWith=updateWith,lodash.values=values,lodash.valuesIn=valuesIn,lodash.without=without,lodash.words=words,lodash.wrap=wrap,lodash.xor=xor,lodash.xorBy=xorBy,lodash.xorWith=xorWith,lodash.zip=zip,lodash.zipObject=zipObject,lodash.zipObjectDeep=zipObjectDeep,lodash.zipWith=zipWith,lodash.entries=toPairs,lodash.entriesIn=toPairsIn,lodash.extend=assignIn,lodash.extendWith=assignInWith,mixin(lodash,lodash),lodash.add=add,lodash.attempt=attempt,lodash.camelCase=camelCase,lodash.capitalize=capitalize,lodash.ceil=ceil,lodash.clamp=clamp,lodash.clone=clone,lodash.cloneDeep=cloneDeep,lodash.cloneDeepWith=cloneDeepWith,lodash.cloneWith=cloneWith,lodash.conformsTo=conformsTo,lodash.deburr=deburr,lodash.defaultTo=defaultTo,lodash.divide=divide,lodash.endsWith=endsWith,lodash.eq=eq,lodash.escape=escape,lodash.escapeRegExp=escapeRegExp,lodash.every=every,lodash.find=find,lodash.findIndex=findIndex,lodash.findKey=findKey,lodash.findLast=findLast,lodash.findLastIndex=findLastIndex,lodash.findLastKey=findLastKey,lodash.floor=floor,lodash.forEach=forEach,lodash.forEachRight=forEachRight,lodash.forIn=forIn,lodash.forInRight=forInRight,lodash.forOwn=forOwn,lodash.forOwnRight=forOwnRight,lodash.get=get,lodash.gt=gt,lodash.gte=gte,lodash.has=has,lodash.hasIn=hasIn,lodash.head=head,lodash.identity=identity,lodash.includes=includes,lodash.indexOf=indexOf,lodash.inRange=inRange,lodash.invoke=invoke,lodash.isArguments=isArguments,lodash.isArray=isArray,lodash.isArrayBuffer=isArrayBuffer,lodash.isArrayLike=isArrayLike,lodash.isArrayLikeObject=isArrayLikeObject,lodash.isBoolean=isBoolean,lodash.isBuffer=isBuffer,lodash.isDate=isDate,lodash.isElement=isElement,lodash.isEmpty=isEmpty,lodash.isEqual=isEqual,lodash.isEqualWith=isEqualWith,lodash.isError=isError,lodash.isFinite=isFinite,lodash.isFunction=isFunction,lodash.isInteger=isInteger,lodash.isLength=isLength,lodash.isMap=isMap,lodash.isMatch=isMatch,lodash.isMatchWith=isMatchWith,lodash.isNaN=isNaN,lodash.isNative=isNative,lodash.isNil=isNil,lodash.isNull=isNull,lodash.isNumber=isNumber,lodash.isObject=isObject,lodash.isObjectLike=isObjectLike,lodash.isPlainObject=isPlainObject,lodash.isRegExp=isRegExp,lodash.isSafeInteger=isSafeInteger,lodash.isSet=isSet,lodash.isString=isString,lodash.isSymbol=isSymbol,lodash.isTypedArray=isTypedArray,lodash.isUndefined=isUndefined,lodash.isWeakMap=isWeakMap,lodash.isWeakSet=isWeakSet,lodash.join=join,lodash.kebabCase=kebabCase,lodash.last=last,lodash.lastIndexOf=lastIndexOf,lodash.lowerCase=lowerCase,lodash.lowerFirst=lowerFirst,lodash.lt=lt,lodash.lte=lte,lodash.max=max,lodash.maxBy=maxBy,lodash.mean=mean,lodash.meanBy=meanBy,lodash.min=min,lodash.minBy=minBy,lodash.stubArray=stubArray,lodash.stubFalse=stubFalse,lodash.stubObject=stubObject,lodash.stubString=stubString,lodash.stubTrue=stubTrue,lodash.multiply=multiply,lodash.nth=nth,lodash.noConflict=noConflict,lodash.noop=noop,lodash.now=now,lodash.pad=pad,lodash.padEnd=padEnd,lodash.padStart=padStart,lodash.parseInt=parseInt,lodash.random=random,lodash.reduce=reduce,lodash.reduceRight=reduceRight,lodash.repeat=repeat,lodash.replace=replace,lodash.result=result,lodash.round=round,lodash.runInContext=runInContext,lodash.sample=sample,lodash.size=size,lodash.snakeCase=snakeCase,lodash.some=some,lodash.sortedIndex=sortedIndex,lodash.sortedIndexBy=sortedIndexBy,lodash.sortedIndexOf=sortedIndexOf,lodash.sortedLastIndex=sortedLastIndex,lodash.sortedLastIndexBy=sortedLastIndexBy,lodash.sortedLastIndexOf=sortedLastIndexOf,lodash.startCase=startCase,lodash.startsWith=startsWith,lodash.subtract=subtract,lodash.sum=sum,lodash.sumBy=sumBy,lodash.template=template,lodash.times=times,lodash.toFinite=toFinite,lodash.toInteger=toInteger,lodash.toLength=toLength,lodash.toLower=toLower,lodash.toNumber=toNumber,lodash.toSafeInteger=toSafeInteger,lodash.toString=toString,lodash.toUpper=toUpper,lodash.trim=trim,lodash.trimEnd=trimEnd,lodash.trimStart=trimStart,lodash.truncate=truncate,lodash.unescape=unescape,lodash.uniqueId=uniqueId,lodash.upperCase=upperCase,lodash.upperFirst=upperFirst,lodash.each=forEach,lodash.eachRight=forEachRight,lodash.first=head,mixin(lodash,function(){var source={};return baseForOwn(lodash,function(func,methodName){hasOwnProperty.call(lodash.prototype,methodName)||(source[methodName]=func)}),source}(),{chain:!1}),lodash.VERSION=VERSION,arrayEach(["bind","bindKey","curry","curryRight","partial","partialRight"],function(methodName){lodash[methodName].placeholder=lodash}),arrayEach(["drop","take"],function(methodName,index){LazyWrapper.prototype[methodName]=function(n){var filtered=this.__filtered__;if(filtered&&!index)return new LazyWrapper(this);n=n===undefined?1:nativeMax(toInteger(n),0);var result=this.clone();return filtered?result.__takeCount__=nativeMin(n,result.__takeCount__):result.__views__.push({size:nativeMin(n,MAX_ARRAY_LENGTH),type:methodName+(result.__dir__<0?"Right":"")}),result},LazyWrapper.prototype[methodName+"Right"]=function(n){return this.reverse()[methodName](n).reverse()}}),arrayEach(["filter","map","takeWhile"],function(methodName,index){var type=index+1,isFilter=type==LAZY_FILTER_FLAG||type==LAZY_WHILE_FLAG;LazyWrapper.prototype[methodName]=function(iteratee){var result=this.clone();return result.__iteratees__.push({iteratee:getIteratee(iteratee,3),type:type}),result.__filtered__=result.__filtered__||isFilter,result}}),arrayEach(["head","last"],function(methodName,index){var takeName="take"+(index?"Right":"");LazyWrapper.prototype[methodName]=function(){return this[takeName](1).value()[0]}}),arrayEach(["initial","tail"],function(methodName,index){var dropName="drop"+(index?"":"Right");LazyWrapper.prototype[methodName]=function(){return this.__filtered__?new LazyWrapper(this):this[dropName](1)}}),LazyWrapper.prototype.compact=function(){return this.filter(identity)},LazyWrapper.prototype.find=function(predicate){return this.filter(predicate).head()},LazyWrapper.prototype.findLast=function(predicate){return this.reverse().find(predicate)},LazyWrapper.prototype.invokeMap=baseRest(function(path,args){return"function"==typeof path?new LazyWrapper(this):this.map(function(value){return baseInvoke(value,path,args)})}),LazyWrapper.prototype.reject=function(predicate){return this.filter(negate(getIteratee(predicate)))},LazyWrapper.prototype.slice=function(start,end){start=toInteger(start);var result=this;return result.__filtered__&&(start>0||0>end)?new LazyWrapper(result):(0>start?result=result.takeRight(-start):start&&(result=result.drop(start)),end!==undefined&&(end=toInteger(end),result=0>end?result.dropRight(-end):result.take(end-start)),result)},LazyWrapper.prototype.takeRightWhile=function(predicate){return this.reverse().takeWhile(predicate).reverse()},LazyWrapper.prototype.toArray=function(){return this.take(MAX_ARRAY_LENGTH)},baseForOwn(LazyWrapper.prototype,function(func,methodName){var checkIteratee=/^(?:filter|find|map|reject)|While$/.test(methodName),isTaker=/^(?:head|last)$/.test(methodName),lodashFunc=lodash[isTaker?"take"+("last"==methodName?"Right":""):methodName],retUnwrapped=isTaker||/^find/.test(methodName);lodashFunc&&(lodash.prototype[methodName]=function(){var value=this.__wrapped__,args=isTaker?[1]:arguments,isLazy=value instanceof LazyWrapper,iteratee=args[0],useLazy=isLazy||isArray(value),interceptor=function(value){var result=lodashFunc.apply(lodash,arrayPush([value],args));return isTaker&&chainAll?result[0]:result};useLazy&&checkIteratee&&"function"==typeof iteratee&&1!=iteratee.length&&(isLazy=useLazy=!1);var chainAll=this.__chain__,isHybrid=!!this.__actions__.length,isUnwrapped=retUnwrapped&&!chainAll,onlyLazy=isLazy&&!isHybrid;if(!retUnwrapped&&useLazy){value=onlyLazy?value:new LazyWrapper(this);var result=func.apply(value,args);return result.__actions__.push({func:thru,args:[interceptor],thisArg:undefined}),new LodashWrapper(result,chainAll)}return isUnwrapped&&onlyLazy?func.apply(this,args):(result=this.thru(interceptor),isUnwrapped?isTaker?result.value()[0]:result.value():result)})}),arrayEach(["pop","push","shift","sort","splice","unshift"],function(methodName){var func=arrayProto[methodName],chainName=/^(?:push|sort|unshift)$/.test(methodName)?"tap":"thru",retUnwrapped=/^(?:pop|shift)$/.test(methodName);lodash.prototype[methodName]=function(){var args=arguments;if(retUnwrapped&&!this.__chain__){var value=this.value();return func.apply(isArray(value)?value:[],args)}return this[chainName](function(value){return func.apply(isArray(value)?value:[],args)})}}),baseForOwn(LazyWrapper.prototype,function(func,methodName){var lodashFunc=lodash[methodName];if(lodashFunc){var key=lodashFunc.name+"",names=realNames[key]||(realNames[key]=[]);names.push({name:methodName,func:lodashFunc})}}),realNames[createHybrid(undefined,BIND_KEY_FLAG).name]=[{name:"wrapper",func:undefined}],LazyWrapper.prototype.clone=lazyClone,LazyWrapper.prototype.reverse=lazyReverse,LazyWrapper.prototype.value=lazyValue,lodash.prototype.at=wrapperAt,lodash.prototype.chain=wrapperChain,lodash.prototype.commit=wrapperCommit,lodash.prototype.next=wrapperNext,lodash.prototype.plant=wrapperPlant,lodash.prototype.reverse=wrapperReverse,lodash.prototype.toJSON=lodash.prototype.valueOf=lodash.prototype.value=wrapperValue,lodash.prototype.first=lodash.prototype.head,iteratorSymbol&&(lodash.prototype[iteratorSymbol]=wrapperToIterator),lodash},_=runInContext();"function"==typeof define&&"object"==typeof define.amd&&define.amd?(root._=_,define(function(){return _})):freeModule?((freeModule.exports=_)._=_,freeExports._=_):root._=_}.call(this);var UsergridAuthMode=Object.freeze({NONE:"none",USER:"user",APP:"app"}),UsergridDirection=Object.freeze({IN:"connecting",OUT:"connections"}),UsergridHttpMethod=Object.freeze({GET:"GET",PUT:"PUT",POST:"POST",DELETE:"DELETE"}),UsergridQueryOperator=Object.freeze({EQUAL:"=",GREATER_THAN:">",GREATER_THAN_EQUAL_TO:">=",LESS_THAN:"<",LESS_THAN_EQUAL_TO:"<="}),UsergridQuerySortOrder=Object.freeze({ASC:"asc",DESC:"desc"}),UsergridApplicationJSONHeaderValue="application/json";!function(global){function UsergridHelpers(){}var name="UsergridHelpers",overwrittenName=global[name];UsergridHelpers.DefaultHeaders=Object.freeze({"Content-Type":UsergridApplicationJSONHeaderValue,Accept:UsergridApplicationJSONHeaderValue}),UsergridHelpers.validateAndRetrieveClient=function(args){var client=void 0;if(args instanceof UsergridClient)client=args;else if(args[0]instanceof UsergridClient)client=args[0];else if(_.get(args,"client"))client=args.client;else{if(!Usergrid.isInitialized)throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument");client=Usergrid}return client},UsergridHelpers.inherits=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})},UsergridHelpers.flattenArgs=function(args){return _.flattenDeep(Array.prototype.slice.call(args))},UsergridHelpers.callback=function(){var args=UsergridHelpers.flattenArgs(arguments).reverse(),emptyFunc=function(){};return _.first(_.flattenDeep([args,_.get(args,"0.callback"),emptyFunc]).filter(_.isFunction))},UsergridHelpers.authForRequests=function(client){var authForRequests=void 0;return _.get(client,"tempAuth.isValid")?(authForRequests=client.tempAuth,client.tempAuth=void 0):_.get(client,"currentUser.auth.isValid")&&client.authMode===UsergridAuthMode.USER?authForRequests=client.currentUser.auth:_.get(client,"appAuth.isValid")&&client.authMode===UsergridAuthMode.APP&&(authForRequests=client.appAuth),authForRequests},UsergridHelpers.userLoginBody=function(options){var body={grant_type:"password",password:options.password};return options.tokenTtl&&(body.ttl=options.tokenTtl),body[options.username?"username":"email"]=options.username?options.username:options.email,body},UsergridHelpers.appLoginBody=function(options){var body={grant_type:"client_credentials",client_id:options.clientId,client_secret:options.clientSecret};return options.tokenTtl&&(body.ttl=options.tokenTtl),body},UsergridHelpers.calculateExpiry=function(expires_in){return Date.now()+1e3*(expires_in?expires_in-5:0)};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;return UsergridHelpers.isUUID=function(uuid){return uuid?uuidValueRegex.test(uuid):!1},UsergridHelpers.useQuotesIfRequired=function(value){return _.isFinite(value)||UsergridHelpers.isUUID(value)||_.isBoolean(value)||_.isObject(value)&&!_.isFunction(value)||_.isArray(value)?value:"'"+value+"'"},UsergridHelpers.setReadOnly=function(obj,key){return _.isArray(key)?key.forEach(function(k){UsergridHelpers.setReadOnly(obj,k)}):_.isPlainObject(obj[key])?Object.freeze(obj[key]):_.isPlainObject(obj)&&void 0===key?Object.freeze(obj):_.has(obj,key)?Object.defineProperty(obj,key,{writable:!1}):obj},UsergridHelpers.setWritable=function(obj,key){return _.isArray(key)?key.forEach(function(k){UsergridHelpers.setWritable(obj,k)}):_.isPlainObject(obj[key])?_.clone(obj[key]):_.isPlainObject(obj)&&void 0===key?_.clone(obj):_.has(obj,key)?Object.defineProperty(obj,key,{writable:!0}):obj},UsergridHelpers.assignPrefabOptions=function(args){return _.isObject(args[0])&&!_.isFunction(args[0])&&_.has(args,"method")&&_.assign(this,args[0]),this},UsergridHelpers.normalize=function(str){return str=str.replace(/\/+/g,"/"),str=str.replace(/:\//g,"://"),str=str.replace(/\/(\?|&|#[^!])/g,"$1"),str=str.replace(/(\?.+)\?/g,"$1&")},UsergridHelpers.urljoin=function(){var input=arguments,options={};"object"==typeof arguments[0]&&(input=arguments[0],options=arguments[1]||{});var joined=[].slice.call(input,0).join("/");return UsergridHelpers.normalize(joined,options)},UsergridHelpers.parseResponseHeaders=function(headerStr){var headers={};if(headerStr)for(var headerPairs=headerStr.split("\r\n"),i=0;i0){var key=headerPair.substring(0,index).toLowerCase();headers[key]=headerPair.substring(index+2)}}return headers},UsergridHelpers.uri=function(client,options){var path="";path=options instanceof UsergridEntity?options.type:options instanceof UsergridQuery?options._type:_.isString(options)?options:_.isArray(options)?_.get(options,"0.type")||_.get(options,"0.path"):options.path||options.type||_.get(options,"entity.type")||_.get(options,"query._type")||_.get(options,"body.type")||_.get(options,"body.path");var uuidOrName="";return options.method!==UsergridHttpMethod.POST&&(uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,_.get(options,"entity.uuid"),_.get(options,"entity.name"),_.get(options,"body.uuid"),_.get(options,"body.name"),""].filter(_.isString))),UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,path,uuidOrName)},UsergridHelpers.updateEntityFromRemote=function(entity,usergridResponse){UsergridHelpers.setWritable(entity,["uuid","name","type","created"]),_.assign(entity,usergridResponse.entity),UsergridHelpers.setReadOnly(entity,["uuid","name","type","created"])},UsergridHelpers.headers=function(client,options,defaultHeaders){var returnHeaders={};_.defaults(returnHeaders,options.headers,defaultHeaders),_.assign(returnHeaders,{"User-Agent":"usergrid-js/v"+UsergridSDKVersion});var authForRequests=UsergridHelpers.authForRequests(client);return authForRequests&&_.assign(returnHeaders,{authorization:"Bearer "+authForRequests.token}),returnHeaders},UsergridHelpers.setEntity=function(options,args){return options.entity=_.first([options.entity,args[0]].filter(function(property){return property instanceof UsergridEntity})),void 0!==options.entity&&(options.type=options.entity.type),options},UsergridHelpers.setAsset=function(options,args){return options.asset=_.first([options.asset,_.get(options,"entity.asset"),args[1],args[0]].filter(function(property){return property instanceof UsergridAsset})),options},UsergridHelpers.setUuidOrName=function(options,args){return options.uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,_.get(options,"entity.uuid"),_.get(options,"body.uuid"),_.get(options,"entity.name"),_.get(options,"body.name"),_.get(args,"0.uuid"),_.get(args,"0.name"),_.get(args,"2"),_.get(args,"1")].filter(_.isString)),options},UsergridHelpers.setPathOrType=function(options,args){var pathOrType=_.first([args.type,_.get(args,"0.type"),_.get(options,"entity.type"),_.get(args,"body.type"),_.get(options,"body.0.type"),_.isArray(args)?args[0]:void 0].filter(_.isString));return options[/\//.test(pathOrType)?"path":"type"]=pathOrType,options},UsergridHelpers.setQs=function(options,args){return options.path&&(options.qs=_.first([options.qs,args[2],args[1],args[0]].filter(_.isPlainObject))),options},UsergridHelpers.setQuery=function(options,args){return options.query=_.first([options,options.query,args[0]].filter(function(property){return property instanceof UsergridQuery})),options},UsergridHelpers.setAsset=function(options,args){return options.asset=_.first([options.asset,_.get(options,"entity.asset"),args[1],args[0]].filter(function(property){return property instanceof UsergridAsset})),options},UsergridHelpers.setBody=function(options,args){if(options.body=_.first([args.entity,args.body,args[0].entity,args[0].body,args[2],args[1],args[0]].filter(function(property){return _.isObject(property)&&!_.isFunction(property)&&!(property instanceof UsergridQuery)&&!(property instanceof UsergridAsset)})),void 0===options.body&&void 0===options.asset)throw new Error('"body" is required when making a '+options.method+" request");return options.body instanceof UsergridEntity?options.body=options.body.jsonValue():options.body instanceof Array&&options.body[0]instanceof UsergridEntity&&(options.body=_.map(options.body,function(entity){return entity.jsonValue()})),options},UsergridHelpers.buildReqest=function(client,method,args){var options={client:client,method:method,queryParams:args.queryParams||_.get(args,"0.queryParams"),callback:UsergridHelpers.callback(args)};return UsergridHelpers.assignPrefabOptions(options,args),UsergridHelpers.setEntity(options,args),(method===UsergridHttpMethod.POST||method===UsergridHttpMethod.PUT)&&(UsergridHelpers.setAsset(options,args),void 0===options.asset&&UsergridHelpers.setBody(options,args)),UsergridHelpers.setUuidOrName(options,args),UsergridHelpers.setPathOrType(options,args),UsergridHelpers.setQs(options,args),UsergridHelpers.setQuery(options,args),options.uri=UsergridHelpers.uri(client,options),new UsergridRequest(options)},UsergridHelpers.buildAppAuthRequest=function(client,auth,callback){var requestOptions={client:client,method:UsergridHttpMethod.POST,uri:UsergridHelpers.uri(client,{path:"token"}),body:UsergridHelpers.appLoginBody(auth),callback:callback};return new UsergridRequest(requestOptions)},UsergridHelpers.buildConnectionRequest=function(client,method,args){var options={client:client,method:method,entity:{},to:{},callback:UsergridHelpers.callback(args)};if(UsergridHelpers.assignPrefabOptions.call(options,args),_.isObject(options.from)&&(options.to=options.from),_.isObject(args[0])&&_.has(args[0],"entity")&&_.has(args[0],"to")&&(_.assign(options.entity,args[0].entity),options.relationship=_.get(args,"0.relationship"),_.assign(options.to,args[0].to)),_.isObject(args[0])&&!_.isFunction(args[0])&&_.isString(args[1])&&(_.assign(options.entity,args[0]),options.relationship=_.first([options.relationship,args[1]].filter(_.isString))),_.isObject(args[2])&&!_.isFunction(args[2])&&_.assign(options.to,args[2]),options.entity.uuidOrName=_.first([options.entity.uuidOrName,options.entity.uuid,options.entity.name,args[1]].filter(_.isString)),options.entity.type||(options.entity.type=_.first([options.entity.type,args[0]].filter(_.isString))),options.relationship=_.first([options.relationship,args[2]].filter(_.isString)),_.isString(args[3])&&!UsergridHelpers.isUUID(args[3])&&_.isString(args[4])?options.to.type=args[3]:_.isString(args[2])&&!UsergridHelpers.isUUID(args[2])&&_.isString(args[3])&&_.isObject(args[0])&&!_.isFunction(args[0])&&(options.to.type=args[2]),options.to.uuidOrName=_.first([options.to.uuidOrName,options.to.uuid,options.to.name,args[4],args[3],args[2]].filter(function(property){return _.isString(options.to.type)&&_.isString(property)||UsergridHelpers.isUUID(property)})),!_.isString(options.entity.uuidOrName))throw new Error('source entity "uuidOrName" is required when connecting or disconnecting entities');if(!_.isString(options.to.uuidOrName))throw new Error('target entity "uuidOrName" is required when connecting or disconnecting entities');if(!_.isString(options.to.type)&&!UsergridHelpers.isUUID(options.to.uuidOrName))throw new Error('target "type" (collection name) parameter is required connecting or disconnecting entities by name');return options.uri=UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,_.isString(options.entity.type)?options.entity.type:"",_.isString(options.entity.uuidOrName)?options.entity.uuidOrName:"",options.relationship,_.isString(options.to.type)?options.to.type:"",_.isString(options.to.uuidOrName)?options.to.uuidOrName:""),new UsergridRequest(options)},UsergridHelpers.buildGetConnectionRequest=function(client,args){var options={client:client,method:"GET",callback:UsergridHelpers.callback(args)};if(UsergridHelpers.assignPrefabOptions.call(options,args),_.isObject(args[1])&&!_.isFunction(args[1])&&_.assign(options,args[1]),options.direction=_.first([options.direction,args[0]].filter(function(property){return property===UsergridDirection.IN||property===UsergridDirection.OUT})),options.relationship=_.first([options.relationship,args[3],args[2]].filter(_.isString)),options.uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,args[2]].filter(_.isString)),options.type=_.first([options.type,args[1]].filter(_.isString)),!_.isString(options.type))throw new Error('"type" (collection name) parameter is required when retrieving connections');if(!_.isString(options.uuidOrName))throw new Error('target entity "uuidOrName" is required when retrieving connections');return options.uri=UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,_.isString(options.type)?options.type:"",_.isString(options.uuidOrName)?options.uuidOrName:"",options.direction,options.relationship),new UsergridRequest(options)},global[name]=UsergridHelpers,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),UsergridHelpers},global[name]}(this);var UsergridClientDefaultOptions={baseUrl:"https://api.usergrid.com",authMode:UsergridAuthMode.USER},UsergridClient=function(options){var __appAuth,self=this;if(self.tempAuth=void 0,self.isSharedInstance=!1,2===arguments.length&&(self.orgId=arguments[0],self.appId=arguments[1]),_.defaults(self,options,UsergridClientDefaultOptions),!self.orgId||!self.appId)throw new Error('"orgId" and "appId" parameters are required when instantiating UsergridClient');return Object.defineProperty(self,"clientId",{enumerable:!1}),Object.defineProperty(self,"clientSecret",{enumerable:!1}),Object.defineProperty(self,"appAuth",{get:function(){return __appAuth},set:function(options){options instanceof UsergridAppAuth?__appAuth=options:"undefined"!=typeof options&&(__appAuth=new UsergridAppAuth(options))}}),self.clientId&&self.clientSecret&&self.setAppAuth(self.clientId,self.clientSecret),self};UsergridClient.prototype={sendRequest:function(usergridRequest){return usergridRequest.sendRequest()},GET:function(){var usergridRequest=UsergridHelpers.buildReqest(this,UsergridHttpMethod.GET,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},PUT:function(){var usergridRequest=UsergridHelpers.buildReqest(this,UsergridHttpMethod.PUT,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},POST:function(){var usergridRequest=UsergridHelpers.buildReqest(this,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},DELETE:function(){var usergridRequest=UsergridHelpers.buildReqest(this,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},connect:function(){var usergridRequest=UsergridHelpers.buildConnectionRequest(this,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},disconnect:function(){var usergridRequest=UsergridHelpers.buildConnectionRequest(this,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},getConnections:function(){var usergridRequest=UsergridHelpers.buildGetConnectionRequest(this,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},usingAuth:function(auth){var self=this;return _.isString(auth)?self.tempAuth=new UsergridAuth(auth):auth instanceof UsergridAuth?self.tempAuth=auth:self.tempAuth=void 0,self},setAppAuth:function(){this.appAuth=new UsergridAppAuth(UsergridHelpers.flattenArgs(arguments))},authenticateApp:function(options){var self=this,authenticateAppCallback=UsergridHelpers.callback(UsergridHelpers.flattenArgs(arguments)),auth=_.first([options,self.appAuth,new UsergridAppAuth(options),new UsergridAppAuth(self.clientId,self.clientSecret)].filter(function(p){return p instanceof UsergridAppAuth}));if(!(auth instanceof UsergridAppAuth))throw new Error("App auth context was not defined when attempting to call .authenticateApp()");if(!auth.clientId||!auth.clientSecret)throw new Error("authenticateApp() failed because clientId or clientSecret are missing");var callback=function(error,usergridResponse){var token=_.get(usergridResponse.responseJSON,"access_token"),expiresIn=_.get(usergridResponse.responseJSON,"expires_in");usergridResponse.ok&&(self.appAuth||(self.appAuth=auth),self.appAuth.token=token,self.appAuth.expiry=UsergridHelpers.calculateExpiry(expiresIn),self.appAuth.tokenTtl=expiresIn),authenticateAppCallback(error,usergridResponse,token)},usergridRequest=UsergridHelpers.buildAppAuthRequest(self,auth,callback);return self.sendRequest(usergridRequest)},authenticateUser:function(options){var self=this,args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args),setAsCurrentUser=void 0!==_.last(args.filter(_.isBoolean))?_.last(args.filter(_.isBoolean)):!0,userToAuthenticate=new UsergridUser(options);userToAuthenticate.login(self,function(error,usergridResponse,token){usergridResponse.ok&&setAsCurrentUser&&(self.currentUser=userToAuthenticate),callback(usergridResponse.error,usergridResponse,token)})},downloadAsset:function(){var self=this,usergridRequest=UsergridHelpers.buildReqest(self,UsergridHttpMethod.GET,UsergridHelpers.flattenArgs(arguments)),assetContentType=_.get(usergridRequest,"entity.file-metadata.content-type");void 0!==assetContentType&&_.assign(usergridRequest.headers,{Accept:assetContentType});var realDownloadAssetCallback=usergridRequest.callback;return usergridRequest.callback=function(error,usergridResponse){var entity=usergridRequest.entity;entity.asset=usergridResponse.asset,realDownloadAssetCallback(error,usergridResponse,entity)},self.sendRequest(usergridRequest)},uploadAsset:function(){var self=this,usergridRequest=UsergridHelpers.buildReqest(self,UsergridHttpMethod.PUT,UsergridHelpers.flattenArgs(arguments));if(void 0===usergridRequest.asset)throw new Error("An UsergridAsset was not defined when attempting to call .uploadAsset()");var realUploadAssetCallback=usergridRequest.callback;return usergridRequest.callback=function(error,usergridResponse){var requestEntity=usergridRequest.entity,responseEntity=usergridResponse.entity,requestAsset=usergridRequest.asset;usergridResponse.ok&&void 0!==responseEntity&&(UsergridHelpers.updateEntityFromRemote(requestEntity,usergridResponse),requestEntity.asset=requestAsset,responseEntity&&(responseEntity.asset=requestAsset)),realUploadAssetCallback(error,usergridResponse,requestEntity)},self.sendRequest(usergridRequest)}};var UsergridSDKVersion="2.0.0",UsergridClientSharedInstance=function(){var self=this;return self.isInitialized=!1,self.isSharedInstance=!0,self};UsergridHelpers.inherits(UsergridClientSharedInstance,UsergridClient);var Usergrid=new UsergridClientSharedInstance;Usergrid.initSharedInstance=function(options){return Usergrid.isInitialized?console.log("Usergrid shared instance is already initialized"):(_.assign(Usergrid,new UsergridClient(options)),Usergrid.isInitialized=!0,Usergrid.isSharedInstance=!0),Usergrid},Usergrid.init=Usergrid.initSharedInstance;var UsergridQuery=function(type){var queryString,sort,self=this,query="",urlTerms={},__nextIsNot=!1;return self._type=type,_.assign(self,{type:function(value){return self._type=value,self},collection:function(value){return self._type=value,self},limit:function(value){return self._limit=value,self},cursor:function(value){return self._cursor=value,self},eq:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.EQUAL+" "+UsergridHelpers.useQuotesIfRequired(value)),self},equal:this.eq,gt:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.GREATER_THAN+" "+UsergridHelpers.useQuotesIfRequired(value)),self},greaterThan:this.gt,gte:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.GREATER_THAN_EQUAL_TO+" "+UsergridHelpers.useQuotesIfRequired(value)),self},greaterThanOrEqual:this.gte,lt:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.LESS_THAN+" "+UsergridHelpers.useQuotesIfRequired(value)),self},lessThan:this.lt,lte:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.LESS_THAN_EQUAL_TO+" "+UsergridHelpers.useQuotesIfRequired(value)),self},lessThanOrEqual:this.lte,contains:function(key,value){return query=self.andJoin(key+" contains "+UsergridHelpers.useQuotesIfRequired(value)),self},locationWithin:function(distanceInMeters,lat,lng){return query=self.andJoin("location within "+distanceInMeters+" of "+lat+", "+lng),self},asc:function(key){return self.sort(key,UsergridQuerySortOrder.ASC),self},desc:function(key){return self.sort(key,UsergridQuerySortOrder.DESC),self},sort:function(key,order){return sort=key&&order?" order by "+key+" "+order:"",self},fromString:function(string){return queryString=string,self},urlTerm:function(key,value){return"ql"===key?self.fromString():urlTerms[key]=value,self},andJoin:function(append){ +return __nextIsNot&&(append="not "+append,__nextIsNot=!1),append?0===query.length?append:_.endsWith(query,"and")||_.endsWith(query,"or")?query+" "+append:query+" and "+append:query},orJoin:function(){return query.length>0&&!_.endsWith(query,"or")?query+" or":query}}),Object.defineProperty(self,"_ql",{get:function(){var ql="select * ";return void 0!==queryString?ql=queryString:(ql+=query.length>0?"where "+(query||""):"",ql+=void 0!==sort?sort:""),ql}}),Object.defineProperty(self,"encodedStringValue",{get:function(){var self=this,limit=self._limit,cursor=self._cursor,requirementsString=self._ql,returnString=void 0;if(void 0!==limit&&(returnString="limit"+UsergridQueryOperator.EQUAL+limit),!_.isEmpty(cursor)){var cursorString="cursor"+UsergridQueryOperator.EQUAL+cursor;_.isEmpty(returnString)?returnString=cursorString:returnString+="&"+cursorString}if(_.forEach(urlTerms,function(value,key){var encodedURLTermString=encodeURIComponent(key)+UsergridQueryOperator.EQUAL+encodeURIComponent(value);_.isEmpty(returnString)?returnString=encodedURLTermString:returnString+="&"+encodedURLTermString}),!_.isEmpty(requirementsString)){var qLString="ql="+encodeURIComponent(requirementsString);_.isEmpty(returnString)?returnString=qLString:returnString+="&"+qLString}return _.isEmpty(returnString)||(returnString="?"+returnString),_.isEmpty(returnString)?void 0:returnString}}),Object.defineProperty(self,"and",{get:function(){return query=self.andJoin(""),self}}),Object.defineProperty(self,"or",{get:function(){return query=self.orJoin(),self}}),Object.defineProperty(self,"not",{get:function(){return __nextIsNot=!0,self}}),self},UsergridRequest=function(options){var self=this,client=UsergridHelpers.validateAndRetrieveClient(options);if(!_.isString(options.type)&&!_.isString(options.path)&&!_.isString(options.uri))throw new Error('one of "type" (collection name), "path", or "uri" parameters are required when initializing a UsergridRequest');if(!_.includes(["GET","PUT","POST","DELETE"],options.method))throw new Error('"method" parameter is required when initializing a UsergridRequest');self.method=options.method,self.callback=options.callback,self.uri=options.uri||UsergridHelpers.uri(client,options),self.entity=options.entity,self.body=options.body||void 0,self.asset=options.asset||void 0,self.query=options.query,self.queryParams=options.queryParams||options.qs;var defaultHeadersToUse=void 0===self.asset?UsergridHelpers.DefaultHeaders:{};if(self.headers=UsergridHelpers.headers(client,options,defaultHeadersToUse),void 0!==self.query&&(self.uri+=UsergridHelpers.normalize(self.query.encodedStringValue,{})),void 0!==self.queryParams&&(_.forOwn(self.queryParams,function(value,key){self.uri+="?"+encodeURIComponent(key)+UsergridQueryOperator.EQUAL+encodeURIComponent(value)}),self.uri=UsergridHelpers.normalize(self.uri,{})),void 0!==self.asset)self.body=new FormData,self.body.append(self.asset.filename,self.asset.data);else try{_.isPlainObject(self.body)?self.body=JSON.stringify(self.body):_.isArray(self.body)&&(self.body=JSON.stringify(self.body))}catch(exception){}return self};UsergridRequest.prototype.sendRequest=function(){var self=this,requestPromise=function(){var promise=new Promise,xmlHttpRequest=new XMLHttpRequest;return xmlHttpRequest.open(self.method,self.uri,!0),xmlHttpRequest.onload=function(){promise.done(xmlHttpRequest)},_.forOwn(self.headers,function(value,key){xmlHttpRequest.setRequestHeader(key,value)}),self.method===UsergridHttpMethod.GET&&_.get(self.headers,"Accept")!==UsergridApplicationJSONHeaderValue&&(xmlHttpRequest.responseType="blob"),xmlHttpRequest.send(self.body),promise},responsePromise=function(xmlRequest){var promise=new Promise,usergridResponse=new UsergridResponse(xmlRequest,self);return promise.done(usergridResponse),promise},onCompletePromise=function(usergridResponse){self.callback(usergridResponse.error,usergridResponse)};return Promise.chain([requestPromise,responsePromise]).then(onCompletePromise),self};var UsergridAuth=function(token,expiry){var self=this;self.token=token,self.expiry=expiry||0;var usingToken=token?!0:!1;return Object.defineProperty(self,"hasToken",{get:function(){return void 0!==self.token},configurable:!0}),Object.defineProperty(self,"isExpired",{get:function(){return usingToken?!1:Date.now()>=self.expiry},configurable:!0}),Object.defineProperty(self,"isValid",{get:function(){return!self.isExpired&&self.hasToken},configurable:!0}),Object.defineProperty(self,"tokenTtl",{configurable:!0,writable:!0}),_.assign(self,{destroy:function(){self.token=void 0,self.expiry=0,self.tokenTtl=void 0}}),self},UsergridAppAuth=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments);return _.isPlainObject(args[0])?(self.clientId=args[0].clientId,self.clientSecret=args[0].clientSecret,self.tokenTtl=args[0].tokenTtl):(self.clientId=args[0],self.clientSecret=args[1],self.tokenTtl=args[2]),UsergridAuth.call(self),_.assign(self,UsergridAuth),self};UsergridHelpers.inherits(UsergridAppAuth,UsergridAuth);var UsergridUserAuth=function(options){var self=this,args=_.flattenDeep(UsergridHelpers.flattenArgs(arguments));return _.isPlainObject(args[0])&&(options=args[0]),self.username=options.username||args[0],self.email=options.email,(options.password||args[1])&&(self.password=options.password||args[1]),self.tokenTtl=options.tokenTtl||args[2],UsergridAuth.call(self),_.assign(self,UsergridAuth),self};UsergridHelpers.inherits(UsergridUserAuth,UsergridAuth);var UsergridEntity=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments);if(0===args.length)throw new Error("A UsergridEntity object cannot be initialized without passing one or more arguments");if(self.asset=void 0,_.isPlainObject(args[0])?_.assign(self,args[0]):(self.type||(self.type=_.isString(args[0])?args[0]:void 0),self.name||(self.name=_.isString(args[1])?args[1]:void 0)),!_.isString(self.type))throw new Error('"type" (or "collection") parameter is required when initializing a UsergridEntity object');return Object.defineProperty(self,"isUser",{get:function(){return"user"===self.type.toLowerCase()}}),Object.defineProperty(self,"hasAsset",{get:function(){return _.has(self,"file-metadata")}}),UsergridHelpers.setReadOnly(self,["uuid","name","type","created"]),self};UsergridEntity.prototype={jsonValue:function(){var jsonValue={};return _.forOwn(this,function(value,key){jsonValue[key]=value}),jsonValue},putProperty:function(key,value){this[key]=value},putProperties:function(obj){_.assign(this,obj)},removeProperty:function(key){this.removeProperties([key])},removeProperties:function(keys){var self=this;keys.forEach(function(key){delete self[key]})},insert:function(key,value,idx){_.isArray(this[key])||(this[key]=this[key]?[this[key]]:[]),this[key].splice.apply(this[key],[idx,0].concat(value))},append:function(key,value){this.insert(key,value,Number.MAX_VALUE)},prepend:function(key,value){this.insert(key,value,0)},pop:function(key){_.isArray(this[key])&&this[key].pop()},shift:function(key){_.isArray(this[key])&&this[key].shift()},reload:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.GET(self,function(error,usergridResponse){UsergridHelpers.updateEntityFromRemote(self,usergridResponse),callback(error,usergridResponse,self)}.bind(self))},save:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args),currentAsset=self.asset;client.PUT(self,function(error,usergridResponse){UsergridHelpers.updateEntityFromRemote(self,usergridResponse),self.hasAsset&&(self.asset=currentAsset),callback(error,usergridResponse,self)}.bind(self))},remove:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.DELETE(self,function(error,usergridResponse){callback(error,usergridResponse,self)}.bind(self))},attachAsset:function(asset){this.asset=asset},uploadAsset:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(_.has(self,"asset.contentType"))client.uploadAsset(self,callback);else{var response=new UsergridResponse.responseWithError({name:"asset_not_found",description:"The specified entity does not have a valid asset attached"});callback(response.error,response,self)}},downloadAsset:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(_.has(self,"asset.contentType"))client.downloadAsset(self,callback);else{var response=new UsergridResponse.responseWithError({name:"asset_not_found",description:"The specified entity does not have a valid asset attached"});callback(response.error,response,self)}},connect:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args[0]=this,client.connect.apply(client,args)},disconnect:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args[0]=this,client.disconnect.apply(client,args)},getConnections:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args.shift(),args.splice(1,0,this),client.getConnections.apply(client,args)}};var UsergridUser=function(obj){if(!_.has(obj,"email")&&!_.has(obj,"username"))throw new Error('"email" or "username" property is required when initializing a UsergridUser object');var self=this;return _.assign(self,obj,UsergridEntity),UsergridEntity.call(self,"user"),UsergridHelpers.setWritable(self,"name"),self};UsergridUser.CheckAvailable=function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);args[0]instanceof UsergridClient&&args.shift();var checkQuery,callback=UsergridHelpers.callback(args);if(args[0].username&&args[0].email)checkQuery=new UsergridQuery("users").eq("username",args[0].username).or.eq("email",args[0].email);else if(args[0].username)checkQuery=new UsergridQuery("users").eq("username",args[0].username);else{if(!args[0].email)throw new Error("'username' or 'email' property is required when checking for available users");checkQuery=new UsergridQuery("users").eq("email",args[0].email)}client.GET(checkQuery,function(error,usergridResponse){callback(error,usergridResponse,usergridResponse.entities.length>0)})},UsergridHelpers.inherits(UsergridUser,UsergridEntity),UsergridUser.prototype.uniqueId=function(){var self=this;return _.first([self.uuid,self.username,self.email].filter(_.isString))},UsergridUser.prototype.create=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.POST(self,function(error,usergridResponse){delete self.password,_.assign(self,usergridResponse.user),callback(error,usergridResponse,self)}.bind(self))},UsergridUser.prototype.login=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.POST("token",UsergridHelpers.userLoginBody(self),function(error,usergridResponse){delete self.password;var responseJSON=usergridResponse.responseJSON,token=_.get(responseJSON,"access_token"),expiresIn=_.get(responseJSON,"expires_in");usergridResponse.ok&&(self.auth=new UsergridUserAuth(self),self.auth.token=token,self.auth.expiry=UsergridHelpers.calculateExpiry(expiresIn),self.auth.tokenTtl=expiresIn),callback(error,usergridResponse,token)})},UsergridUser.prototype.logout=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(self.auth&&self.auth.isValid){var revokeAll=_.first(args.filter(_.isBoolean))||!1,queryParams=void 0;revokeAll||(queryParams={token:self.auth.token});var requestOptions={client:client,path:["users",self.uniqueId(),"revoketoken"+(revokeAll?"s":"")].join("/"),method:UsergridHttpMethod.PUT,queryParams:queryParams,callback:function(error,usergridResponse){self.auth.destroy(),callback(error,usergridResponse,usergridResponse.ok)}.bind(self)},request=new UsergridRequest(requestOptions);client.sendRequest(request)}else{var response=new UsergridResponse.responseWithError({name:"no_valid_token",description:"this user does not have a valid token"});callback(response.error,response)}},UsergridUser.prototype.logoutAllSessions=function(){var args=UsergridHelpers.flattenArgs(arguments);return args=_.concat([UsergridHelpers.validateAndRetrieveClient(args),!0],args),this.logout.apply(this,args)},UsergridUser.prototype.resetPassword=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);args[0]instanceof UsergridClient&&args.shift();var body={oldpassword:_.isPlainObject(args[0])?args[0].oldPassword:_.isString(args[0])?args[0]:void 0,newpassword:_.isPlainObject(args[0])?args[0].newPassword:_.isString(args[1])?args[1]:void 0};if(!body.oldpassword||!body.newpassword)throw new Error('"oldPassword" and "newPassword" properties are required when resetting a user password');client.PUT(["users",self.uniqueId(),"password"].join("/"),body,callback)};var UsergridResponseError=function(options){var self=this;return _.assign(self,options),self};UsergridResponseError.fromJSON=function(responseErrorObject){var usergridResponseError=void 0,error={name:_.get(responseErrorObject,"error")};return void 0!==error.name&&(_.assign(error,{exception:_.get(responseErrorObject,"exception"),description:_.get(responseErrorObject,"error_description")||_.get(responseErrorObject,"description")}),usergridResponseError=new UsergridResponseError(error)),usergridResponseError};var UsergridResponse=function(xmlRequest,usergridRequest){var self=this;if(self.ok=!1,self.request=usergridRequest,xmlRequest){self.statusCode=parseInt(xmlRequest.status),self.ok=self.statusCode<400,self.headers=UsergridHelpers.parseResponseHeaders(xmlRequest.getAllResponseHeaders());var responseContentType=_.get(self.headers,"content-type");if("application/json"===responseContentType){try{var responseJSON=JSON.parse(xmlRequest.responseText)}catch(e){responseJSON={}}self.parseResponseJSON(responseJSON),Object.defineProperty(self,"cursor",{get:function(){return _.get(self,"responseJSON.cursor")}}),Object.defineProperty(self,"hasNextPage",{get:function(){return void 0!==self.cursor}})}else self.asset=new UsergridAsset(xmlRequest.response)}return self};UsergridResponse.responseWithError=function(options){var usergridResponse=new UsergridResponse;return usergridResponse.error=new UsergridResponseError(options),usergridResponse},UsergridResponse.prototype={parseResponseJSON:function(responseJSON){var self=this;if(void 0!==responseJSON)if(_.assign(self,{responseJSON:_.cloneDeep(responseJSON)}),self.ok){var entitiesJSON=_.get(responseJSON,"entities");if(entitiesJSON){var entities=_.map(entitiesJSON,function(entityJSON){var entity=new UsergridEntity(entityJSON);return entity.isUser&&(entity=new UsergridUser(entity)),entity});_.assign(self,{entities:entities}),delete self.responseJSON.entities,self.first=_.first(entities)||void 0,self.entity=self.first,self.last=_.last(entities)||void 0,"/users"===_.get(responseJSON,"path")&&(self.user=self.first,self.users=self.entities),UsergridHelpers.setReadOnly(self.responseJSON)}}else self.error=UsergridResponseError.fromJSON(responseJSON)},loadNextPage:function(){var self=this,cursor=self.cursor;if(cursor){var args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args),client=UsergridHelpers.validateAndRetrieveClient(args),type=_.last(_.get(self,"responseJSON.path").split("/")),limit=_.first(_.get(self,"responseJSON.params.limit")),ql=_.first(_.get(self,"responseJSON.params.ql")),query=new UsergridQuery(type).fromString(ql).cursor(cursor).limit(limit);client.GET(query,callback)}else callback(UsergridResponse.responseWithError({name:"cursor_not_found",description:"Cursor must be present in order perform loadNextPage()."}))}};var UsergridAssetDefaultFileName="file",UsergridAsset=function(fileOrBlob){if(!fileOrBlob instanceof File||!fileOrBlob instanceof Blob)throw new Error("UsergridAsset must be initialized with a 'File' or 'Blob'");var self=this;return self.data=fileOrBlob,self.filename=fileOrBlob.name||UsergridAssetDefaultFileName,self.contentLength=fileOrBlob.size,self.contentType=fileOrBlob.type,self}; \ No newline at end of file From 8a46f91b9ab9d395bf8d875a57f6bf0c3cb419ba Mon Sep 17 00:00:00 2001 From: Robert Walsh Date: Thu, 13 Oct 2016 18:33:32 -0500 Subject: [PATCH 30/36] Initial update of README --- README.md | 1348 +++++++++++++++++++++++------------------------------ 1 file changed, 573 insertions(+), 775 deletions(-) diff --git a/README.md b/README.md index 2896503..0c87aae 100755 --- a/README.md +++ b/README.md @@ -2,869 +2,667 @@ [![Build Status](https://travis-ci.org/RobertWalsh/usergrid-javascript.svg?branch=master)](https://travis-ci.org/RobertWalsh/usergrid-javascript) -##Quickstart -Detailed instructions follow but if you just want a quick example of how to get started with this SDK, here’s a minimal HTML5 file that shows you how to include & initialize the SDK, as well as how to read & write data from Usergrid with it. +Version 2.0 of this SDK is currently a work in progress; documentation and implementation are subject to change. -```html - - - - - - +_**Note:** This Javascript SDK 2.0 for Usergrid is **not** backwards compatible with 0.1X versions of the SDK. If your application is dependent on the 0.1X set of Javascript APIs, you will need to continue using the 0.1X version (see below for installation instructions)._ + +## 2.X Bugs - - - - + ```js + Usergrid.init({ + orgId: '', + appId: '' + }) + ``` + +2. The instance pattern enables the developer to manage instances of the Usergrid client independently and in an isolated fashion. The primary use-case for this is when an application connects to multiple Usergrid targets. + + ```js + var client = new UsergridClient(config) + ``` + +_**Note:** Examples in this readme assume you are using the `Usergrid` shared instance. If you've implemented the instance pattern instead, simply replace `Usergrid` with your client instance variable. See `/tests` for additional examples._ + +## RESTful operations + +When making any RESTful call, a `type` parameter (or `path`) is always required. Whether you specify this as an argument, in an object as a parameter, or as part of a `UsergridQuery` object is up to you. + +### GET() + +To get entities in a collection: + +```js +Usergrid.GET('collection', function(error, usergridResponse) { + // usergridResponse.entities is an array of UsergridEntity objects +}) ``` + +To get a specific entity in a collection by uuid or name: -##Version +```js +Usergrid.GET('collection', '', function(error, usergridResponse) { + // usergridResponse.entity, if found, is a UsergridEntity object +}) +``` + +To get specific entities in a collection by passing a UsergridQuery object: + +```js +var query = new UsergridQuery('cats') + .gt('weight', 2.4) + .contains('color', 'bl*') + .not + .eq('color', 'blue') + .or + .eq('color', 'orange') + +// this will build out the following query: +// select * where weight > 2.4 and color contains 'bl*' and not color = 'blue' or color = 'orange' + +Usergrid.GET(query, function(error, usergridResponse) { + // usergridResponse.entities is an array of UsergridEntity objects matching the specified query +}) +``` + +### POST() and PUT() + +POST and PUT requests both require a JSON body payload. You can pass either a standard JavaScript object or a `UsergridEntity` instance. While the former works in principle, best practise is to use a `UsergridEntity` wherever practical. When an entity has a uuid or name property and already exists on the server, use a PUT request to update it. If it does not, use POST to create it. + +To create a new entity in a collection (POST): + +```js +var entity = new UsergridEntity({ + type: 'restaurant', + restaurant: 'Dino's Deep Dish, + cuisine: 'pizza' +}) + +// or + +var entity = { + type: 'restaurant', + restaurant: 'Dino's Deep Dish, + cuisine: 'pizza' +} + +Usergrid.POST(entity, function(error, usergridResponse) { + // usergridResponse.entity should now have a uuid property and be created +}) + +// you can also POST an array of entities: + +var entities = [ + new UsergridEntity({ + type: 'restaurant', + restaurant: 'Dino's Deep Dish, + cuisine: 'pizza' + }), + new UsergridEntity({ + type: 'restaurant', + restaurant: 'Pizza da Napoli', + cuisine: 'pizza' + }) +] + +Usergrid.POST(entities, function(error, usergridResponse) { + // usergridResponse.entities is an array of UsergridEntity objects matching the specified entity objects. +}) +``` + +To update an entity in a collection (PUT request): + +```js +var entity = new UsergridEntity({ + type: 'restaurant', + restaurant: 'Pizza da Napoli', + cuisine: 'pizza' +}) + +Usergrid.POST(entity, function(error, usergridResponse) { + entity.owner = 'Mia Carrara' + Usergrid.PUT(entity, function(error, usergridResponse) { + // entity now has the property 'owner' + }) +}) + +// or update a set of entities by passing a UsergridQuery object + +var query = new UsergridQuery('restaurants') + .eq('cuisine', 'italian') + +// this will build out the following query: +// select * where cuisine = 'italian' + +Usergrid.PUT(query, { keywords: ['pasta'] }, function(error, usergridResponse) { + /* the first 10 entities matching this query criteria will be updated: + e.g.: + [ + { + "type": "restaurant", + "restaurant": "Il Tarazzo", + "cuisine": "italian", + "keywords": [ + "pasta" + ] + }, + { + "type": "restaurant", + "restaurant": "Cono Sur Pizza & Pasta", + "cuisine": "italian", + "keywords": [ + "pasta" + ] + } + ] + */ +}) +``` + +### DELETE() -Current Version: **0.11.0** +DELETE requests require either a specific entity or a `UsergridQuery` object to be passed as an argument. + +To delete a specific entity in a collection by uuid or name: -See change log: +```js +Usergrid.DELETE('collection', '', function(error, usergridResponse) { + // if successful, entity will now be deleted +}) +``` + +To specific entities in a collection by passing a `UsergridQuery` object: + +```js +var query = new UsergridQuery('cats') + .eq('color', 'black') + .or + .eq('color', 'white') + +// this will build out the following query: +// select * where color = 'black' or color = 'white' + +Usergrid.DELETE(query, function(error, usergridResponse) { + // the first 10 entities matching this query criteria will be deleted +}) +``` - +## Entity operations and convenience methods -##Comments / questions -For help using this SDK, reach out on the Usergrid google group: +`UsergridEntity` has a number of helper/convenience methods to make working with entities more convenient. If you are _not_ utilizing the `Usergrid` shared instance, you must pass an instance of `UsergridClient` as the first argument to any of these helper methods. -https://groups.google.com/forum/?hl=en#!forum/usergrid +### reload() -Or just open github issues. +Reloads the entity from the server +```js +entity.reload(function(error, usergridResponse) { + // entity is now reloaded from the server +}) +``` + +### save() +Saves (or creates) the entity on the server -##Overview -This open source SDK simplifies writing JavaScript / HTML5 applications that connect to Usergrid. The repo is located here: +```js +entity.aNewProperty = 'A new value' +entity.save(function(error, usergridResponse) { + // entity is now updated on the server +}) +``` + +### remove() - +Deletes the entity from the server -To find out more about Usergrid, see: +```js +entity.remove(function(error, usergridResponse) { + // entity is now deleted on the server and the local instance should be destroyed +}) +``` + +## Authentication, current user, and auth-fallback - +### appAuth and authenticateApp() -To view the Usergrid documentation, see: +`Usergrid` can use the app client ID and secret that were passed upon initialization and automatically retrieve an app-level token for these credentials. - +```js +Usergrid.setAppAuth('', '') +Usergrid.authenticateApp(function(error, usergridResponse, token) { + // Usergrid.appAuth is created automatically when this call is successful +}) +``` +### currentUser and authenticateUser() -##Node.js -Want to use Node.js? No problem - use the Usergrid Node Module: +`Usergrid` has a special `currentUser` property. By default, when calling `authenticateUser()`, `.currentUser` will be set to this user if the authentication flow is successful. - +```js +Usergrid.authenticateUser({ + username: '', + password: '' +}, function(error, usergridResponse, token) { + // Usergrid.currentUser is set to the authenticated user and the token is stored within that context +}) +``` + +If you want to utilize authenticateUser without setting as the current user, simply pass a `false` boolean value as the second parameter: + +```js +Usergrid.authenticateUser({ + username: '', + password: '' +}, false, function(error, usergridResponse, token) { + +}) +``` -or on github: +### authMode - +Auth-mode defines what the client should do when a user token is not present. By default, `Usergrid.authMode` is set to `UsergridAuthMode.NONE`, whereby when a token is *not* present, an API call will be performed unauthenticated. If instead `Usergrid.authMode` is set to `UsergridAuthMode.APP`, the API call will instead be performed using client credentials, _if_ they're available (i.e. `authenticateApp()` was performed at some point). -The syntax for this Javascript SDK and the Usergrid Node module are almost exactly the same so you can easily transition between them. +### usingAuth() +At times it is desireable to have complete, granular control over the authentication context of an API call. To facilitate this, the passthrough function `.usingAuth()` allows you to pre-define the auth context of the next API call. -##About the samples -This SDK comes with a variety of samples that you can use to learn how to connect your project to App Services (Usergrid). +```js +// assume Usergrid.authMode = UsergridAuthMode.NONE + +Usergrid.usingAuth(Usergrid.appAuth).POST('roles/guest/permissions', { + permission: "get,post,put,delete:/**" +}, function(error, usergridResponse) { + // here we've temporarily used the client credentials to modify permissions + // subsequent calls will not use this auth context +}) +``` + +## User operations and convenience methods + +`UsergridUser` has a number of helper/convenience methods to make working with user entities more convenient. If you are _not_ utilizing the `Usergrid` shared instance, you must pass an instance of `UsergridClient` as the first argument to any of these helper methods. + +### create() + +Creating a new user: + +```js +var user = new UsergridUser({ + username: 'username', + password: 'password' +}) + +user.create(function(error, usergridResponse, user) { + // user has now been created and should have a valid uuid +}) +``` + +### login() + +A simpler means of retrieving a user-level token: + +```js +var user = new UsergridUser({ + username: 'username', + password: 'password' +}) + +user.login(function(error, usergridResponse, token) { + // user is now logged in +}) +``` -**Note:** All the sample code in this file is pulled directly from the "test" example, so you can rest-assured that it will work! You can find it here: +### logout() - +Logs out the selected user. You can also use this convenience method on `Usergrid.currentUser`. +```js +user.logout(function(error, usergridResponse, success) { + // user is now logged out +}) +``` + +### logoutAllSessions() -##Installing -Once you have downloaded the SDK, add the usergrid.js file to your project. This file is located in the root of the SDK. Include it in the top of your HTML file (in between the head tags): +Logs out all sessions for the selected user and destroys all active tokens. You can also use this convenience method on `Usergrid.currentUser`. - +```js +user.logoutAllSessions(function(error, usergridResponse, success) { + // user is now logged out from everywhere +}) +``` + +### resetPassword() + +Resets the password for the selected user. + +```js +user.resetPassword({ + oldPassword: '2cool4u', + newPassword: 'correct-horse-battery-staple', +}, function(error, response) { + // if it was done correctly, the new password will be changed +}) +``` + +### UsergridUser.CheckAvailable() + +This is a class (static) method that allows you to check whether a username or email address is available or not. + +```js +UsergridUser.CheckAvailable(client, { + email: 'email' +}, function(err, response, exists) { + // 'exists' is a boolean value that indicates whether a user already exists +}) + +UsergridUser.CheckAvailable(client, { + username: 'username' +}, function(err, response, exists) { + +}) + +UsergridUser.CheckAvailable(client, { + email: 'email', + username: 'username', // checks both email and username +}, function(err, response, exists) { + // 'exists' returns true if either username or email exist +}) +``` + +## Querying and filtering data -##Getting started -You are now ready to create a new `Client` object, which is the main entry point in the SDK: +### UsergridQuery initialization - var client = new Usergrid.Client({ - orgName:'yourorgname', - appName:'sandbox', - logging: true, // Optional - turn on logging, off by default - buildCurl: true // Optional - turn on curl commands, off by default - }); +The `UsergridQuery` class allows you to build out complex query filters using the Usergrid [query syntax](http://docs.apigee.com/app-services/content/querying-your-data). -The last two items are optional. The `logging` option will enable console.log output from the client, and will output various bits of information (calls that are being made, errors that happen). The `buildCurl` option will cause cURL equivalent commands of all calls to the API to be displayed in the console.log output (see more about this below). +The first parameter of the `UsergridQuery` builder pattern should be the collection (or type) you intend to query. You can either pass this as an argument, or as the first builder object: -You are now ready to use the `Client` object to make calls against the API. +```js +var query = new UsergridQuery('cats') +// or +var query = new UsergridQuery().type('cats') +var query = new UsergridQuery().collection('cats') +``` -##Asynchronous vs. synchronous calls (a quick discussion) -This SDK works by making RESTful API calls from your application to the App Services (Usergrid) API. This SDK currently only supports asynchronous calls. +You then can layer on additional queries: -If an API call is _synchronous_, it means that code execution will block (or wait) for the API call to return before continuing. This SDK does not yet support synchronous calls. +```js +var query = new UsergridQuery('cats') + .gt('weight', 2.4) + .contains('color', 'bl*') + .not + .eq('color', 'white') + .or + .eq('color', 'orange') +``` + +You can also adjust the number of results returned: -_Asynchronous_ calls, which are supported by this SDK, do not block (or wait) for the API call to return from the server. Execution continues on in your program, and when the call returns from the server, a "callback" function is executed. For example, in the following code, the function `dogCreateCallback` will be called when the `createEntity` call returns from the server. Meanwhile, execution will continue. +```js +var query = new UsergridQuery('cats').eq('color', 'black').limit(100) +// returns a maximum of 100 entiteis +``` + +And sort the results: - function dogCreateCallback(err, dog) { - alert('I will probably be called second'); - if (err) { - // Error - Dog not created - } else { - // Success - Dog was created - } - } - - client.createEntity({type:'dogs'}, dogCreateCallback); - - alert('I will probably be called first'); +```js +var query = new UsergridQuery('cats').eq('color', 'black').asc('name') +// sorts by 'name', ascending +``` + +And you can do geo-location queries: -The result of this is that we cannot guarantee the order of the two alert statements. Most likely, the alert right after the `createEntity` function will be called first because the API call will take a second or so to complete. +```js +var query = new UsergridQuery('devices').locationWithin(, , ) +``` + +### Using a query in a request + +Queries can be passed as parameters to GET, PUT, and DELETE requests: + +```js +Usergrid.GET(query, function(error, usergridResponse, entities) { + // +}) + +Usergrid.PUT(query, { aNewProperty: "A new value" }, function(error, usergridResponse, entities) { + // +}) + +Usergrid.DELETE(query, function(error, usergridResponse, entities) { + // +}) +``` + +While not a typical use case, sometimes it is useful to be able to create a query that works on multiple collections. Therefore, in each one of these RESTful calls, you can optionally pass a 'type' string as the first argument: -The important point is that program execution will continue asynchronously, the callback function will be called once program execution completes. +```js +Usergrid.GET('cats', query, function(error, usergridResponse, entities) { + // +}) +``` + +### List of query builder objects -##Entities and collections -Usergrid stores its data as _entities_ in _collections_. Entities are essentially JSON objects and collections are just like folders for storing these objects. You can learn more about entities and collections in the App Services docs: - - +`type('string')` +> The collection name to query -##Entities -You can easily create new entities, or access existing ones. Here is a simple example that shows how to create a new entity of type "dogs": - - var options = { - type:'dogs', - name:'einstein' - } - - client.createEntity(options, function (err, dog) { - if (err) { - //Error - Dog not created - } else { - //Success - Dog was created - } - }); - -**Note:** All calls to the API will be executed asynchronously, so it is important that you use a callback. - -Once your object is created, you can update properties on it by using the `set` method, then save it back to the database using the `save` method: - - // Once the dog is created, you can set single properties (key, value) - dog.set('breed','mutt'); - - // The set function can also take a JSON object - var data = { - master:'Doc', - state:'hungry' - } - - // Set is additive, so previously set properties are not overwritten unless a property with the same name exists in the data object - dog.set(data); - - // And save back to the database - dog.save(function(err){ - if (err){ - // Error - dog not saved - } else { - // Success - dog was saved - } - }); - -**Note:** Using the `set` function will set the properties locally. Make sure you call the `save` method on the entity to save them back to the database! - -You can also refresh the object from the database if needed (in case the data has been updated by a different client or device) by using the `fetch` method. Use the `get` method to retrieve properties from the object: - - // Call fetch to refresh the data from the server - dog.fetch(function(err){ - if (err){ - // Error - dog not refreshed from database - } else { - // Dog has been refreshed from the database - // Will only work if the UUID for the entity is in the dog object - - // Get single properties from the object using the get method - var master = dog.get('master'); - var name = dog.get('name'); - - // Or, get all the data as a JSON object: - var data = dog.get(); - - // Based on statements above, the data object should look like this: - /* - { - type:'dogs', - name:'einstein', - master:'Doc', - state:'hungry', - breed:'mutt' - } - */ - - } - }); - -Use the `destroy` method to remove the entity from the database: - - // The destroy method will delete the entity from the database - dog.destroy(function(err){ - if (err){ - // Error - dog not removed from database - } else { - // Success - dog was removed from database - dog = null; - // No real dogs were harmed! - } - }); - -##The collection object -The collection object models collections in the database. Once you start programming your app, you will likely find that this is a useful method of interacting with the database. Creating a collection will automatically populate the object with entities from the collection. - -The following example shows how to create a collection object, then how to use those entities once they have been populated from the server: - - // Options object needs to have the type (which is the collection type) - // ”qs” is for “query string”. “ql” is for “query language” - var options = { - type:'dogs', - qs:{ql:'order by index'} - } - - client.createCollection(options, function (err, dogs) { - if (err) { - // Error - could not make collection - } else { - // Success - new collection created - - // We got the dogs, now display the entities - while(dogs.hasNextEntity()) { - // Get a reference to the dog - dog = dogs.getNextEntity(); - // Do something with the entity - var name = dog.get('name'); - } - - } - }); - -You can also add a new entity of the same type to the collection: - - // Create a new dog and add it to the collection - var options = { - name:'extra-dog', - fur:'shedding' - } - // Just pass the options to the addEntity method - // to the collection and it is saved automatically - dogs.addEntity(options, function(err, dog, data) { - if (err) { - // Error - extra dog not saved or added to collection - } else { - // Success - extra dog saved and added to collection - } - }); - -##Collection iteration and paging -At any given time, the collection object will have one page of data loaded. To get the next page of data from the server and iterate across the entities, use the following pattern: - - if (dogs.hasNextPage()) { - // There is a next page, so get it from the server - dogs.getNextPage(function(err){ - if (err) { - // Error - could not get next page of dogs - } else { - // Success - got next page of dogs, so do something with it - while(dogs.hasNextEntity()) { - // Get a reference to the dog - dog = dogs.getNextEntity(); - // Do something with the entity - var name = dog.get('name'); - } - } - }); - } - -You can use the same pattern with the `hasPreviousPage` and `getPreviousPage` methods to get a previous page of data. - -By default, the database will return 10 entities per page. Use the `qs` (query string) property (more about this below) to set a different limit (up to 999): - - var options = { - type:'dogs', - qs:{limit:50} // Set a limit of 50 entities per page - } - - client.createCollection(options, function (err, dogs) { - if (err) { - // Error - could not get all dogs - } else { - // Success - got at most 50 dogs - - // We got 50 dogs, now display the entities - while(dogs.hasNextEntity()) { - // Get a reference to the dog - var dog = dogs.getNextEntity(); - // Do something with the entity - var name = dog.get('name'); - } - - // Wait! What if we want to display them again?? - // Simple! Just reset the entity pointer: - dogs.resetEntityPointer(); - while(dogs.hasNextEntity()) { - // Get a reference to the dog - var dog = dogs.getNextEntity(); - // Do something with the entity - var name = dog.get('name'); - } - - } - }); - -Several convenience methods exist to make working with pages of data easier: - -* `resetPaging` - Calls made after this will get the first page of data (the cursor, which points to the current page of data, is deleted) -* `getFirstEntity` - Gets the first entity of a page -* `getLastEntity` - Gets the last entity of a page -* `resetEntityPointer` - Sets the internal pointer back to the first element of the page -* `getEntityByUUID` - Returns the entity if it is in the current page - -###Custom Queries -A custom query allows you to tell the API that you want your results filtered or altered in some way. - -Use the `qs` property in the options object - "qs" stands for "query string". By adding a JSON object of key/value pairs to the `qs` property of the options object, you signal that you want those values used for the key/value pairs in the query string that is sent to the server. - -For example, to specify that the query results should be ordered by creation date, add the `qs` parameter to the options object: - - var options = { - type:'dogs', - qs:{ql:'order by created DESC'} - }; - -The `qs` object above will be converted into a query language call that looks like this: - - /dogs?ql=order by created DESC +`collection('string')` -If you also wanted to get more entities in the result set than the default 10, say 100, you can specify a query similar to the following (the limit can be a maximum of 999): +> An alias for `type` - dogs.qs = {ql:'order by created DESC',limit:'100'}; +`eq('key', 'value')` or `equal('key', 'value')` -The `qs` object above will be converted into a call that looks like this: - - /dogs?ql=order by created DESC&limit=100 - -**Note**: There are many cases where expanding the result set is useful. But be careful -- the more results you get back in a single call, the longer it will take to transmit the data back to your app. +> Equal to (e.g. `where color = 'black'`) -If you need to change the query on an existing object, simply access the `qs` property directly: +`contains('key', 'value')` - dogs.qs = {ql:'order by created DESC'}; +> Contains a string (e.g.` where color contains 'bl*'`) -Then make your fetch call: +`gt('key', 'value')` or `greaterThan('key', 'value')` - dogs.fetch(...) +> Greater than (e.g. `where weight > 2.4`) -Another common requirement is to limit the results to a specific query. For example, to get all brown dogs, use the following syntax: +`gte('key', 'value')` or `greaterThanOrEqual('key', 'value')` - dogs.qs = {ql:"select * where color='brown'"}; +> Greater than or equal to (e.g. `where weight >= 2.4`) -You can also limit the results returned such that only the fields you specify are returned: +`lt('key', 'value')` or `lessThan('key', 'value')` - dogs.qs = {'ql':"select name, age where color='brown'"}; +> Less than (e.g. `where weight < 2.4`) -**Note:** In the two preceding examples that we put single quotes around 'brown', so it will be searched as a string. +`lte('key', 'value')` or `lessThanOrEqual('key', 'value')` -You can find more information on custom queries here: +> Less than or equal to (e.g. `where weight <= 2.4`) - -##Counters -Counters can be used by an application to create custom statistics, such as how many times an a file has been downloaded or how many instances of an application are in use. +`not` -###Create the counter instance +> Negates the next block in the builder pattern, e.g.: -**Note:** The count is not altered upon instantiation +```js +var query = new UsergridQuery('cats').not.eq('color', 'black') +// select * from cats where not color = 'black' +``` - var counter = new Usergrid.Counter({ - client: client, - data: { - category: 'usage', - //a timestamp of '0' defaults to the current time - timestamp: 0, - counters: { - running_instances: 0, - total_instances: 0 - } - } - }, function(err, data) { - if (err) { - // Error - there was a problem creating the counter - } else { - // Success - the counter was created properly - } - }); - -###Updating counters +`and` -When an application starts, we want to increment the 'running_instances' and 'total_instances' counters. +> Joins two queries by requiring both of them. `and` is also implied when joining two queries _without_ an operator. E.g.: - // add 1 running instance - counter.increment({ - name: 'running_instances', - value: 1 - }, function(err, data) { - // ... - }); +```js +var query = new UsergridQuery('cats').eq('color', 'black').eq('fur', 'longHair') +// is identical to: +var query = new UsergridQuery('cats').eq('color', 'black').and.eq('fur', 'longHair') +``` - // add 1 total instance - counter.increment({ - name: 'total_instances', - value: 1 - }, function(err, data) { - // ... - }); +`or` -When the application exits, we want to decrement 'running_instances' +> Joins two queries by requiring only one of them. `or` is never implied. E.g.: - // subtract 1 total instance - counter.decrement({ - name: 'total_instances', - value: 1 - }, function(err, data) { - // ... - }); +```js +var query = new UsergridQuery('cats').eq('color', 'black').or.eq('color', 'white') +``` + +> When using `or` and `and` operators, `and` joins will take precedence over `or` joins. You can read more about query operators and precedence [here](http://docs.apigee.com/api-baas/content/supported-query-operators-data-types). -Once you have completed your testing, you can reset these values to 0. +`locationWithin(distanceInMeters, latitude, longitude)` - counter.reset({ - name: 'total_instances' - }, function(err, data) { - // ... - }); +> Returns entities which have a location within the specified radius. Arguments can be `float` or `int`. -##Assets +`asc('key')` -Assets can be attached to any entity as binary data. This can be used by your application to store images and other file types. There is a limit of one asset per entity. +> Sorts the results by the specified property, ascending -####Attaching an asset - -An asset can be attached to any entity using Enity.attachAsset(file, callback). You can also call attachAsset() on the same entity to change the asset attached to it. - - //Create a new entity to attach an asset to - you can also use an existing entity - var properties = { - type:'user', - username:'someUser', - }; - - dataClient.createEntity(properties, function(err, response, entity) { - if (!err) { - //The entity was created, so call attachAsset() on it. - entity.attachAsset(file, function(err, response){ - if (!err){ - //Success - the asset was attached - } else { - //Error - } - }); - } - }); - -##Retrieving Assets - -To retrieve the data, call Entity.downloadAsset(callback). A blob is returned -in the success callback. - - entity.downloadAsset(function(err, file){ - if (err) { - // Error - there was a problem retrieving the data - } else { - // Success - the asset was downloaded - - // Create an image tag to hold our downloaded image data - var img = document.createElement("img"); - - // Create a FileReader to feed the image - // into our newly-created element - var reader = new FileReader(); - reader.onload = (function(aImg) { - return function(e) { - aImg.src = e.target.result; - }; - })(img); - reader.readAsDataURL(file); - - // Append the img element to our page - document.body.appendChild(img); - } - }) +`desc('key')` +> Sorts the results by the specified property, descending +`sort('key', 'order')` -##Modeling users with the entity object -Use the entity object to model users. Simply specify a type of "users". - -**Note:** Remember that user entities use "username", not "name", as the distinct key. -Here is an example: - - // Type is 'users', set additional parameters as needed. - var options = { - type:'users', - username:'marty', - password:'mysecurepassword', - name:'Marty McFly', - city:'Hill Valley' - } - - client.createEntity(options, function (err, marty) { - if (err){ - //Error - user not created - } else { - //Success - user created - var name = marty.get('name'); - } - }); - -If the user is modified, just call save on the user again: - - // Add properties cumulatively. - marty.set('state', 'California'); - marty.set('girlfriend','Jennifer'); - - marty.save(function(err){ - if (err){ - // Error - user not updated - } else { - // Success - user updated - } - }); - -To refresh the user's information in the database: - - marty.fetch(function(err){ - if (err){ - // Error - not refreshed - } else { - // Success - user refreshed - - // Do something with the entity - var girlfriend = marty.get('girlfriend'); - } - }); - -###To sign up a new user -When a new user wants to sign up in your app, simply create a form to catch their information, then use the `client.signup` method: - - // Method signature: client.signup(username, password, email, name, callback) - client.signup('marty', 'mysecurepassword', 'marty@timetravel.com', 'Marty McFly', - function (err, marty) { - if (err){ - error('User not created'); - runner(step, marty); - } else { - success('User created'); - runner(step, marty); - } - } - ); - - -###To log a user in -Logging a user in means sending the user's username and password to the server, and getting back an access (OAuth) token. You can then use this token to make calls to the API on the user's behalf. The following example shows how to log a user in and log them out: - - username = 'marty'; - password = 'mysecurepassword'; - client.login(username, password, function (err) { - if (err) { - // Error - could not log user in - } else { - // Success - user has been logged in - - // The login call will return an OAuth token, which is saved - // in the client. Any calls made now will use the token. - // Once a user has logged in, their user object is stored - // in the client and you can access it this way: - var token = client.token; - - // Then make calls against the API. For example, you can - // get the logged in user entity this way: - client.getLoggedInUser(function(err, data, user) { - if(err) { - // Error - could not get logged in user - } else { - // Success - got logged in user - - // You can then get info from the user entity object: - var username = user.get('username'); - } - }); - } - }); - -If you need to change a user's password, set the `oldpassword` and `newpassword` fields, then call save: - - marty.set('oldpassword', 'mysecurepassword'); - marty.set('newpassword', 'mynewsecurepassword'); - marty.save(function(err){ - if (err){ - // Error - user password not updated - } else { - // Success - user password updated - } - }); - -To log a user out, call the `logout` function: - - client.logout(); - - // verify the logout worked - if (client.isLoggedIn()) { - // Error - logout failed - } else { - // Success - user has been logged out - } - -###Making connections -Connections are a way to connect two entities with a word, typically a verb. This is called an _entity relationship_. For example, if you have a user entity with username of marty, and a dog entity with a name of einstein, then using our RESTful API, you could make a call like this: - - POST users/marty/likes/dogs/einstein - -This creates a one-way connection between marty and einstein, where marty "likes" einstein. - -Complete documentation on the entity relationships API can be found here: - - - -For example, say we have a new dog named einstein: - - var options = { - type:'dogs', - name:'einstein', - breed:'mutt' - } - - client.createEntity(options, function (err, dog) { - if (err) { - // Error - new dog not created - } else { - // Success - new dog created - } - }); - -Then, we can create a "likes" connection between our user, Marty, and the dog named einstein: - - marty.connect('likes', dog, function (err, data) { - if (err) { - // Error - connection not created - } else { - // Success - the connection call succeeded - // Now let’s do a getConnections call to verify that it worked - marty.getConnections('likes', function (err, data) { - if (err) { - // Error - could not get connections - } else { - // Success - got all the connections - // Verify that connection exists - if (marty.likes.einstein) { - // Success - connection exists - } else { - // Error - connection does not exist - } - } - }); - } - }); - -We could have just as easily used any other word as the connection (e.g. "owns", "feeds", "cares-for", etc.). - -Now, if you want to remove the connection, do the following: - - marty.disconnect('likes', dog, function (err, data) { - if (err) { - // Error - connection not deleted - } else { - // Success - the connection has been deleted - marty.getConnections('likes', function (err, data) { - if (err) { - // Error - error getting connections - } else { - // Success! - now verify that the connection exists - if (marty.likes.einstein) { - // Error - connection still exists - } else { - // Success - connection deleted - } - } - }); - } - }); - -If you no longer need the object, call the `destroy` method and the object will be deleted from database: - - marty.destroy(function(err){ - if (err){ - // Error - user not deleted from database - } else { - // Success - user deleted from database - marty = null; // Blow away the local object - } - }); - -##Making generic calls -If you find that you need to make calls to the API that fall outside of the scope of the entity and collection objects, you can use the following format to make any REST calls against the API: - - client.request(options, callback); - -This format allows you to make almost any call against the Usergrid API. For example, to get a list of users: - - var options = { - method:'GET', - endpoint:'users' - }; - client.request(options, function (err, data) { - if (err) { - // Error - GET failed - } else { - // Data will contain raw results from API call - // Success - GET worked - } - }); - -Or, to create a new user: - - var options = { - method:'POST', - endpoint:'users', - body:{ username:'fred', password:'secret' } - }; - client.request(options, function (err, data) { - if (err) { - // Error - POST failed - } else { - // Data will contain raw results from API call - // Success - POST worked - } - }); - -Or, to update a user: - - var options = { - method:'PUT', - endpoint:'users/fred', - body:{ newkey:'newvalue' } - }; - client.request(options, function (err, data) { - if (err) { - // Error - PUT failed - } else { - // Data will contain raw results from API call - // Success - PUT worked - } - }); - -Or, to delete a user: - - var options = { - method:'DELETE', - endpoint:'users/fred' - }; - client.request(options, function (err, data) { - if (err) { - // Error - DELETE failed - } else { - // Data will contain raw results from API call - // Success - DELETE worked - } - }); - -The `options` object for the `client.request` function includes the following: - -* `method` - HTTP method (`GET`, `POST`, `PUT`, or `DELETE`), defaults to `GET` -* `qs` - object containing querystring values to be appended to the URI -* `body` - object containing entity body for POST and PUT requests -* `endpoint` - API endpoint, for example "users/fred" -* `mQuery` - boolean, set to `true` if running management query, defaults to `false` -* `buildCurl` - boolean, set to `true` if you want to see equivalent curl commands in console.log, defaults to `false` - -You can make any call to the API using the format above. However, in practice using the higher level entity and collection objects will make life easier as they take care of much of the heavy lifting. - - -###Validation -An extension for validation is provided for you to use in your apps. The file is located here: - - /extensions/usergrid.session.js - -Include this file at the top of your HTML file - AFTER the SDK file: - - - +> Sorts the results by the specified property, in the specified order (`asc` or `desc`). + +`limit(int)` -A variety of functions are provided for verifying many common types such as usernames, passwords, and so on. Feel free to copy and modify these functions for use in your own projects. - - -###cURL -[cURL](http://curl.haxx.se/) is an excellent way to make calls directly against the API. As mentioned in the **Getting started** section of this guide, one of the parameters you can add to the new client `options` object is **buildCurl**: - - var client = new Usergrid.Client({ - orgName:'yourorgname', - appName:'sandbox', - logging: true, // Optional - turn on logging, off by default - buildCurl: true // Optional - turn on curl commands, off by default - }); +> The maximum number of entities to return -If you set this parameter to `true`, the SDK will build equivalent `curl` commands and send them to the console.log window. +`cursor('string')` -More information on cURL can be found here: - - - -## Contributing -We welcome your enhancements! - -Like [Usergrid](https://github.com/apache/usergrid-javascript), the Usergrid Javascript SDK is open source and licensed under the Apache License, Version 2.0. +> A pagination cursor string -1. Fork it. -2. Create your feature branch (`git checkout -b my-new-feature`). -3. Commit your changes (`git commit -am 'Added some feature'`). -4. Push your changes to the upstream branch (`git push origin my-new-feature`). -5. Create new Pull Request (make sure you describe what you did and why your mod is needed). +`fromString('query string')` -###Contributing to usergrid.js -usergrid.js and usergrid.min.js are built from modular components using Grunt. If you want to contribute updates to these files, please commit your changes to the modules in /lib/modules. Do not contribute directly to usergrid.js or your changes could get overwritten in a future build. +> A special builder property that allows you to input a pre-defined query string. All other builder properties will be ignored when this property is defined. For example: + +```js +var query = new UsergridQuery().fromString("select * where color = 'black' order by name asc") +``` -##More information -For more information on Usergrid, visit . +## UsergridResponse object -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at +`UsergridResponse` implements several Usergrid-specific enhancements to [request](https://github.com/request/request). Notably: - +### ok + +You can check `usergridResponse.ok`, a `bool` value, to see if the response was successful. Any status code < 400 returns true. + +```js +Usergrid.GET('collection', function(error, usergridResponse, entities) { + if (usergridResponse.ok) { + // woo! + } +}) +``` + +### entity, entities, user, users, first, last + +Depending on the call you make, you will receive either an array of UsergridEntity objects, or a single entity as the third parameter in the callback. If you're querying the `users` collection, these will also be `UsergridUser` objects, a subclass of `UsergridEntity`. + +- `.first` returns the first entity in an array of entities; `.entity` is an alias to `.first`. If there are no entities, both of these will be undefined. +- `.last` returns the last entity in an array of entities; if there is only one entity in the array, this will be the same as `.first` _and_ `.entity`, and will be undefined if there are no entities in the response. +- `.entities` will either be an array of entities in the response, or an empty array. +- `.user` is a special alias for `.entity` for when querying the `users` collection. Instead of being a `UsergridEntity`, it will be its subclass, `UsergridUser`. +- `.users` is the same as `.user`, though behaves as `.entities` does by returning either an array of UsergridUser objects or an empty array. + +Examples: + +```js +Usergrid.GET('collection', function(error, response) { + // you can access: + // response.entities (the returned entities) + // response.first (the first entity) + // response.entity (same as response.first) + // response.last (the last entity returned) +}) + +Usergrid.GET('collection', '', function(error, response) { + // you can access: + // response.entity (the returned entity) + // response.entities (containing only the returned entity) + // response.first (same as response.entity) + // response.last (same as response.entity) +}) + +Usergrid.GET('users', function(error, usergridResponse) { + // you can access: + // response.users (the returned users) + // response.entities (same as response.users) + // response.user (the first user) + // response.entity (same as response.user) + // response.first (same as response.user) + // response.last (the last user) +}) + +Usergrid.GET('users', '', function(error, response) { + // you can access; + // response.users (containing only the one user) + // response.entities (same as response.users) + // response.user (the returned user) + // response.entity (same as response.user) + // response.first (same as response.user) + // response.last (same as response.user) +}) +``` + +## Connections + +Connections can be managed using `Usergrid.connect()`, `Usergrid.disconnect()`, and `Usergrid.getConnections()`, or entity convenience methods of the same name. + +### connect + +Create a connection between two entities: + +```js +Usergrid.connect(entity1, 'relationship', entity2, function(error, usergridResponse) { + // entity1 now has an outbound connection to entity2 +}) +``` + +### getConnections + +Retrieve outbound connections: + +```js +client.getConnections(UsergridClient.Connections.DIRECTION_OUT, entity1, 'relationship', function(error, usergridResponse) { + // usergridResponse.entities is an array of entities that entity1 is connected to via 'relationship' + // in this case, we'll see entity2 in the array +}) +``` + +Retrieve inbound connections: + +```js +client.getConnections(UsergridClient.Connections.DIRECTION_IN, entity2, 'relationship', function(error, usergridResponse) { + // usergridResponse.entities is an array of entities that connect to entity2 via 'relationship' + // in this case, we'll see entity1 in the array +})``` + +### disconnect + +Delete a connection between two entities: + +```js +Usergrid.disconnect(entity1, 'relationship', entity2, function(error, usergridResponse) { + // entity1's outbound connection to entity2 has been destroyed +}) +``` + +## Assets -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. +Assets can be uploaded and downloaded either directly using `Usergrid.POST` or `Usergrid.PUT`, or via `UsergridEntity` convenience methods. Before uploading an asset, you will need to initialize a `UsergridAsset` instance. +### UsergridAsset init +NEED TO WRITE THIS + \ No newline at end of file From e129990af89ea7a41f47d6f9d9a7999d6929e0d5 Mon Sep 17 00:00:00 2001 From: Robert Walsh Date: Thu, 13 Oct 2016 18:40:13 -0500 Subject: [PATCH 31/36] More updates to README --- README.md | 22 ++++++++++------------ lib/modules/UsergridUser.js | 2 +- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 0c87aae..6c22b13 100755 --- a/README.md +++ b/README.md @@ -433,24 +433,24 @@ var query = new UsergridQuery('devices').locationWithin(, 0); - }) + }); }; UsergridHelpers.inherits(UsergridUser, UsergridEntity); From 011b8d0280816b06bdb275f549497be48712af31 Mon Sep 17 00:00:00 2001 From: Robert Walsh Date: Thu, 13 Oct 2016 19:45:54 -0500 Subject: [PATCH 32/36] Adding Apache 2.0 license to all files. --- examples/all-calls/app.js | 25 ---------------------- examples/resources/css/styles.css | 8 ------- lib/modules/UsergridQuery.js | 29 ++++++++++++++++---------- lib/modules/util/UsergridHelpers.js | 20 ++++++++++++++++++ tests/mocha/index.html | 2 -- tests/mocha/test_asset.js | 14 ++++++++++++- tests/mocha/test_client_auth.js | 14 ++++++++++++- tests/mocha/test_client_connections.js | 14 ++++++++++++- tests/mocha/test_client_init.js | 14 ++++++++++++- tests/mocha/test_client_rest.js | 14 ++++++++++++- tests/mocha/test_entity.js | 13 ++++++++++++ tests/mocha/test_helpers.js | 13 ++++++++++++ tests/mocha/test_query.js | 29 ++++++++++++-------------- tests/mocha/test_response.js | 14 ++++++++++++- tests/mocha/test_response_error.js | 14 ++++++++++++- tests/mocha/test_user.js | 14 ++++++++++++- tests/mocha/test_usergrid_init.js | 14 ++++++++++++- tests/resources/css/mocha.css | 13 ++++++++++++ tests/resources/css/styles.css | 14 ------------- 19 files changed, 207 insertions(+), 85 deletions(-) diff --git a/examples/all-calls/app.js b/examples/all-calls/app.js index c1a629e..0c72c0b 100755 --- a/examples/all-calls/app.js +++ b/examples/all-calls/app.js @@ -1,29 +1,4 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to You under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - /* -* All Calls is a sample app that is powered by Usergrid -* This app shows how to make the 4 REST calls (GET, POST, -* PUT, DELETE) against the usergrid API. -* -* Learn more at http://Usergrid.com/docs -* -* Copyright 2012 Apigee Corporation -* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/examples/resources/css/styles.css b/examples/resources/css/styles.css index 7492f93..0095631 100755 --- a/examples/resources/css/styles.css +++ b/examples/resources/css/styles.css @@ -1,12 +1,4 @@ /** -* All Calls is a Node.js sample app that is powered by Usergrid -* This app shows how to make the 4 REST calls (GET, POST, -* PUT, DELETE) against the usergrid API. -* -* Learn more at http://Usergrid.com/docs -* -* Copyright 2012 Apigee Corporation -* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/lib/modules/UsergridQuery.js b/lib/modules/UsergridQuery.js index f5473ae..f8997d7 100644 --- a/lib/modules/UsergridQuery.js +++ b/lib/modules/UsergridQuery.js @@ -1,15 +1,22 @@ /* - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + *Licensed to the Apache Software Foundation (ASF) under one + *or more contributor license agreements. See the NOTICE file + *distributed with this work for additional information + *regarding copyright ownership. The ASF licenses this file + *to you under the Apache License, Version 2.0 (the + *"License"); you may not use this file except in compliance + *with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + + *Unless required by applicable law or agreed to in writing, + *software distributed under the License is distributed on an + *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + *KIND, either express or implied. See the License for the + *specific language governing permissions and limitations + *under the License. + * + * @author ryan bridges (rbridges@apigee.com) */ 'use strict'; diff --git a/lib/modules/util/UsergridHelpers.js b/lib/modules/util/UsergridHelpers.js index 21e7c6d..66624b0 100644 --- a/lib/modules/util/UsergridHelpers.js +++ b/lib/modules/util/UsergridHelpers.js @@ -1,3 +1,23 @@ +/* + *Licensed to the Apache Software Foundation (ASF) under one + *or more contributor license agreements. See the NOTICE file + *distributed with this work for additional information + *regarding copyright ownership. The ASF licenses this file + *to you under the Apache License, Version 2.0 (the + *"License"); you may not use this file except in compliance + *with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + + *Unless required by applicable law or agreed to in writing, + *software distributed under the License is distributed on an + *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + *KIND, either express or implied. See the License for the + *specific language governing permissions and limitations + *under the License. + * + * @author ryan bridges (rbridges@apigee.com) + */ 'use strict'; diff --git a/tests/mocha/index.html b/tests/mocha/index.html index 59132af..4c97669 100644 --- a/tests/mocha/index.html +++ b/tests/mocha/index.html @@ -1,4 +1,3 @@ - - diff --git a/tests/mocha/test_asset.js b/tests/mocha/test_asset.js index 80c7507..0e06147 100644 --- a/tests/mocha/test_asset.js +++ b/tests/mocha/test_asset.js @@ -1,4 +1,16 @@ -'use strict'; +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ configs.forEach(function(config) { diff --git a/tests/mocha/test_client_auth.js b/tests/mocha/test_client_auth.js index 6c2689f..7c2a122 100644 --- a/tests/mocha/test_client_auth.js +++ b/tests/mocha/test_client_auth.js @@ -1,4 +1,16 @@ -'use strict'; +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ configs.forEach(function(config) { diff --git a/tests/mocha/test_client_connections.js b/tests/mocha/test_client_connections.js index 2a450ed..965a03e 100644 --- a/tests/mocha/test_client_connections.js +++ b/tests/mocha/test_client_connections.js @@ -1,4 +1,16 @@ -'use strict'; +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ configs.forEach(function(config) { diff --git a/tests/mocha/test_client_init.js b/tests/mocha/test_client_init.js index bbcc1c1..d1b31a3 100644 --- a/tests/mocha/test_client_init.js +++ b/tests/mocha/test_client_init.js @@ -1,4 +1,16 @@ -// 'use strict'; +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ describe('Client Initialization', function() { it('should fail to initialize without an orgId and appId', function() { diff --git a/tests/mocha/test_client_rest.js b/tests/mocha/test_client_rest.js index a4696ab..a250bd4 100644 --- a/tests/mocha/test_client_rest.js +++ b/tests/mocha/test_client_rest.js @@ -1,4 +1,16 @@ -'use strict'; +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ configs.forEach(function(config) { diff --git a/tests/mocha/test_entity.js b/tests/mocha/test_entity.js index 1e27da6..960f07b 100644 --- a/tests/mocha/test_entity.js +++ b/tests/mocha/test_entity.js @@ -1,3 +1,16 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ configs.forEach(function(config) { diff --git a/tests/mocha/test_helpers.js b/tests/mocha/test_helpers.js index 7cf4bbd..7e72ea5 100644 --- a/tests/mocha/test_helpers.js +++ b/tests/mocha/test_helpers.js @@ -1,3 +1,16 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ var targetedConfigs = { "1.0": { diff --git a/tests/mocha/test_query.js b/tests/mocha/test_query.js index 9538f15..0f9fc87 100644 --- a/tests/mocha/test_query.js +++ b/tests/mocha/test_query.js @@ -1,19 +1,16 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to You under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ describe('UsergridQuery', function() { diff --git a/tests/mocha/test_response.js b/tests/mocha/test_response.js index 6d2db05..fadcf65 100644 --- a/tests/mocha/test_response.js +++ b/tests/mocha/test_response.js @@ -1,4 +1,16 @@ -'use strict'; +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ configs.forEach(function(config) { diff --git a/tests/mocha/test_response_error.js b/tests/mocha/test_response_error.js index 9b2cbe8..e96eb46 100644 --- a/tests/mocha/test_response_error.js +++ b/tests/mocha/test_response_error.js @@ -1,4 +1,16 @@ -'use strict'; +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ configs.forEach(function(config) { diff --git a/tests/mocha/test_user.js b/tests/mocha/test_user.js index fbba543..ac04340 100644 --- a/tests/mocha/test_user.js +++ b/tests/mocha/test_user.js @@ -1,4 +1,16 @@ -'use strict'; +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ configs.forEach(function(config) { diff --git a/tests/mocha/test_usergrid_init.js b/tests/mocha/test_usergrid_init.js index e1c910f..8e8181f 100644 --- a/tests/mocha/test_usergrid_init.js +++ b/tests/mocha/test_usergrid_init.js @@ -1,4 +1,16 @@ -'use strict'; +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ configs.forEach(function(config) { diff --git a/tests/resources/css/mocha.css b/tests/resources/css/mocha.css index dfa7138..f5dc118 100644 --- a/tests/resources/css/mocha.css +++ b/tests/resources/css/mocha.css @@ -1,3 +1,16 @@ +/** + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ @charset "utf-8"; diff --git a/tests/resources/css/styles.css b/tests/resources/css/styles.css index 7492f93..7daf953 100755 --- a/tests/resources/css/styles.css +++ b/tests/resources/css/styles.css @@ -1,12 +1,4 @@ /** -* All Calls is a Node.js sample app that is powered by Usergrid -* This app shows how to make the 4 REST calls (GET, POST, -* PUT, DELETE) against the usergrid API. -* -* Learn more at http://Usergrid.com/docs -* -* Copyright 2012 Apigee Corporation -* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -20,12 +12,6 @@ * limitations under the License. */ -/** -* @file styles.css -* @author Rod Simpson (rod@apigee.com) -* -*/ - body { background-color: #fff; min-height: 800px; From 72f3ada207887309daadbbd5267afbc6000928bb Mon Sep 17 00:00:00 2001 From: Robert Walsh Date: Thu, 13 Oct 2016 20:29:58 -0500 Subject: [PATCH 33/36] =?UTF-8?q?Added=20=E2=80=98use=20strict=E2=80=99=20?= =?UTF-8?q?to=20all=20test=20modules.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/mocha/test_asset.js | 2 ++ tests/mocha/test_client_auth.js | 2 ++ tests/mocha/test_client_connections.js | 2 ++ tests/mocha/test_client_init.js | 2 ++ tests/mocha/test_client_rest.js | 2 ++ tests/mocha/test_entity.js | 2 ++ tests/mocha/test_helpers.js | 2 ++ tests/mocha/test_query.js | 2 ++ tests/mocha/test_response.js | 2 ++ tests/mocha/test_response_error.js | 2 ++ tests/mocha/test_user.js | 2 ++ tests/mocha/test_usergrid_init.js | 2 ++ 12 files changed, 24 insertions(+) diff --git a/tests/mocha/test_asset.js b/tests/mocha/test_asset.js index 0e06147..45ae1b1 100644 --- a/tests/mocha/test_asset.js +++ b/tests/mocha/test_asset.js @@ -12,6 +12,8 @@ limitations under the License. */ +'use strict'; + configs.forEach(function(config) { var client = new UsergridClient(config); diff --git a/tests/mocha/test_client_auth.js b/tests/mocha/test_client_auth.js index 7c2a122..0f2644b 100644 --- a/tests/mocha/test_client_auth.js +++ b/tests/mocha/test_client_auth.js @@ -12,6 +12,8 @@ limitations under the License. */ +'use strict'; + configs.forEach(function(config) { describe('Client Auth Tests ' + config.target, function () { diff --git a/tests/mocha/test_client_connections.js b/tests/mocha/test_client_connections.js index 965a03e..caa775a 100644 --- a/tests/mocha/test_client_connections.js +++ b/tests/mocha/test_client_connections.js @@ -12,6 +12,8 @@ limitations under the License. */ +'use strict'; + configs.forEach(function(config) { var client = new UsergridClient(config); diff --git a/tests/mocha/test_client_init.js b/tests/mocha/test_client_init.js index d1b31a3..a909231 100644 --- a/tests/mocha/test_client_init.js +++ b/tests/mocha/test_client_init.js @@ -12,6 +12,8 @@ limitations under the License. */ +'use strict'; + describe('Client Initialization', function() { it('should fail to initialize without an orgId and appId', function() { should(function() { diff --git a/tests/mocha/test_client_rest.js b/tests/mocha/test_client_rest.js index a250bd4..684037c 100644 --- a/tests/mocha/test_client_rest.js +++ b/tests/mocha/test_client_rest.js @@ -12,6 +12,8 @@ limitations under the License. */ +'use strict'; + configs.forEach(function(config) { var client = new UsergridClient(config); diff --git a/tests/mocha/test_entity.js b/tests/mocha/test_entity.js index 960f07b..95bd1ab 100644 --- a/tests/mocha/test_entity.js +++ b/tests/mocha/test_entity.js @@ -12,6 +12,8 @@ limitations under the License. */ +'use strict'; + configs.forEach(function(config) { var client = new UsergridClient(config); diff --git a/tests/mocha/test_helpers.js b/tests/mocha/test_helpers.js index 7e72ea5..fe5bf88 100644 --- a/tests/mocha/test_helpers.js +++ b/tests/mocha/test_helpers.js @@ -12,6 +12,8 @@ limitations under the License. */ +'use strict'; + var targetedConfigs = { "1.0": { "orgId": "rwalsh", diff --git a/tests/mocha/test_query.js b/tests/mocha/test_query.js index 0f9fc87..d4f9092 100644 --- a/tests/mocha/test_query.js +++ b/tests/mocha/test_query.js @@ -12,6 +12,8 @@ limitations under the License. */ +'use strict'; + describe('UsergridQuery', function() { describe('_type', function() { diff --git a/tests/mocha/test_response.js b/tests/mocha/test_response.js index fadcf65..1dce049 100644 --- a/tests/mocha/test_response.js +++ b/tests/mocha/test_response.js @@ -12,6 +12,8 @@ limitations under the License. */ +'use strict'; + configs.forEach(function(config) { var client = new UsergridClient(config); diff --git a/tests/mocha/test_response_error.js b/tests/mocha/test_response_error.js index e96eb46..ee3a491 100644 --- a/tests/mocha/test_response_error.js +++ b/tests/mocha/test_response_error.js @@ -12,6 +12,8 @@ limitations under the License. */ +'use strict'; + configs.forEach(function(config) { var client = new UsergridClient(config); diff --git a/tests/mocha/test_user.js b/tests/mocha/test_user.js index ac04340..93d0f8a 100644 --- a/tests/mocha/test_user.js +++ b/tests/mocha/test_user.js @@ -12,6 +12,8 @@ limitations under the License. */ +'use strict'; + configs.forEach(function(config) { var client = new UsergridClient(config); diff --git a/tests/mocha/test_usergrid_init.js b/tests/mocha/test_usergrid_init.js index 8e8181f..3ed6159 100644 --- a/tests/mocha/test_usergrid_init.js +++ b/tests/mocha/test_usergrid_init.js @@ -12,6 +12,8 @@ limitations under the License. */ +'use strict'; + configs.forEach(function(config) { describe('Usergrid init() / initSharedInstance() ' + config.target, function () { From f76fdbeec2b70510b4c66bbd6365e7ccf7f79db8 Mon Sep 17 00:00:00 2001 From: Robert Walsh Date: Thu, 13 Oct 2016 21:24:28 -0500 Subject: [PATCH 34/36] Update README with UsergridAsset information. --- README.md | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 59 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6c22b13..43c1bb5 100755 --- a/README.md +++ b/README.md @@ -658,9 +658,66 @@ Usergrid.disconnect(entity1, 'relationship', entity2, function(error, usergridRe ## Assets -Assets can be uploaded and downloaded either directly using `Usergrid.POST` or `Usergrid.PUT`, or via `UsergridEntity` convenience methods. Before uploading an asset, you will need to initialize a `UsergridAsset` instance. +Assets can be uploaded and downloaded either directly using `Usergrid.uploadAsset()` or `Usergrid.downloadAsset()`, or via `UsergridEntity` convenience methods. Before uploading an asset, you will need to initialize a `UsergridAsset` instance. ### UsergridAsset init -NEED TO WRITE THIS +UsergridAsset's can only be initialized with [File](https://developer.mozilla.org/en-US/docs/Web/API/File) or [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects. + +Loading an image blob via `XMLHttpRequest`: + +```js +var usergridAsset; +var req = new XMLHttpRequest(); +req.open('GET', 'https://raw.githubusercontent.com/apache/usergrid-javascript/master/tests/resources/images/apigee.png', true); +req.responseType = 'blob'; +req.onload = function () { + var blobResponse = req.response; + usergridAsset = new UsergridAsset(blobResponse); // asset.data will now contain the contents and info from the 'blob' response. +}; +req.send(null); +``` + +You can also access `asset.contentType` and `asset.contentLength` once data has been loaded into a `UsergridAsset`. + +###Usergrid.uploadAsset() and Usergrid.downloadAsset() + +POST binary data to a collection by creating a new entity: + +```js +var asset = new UsergridAsset(fileOrBlob); +Usergrid.uploadAsset('collection',asset,function(error, assetResponse, entityWithAsset) { + // asset is now uploaded to Usergrid +}); +``` + +PUT binary data to an existing entity via attachAsset(): + + +```js +var asset = new UsergridAsset(fileOrBlob); +entity.attachAsset(asset); +Usergrid.uploadAsset(entity,function(error, assetResponse, entityWithAsset) { + // access the asset via entity.asset +}); +``` + +### UsergridEntity convenience methods + +`entity.uploadAsset()` is a convenient way to upload an asset that is attached to an entity: + +```js +var asset = new UsergridAsset(fileOrBlob) +entity.attachAsset(asset) +entity.uploadAsset(function(error, assetResponse, entityWithAsset) { + // asset is now uploaded to Usergrid +}) +``` + +`entity.downloadAsset()` allows you to download a binary asset: + +```js +entity.uploadAsset(function(error, assetResponse, entityWithAsset) { + // access the asset via entityWithAsset.asset +})``` \ No newline at end of file From 8fea25eef7e97814ee2b88182b51c99952c197cc Mon Sep 17 00:00:00 2001 From: Robert Walsh Date: Fri, 14 Oct 2016 12:29:05 -0500 Subject: [PATCH 35/36] More cleanup. --- lib/modules/UsergridAsset.js | 4 +- lib/modules/UsergridAuth.js | 4 +- lib/modules/UsergridClient.js | 36 ++--- lib/modules/UsergridEntity.js | 4 +- lib/modules/UsergridEnums.js | 2 +- lib/modules/UsergridQuery.js | 60 ++++---- lib/modules/UsergridRequest.js | 24 +-- lib/modules/UsergridResponse.js | 107 ++++++------- lib/modules/UsergridUser.js | 73 ++++----- lib/modules/util/UsergridHelpers.js | 157 ++++++++++--------- usergrid.js | 225 +++++++++++++--------------- usergrid.min.js | 6 +- 12 files changed, 343 insertions(+), 359 deletions(-) diff --git a/lib/modules/UsergridAsset.js b/lib/modules/UsergridAsset.js index 25715cd..5bd3b59 100644 --- a/lib/modules/UsergridAsset.js +++ b/lib/modules/UsergridAsset.js @@ -12,9 +12,9 @@ limitations under the License. */ -'use strict'; +"use strict"; -var UsergridAssetDefaultFileName = 'file'; +var UsergridAssetDefaultFileName = "file"; var UsergridAsset = function(fileOrBlob) { if( !fileOrBlob instanceof File || !fileOrBlob instanceof Blob ) { diff --git a/lib/modules/UsergridAuth.js b/lib/modules/UsergridAuth.js index 2f80671..0c4aabd 100644 --- a/lib/modules/UsergridAuth.js +++ b/lib/modules/UsergridAuth.js @@ -12,7 +12,7 @@ limitations under the License. */ -'use strict'; +"use strict"; var UsergridAuth = function(token, expiry) { var self = this; @@ -43,7 +43,7 @@ var UsergridAuth = function(token, expiry) { configurable: true }); - Object.defineProperty(self, 'tokenTtl', { + Object.defineProperty(self, "tokenTtl", { configurable: true, writable: true }); diff --git a/lib/modules/UsergridClient.js b/lib/modules/UsergridClient.js index c29eeac..04ccd05 100644 --- a/lib/modules/UsergridClient.js +++ b/lib/modules/UsergridClient.js @@ -12,10 +12,10 @@ limitations under the License. */ -'use strict'; +"use strict"; var UsergridClientDefaultOptions = { - baseUrl: 'https://api.usergrid.com', + baseUrl: "https://api.usergrid.com", authMode: UsergridAuthMode.USER }; @@ -34,18 +34,18 @@ var UsergridClient = function(options) { _.defaults(self, options, UsergridClientDefaultOptions); if (!self.orgId || !self.appId) { - throw new Error('"orgId" and "appId" parameters are required when instantiating UsergridClient'); + throw new Error("'orgId' and 'appId' parameters are required when instantiating UsergridClient"); } - Object.defineProperty(self, 'clientId', { + Object.defineProperty(self, "clientId", { enumerable: false }); - Object.defineProperty(self, 'clientSecret', { + Object.defineProperty(self, "clientSecret", { enumerable: false }); - Object.defineProperty(self, 'appAuth', { + Object.defineProperty(self, "appAuth", { get: function() { return __appAuth; }, @@ -70,19 +70,19 @@ UsergridClient.prototype = { return usergridRequest.sendRequest(); }, GET: function() { - var usergridRequest = UsergridHelpers.buildReqest(this,UsergridHttpMethod.GET,UsergridHelpers.flattenArgs(arguments)); + var usergridRequest = UsergridHelpers.buildRequest(this,UsergridHttpMethod.GET,UsergridHelpers.flattenArgs(arguments)); return this.sendRequest(usergridRequest); }, PUT: function() { - var usergridRequest = UsergridHelpers.buildReqest(this,UsergridHttpMethod.PUT,UsergridHelpers.flattenArgs(arguments)); + var usergridRequest = UsergridHelpers.buildRequest(this,UsergridHttpMethod.PUT,UsergridHelpers.flattenArgs(arguments)); return this.sendRequest(usergridRequest); }, POST: function() { - var usergridRequest = UsergridHelpers.buildReqest(this,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments)); + var usergridRequest = UsergridHelpers.buildRequest(this,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments)); return this.sendRequest(usergridRequest); }, DELETE: function() { - var usergridRequest = UsergridHelpers.buildReqest(this,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments)); + var usergridRequest = UsergridHelpers.buildRequest(this,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments)); return this.sendRequest(usergridRequest); }, connect: function() { @@ -115,14 +115,14 @@ UsergridClient.prototype = { })); if (!(auth instanceof UsergridAppAuth)) { - throw new Error('App auth context was not defined when attempting to call .authenticateApp()'); + throw new Error("App auth context was not defined when attempting to call .authenticateApp()"); } else if (!auth.clientId || !auth.clientSecret) { - throw new Error('authenticateApp() failed because clientId or clientSecret are missing'); + throw new Error("authenticateApp() failed because clientId or clientSecret are missing"); } var callback = function(error,usergridResponse) { - var token = _.get(usergridResponse.responseJSON,'access_token'); - var expiresIn = _.get(usergridResponse.responseJSON,'expires_in'); + var token = _.get(usergridResponse.responseJSON,"access_token"); + var expiresIn = _.get(usergridResponse.responseJSON,"expires_in"); if (usergridResponse.ok) { if (!self.appAuth) { self.appAuth = auth; @@ -153,8 +153,8 @@ UsergridClient.prototype = { }, downloadAsset: function() { var self = this; - var usergridRequest = UsergridHelpers.buildReqest(self,UsergridHttpMethod.GET,UsergridHelpers.flattenArgs(arguments)); - var assetContentType = _.get(usergridRequest,'entity.file-metadata.content-type'); + var usergridRequest = UsergridHelpers.buildRequest(self,UsergridHttpMethod.GET,UsergridHelpers.flattenArgs(arguments)); + var assetContentType = _.get(usergridRequest,"entity.file-metadata.content-type"); if( assetContentType !== undefined ) { _.assign(usergridRequest.headers,{"Accept":assetContentType}); } @@ -168,9 +168,9 @@ UsergridClient.prototype = { }, uploadAsset: function() { var self = this; - var usergridRequest = UsergridHelpers.buildReqest(self,UsergridHttpMethod.PUT,UsergridHelpers.flattenArgs(arguments)); + var usergridRequest = UsergridHelpers.buildRequest(self,UsergridHttpMethod.PUT,UsergridHelpers.flattenArgs(arguments)); if (usergridRequest.asset === undefined) { - throw new Error('An UsergridAsset was not defined when attempting to call .uploadAsset()'); + throw new Error("An UsergridAsset was not defined when attempting to call .uploadAsset()"); } var realUploadAssetCallback = usergridRequest.callback; diff --git a/lib/modules/UsergridEntity.js b/lib/modules/UsergridEntity.js index 7777803..9ac8dea 100644 --- a/lib/modules/UsergridEntity.js +++ b/lib/modules/UsergridEntity.js @@ -149,7 +149,7 @@ UsergridEntity.prototype = { if( _.has(self,'asset.contentType') ) { client.uploadAsset(self,callback); } else { - var response = new UsergridResponse.responseWithError({ + var response = UsergridResponse.responseWithError({ name: 'asset_not_found', description: 'The specified entity does not have a valid asset attached' }); @@ -166,7 +166,7 @@ UsergridEntity.prototype = { if( _.has(self,'asset.contentType') ) { client.downloadAsset(self,callback); } else { - var response = new UsergridResponse.responseWithError({ + var response = UsergridResponse.responseWithError({ name: 'asset_not_found', description: 'The specified entity does not have a valid asset attached' }); diff --git a/lib/modules/UsergridEnums.js b/lib/modules/UsergridEnums.js index ea1baaa..1d11d96 100644 --- a/lib/modules/UsergridEnums.js +++ b/lib/modules/UsergridEnums.js @@ -12,7 +12,7 @@ limitations under the License. */ -'use strict'; +"use strict"; var UsergridAuthMode = Object.freeze({ NONE: "none", diff --git a/lib/modules/UsergridQuery.js b/lib/modules/UsergridQuery.js index f8997d7..6f551c4 100644 --- a/lib/modules/UsergridQuery.js +++ b/lib/modules/UsergridQuery.js @@ -19,13 +19,13 @@ * @author ryan bridges (rbridges@apigee.com) */ -'use strict'; +"use strict"; var UsergridQuery = function(type) { var self = this; - var query = '', + var query = "", queryString, sort, urlTerms = {}, @@ -52,36 +52,36 @@ var UsergridQuery = function(type) { return self; }, eq: function(key, value) { - query = self.andJoin(key + ' ' + UsergridQueryOperator.EQUAL + ' ' + UsergridHelpers.useQuotesIfRequired(value)); + query = self.andJoin(key + " " + UsergridQueryOperator.EQUAL + " " + UsergridHelpers.useQuotesIfRequired(value)); return self; }, equal: this.eq, gt: function(key, value) { - query = self.andJoin(key + ' ' + UsergridQueryOperator.GREATER_THAN + ' ' + UsergridHelpers.useQuotesIfRequired(value)); + query = self.andJoin(key + " " + UsergridQueryOperator.GREATER_THAN + " " + UsergridHelpers.useQuotesIfRequired(value)); return self; }, greaterThan: this.gt, gte: function(key, value) { - query = self.andJoin(key + ' ' + UsergridQueryOperator.GREATER_THAN_EQUAL_TO + ' ' + UsergridHelpers.useQuotesIfRequired(value)); + query = self.andJoin(key + " " + UsergridQueryOperator.GREATER_THAN_EQUAL_TO + " " + UsergridHelpers.useQuotesIfRequired(value)); return self; }, greaterThanOrEqual: this.gte, lt: function(key, value) { - query = self.andJoin(key + ' ' + UsergridQueryOperator.LESS_THAN + ' ' + UsergridHelpers.useQuotesIfRequired(value)); + query = self.andJoin(key + " " + UsergridQueryOperator.LESS_THAN + " " + UsergridHelpers.useQuotesIfRequired(value)); return self; }, lessThan: this.lt, lte: function(key, value) { - query = self.andJoin(key + ' ' + UsergridQueryOperator.LESS_THAN_EQUAL_TO + ' ' + UsergridHelpers.useQuotesIfRequired(value)); + query = self.andJoin(key + " " + UsergridQueryOperator.LESS_THAN_EQUAL_TO + " " + UsergridHelpers.useQuotesIfRequired(value)); return self; }, lessThanOrEqual: this.lte, contains: function(key, value) { - query = self.andJoin(key + ' contains ' + UsergridHelpers.useQuotesIfRequired(value)); + query = self.andJoin(key + " contains " + UsergridHelpers.useQuotesIfRequired(value)); return self; }, locationWithin: function(distanceInMeters, lat, lng) { - query = self.andJoin('location within ' + distanceInMeters + ' of ' + lat + ', ' + lng); + query = self.andJoin("location within " + distanceInMeters + " of " + lat + ", " + lng); return self; }, asc: function(key) { @@ -93,7 +93,7 @@ var UsergridQuery = function(type) { return self; }, sort: function(key, order) { - sort = (key && order) ? (' order by ' + key + ' ' + order) : ''; + sort = (key && order) ? (" order by " + key + " " + order) : ""; return self; }, fromString: function(string) { @@ -101,7 +101,7 @@ var UsergridQuery = function(type) { return self; }, urlTerm: function(key,value) { - if( key === 'ql' ) { + if( key === "ql" ) { self.fromString(); } else { urlTerms[key] = value; @@ -110,7 +110,7 @@ var UsergridQuery = function(type) { }, andJoin: function(append) { if (__nextIsNot) { - append = 'not ' + append; + append = "not " + append; __nextIsNot = false; } if (!append) { @@ -118,29 +118,29 @@ var UsergridQuery = function(type) { } else if (query.length === 0) { return append; } else { - return (_.endsWith(query, 'and') || _.endsWith(query, 'or')) ? (query + ' ' + append) : (query + ' and ' + append); + return (_.endsWith(query, "and") || _.endsWith(query, "or")) ? (query + " " + append) : (query + " and " + append); } }, orJoin: function() { - return (query.length > 0 && !_.endsWith(query, 'or')) ? (query + ' or') : query; + return (query.length > 0 && !_.endsWith(query, "or")) ? (query + " or") : query; } }); // public accessors - Object.defineProperty(self, '_ql', { + Object.defineProperty(self, "_ql", { get: function() { - var ql = 'select * '; + var ql = "select * "; if (queryString !== undefined) { ql = queryString; } else { - ql += ((query.length > 0) ? 'where ' + (query || '') : ''); - ql += ((sort !== undefined) ? sort : ''); + ql += ((query.length > 0) ? "where " + (query || "") : ""); + ql += ((sort !== undefined) ? sort : ""); } return ql; } }); - Object.defineProperty(self, 'encodedStringValue', { + Object.defineProperty(self, "encodedStringValue", { get: function() { var self = this; var limit = self._limit; @@ -149,14 +149,14 @@ var UsergridQuery = function(type) { var returnString = undefined; if( limit !== undefined ) { - returnString = 'limit' + UsergridQueryOperator.EQUAL + limit; + returnString = "limit" + UsergridQueryOperator.EQUAL + limit; } if( !_.isEmpty(cursor) ) { - var cursorString = 'cursor' + UsergridQueryOperator.EQUAL + cursor; + var cursorString = "cursor" + UsergridQueryOperator.EQUAL + cursor; if( _.isEmpty(returnString) ) { returnString = cursorString; } else { - returnString += '&' + cursorString; + returnString += "&" + cursorString; } } _.forEach(urlTerms,function(value,key) { @@ -164,40 +164,40 @@ var UsergridQuery = function(type) { if( _.isEmpty(returnString) ) { returnString = encodedURLTermString; } else { - returnString += '&' + encodedURLTermString; + returnString += "&" + encodedURLTermString; } }); if( !_.isEmpty(requirementsString) ) { - var qLString = 'ql=' + encodeURIComponent(requirementsString); + var qLString = "ql=" + encodeURIComponent(requirementsString); if( _.isEmpty(returnString) ) { returnString = qLString; } else { - returnString += '&' + qLString; + returnString += "&" + qLString; } } if( !_.isEmpty(returnString) ) { - returnString = '?' + returnString; + returnString = "?" + returnString; } return !_.isEmpty(returnString) ? returnString : undefined; } }); - Object.defineProperty(self, 'and', { + Object.defineProperty(self, "and", { get: function() { - query = self.andJoin(''); + query = self.andJoin(""); return self; } }); - Object.defineProperty(self, 'or', { + Object.defineProperty(self, "or", { get: function() { query = self.orJoin(); return self; } }); - Object.defineProperty(self, 'not', { + Object.defineProperty(self, "not", { get: function() { __nextIsNot = true; return self; diff --git a/lib/modules/UsergridRequest.js b/lib/modules/UsergridRequest.js index 09723d0..5152622 100644 --- a/lib/modules/UsergridRequest.js +++ b/lib/modules/UsergridRequest.js @@ -12,44 +12,44 @@ limitations under the License. */ -'use strict'; +"use strict"; var UsergridRequest = function(options) { var self = this; var client = UsergridHelpers.validateAndRetrieveClient(options); if (!_.isString(options.type) && !_.isString(options.path) && !_.isString(options.uri)) { - throw new Error('one of "type" (collection name), "path", or "uri" parameters are required when initializing a UsergridRequest') + throw new Error("one of 'type' (collection name), 'path', or 'uri' parameters are required when initializing a UsergridRequest"); } - if (!_.includes(['GET', 'PUT', 'POST', 'DELETE'], options.method)) { - throw new Error('"method" parameter is required when initializing a UsergridRequest') + if (!_.includes(["GET", "PUT", "POST", "DELETE"], options.method)) { + throw new Error("'method' parameter is required when initializing a UsergridRequest"); } self.method = options.method; self.callback = options.callback; self.uri = options.uri || UsergridHelpers.uri(client, options); self.entity = options.entity; - self.body = options.body || undefined; - self.asset = options.asset || undefined; + self.body = options.body; + self.asset = options.asset; self.query = options.query; self.queryParams = options.queryParams || options.qs; - var defaultHeadersToUse = self.asset === undefined ? UsergridHelpers.DefaultHeaders : {}; + var defaultHeadersToUse = !self.asset ? UsergridHelpers.DefaultHeaders : {}; self.headers = UsergridHelpers.headers(client, options, defaultHeadersToUse); if( self.query !== undefined ) { self.uri += UsergridHelpers.normalize(self.query.encodedStringValue, {}); } - if( self.queryParams !== undefined ) { + if( self.queryParams ) { _.forOwn(self.queryParams, function(value,key){ - self.uri += '?' + encodeURIComponent(key) + UsergridQueryOperator.EQUAL + encodeURIComponent(value); + self.uri += "?" + encodeURIComponent(key) + UsergridQueryOperator.EQUAL + encodeURIComponent(value); }); self.uri = UsergridHelpers.normalize(self.uri,{}); } - if( self.asset !== undefined ) { + if( self.asset ) { self.body = new FormData(); self.body.append(self.asset.filename, self.asset.data); } else { @@ -59,7 +59,9 @@ var UsergridRequest = function(options) { } else if( _.isArray(self.body) ) { self.body = JSON.stringify(self.body); } - } catch( exception ) { } + } catch( exception ) { + console.warn("Unable to convert 'UsergridRequest.body' to a JSON String: " + exception); + } } return self; diff --git a/lib/modules/UsergridResponse.js b/lib/modules/UsergridResponse.js index 506d800..6c45b8b 100644 --- a/lib/modules/UsergridResponse.js +++ b/lib/modules/UsergridResponse.js @@ -12,7 +12,7 @@ limitations under the License. */ -'use strict'; +"use strict"; var UsergridResponseError = function(options) { var self = this; @@ -21,17 +21,17 @@ var UsergridResponseError = function(options) { }; UsergridResponseError.fromJSON = function(responseErrorObject) { - var usergridResponseError = undefined; - var error = { name: _.get(responseErrorObject,'error') }; - if ( error.name !== undefined ) { + var usergridResponseError; + var error = { name: _.get(responseErrorObject,"error") }; + if ( error.name ) { _.assign(error, { - exception: _.get(responseErrorObject,'exception'), - description: _.get(responseErrorObject,'error_description') || _.get(responseErrorObject,'description') + exception: _.get(responseErrorObject,"exception"), + description: _.get(responseErrorObject,"error_description") || _.get(responseErrorObject,"description") }); usergridResponseError = new UsergridResponseError(error); } return usergridResponseError; -} +}; var UsergridResponse = function(xmlRequest,usergridRequest) { var self = this; @@ -43,27 +43,14 @@ var UsergridResponse = function(xmlRequest,usergridRequest) { self.ok = (self.statusCode < 400); self.headers = UsergridHelpers.parseResponseHeaders(xmlRequest.getAllResponseHeaders()); - var responseContentType = _.get(self.headers,'content-type'); - if( responseContentType === 'application/json' ) { + var responseContentType = _.get(self.headers,"content-type"); + if( responseContentType === UsergridApplicationJSONHeaderValue ) { try { var responseJSON = JSON.parse(xmlRequest.responseText); - } catch (e) { - responseJSON = {}; - } - - self.parseResponseJSON(responseJSON); - - Object.defineProperty(self, 'cursor', { - get: function() { - return _.get(self,'responseJSON.cursor'); + if( responseJSON ) { + self.parseResponseJSON(responseJSON) } - }); - - Object.defineProperty(self, 'hasNextPage', { - get: function () { - return self.cursor !== undefined; - } - }); + } catch (e) {} } else { self.asset = new UsergridAsset(xmlRequest.response); } @@ -80,52 +67,56 @@ UsergridResponse.responseWithError = function(options) { UsergridResponse.prototype = { parseResponseJSON: function(responseJSON) { var self = this; - if( responseJSON !== undefined ) { - _.assign(self, { responseJSON: _.cloneDeep(responseJSON) }); - if (self.ok) { - var entitiesJSON = _.get(responseJSON,'entities'); - if (entitiesJSON) { - var entities = _.map(entitiesJSON,function(entityJSON) { - var entity = new UsergridEntity(entityJSON); - if (entity.isUser) { - entity = new UsergridUser(entity); - } - return entity; - }); - _.assign(self, { entities: entities }); - delete self.responseJSON.entities; + self.responseJSON = _.cloneDeep(responseJSON); + if (self.ok) { + self.cursor = _.get(self,"responseJSON.cursor"); + self.hasNextPage = (!_.isNil(self.cursor)); + var entitiesJSON = _.get(responseJSON,"entities"); + if (entitiesJSON) { + self.parseResponseEntities(entitiesJSON); + delete self.responseJSON.entities; + } + } else { + self.error = UsergridResponseError.fromJSON(responseJSON); + } + UsergridHelpers.setReadOnly(self.responseJSON); + }, + parseResponseEntities: function(entitiesJSON) { + var self = this; + self.entities = _.map(entitiesJSON,function(entityJSON) { + var entity = new UsergridEntity(entityJSON); + if (entity.isUser) { + entity = new UsergridUser(entity); + } + return entity; + }); - self.first = _.first(entities) || undefined; - self.entity = self.first; - self.last = _.last(entities) || undefined; + self.first = _.first(self.entities); + self.entity = self.first; + self.last = _.last(self.entities); - if (_.get(responseJSON, 'path') === '/users') { - self.user = self.first; - self.users = self.entities; - } - UsergridHelpers.setReadOnly(self.responseJSON); - } - } else { - self.error = UsergridResponseError.fromJSON(responseJSON); - } + if (_.get(self, "responseJSON.path") === "/users") { + self.user = self.first; + self.users = self.entities; } }, loadNextPage: function() { var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var callback = UsergridHelpers.callback(args); var cursor = self.cursor; + if (!cursor) { callback(UsergridResponse.responseWithError({ - name:'cursor_not_found', - description:'Cursor must be present in order perform loadNextPage().'}) + name:"cursor_not_found", + description:"Cursor must be present in order perform loadNextPage()."}) ); } else { - var args = UsergridHelpers.flattenArgs(arguments); - var callback = UsergridHelpers.callback(args); var client = UsergridHelpers.validateAndRetrieveClient(args); - var type = _.last(_.get(self,'responseJSON.path').split('/')); - var limit = _.first(_.get(self,'responseJSON.params.limit')); - var ql = _.first(_.get(self,'responseJSON.params.ql')); + var type = _.last(_.get(self,"responseJSON.path").split("/")); + var limit = _.first(_.get(self,"responseJSON.params.limit")); + var ql = _.first(_.get(self,"responseJSON.params.ql")); var query = new UsergridQuery(type).fromString(ql).cursor(cursor).limit(limit); client.GET(query, callback); diff --git a/lib/modules/UsergridUser.js b/lib/modules/UsergridUser.js index 52b81d0..7c0337c 100644 --- a/lib/modules/UsergridUser.js +++ b/lib/modules/UsergridUser.js @@ -12,13 +12,13 @@ limitations under the License. */ -'use strict'; +"use strict"; var UsergridUser = function(obj) { - if (! _.has(obj,'email') && !_.has(obj,'username')) { + if (! _.has(obj,"email") && !_.has(obj,"username")) { // This is not a user entity - throw new Error('"email" or "username" property is required when initializing a UsergridUser object'); + throw new Error("'email' or 'username' property is required when initializing a UsergridUser object"); } var self = this; @@ -26,32 +26,32 @@ var UsergridUser = function(obj) { _.assign(self, obj, UsergridEntity); UsergridEntity.call(self, "user"); - UsergridHelpers.setWritable(self, 'name'); + UsergridHelpers.setWritable(self, "name"); return self; }; UsergridUser.CheckAvailable = function() { var args = UsergridHelpers.flattenArgs(arguments); var client = UsergridHelpers.validateAndRetrieveClient(args); - if (args[0] instanceof UsergridClient) { - args.shift(); - } var callback = UsergridHelpers.callback(args); - var checkQuery; - - if (args[0].username && args[0].email) { - checkQuery = new UsergridQuery('users').eq('username', args[0].username).or.eq('email', args[0].email); - } else if (args[0].username) { - checkQuery = new UsergridQuery('users').eq('username', args[0].username); - } else if (args[0].email) { - checkQuery = new UsergridQuery('users').eq('email', args[0].email); - } else { + + var username = args[0].username || args[1].username; + var email = args[0].email || args[1].email; + + if( !username && !email ) { throw new Error("'username' or 'email' property is required when checking for available users"); + } else { + var checkQuery = new UsergridQuery("users"); + if (username) { + checkQuery.eq("username", username); + } + if (email) { + checkQuery.or.eq("email", email); + } + client.GET(checkQuery, function(error,usergridResponse) { + callback(error, usergridResponse, usergridResponse.entities.length > 0); + }); } - - client.GET(checkQuery, function(error,usergridResponse) { - callback(error, usergridResponse, usergridResponse.entities.length > 0); - }); }; UsergridHelpers.inherits(UsergridUser, UsergridEntity); @@ -79,12 +79,12 @@ UsergridUser.prototype.login = function() { var client = UsergridHelpers.validateAndRetrieveClient(args); var callback = UsergridHelpers.callback(args); - client.POST('token', UsergridHelpers.userLoginBody(self), function (error,usergridResponse) { + client.POST("token", UsergridHelpers.userLoginBody(self), function (error,usergridResponse) { delete self.password; var responseJSON = usergridResponse.responseJSON; - var token = _.get(responseJSON,'access_token'); - var expiresIn = _.get(responseJSON,'expires_in'); + var token = _.get(responseJSON,"access_token"); + var expiresIn = _.get(responseJSON,"expires_in"); if (usergridResponse.ok) { self.auth = new UsergridUserAuth(self); @@ -103,28 +103,25 @@ UsergridUser.prototype.logout = function() { var callback = UsergridHelpers.callback(args); if (!self.auth || !self.auth.isValid) { - var response = new UsergridResponse.responseWithError({ - name: 'no_valid_token', - description: 'this user does not have a valid token' + var response = UsergridResponse.responseWithError({ + name: "no_valid_token", + description: "this user does not have a valid token" }); callback(response.error,response); } else { var revokeAll = _.first(args.filter(_.isBoolean)) || false; - var queryParams = undefined; - if (!revokeAll) { - queryParams = {token: self.auth.token}; - } - var requestOptions = { client: client, - path: ['users', self.uniqueId(), ('revoketoken' + ((revokeAll) ? "s" : ""))].join('/'), + path: ["users", self.uniqueId(), ("revoketoken" + ((revokeAll) ? "s" : ""))].join("/"), method: UsergridHttpMethod.PUT, - queryParams: queryParams, callback: function (error,usergridResponse) { self.auth.destroy(); callback(error,usergridResponse,usergridResponse.ok); }.bind(self) }; + if (!revokeAll) { + requestOptions.queryParams = {token: self.auth.token}; + } var request = new UsergridRequest(requestOptions); client.sendRequest(request); } @@ -145,14 +142,10 @@ UsergridUser.prototype.resetPassword = function() { if (args[0] instanceof UsergridClient) { args.shift(); } - var body = { - oldpassword: _.isPlainObject(args[0]) ? args[0].oldPassword : _.isString(args[0]) ? args[0] : undefined, - newpassword: _.isPlainObject(args[0]) ? args[0].newPassword : _.isString(args[1]) ? args[1] : undefined - }; + var body = UsergridHelpers.userResetPasswordBody(args); if (!body.oldpassword || !body.newpassword) { - throw new Error('"oldPassword" and "newPassword" properties are required when resetting a user password'); + throw new Error("'oldPassword' and 'newPassword' properties are required when resetting a user password"); } - - client.PUT(['users',self.uniqueId(),'password'].join('/'), body, callback); + client.PUT(["users",self.uniqueId(),"password"].join("/"), body, callback); }; \ No newline at end of file diff --git a/lib/modules/util/UsergridHelpers.js b/lib/modules/util/UsergridHelpers.js index 66624b0..7e963ce 100644 --- a/lib/modules/util/UsergridHelpers.js +++ b/lib/modules/util/UsergridHelpers.js @@ -19,27 +19,27 @@ * @author ryan bridges (rbridges@apigee.com) */ -'use strict'; +"use strict"; -var UsergridApplicationJSONHeaderValue = 'application/json'; +var UsergridApplicationJSONHeaderValue = "application/json"; (function(global) { - var name = 'UsergridHelpers', overwrittenName = global[name]; + var name = "UsergridHelpers", overwrittenName = global[name]; function UsergridHelpers() { } UsergridHelpers.DefaultHeaders = Object.freeze({ - 'Content-Type': UsergridApplicationJSONHeaderValue, - 'Accept': UsergridApplicationJSONHeaderValue + "Content-Type": UsergridApplicationJSONHeaderValue, + "Accept": UsergridApplicationJSONHeaderValue }); UsergridHelpers.validateAndRetrieveClient = function(args) { - var client = undefined; - if (args instanceof UsergridClient) { client = args; } - else if (args[0] instanceof UsergridClient) { client = args[0]; } - else if (_.get(args,'client')) { client = args.client; } - else if (Usergrid.isInitialized) { client = Usergrid; } - else { throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument"); } + var client = _.first([args, args[0], _.get(args,"client"), (Usergrid.isInitialized) ? Usergrid : undefined].filter(function(client) { + return client instanceof UsergridClient; + })); + if( !client ) { + throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument"); + } return client; }; @@ -62,7 +62,7 @@ var UsergridApplicationJSONHeaderValue = 'application/json'; UsergridHelpers.callback = function() { var args = UsergridHelpers.flattenArgs(arguments).reverse(); var emptyFunc = function() {}; - return _.first(_.flattenDeep([args, _.get(args,'0.callback'), emptyFunc]).filter(_.isFunction)); + return _.first(_.flattenDeep([args, _.get(args,"0.callback"), emptyFunc]).filter(_.isFunction)); }; UsergridHelpers.authForRequests = function(client) { @@ -80,7 +80,7 @@ var UsergridApplicationJSONHeaderValue = 'application/json'; UsergridHelpers.userLoginBody = function(options) { var body = { - grant_type: 'password', + grant_type: "password", password: options.password }; if (options.tokenTtl) { @@ -92,7 +92,7 @@ var UsergridApplicationJSONHeaderValue = 'application/json'; UsergridHelpers.appLoginBody = function(options) { var body = { - grant_type: 'client_credentials', + grant_type: "client_credentials", client_id: options.clientId, client_secret: options.clientSecret }; @@ -102,6 +102,13 @@ var UsergridApplicationJSONHeaderValue = 'application/json'; return body; }; + UsergridHelpers.userResetPasswordBody = function(args) { + return { + oldpassword: _.isPlainObject(args[0]) ? args[0].oldPassword : _.isString(args[0]) ? args[0] : undefined, + newpassword: _.isPlainObject(args[0]) ? args[0].newPassword : _.isString(args[1]) ? args[1] : undefined + }; + }; + UsergridHelpers.calculateExpiry = function(expires_in) { return Date.now() + ((expires_in ? expires_in - 5 : 0) * 1000); }; @@ -149,7 +156,7 @@ var UsergridApplicationJSONHeaderValue = 'application/json'; }; UsergridHelpers.assignPrefabOptions = function(args) { - // if a preformatted options argument passed, assign it to options + // if a pre-formatted options argument passed, assign it to options if (_.isObject(args[0]) && !_.isFunction(args[0]) && _.has(args,"method")) { _.assign(this, args[0]) } @@ -159,16 +166,16 @@ var UsergridApplicationJSONHeaderValue = 'application/json'; UsergridHelpers.normalize = function(str) { // remove consecutive slashes - str = str.replace(/\/+/g, '/'); + str = str.replace(/\/+/g, "/"); // make sure protocol is followed by two slashes - str = str.replace(/:\//g, '://'); + str = str.replace(/:\//g, "://"); // remove trailing slash before parameters or hash - str = str.replace(/\/(\?|&|#[^!])/g, '$1'); + str = str.replace(/\/(\?|&|#[^!])/g, "$1"); // replace ? in parameters with & - str = str.replace(/(\?.+)\?/g, '$1&'); + str = str.replace(/(\?.+)\?/g, "$1&"); return str; }; @@ -177,27 +184,27 @@ var UsergridApplicationJSONHeaderValue = 'application/json'; var input = arguments; var options = {}; - if (typeof arguments[0] === 'object') { + if (typeof arguments[0] === "object") { // new syntax with array and options input = arguments[0]; options = arguments[1] || {}; } - var joined = [].slice.call(input, 0).join('/'); + var joined = [].slice.call(input, 0).join("/"); return UsergridHelpers.normalize(joined, options); }; UsergridHelpers.parseResponseHeaders = function(headerStr) { var headers = {}; if (headerStr) { - var headerPairs = headerStr.split('\u000d\u000a'); + var headerPairs = headerStr.split("\u000d\u000a"); for (var i = 0; i < headerPairs.length; i++) { - // Can't use split() here because it does the wrong thing + // Can"t use split() here because it does the wrong thing // if the header value has the string ": " in it. var headerPair = headerPairs[i]; - var index = headerPair.indexOf('\u003a\u0020'); + var index = headerPair.indexOf("\u003a\u0020"); if (index > 0) { var key = headerPair.substring(0, index).toLowerCase(); headers[key] = headerPair.substring(index + 2); @@ -208,7 +215,7 @@ var UsergridApplicationJSONHeaderValue = 'application/json'; }; UsergridHelpers.uri = function(client, options) { - var path = ''; + var path = ""; if( options instanceof UsergridEntity ) { path = options.type } else if( options instanceof UsergridQuery ) { @@ -216,41 +223,41 @@ var UsergridApplicationJSONHeaderValue = 'application/json'; } else if( _.isString(options) ) { path = options } else if( _.isArray(options) ) { - path = _.get(options,'0.type') || _.get(options,'0.path') + path = _.get(options,"0.type") || _.get(options,"0.path") } else { - path = options.path || options.type || _.get(options,"entity.type") || _.get(options,"query._type") || _.get(options,'body.type') || _.get(options,'body.path') + path = options.path || options.type || _.get(options,"entity.type") || _.get(options,"query._type") || _.get(options,"body.type") || _.get(options,"body.path") } - var uuidOrName = ''; + var uuidOrName = ""; if( options.method !== UsergridHttpMethod.POST ) { uuidOrName = _.first([ options.uuidOrName, options.uuid, options.name, - _.get(options,'entity.uuid'), - _.get(options,'entity.name'), - _.get(options,'body.uuid'), - _.get(options,'body.name'), - '' + _.get(options,"entity.uuid"), + _.get(options,"entity.name"), + _.get(options,"body.uuid"), + _.get(options,"body.name"), + "" ].filter(_.isString)); } return UsergridHelpers.urljoin(client.baseUrl, client.orgId, client.appId, path, uuidOrName); }; UsergridHelpers.updateEntityFromRemote = function(entity,usergridResponse) { - UsergridHelpers.setWritable(entity, ['uuid', 'name', 'type', 'created']); + UsergridHelpers.setWritable(entity, ["uuid", "name", "type", "created"]); _.assign(entity, usergridResponse.entity); - UsergridHelpers.setReadOnly(entity, ['uuid', 'name', 'type', 'created']); + UsergridHelpers.setReadOnly(entity, ["uuid", "name", "type", "created"]); }; UsergridHelpers.headers = function(client, options, defaultHeaders) { var returnHeaders = {}; _.defaults(returnHeaders, options.headers, defaultHeaders); - _.assign(returnHeaders, { 'User-Agent':'usergrid-js/v' + UsergridSDKVersion } ); + _.assign(returnHeaders, { "User-Agent":"usergrid-js/v" + UsergridSDKVersion } ); var authForRequests = UsergridHelpers.authForRequests(client); if (authForRequests) { - _.assign(returnHeaders, { authorization: 'Bearer ' + authForRequests.token }); + _.assign(returnHeaders, { authorization: "Bearer " + authForRequests.token }); } return returnHeaders; }; @@ -266,7 +273,7 @@ var UsergridApplicationJSONHeaderValue = 'application/json'; }; UsergridHelpers.setAsset = function(options,args) { - options.asset = _.first([options.asset, _.get(options,'entity.asset'), args[1], args[0]].filter(function(property) { + options.asset = _.first([options.asset, _.get(options,"entity.asset"), args[1], args[0]].filter(function(property) { return (property instanceof UsergridAsset); })); return options; @@ -277,14 +284,14 @@ var UsergridApplicationJSONHeaderValue = 'application/json'; options.uuidOrName, options.uuid, options.name, - _.get(options,'entity.uuid'), - _.get(options,'body.uuid'), - _.get(options,'entity.name'), - _.get(options,'body.name'), - _.get(args,'0.uuid'), - _.get(args,'0.name'), - _.get(args,'2'), - _.get(args,'1') + _.get(options,"entity.uuid"), + _.get(options,"body.uuid"), + _.get(options,"entity.name"), + _.get(options,"body.name"), + _.get(args,"0.uuid"), + _.get(args,"0.name"), + _.get(args,"2"), + _.get(args,"1") ].filter(_.isString)); return options; }; @@ -292,13 +299,13 @@ var UsergridApplicationJSONHeaderValue = 'application/json'; UsergridHelpers.setPathOrType = function(options,args) { var pathOrType = _.first([ args.type, - _.get(args,'0.type'), - _.get(options,'entity.type'), - _.get(args,'body.type'), - _.get(options,'body.0.type'), + _.get(args,"0.type"), + _.get(options,"entity.type"), + _.get(args,"body.type"), + _.get(options,"body.0.type"), _.isArray(args) ? args[0] : undefined ].filter(_.isString)); - options[(/\//.test(pathOrType)) ? 'path' : 'type'] = pathOrType; + options[(/\//.test(pathOrType)) ? "path" : "type"] = pathOrType; return options; }; @@ -317,35 +324,36 @@ var UsergridApplicationJSONHeaderValue = 'application/json'; }; UsergridHelpers.setAsset = function(options,args) { - options.asset = _.first([options.asset, _.get(options,'entity.asset'), args[1], args[0]].filter(function(property) { + options.asset = _.first([options.asset, _.get(options,"entity.asset"), args[1], args[0]].filter(function(property) { return (property instanceof UsergridAsset); })); return options; }; UsergridHelpers.setBody = function(options,args) { - options.body = _.first([args.entity, args.body, args[0].entity, args[0].body, args[2], args[1], args[0]].filter(function(property) { + var body = _.first([args.entity, args.body, args[0].entity, args[0].body, args[2], args[1], args[0]].filter(function(property) { return _.isObject(property) && !_.isFunction(property) && !(property instanceof UsergridQuery) && !(property instanceof UsergridAsset); })); - if (options.body === undefined && options.asset === undefined) { - throw new Error('"body" is required when making a ' + options.method + ' request'); - } - if( options.body instanceof UsergridEntity ) { - options.body = options.body.jsonValue(); - } else if( options.body instanceof Array ) { - if( options.body[0] instanceof UsergridEntity ) { - options.body = _.map(options.body, function(entity){ return entity.jsonValue(); }); + if( body instanceof UsergridEntity ) { + body = body.jsonValue(); + } else if( _.isArray(body) ) { + if( body[0] instanceof UsergridEntity ) { + body = _.map(body, function(entity){ + return entity.jsonValue(); + }); } } + + options.body = body; return options; }; - UsergridHelpers.buildReqest = function(client, method, args) { + UsergridHelpers.buildRequest = function(client, method, args) { var options = { client: client, method: method, - queryParams: args.queryParams || _.get(args,'0.queryParams'), + queryParams: args.queryParams || _.get(args,"0.queryParams"), callback: UsergridHelpers.callback(args) }; @@ -354,8 +362,11 @@ var UsergridApplicationJSONHeaderValue = 'application/json'; if( method === UsergridHttpMethod.POST || method === UsergridHttpMethod.PUT ) { UsergridHelpers.setAsset(options, args); - if( options.asset === undefined ) { + if( !options.asset ) { UsergridHelpers.setBody(options, args); + if ( !options.body ) { + throw new Error("'body' is required when making a " + options.method + " request"); + } } } @@ -373,7 +384,7 @@ var UsergridApplicationJSONHeaderValue = 'application/json'; var requestOptions = { client: client, method: UsergridHttpMethod.POST, - uri: UsergridHelpers.uri(client, {path: 'token'} ), + uri: UsergridHelpers.uri(client, {path: "token"} ), body: UsergridHelpers.appLoginBody(auth), callback: callback }; @@ -396,9 +407,9 @@ var UsergridApplicationJSONHeaderValue = 'application/json'; options.to = options.from; } - if( _.isObject(args[0]) && _.has(args[0],'entity') && _.has(args[0],'to') ) { + if( _.isObject(args[0]) && _.has(args[0],"entity") && _.has(args[0],"to") ) { _.assign(options.entity,args[0].entity); - options.relationship = _.get(args,'0.relationship'); + options.relationship = _.get(args,"0.relationship"); _.assign(options.to,args[0].to); } @@ -430,15 +441,15 @@ var UsergridApplicationJSONHeaderValue = 'application/json'; })); if (!_.isString(options.entity.uuidOrName)) { - throw new Error('source entity "uuidOrName" is required when connecting or disconnecting entities'); + throw new Error("source entity 'uuidOrName' is required when connecting or disconnecting entities"); } if (!_.isString(options.to.uuidOrName)) { - throw new Error('target entity "uuidOrName" is required when connecting or disconnecting entities'); + throw new Error("target entity 'uuidOrName' is required when connecting or disconnecting entities"); } if (!_.isString(options.to.type) && !UsergridHelpers.isUUID(options.to.uuidOrName)) { - throw new Error('target "type" (collection name) parameter is required connecting or disconnecting entities by name'); + throw new Error("target 'type' (collection name) parameter is required connecting or disconnecting entities by name"); } options.uri = UsergridHelpers.urljoin( @@ -458,7 +469,7 @@ var UsergridApplicationJSONHeaderValue = 'application/json'; UsergridHelpers.buildGetConnectionRequest = function(client,args) { var options = { client: client, - method: 'GET', + method: "GET", callback: UsergridHelpers.callback(args) }; @@ -476,11 +487,11 @@ var UsergridApplicationJSONHeaderValue = 'application/json'; options.type = _.first([options.type, args[1]].filter(_.isString)); if (!_.isString(options.type)) { - throw new Error('"type" (collection name) parameter is required when retrieving connections'); + throw new Error("'type' (collection name) parameter is required when retrieving connections"); } if (!_.isString(options.uuidOrName)) { - throw new Error('target entity "uuidOrName" is required when retrieving connections'); + throw new Error("target entity 'uuidOrName' is required when retrieving connections"); } options.uri = UsergridHelpers.urljoin( diff --git a/usergrid.js b/usergrid.js index a37ae44..c62d62d 100644 --- a/usergrid.js +++ b/usergrid.js @@ -17,7 +17,7 @@ *under the License. * * - * usergrid@2.0.0 2016-10-13 + * usergrid@2.0.0 2016-10-14 */ "use strict"; @@ -5388,16 +5388,10 @@ var UsergridApplicationJSONHeaderValue = "application/json"; Accept: UsergridApplicationJSONHeaderValue }); UsergridHelpers.validateAndRetrieveClient = function(args) { - var client = undefined; - if (args instanceof UsergridClient) { - client = args; - } else if (args[0] instanceof UsergridClient) { - client = args[0]; - } else if (_.get(args, "client")) { - client = args.client; - } else if (Usergrid.isInitialized) { - client = Usergrid; - } else { + var client = _.first([ args, args[0], _.get(args, "client"), Usergrid.isInitialized ? Usergrid : undefined ].filter(function(client) { + return client instanceof UsergridClient; + })); + if (!client) { throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument"); } return client; @@ -5455,6 +5449,12 @@ var UsergridApplicationJSONHeaderValue = "application/json"; } return body; }; + UsergridHelpers.userResetPasswordBody = function(args) { + return { + oldpassword: _.isPlainObject(args[0]) ? args[0].oldPassword : _.isString(args[0]) ? args[0] : undefined, + newpassword: _.isPlainObject(args[0]) ? args[0].newPassword : _.isString(args[1]) ? args[1] : undefined + }; + }; UsergridHelpers.calculateExpiry = function(expires_in) { return Date.now() + (expires_in ? expires_in - 5 : 0) * 1e3; }; @@ -5618,24 +5618,22 @@ var UsergridApplicationJSONHeaderValue = "application/json"; return options; }; UsergridHelpers.setBody = function(options, args) { - options.body = _.first([ args.entity, args.body, args[0].entity, args[0].body, args[2], args[1], args[0] ].filter(function(property) { + var body = _.first([ args.entity, args.body, args[0].entity, args[0].body, args[2], args[1], args[0] ].filter(function(property) { return _.isObject(property) && !_.isFunction(property) && !(property instanceof UsergridQuery) && !(property instanceof UsergridAsset); })); - if (options.body === undefined && options.asset === undefined) { - throw new Error('"body" is required when making a ' + options.method + " request"); - } - if (options.body instanceof UsergridEntity) { - options.body = options.body.jsonValue(); - } else if (options.body instanceof Array) { - if (options.body[0] instanceof UsergridEntity) { - options.body = _.map(options.body, function(entity) { + if (body instanceof UsergridEntity) { + body = body.jsonValue(); + } else if (_.isArray(body)) { + if (body[0] instanceof UsergridEntity) { + body = _.map(body, function(entity) { return entity.jsonValue(); }); } } + options.body = body; return options; }; - UsergridHelpers.buildReqest = function(client, method, args) { + UsergridHelpers.buildRequest = function(client, method, args) { var options = { client: client, method: method, @@ -5646,8 +5644,11 @@ var UsergridApplicationJSONHeaderValue = "application/json"; UsergridHelpers.setEntity(options, args); if (method === UsergridHttpMethod.POST || method === UsergridHttpMethod.PUT) { UsergridHelpers.setAsset(options, args); - if (options.asset === undefined) { + if (!options.asset) { UsergridHelpers.setBody(options, args); + if (!options.body) { + throw new Error("'body' is required when making a " + options.method + " request"); + } } } UsergridHelpers.setUuidOrName(options, args); @@ -5707,13 +5708,13 @@ var UsergridApplicationJSONHeaderValue = "application/json"; return _.isString(options.to.type) && _.isString(property) || UsergridHelpers.isUUID(property); })); if (!_.isString(options.entity.uuidOrName)) { - throw new Error('source entity "uuidOrName" is required when connecting or disconnecting entities'); + throw new Error("source entity 'uuidOrName' is required when connecting or disconnecting entities"); } if (!_.isString(options.to.uuidOrName)) { - throw new Error('target entity "uuidOrName" is required when connecting or disconnecting entities'); + throw new Error("target entity 'uuidOrName' is required when connecting or disconnecting entities"); } if (!_.isString(options.to.type) && !UsergridHelpers.isUUID(options.to.uuidOrName)) { - throw new Error('target "type" (collection name) parameter is required connecting or disconnecting entities by name'); + throw new Error("target 'type' (collection name) parameter is required connecting or disconnecting entities by name"); } options.uri = UsergridHelpers.urljoin(client.baseUrl, client.orgId, client.appId, _.isString(options.entity.type) ? options.entity.type : "", _.isString(options.entity.uuidOrName) ? options.entity.uuidOrName : "", options.relationship, _.isString(options.to.type) ? options.to.type : "", _.isString(options.to.uuidOrName) ? options.to.uuidOrName : ""); return new UsergridRequest(options); @@ -5735,10 +5736,10 @@ var UsergridApplicationJSONHeaderValue = "application/json"; options.uuidOrName = _.first([ options.uuidOrName, options.uuid, options.name, args[2] ].filter(_.isString)); options.type = _.first([ options.type, args[1] ].filter(_.isString)); if (!_.isString(options.type)) { - throw new Error('"type" (collection name) parameter is required when retrieving connections'); + throw new Error("'type' (collection name) parameter is required when retrieving connections"); } if (!_.isString(options.uuidOrName)) { - throw new Error('target entity "uuidOrName" is required when retrieving connections'); + throw new Error("target entity 'uuidOrName' is required when retrieving connections"); } options.uri = UsergridHelpers.urljoin(client.baseUrl, client.orgId, client.appId, _.isString(options.type) ? options.type : "", _.isString(options.uuidOrName) ? options.uuidOrName : "", options.direction, options.relationship); return new UsergridRequest(options); @@ -5771,7 +5772,7 @@ var UsergridClient = function(options) { } _.defaults(self, options, UsergridClientDefaultOptions); if (!self.orgId || !self.appId) { - throw new Error('"orgId" and "appId" parameters are required when instantiating UsergridClient'); + throw new Error("'orgId' and 'appId' parameters are required when instantiating UsergridClient"); } Object.defineProperty(self, "clientId", { enumerable: false @@ -5802,19 +5803,19 @@ UsergridClient.prototype = { return usergridRequest.sendRequest(); }, GET: function() { - var usergridRequest = UsergridHelpers.buildReqest(this, UsergridHttpMethod.GET, UsergridHelpers.flattenArgs(arguments)); + var usergridRequest = UsergridHelpers.buildRequest(this, UsergridHttpMethod.GET, UsergridHelpers.flattenArgs(arguments)); return this.sendRequest(usergridRequest); }, PUT: function() { - var usergridRequest = UsergridHelpers.buildReqest(this, UsergridHttpMethod.PUT, UsergridHelpers.flattenArgs(arguments)); + var usergridRequest = UsergridHelpers.buildRequest(this, UsergridHttpMethod.PUT, UsergridHelpers.flattenArgs(arguments)); return this.sendRequest(usergridRequest); }, POST: function() { - var usergridRequest = UsergridHelpers.buildReqest(this, UsergridHttpMethod.POST, UsergridHelpers.flattenArgs(arguments)); + var usergridRequest = UsergridHelpers.buildRequest(this, UsergridHttpMethod.POST, UsergridHelpers.flattenArgs(arguments)); return this.sendRequest(usergridRequest); }, DELETE: function() { - var usergridRequest = UsergridHelpers.buildReqest(this, UsergridHttpMethod.DELETE, UsergridHelpers.flattenArgs(arguments)); + var usergridRequest = UsergridHelpers.buildRequest(this, UsergridHttpMethod.DELETE, UsergridHelpers.flattenArgs(arguments)); return this.sendRequest(usergridRequest); }, connect: function() { @@ -5885,7 +5886,7 @@ UsergridClient.prototype = { }, downloadAsset: function() { var self = this; - var usergridRequest = UsergridHelpers.buildReqest(self, UsergridHttpMethod.GET, UsergridHelpers.flattenArgs(arguments)); + var usergridRequest = UsergridHelpers.buildRequest(self, UsergridHttpMethod.GET, UsergridHelpers.flattenArgs(arguments)); var assetContentType = _.get(usergridRequest, "entity.file-metadata.content-type"); if (assetContentType !== undefined) { _.assign(usergridRequest.headers, { @@ -5902,7 +5903,7 @@ UsergridClient.prototype = { }, uploadAsset: function() { var self = this; - var usergridRequest = UsergridHelpers.buildReqest(self, UsergridHttpMethod.PUT, UsergridHelpers.flattenArgs(arguments)); + var usergridRequest = UsergridHelpers.buildRequest(self, UsergridHttpMethod.PUT, UsergridHelpers.flattenArgs(arguments)); if (usergridRequest.asset === undefined) { throw new Error("An UsergridAsset was not defined when attempting to call .uploadAsset()"); } @@ -6128,31 +6129,31 @@ var UsergridRequest = function(options) { var self = this; var client = UsergridHelpers.validateAndRetrieveClient(options); if (!_.isString(options.type) && !_.isString(options.path) && !_.isString(options.uri)) { - throw new Error('one of "type" (collection name), "path", or "uri" parameters are required when initializing a UsergridRequest'); + throw new Error("one of 'type' (collection name), 'path', or 'uri' parameters are required when initializing a UsergridRequest"); } if (!_.includes([ "GET", "PUT", "POST", "DELETE" ], options.method)) { - throw new Error('"method" parameter is required when initializing a UsergridRequest'); + throw new Error("'method' parameter is required when initializing a UsergridRequest"); } self.method = options.method; self.callback = options.callback; self.uri = options.uri || UsergridHelpers.uri(client, options); self.entity = options.entity; - self.body = options.body || undefined; - self.asset = options.asset || undefined; + self.body = options.body; + self.asset = options.asset; self.query = options.query; self.queryParams = options.queryParams || options.qs; - var defaultHeadersToUse = self.asset === undefined ? UsergridHelpers.DefaultHeaders : {}; + var defaultHeadersToUse = !self.asset ? UsergridHelpers.DefaultHeaders : {}; self.headers = UsergridHelpers.headers(client, options, defaultHeadersToUse); if (self.query !== undefined) { self.uri += UsergridHelpers.normalize(self.query.encodedStringValue, {}); } - if (self.queryParams !== undefined) { + if (self.queryParams) { _.forOwn(self.queryParams, function(value, key) { self.uri += "?" + encodeURIComponent(key) + UsergridQueryOperator.EQUAL + encodeURIComponent(value); }); self.uri = UsergridHelpers.normalize(self.uri, {}); } - if (self.asset !== undefined) { + if (self.asset) { self.body = new FormData(); self.body.append(self.asset.filename, self.asset.data); } else { @@ -6162,7 +6163,9 @@ var UsergridRequest = function(options) { } else if (_.isArray(self.body)) { self.body = JSON.stringify(self.body); } - } catch (exception) {} + } catch (exception) { + console.warn("Unable to convert 'UsergridRequest.body' to a JSON String: " + exception); + } } return self; }; @@ -6400,7 +6403,7 @@ UsergridEntity.prototype = { if (_.has(self, "asset.contentType")) { client.uploadAsset(self, callback); } else { - var response = new UsergridResponse.responseWithError({ + var response = UsergridResponse.responseWithError({ name: "asset_not_found", description: "The specified entity does not have a valid asset attached" }); @@ -6415,7 +6418,7 @@ UsergridEntity.prototype = { if (_.has(self, "asset.contentType")) { client.downloadAsset(self, callback); } else { - var response = new UsergridResponse.responseWithError({ + var response = UsergridResponse.responseWithError({ name: "asset_not_found", description: "The specified entity does not have a valid asset attached" }); @@ -6447,7 +6450,7 @@ UsergridEntity.prototype = { var UsergridUser = function(obj) { if (!_.has(obj, "email") && !_.has(obj, "username")) { - throw new Error('"email" or "username" property is required when initializing a UsergridUser object'); + throw new Error("'email' or 'username' property is required when initializing a UsergridUser object"); } var self = this; _.assign(self, obj, UsergridEntity); @@ -6459,23 +6462,23 @@ var UsergridUser = function(obj) { UsergridUser.CheckAvailable = function() { var args = UsergridHelpers.flattenArgs(arguments); var client = UsergridHelpers.validateAndRetrieveClient(args); - if (args[0] instanceof UsergridClient) { - args.shift(); - } var callback = UsergridHelpers.callback(args); - var checkQuery; - if (args[0].username && args[0].email) { - checkQuery = new UsergridQuery("users").eq("username", args[0].username).or.eq("email", args[0].email); - } else if (args[0].username) { - checkQuery = new UsergridQuery("users").eq("username", args[0].username); - } else if (args[0].email) { - checkQuery = new UsergridQuery("users").eq("email", args[0].email); - } else { + var username = args[0].username || args[1].username; + var email = args[0].email || args[1].email; + if (!username && !email) { throw new Error("'username' or 'email' property is required when checking for available users"); + } else { + var checkQuery = new UsergridQuery("users"); + if (username) { + checkQuery.eq("username", username); + } + if (email) { + checkQuery.or.eq("email", email); + } + client.GET(checkQuery, function(error, usergridResponse) { + callback(error, usergridResponse, usergridResponse.entities.length > 0); + }); } - client.GET(checkQuery, function(error, usergridResponse) { - callback(error, usergridResponse, usergridResponse.entities.length > 0); - }); }; UsergridHelpers.inherits(UsergridUser, UsergridEntity); @@ -6523,29 +6526,27 @@ UsergridUser.prototype.logout = function() { var client = UsergridHelpers.validateAndRetrieveClient(args); var callback = UsergridHelpers.callback(args); if (!self.auth || !self.auth.isValid) { - var response = new UsergridResponse.responseWithError({ + var response = UsergridResponse.responseWithError({ name: "no_valid_token", description: "this user does not have a valid token" }); callback(response.error, response); } else { var revokeAll = _.first(args.filter(_.isBoolean)) || false; - var queryParams = undefined; - if (!revokeAll) { - queryParams = { - token: self.auth.token - }; - } var requestOptions = { client: client, path: [ "users", self.uniqueId(), "revoketoken" + (revokeAll ? "s" : "") ].join("/"), method: UsergridHttpMethod.PUT, - queryParams: queryParams, callback: function(error, usergridResponse) { self.auth.destroy(); callback(error, usergridResponse, usergridResponse.ok); }.bind(self) }; + if (!revokeAll) { + requestOptions.queryParams = { + token: self.auth.token + }; + } var request = new UsergridRequest(requestOptions); client.sendRequest(request); } @@ -6565,12 +6566,9 @@ UsergridUser.prototype.resetPassword = function() { if (args[0] instanceof UsergridClient) { args.shift(); } - var body = { - oldpassword: _.isPlainObject(args[0]) ? args[0].oldPassword : _.isString(args[0]) ? args[0] : undefined, - newpassword: _.isPlainObject(args[0]) ? args[0].newPassword : _.isString(args[1]) ? args[1] : undefined - }; + var body = UsergridHelpers.userResetPasswordBody(args); if (!body.oldpassword || !body.newpassword) { - throw new Error('"oldPassword" and "newPassword" properties are required when resetting a user password'); + throw new Error("'oldPassword' and 'newPassword' properties are required when resetting a user password"); } client.PUT([ "users", self.uniqueId(), "password" ].join("/"), body, callback); }; @@ -6584,11 +6582,11 @@ var UsergridResponseError = function(options) { }; UsergridResponseError.fromJSON = function(responseErrorObject) { - var usergridResponseError = undefined; + var usergridResponseError; var error = { name: _.get(responseErrorObject, "error") }; - if (error.name !== undefined) { + if (error.name) { _.assign(error, { exception: _.get(responseErrorObject, "exception"), description: _.get(responseErrorObject, "error_description") || _.get(responseErrorObject, "description") @@ -6607,23 +6605,13 @@ var UsergridResponse = function(xmlRequest, usergridRequest) { self.ok = self.statusCode < 400; self.headers = UsergridHelpers.parseResponseHeaders(xmlRequest.getAllResponseHeaders()); var responseContentType = _.get(self.headers, "content-type"); - if (responseContentType === "application/json") { + if (responseContentType === UsergridApplicationJSONHeaderValue) { try { var responseJSON = JSON.parse(xmlRequest.responseText); - } catch (e) { - responseJSON = {}; - } - self.parseResponseJSON(responseJSON); - Object.defineProperty(self, "cursor", { - get: function() { - return _.get(self, "responseJSON.cursor"); + if (responseJSON) { + self.parseResponseJSON(responseJSON); } - }); - Object.defineProperty(self, "hasNextPage", { - get: function() { - return self.cursor !== undefined; - } - }); + } catch (e) {} } else { self.asset = new UsergridAsset(xmlRequest.response); } @@ -6640,40 +6628,41 @@ UsergridResponse.responseWithError = function(options) { UsergridResponse.prototype = { parseResponseJSON: function(responseJSON) { var self = this; - if (responseJSON !== undefined) { - _.assign(self, { - responseJSON: _.cloneDeep(responseJSON) - }); - if (self.ok) { - var entitiesJSON = _.get(responseJSON, "entities"); - if (entitiesJSON) { - var entities = _.map(entitiesJSON, function(entityJSON) { - var entity = new UsergridEntity(entityJSON); - if (entity.isUser) { - entity = new UsergridUser(entity); - } - return entity; - }); - _.assign(self, { - entities: entities - }); - delete self.responseJSON.entities; - self.first = _.first(entities) || undefined; - self.entity = self.first; - self.last = _.last(entities) || undefined; - if (_.get(responseJSON, "path") === "/users") { - self.user = self.first; - self.users = self.entities; - } - UsergridHelpers.setReadOnly(self.responseJSON); - } - } else { - self.error = UsergridResponseError.fromJSON(responseJSON); + self.responseJSON = _.cloneDeep(responseJSON); + if (self.ok) { + self.cursor = _.get(self, "responseJSON.cursor"); + self.hasNextPage = !_.isNil(self.cursor); + var entitiesJSON = _.get(responseJSON, "entities"); + if (entitiesJSON) { + self.parseResponseEntities(entitiesJSON); + delete self.responseJSON.entities; } + } else { + self.error = UsergridResponseError.fromJSON(responseJSON); + } + UsergridHelpers.setReadOnly(self.responseJSON); + }, + parseResponseEntities: function(entitiesJSON) { + var self = this; + self.entities = _.map(entitiesJSON, function(entityJSON) { + var entity = new UsergridEntity(entityJSON); + if (entity.isUser) { + entity = new UsergridUser(entity); + } + return entity; + }); + self.first = _.first(self.entities); + self.entity = self.first; + self.last = _.last(self.entities); + if (_.get(self, "responseJSON.path") === "/users") { + self.user = self.first; + self.users = self.entities; } }, loadNextPage: function() { var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var callback = UsergridHelpers.callback(args); var cursor = self.cursor; if (!cursor) { callback(UsergridResponse.responseWithError({ @@ -6681,8 +6670,6 @@ UsergridResponse.prototype = { description: "Cursor must be present in order perform loadNextPage()." })); } else { - var args = UsergridHelpers.flattenArgs(arguments); - var callback = UsergridHelpers.callback(args); var client = UsergridHelpers.validateAndRetrieveClient(args); var type = _.last(_.get(self, "responseJSON.path").split("/")); var limit = _.first(_.get(self, "responseJSON.params.limit")); diff --git a/usergrid.min.js b/usergrid.min.js index fc4abc4..acbbb54 100644 --- a/usergrid.min.js +++ b/usergrid.min.js @@ -17,11 +17,11 @@ *under the License. * * - * usergrid@2.0.0 2016-10-13 + * usergrid@2.0.0 2016-10-14 */ "use strict";!function(global){function Promise(){this.complete=!1,this.result=null,this.callbacks=[]}var name="Promise",overwrittenName=global[name];return Promise.prototype.then=function(callback,context){var f=function(){return callback.apply(context,arguments)};this.complete?f(this.result):this.callbacks.push(f)},Promise.prototype.done=function(result){this.complete=!0,this.result=result,this.callbacks&&(_.forEach(this.callbacks,function(callback){callback(result)}),this.callbacks.length=0)},Promise.join=function(promises){function notifier(i){return function(result){completed+=1,results[i]=result,completed===total&&p.done(results)}}for(var p=new Promise,total=promises.length,completed=0,results=[],i=0;total>i;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,result){var p=new Promise;return null===promises||0===promises.length?p.done(result):promises[0](result).then(function(res){promises.splice(0,1),promises?Promise.chain(promises,res).then(function(r){p.done(r)}):p.done(res)}),p},global[name]=Promise,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Promise},global[name]}(this),function(){function addMapEntry(map,pair){return map.set(pair[0],pair[1]),map}function addSetEntry(set,value){return set.add(value),set}function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}function arrayAggregator(array,setter,iteratee,accumulator){for(var index=-1,length=array?array.length:0;++index-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1;);return index}function charsEndIndex(strSymbols,chrSymbols){for(var index=strSymbols.length;index--&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1;);return index}function countHolders(array,placeholder){for(var length=array.length,result=0;length--;)array[length]===placeholder&&++result;return result}function escapeStringChar(chr){return"\\"+stringEscapes[chr]}function getValue(object,key){return null==object?undefined:object[key]}function hasUnicode(string){return reHasUnicode.test(string)}function hasUnicodeWord(string){return reHasUnicodeWord.test(string)}function iteratorToArray(iterator){for(var data,result=[];!(data=iterator.next()).done;)result.push(data.value);return result}function mapToArray(map){var index=-1,result=Array(map.size);return map.forEach(function(value,key){result[++index]=[key,value]}),result}function overArg(func,transform){return function(arg){return func(transform(arg))}}function replaceHolders(array,placeholder){for(var index=-1,length=array.length,resIndex=0,result=[];++index>>1,wrapFlags=[["ary",ARY_FLAG],["bind",BIND_FLAG],["bindKey",BIND_KEY_FLAG],["curry",CURRY_FLAG],["curryRight",CURRY_RIGHT_FLAG],["flip",FLIP_FLAG],["partial",PARTIAL_FLAG],["partialRight",PARTIAL_RIGHT_FLAG],["rearg",REARG_FLAG]],argsTag="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",genTag="[object GeneratorFunction]",mapTag="[object Map]",numberTag="[object Number]",objectTag="[object Object]",promiseTag="[object Promise]",proxyTag="[object Proxy]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]",weakMapTag="[object WeakMap]",weakSetTag="[object WeakSet]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]",reEmptyStringLeading=/\b__p \+= '';/g,reEmptyStringMiddle=/\b(__p \+=) '' \+/g,reEmptyStringTrailing=/(__e\(.*?\)|\b__t\)) \+\n'';/g,reEscapedHtml=/&(?:amp|lt|gt|quot|#39);/g,reUnescapedHtml=/[&<>"']/g,reHasEscapedHtml=RegExp(reEscapedHtml.source),reHasUnescapedHtml=RegExp(reUnescapedHtml.source),reEscape=/<%-([\s\S]+?)%>/g,reEvaluate=/<%([\s\S]+?)%>/g,reInterpolate=/<%=([\s\S]+?)%>/g,reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/,reLeadingDot=/^\./,rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reHasRegExpChar=RegExp(reRegExpChar.source),reTrim=/^\s+|\s+$/g,reTrimStart=/^\s+/,reTrimEnd=/\s+$/,reWrapComment=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,reWrapDetails=/\{\n\/\* \[wrapped with (.+)\] \*/,reSplitDetails=/,? & /,reAsciiWord=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,reEscapeChar=/\\(\\)?/g,reEsTemplate=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,reFlags=/\w*$/,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsHostCtor=/^\[object .+?Constructor\]$/,reIsOctal=/^0o[0-7]+$/i,reIsUint=/^(?:0|[1-9]\d*)$/,reLatin=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,reNoMatch=/($^)/,reUnescapedString=/['\n\r\u2028\u2029\\]/g,rsAstralRange="\\ud800-\\udfff",rsComboMarksRange="\\u0300-\\u036f\\ufe20-\\ufe23",rsComboSymbolsRange="\\u20d0-\\u20f0",rsDingbatRange="\\u2700-\\u27bf",rsLowerRange="a-z\\xdf-\\xf6\\xf8-\\xff",rsMathOpRange="\\xac\\xb1\\xd7\\xf7",rsNonCharRange="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",rsPunctuationRange="\\u2000-\\u206f",rsSpaceRange=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",rsUpperRange="A-Z\\xc0-\\xd6\\xd8-\\xde",rsVarRange="\\ufe0e\\ufe0f",rsBreakRange=rsMathOpRange+rsNonCharRange+rsPunctuationRange+rsSpaceRange,rsApos="['’]",rsAstral="["+rsAstralRange+"]",rsBreak="["+rsBreakRange+"]",rsCombo="["+rsComboMarksRange+rsComboSymbolsRange+"]",rsDigits="\\d+",rsDingbat="["+rsDingbatRange+"]",rsLower="["+rsLowerRange+"]",rsMisc="[^"+rsAstralRange+rsBreakRange+rsDigits+rsDingbatRange+rsLowerRange+rsUpperRange+"]",rsFitz="\\ud83c[\\udffb-\\udfff]",rsModifier="(?:"+rsCombo+"|"+rsFitz+")",rsNonAstral="[^"+rsAstralRange+"]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",rsUpper="["+rsUpperRange+"]",rsZWJ="\\u200d",rsLowerMisc="(?:"+rsLower+"|"+rsMisc+")",rsUpperMisc="(?:"+rsUpper+"|"+rsMisc+")",rsOptLowerContr="(?:"+rsApos+"(?:d|ll|m|re|s|t|ve))?",rsOptUpperContr="(?:"+rsApos+"(?:D|LL|M|RE|S|T|VE))?",reOptMod=rsModifier+"?",rsOptVar="["+rsVarRange+"]?",rsOptJoin="(?:"+rsZWJ+"(?:"+[rsNonAstral,rsRegional,rsSurrPair].join("|")+")"+rsOptVar+reOptMod+")*",rsSeq=rsOptVar+reOptMod+rsOptJoin,rsEmoji="(?:"+[rsDingbat,rsRegional,rsSurrPair].join("|")+")"+rsSeq,rsSymbol="(?:"+[rsNonAstral+rsCombo+"?",rsCombo,rsRegional,rsSurrPair,rsAstral].join("|")+")",reApos=RegExp(rsApos,"g"),reComboMark=RegExp(rsCombo,"g"),reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g"),reUnicodeWord=RegExp([rsUpper+"?"+rsLower+"+"+rsOptLowerContr+"(?="+[rsBreak,rsUpper,"$"].join("|")+")",rsUpperMisc+"+"+rsOptUpperContr+"(?="+[rsBreak,rsUpper+rsLowerMisc,"$"].join("|")+")",rsUpper+"?"+rsLowerMisc+"+"+rsOptLowerContr,rsUpper+"+"+rsOptUpperContr,rsDigits,rsEmoji].join("|"),"g"),reHasUnicode=RegExp("["+rsZWJ+rsAstralRange+rsComboMarksRange+rsComboSymbolsRange+rsVarRange+"]"),reHasUnicodeWord=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,contextProps=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],templateCounter=-1,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[dataViewTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[mapTag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[setTag]=cloneableTags[stringTag]=cloneableTags[symbolTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=!0,cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[weakMapTag]=!1;var deburredLetters={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"},htmlEscapes={"&":"&","<":"<",">":">",'"':""","'":"'"},htmlUnescapes={"&":"&","<":"<",">":">",""":'"',"'":"'"},stringEscapes={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},freeParseFloat=parseFloat,freeParseInt=parseInt,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,freeProcess=moduleExports&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding("util")}catch(e){}}(),nodeIsArrayBuffer=nodeUtil&&nodeUtil.isArrayBuffer,nodeIsDate=nodeUtil&&nodeUtil.isDate,nodeIsMap=nodeUtil&&nodeUtil.isMap,nodeIsRegExp=nodeUtil&&nodeUtil.isRegExp,nodeIsSet=nodeUtil&&nodeUtil.isSet,nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,asciiSize=baseProperty("length"),deburrLetter=basePropertyOf(deburredLetters),escapeHtmlChar=basePropertyOf(htmlEscapes),unescapeHtmlChar=basePropertyOf(htmlUnescapes),runInContext=function runInContext(context){function lodash(value){if(isObjectLike(value)&&!isArray(value)&&!(value instanceof LazyWrapper)){if(value instanceof LodashWrapper)return value;if(hasOwnProperty.call(value,"__wrapped__"))return wrapperClone(value)}return new LodashWrapper(value)}function baseLodash(){}function LodashWrapper(value,chainAll){this.__wrapped__=value,this.__actions__=[],this.__chain__=!!chainAll,this.__index__=0,this.__values__=undefined}function LazyWrapper(value){this.__wrapped__=value,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=MAX_ARRAY_LENGTH,this.__views__=[]}function lazyClone(){var result=new LazyWrapper(this.__wrapped__);return result.__actions__=copyArray(this.__actions__),result.__dir__=this.__dir__,result.__filtered__=this.__filtered__,result.__iteratees__=copyArray(this.__iteratees__),result.__takeCount__=this.__takeCount__,result.__views__=copyArray(this.__views__),result}function lazyReverse(){if(this.__filtered__){var result=new LazyWrapper(this);result.__dir__=-1,result.__filtered__=!0}else result=this.clone(),result.__dir__*=-1;return result}function lazyValue(){var array=this.__wrapped__.value(),dir=this.__dir__,isArr=isArray(array),isRight=0>dir,arrLength=isArr?array.length:0,view=getView(0,arrLength,this.__views__),start=view.start,end=view.end,length=end-start,index=isRight?end:start-1,iteratees=this.__iteratees__,iterLength=iteratees.length,resIndex=0,takeCount=nativeMin(length,this.__takeCount__);if(!isArr||LARGE_ARRAY_SIZE>arrLength||arrLength==length&&takeCount==length)return baseWrapperValue(array,this.__actions__);var result=[];outer:for(;length--&&takeCount>resIndex;){index+=dir;for(var iterIndex=-1,value=array[index];++iterIndexindex)return!1;var lastIndex=data.length-1;return index==lastIndex?data.pop():splice.call(data,index,1),--this.size,!0}function listCacheGet(key){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?undefined:data[index][1]}function listCacheHas(key){return assocIndexOf(this.__data__,key)>-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?(++this.size,data.push([key,value])):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index=number?number:upper),lower!==undefined&&(number=number>=lower?number:lower)),number}function baseClone(value,isDeep,isFull,customizer,key,object,stack){var result;if(customizer&&(result=object?customizer(value,key,object,stack):customizer(value)),result!==undefined)return result;if(!isObject(value))return value;var isArr=isArray(value);if(isArr){if(result=initCloneArray(value),!isDeep)return copyArray(value,result)}else{var tag=getTag(value),isFunc=tag==funcTag||tag==genTag;if(isBuffer(value))return cloneBuffer(value,isDeep);if(tag==objectTag||tag==argsTag||isFunc&&!object){if(result=initCloneObject(isFunc?{}:value),!isDeep)return copySymbols(value,baseAssign(result,value))}else{if(!cloneableTags[tag])return object?value:{};result=initCloneByTag(value,tag,baseClone,isDeep)}}stack||(stack=new Stack);var stacked=stack.get(value);if(stacked)return stacked;stack.set(value,result);var props=isArr?undefined:(isFull?getAllKeys:keys)(value);return arrayEach(props||value,function(subValue,key){props&&(key=subValue,subValue=value[key]),assignValue(result,key,baseClone(subValue,isDeep,isFull,customizer,key,value,stack))}),result}function baseConforms(source){var props=keys(source);return function(object){return baseConformsTo(object,source,props)}}function baseConformsTo(object,source,props){var length=props.length;if(null==object)return!length;for(object=Object(object);length--;){var key=props[length],predicate=source[key],value=object[key];if(value===undefined&&!(key in object)||!predicate(value))return!1}return!0}function baseDelay(func,wait,args){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return setTimeout(function(){func.apply(undefined,args)},wait)}function baseDifference(array,values,iteratee,comparator){var index=-1,includes=arrayIncludes,isCommon=!0,length=array.length,result=[],valuesLength=values.length;if(!length)return result;iteratee&&(values=arrayMap(values,baseUnary(iteratee))),comparator?(includes=arrayIncludesWith,isCommon=!1):values.length>=LARGE_ARRAY_SIZE&&(includes=cacheHas,isCommon=!1,values=new SetCache(values));outer:for(;++indexstart&&(start=-start>length?0:length+start),end=end===undefined||end>length?length:toInteger(end),0>end&&(end+=length),end=start>end?0:toLength(end);end>start;)array[start++]=value;return array}function baseFilter(collection,predicate){var result=[];return baseEach(collection,function(value,index,collection){predicate(value,index,collection)&&result.push(value)}),result}function baseFlatten(array,depth,predicate,isStrict,result){var index=-1,length=array.length;for(predicate||(predicate=isFlattenable),result||(result=[]);++index0&&predicate(value)?depth>1?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}function baseForOwn(object,iteratee){return object&&baseFor(object,iteratee,keys)}function baseForOwnRight(object,iteratee){return object&&baseForRight(object,iteratee,keys)}function baseFunctions(object,props){return arrayFilter(props,function(key){return isFunction(object[key])})}function baseGet(object,path){path=isKey(path,object)?[path]:castPath(path);for(var index=0,length=path.length;null!=object&&length>index;)object=object[toKey(path[index++])];return index&&index==length?object:undefined}function baseGetAllKeys(object,keysFunc,symbolsFunc){var result=keysFunc(object);return isArray(object)?result:arrayPush(result,symbolsFunc(object))}function baseGetTag(value){return objectToString.call(value)}function baseGt(value,other){return value>other}function baseHas(object,key){return null!=object&&hasOwnProperty.call(object,key)}function baseHasIn(object,key){return null!=object&&key in Object(object)}function baseInRange(number,start,end){return number>=nativeMin(start,end)&&number=120&&array.length>=120)?new SetCache(othIndex&&array):undefined}array=arrays[0];var index=-1,seen=caches[0];outer:for(;++indexvalue}function baseMap(collection,iteratee){var index=-1,result=isArrayLike(collection)?Array(collection.length):[];return baseEach(collection,function(value,key,collection){result[++index]=iteratee(value,key,collection)}),result}function baseMatches(source){var matchData=getMatchData(source);return 1==matchData.length&&matchData[0][2]?matchesStrictComparable(matchData[0][0],matchData[0][1]):function(object){return object===source||baseIsMatch(object,source,matchData)}}function baseMatchesProperty(path,srcValue){return isKey(path)&&isStrictComparable(srcValue)?matchesStrictComparable(toKey(path),srcValue):function(object){var objValue=get(object,path);return objValue===undefined&&objValue===srcValue?hasIn(object,path):baseIsEqual(srcValue,objValue,undefined,UNORDERED_COMPARE_FLAG|PARTIAL_COMPARE_FLAG)}}function baseMerge(object,source,srcIndex,customizer,stack){object!==source&&baseFor(source,function(srcValue,key){if(isObject(srcValue))stack||(stack=new Stack),baseMergeDeep(object,source,key,srcIndex,baseMerge,customizer,stack);else{var newValue=customizer?customizer(object[key],srcValue,key+"",object,source,stack):undefined;newValue===undefined&&(newValue=srcValue),assignMergeValue(object,key,newValue)}},keysIn)}function baseMergeDeep(object,source,key,srcIndex,mergeFunc,customizer,stack){var objValue=object[key],srcValue=source[key],stacked=stack.get(srcValue);if(stacked)return void assignMergeValue(object,key,stacked);var newValue=customizer?customizer(objValue,srcValue,key+"",object,source,stack):undefined,isCommon=newValue===undefined;if(isCommon){var isArr=isArray(srcValue),isBuff=!isArr&&isBuffer(srcValue),isTyped=!isArr&&!isBuff&&isTypedArray(srcValue);newValue=srcValue,isArr||isBuff||isTyped?isArray(objValue)?newValue=objValue:isArrayLikeObject(objValue)?newValue=copyArray(objValue):isBuff?(isCommon=!1,newValue=cloneBuffer(srcValue,!0)):isTyped?(isCommon=!1,newValue=cloneTypedArray(srcValue,!0)):newValue=[]:isPlainObject(srcValue)||isArguments(srcValue)?(newValue=objValue,isArguments(objValue)?newValue=toPlainObject(objValue):(!isObject(objValue)||srcIndex&&isFunction(objValue))&&(newValue=initCloneObject(srcValue))):isCommon=!1}isCommon&&(stack.set(srcValue,newValue),mergeFunc(newValue,srcValue,srcIndex,customizer,stack),stack["delete"](srcValue)),assignMergeValue(object,key,newValue)}function baseNth(array,n){var length=array.length;if(length)return n+=0>n?length:0,isIndex(n,length)?array[n]:undefined}function baseOrderBy(collection,iteratees,orders){var index=-1;iteratees=arrayMap(iteratees.length?iteratees:[identity],baseUnary(getIteratee()));var result=baseMap(collection,function(value,key,collection){var criteria=arrayMap(iteratees,function(iteratee){return iteratee(value)});return{criteria:criteria,index:++index,value:value}});return baseSortBy(result,function(object,other){return compareMultiple(object,other,orders)})}function basePick(object,props){return object=Object(object),basePickBy(object,props,function(value,key){return key in object})}function basePickBy(object,props,predicate){for(var index=-1,length=props.length,result={};++index-1;)seen!==array&&splice.call(seen,fromIndex,1),splice.call(array,fromIndex,1);return array}function basePullAt(array,indexes){for(var length=array?indexes.length:0,lastIndex=length-1;length--;){var index=indexes[length];if(length==lastIndex||index!==previous){var previous=index;if(isIndex(index))splice.call(array,index,1);else if(isKey(index,array))delete array[toKey(index)];else{var path=castPath(index),object=parent(array,path);null!=object&&delete object[toKey(last(path))]}}}return array}function baseRandom(lower,upper){return lower+nativeFloor(nativeRandom()*(upper-lower+1))}function baseRange(start,end,step,fromRight){for(var index=-1,length=nativeMax(nativeCeil((end-start)/(step||1)),0),result=Array(length);length--;)result[fromRight?length:++index]=start,start+=step;return result}function baseRepeat(string,n){var result="";if(!string||1>n||n>MAX_SAFE_INTEGER)return result;do n%2&&(result+=string),n=nativeFloor(n/2),n&&(string+=string);while(n);return result}function baseRest(func,start){return setToString(overRest(func,start,identity),func+"")}function baseSample(collection){return arraySample(values(collection))}function baseSampleSize(collection,n){var array=values(collection);return shuffleSelf(array,baseClamp(n,0,array.length))}function baseSet(object,path,value,customizer){if(!isObject(object))return object;path=isKey(path,object)?[path]:castPath(path);for(var index=-1,length=path.length,lastIndex=length-1,nested=object;null!=nested&&++indexstart&&(start=-start>length?0:length+start),end=end>length?length:end,0>end&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index=high){for(;high>low;){var mid=low+high>>>1,computed=array[mid];null!==computed&&!isSymbol(computed)&&(retHighest?value>=computed:value>computed)?low=mid+1:high=mid}return high}return baseSortedIndexBy(array,value,identity,retHighest)}function baseSortedIndexBy(array,value,iteratee,retHighest){value=iteratee(value);for(var low=0,high=array?array.length:0,valIsNaN=value!==value,valIsNull=null===value,valIsSymbol=isSymbol(value),valIsUndefined=value===undefined;high>low;){var mid=nativeFloor((low+high)/2),computed=iteratee(array[mid]),othIsDefined=computed!==undefined,othIsNull=null===computed,othIsReflexive=computed===computed,othIsSymbol=isSymbol(computed);if(valIsNaN)var setLow=retHighest||othIsReflexive;else setLow=valIsUndefined?othIsReflexive&&(retHighest||othIsDefined):valIsNull?othIsReflexive&&othIsDefined&&(retHighest||!othIsNull):valIsSymbol?othIsReflexive&&othIsDefined&&!othIsNull&&(retHighest||!othIsSymbol):othIsNull||othIsSymbol?!1:retHighest?value>=computed:value>computed;setLow?low=mid+1:high=mid}return nativeMin(high,MAX_ARRAY_INDEX)}function baseSortedUniq(array,iteratee){for(var index=-1,length=array.length,resIndex=0,result=[];++index=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++indexindex?values[index]:undefined;assignFunc(result,props[index],value)}return result}function castArrayLikeObject(value){return isArrayLikeObject(value)?value:[]}function castFunction(value){return"function"==typeof value?value:identity}function castPath(value){return isArray(value)?value:stringToPath(value)}function castSlice(array,start,end){var length=array.length;return end=end===undefined?length:end,!start&&end>=length?array:baseSlice(array,start,end)}function cloneBuffer(buffer,isDeep){if(isDeep)return buffer.slice();var length=buffer.length,result=allocUnsafe?allocUnsafe(length):new buffer.constructor(length);return buffer.copy(result),result}function cloneArrayBuffer(arrayBuffer){var result=new arrayBuffer.constructor(arrayBuffer.byteLength);return new Uint8Array(result).set(new Uint8Array(arrayBuffer)),result}function cloneDataView(dataView,isDeep){var buffer=isDeep?cloneArrayBuffer(dataView.buffer):dataView.buffer;return new dataView.constructor(buffer,dataView.byteOffset,dataView.byteLength)}function cloneMap(map,isDeep,cloneFunc){var array=isDeep?cloneFunc(mapToArray(map),!0):mapToArray(map);return arrayReduce(array,addMapEntry,new map.constructor)}function cloneRegExp(regexp){var result=new regexp.constructor(regexp.source,reFlags.exec(regexp));return result.lastIndex=regexp.lastIndex,result}function cloneSet(set,isDeep,cloneFunc){var array=isDeep?cloneFunc(setToArray(set),!0):setToArray(set);return arrayReduce(array,addSetEntry,new set.constructor)}function cloneSymbol(symbol){return symbolValueOf?Object(symbolValueOf.call(symbol)):{}}function cloneTypedArray(typedArray,isDeep){var buffer=isDeep?cloneArrayBuffer(typedArray.buffer):typedArray.buffer;return new typedArray.constructor(buffer,typedArray.byteOffset,typedArray.length)}function compareAscending(value,other){if(value!==other){var valIsDefined=value!==undefined,valIsNull=null===value,valIsReflexive=value===value,valIsSymbol=isSymbol(value),othIsDefined=other!==undefined,othIsNull=null===other,othIsReflexive=other===other,othIsSymbol=isSymbol(other);if(!othIsNull&&!othIsSymbol&&!valIsSymbol&&value>other||valIsSymbol&&othIsDefined&&othIsReflexive&&!othIsNull&&!othIsSymbol||valIsNull&&othIsDefined&&othIsReflexive||!valIsDefined&&othIsReflexive||!valIsReflexive)return 1;if(!valIsNull&&!valIsSymbol&&!othIsSymbol&&other>value||othIsSymbol&&valIsDefined&&valIsReflexive&&!valIsNull&&!valIsSymbol||othIsNull&&valIsDefined&&valIsReflexive||!othIsDefined&&valIsReflexive||!othIsReflexive)return-1}return 0}function compareMultiple(object,other,orders){for(var index=-1,objCriteria=object.criteria,othCriteria=other.criteria,length=objCriteria.length,ordersLength=orders.length;++index=ordersLength)return result;var order=orders[index];return result*("desc"==order?-1:1)}}return object.index-other.index}function composeArgs(args,partials,holders,isCurried){for(var argsIndex=-1,argsLength=args.length,holdersLength=holders.length,leftIndex=-1,leftLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(leftLength+rangeLength),isUncurried=!isCurried;++leftIndexargsIndex)&&(result[holders[argsIndex]]=args[argsIndex]);for(;rangeLength--;)result[leftIndex++]=args[argsIndex++];return result}function composeArgsRight(args,partials,holders,isCurried){for(var argsIndex=-1,argsLength=args.length,holdersIndex=-1,holdersLength=holders.length,rightIndex=-1,rightLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(rangeLength+rightLength),isUncurried=!isCurried;++argsIndexargsIndex)&&(result[offset+holders[holdersIndex]]=args[argsIndex++]);return result}function copyArray(source,array){var index=-1,length=source.length;for(array||(array=Array(length));++index1?sources[length-1]:undefined,guard=length>2?sources[2]:undefined;for(customizer=assigner.length>3&&"function"==typeof customizer?(length--,customizer):undefined,guard&&isIterateeCall(sources[0],sources[1],guard)&&(customizer=3>length?undefined:customizer,length=1),object=Object(object);++indexlength&&args[0]!==placeholder&&args[length-1]!==placeholder?[]:replaceHolders(args,placeholder);if(length-=holders.length,arity>length)return createRecurry(func,bitmask,createHybrid,wrapper.placeholder,undefined,args,holders,undefined,undefined,arity-length);var fn=this&&this!==root&&this instanceof wrapper?Ctor:func;return apply(fn,this,args)}var Ctor=createCtor(func);return wrapper}function createFind(findIndexFunc){return function(collection,predicate,fromIndex){var iterable=Object(collection);if(!isArrayLike(collection)){var iteratee=getIteratee(predicate,3);collection=keys(collection),predicate=function(key){return iteratee(iterable[key],key,iterable)}}var index=findIndexFunc(collection,predicate,fromIndex);return index>-1?iterable[iteratee?collection[index]:index]:undefined}}function createFlow(fromRight){return flatRest(function(funcs){var length=funcs.length,index=length,prereq=LodashWrapper.prototype.thru;for(fromRight&&funcs.reverse();index--;){var func=funcs[index];if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);if(prereq&&!wrapper&&"wrapper"==getFuncName(func))var wrapper=new LodashWrapper([],!0)}for(index=wrapper?index:length;++index=LARGE_ARRAY_SIZE)return wrapper.plant(value).value();for(var index=0,result=length?funcs[index].apply(this,args):value;++indexlength){var newHolders=replaceHolders(args,placeholder);return createRecurry(func,bitmask,createHybrid,wrapper.placeholder,thisArg,args,newHolders,argPos,ary,arity-length)}var thisBinding=isBind?thisArg:this,fn=isBindKey?thisBinding[func]:func;return length=args.length,argPos?args=reorder(args,argPos):isFlip&&length>1&&args.reverse(),isAry&&length>ary&&(args.length=ary),this&&this!==root&&this instanceof wrapper&&(fn=Ctor||createCtor(fn)),fn.apply(thisBinding,args)}var isAry=bitmask&ARY_FLAG,isBind=bitmask&BIND_FLAG,isBindKey=bitmask&BIND_KEY_FLAG,isCurried=bitmask&(CURRY_FLAG|CURRY_RIGHT_FLAG),isFlip=bitmask&FLIP_FLAG,Ctor=isBindKey?undefined:createCtor(func);return wrapper}function createInverter(setter,toIteratee){return function(object,iteratee){return baseInverter(object,setter,toIteratee(iteratee),{})}}function createMathOperation(operator,defaultValue){return function(value,other){var result;if(value===undefined&&other===undefined)return defaultValue;if(value!==undefined&&(result=value),other!==undefined){if(result===undefined)return other;"string"==typeof value||"string"==typeof other?(value=baseToString(value),other=baseToString(other)):(value=baseToNumber(value),other=baseToNumber(other)),result=operator(value,other)}return result}}function createOver(arrayFunc){return flatRest(function(iteratees){return iteratees=arrayMap(iteratees,baseUnary(getIteratee())),baseRest(function(args){var thisArg=this;return arrayFunc(iteratees,function(iteratee){return apply(iteratee,thisArg,args)})})})}function createPadding(length,chars){chars=chars===undefined?" ":baseToString(chars);var charsLength=chars.length;if(2>charsLength)return charsLength?baseRepeat(chars,length):chars;var result=baseRepeat(chars,nativeCeil(length/stringSize(chars)));return hasUnicode(chars)?castSlice(stringToArray(result),0,length).join(""):result.slice(0,length)}function createPartial(func,bitmask,thisArg,partials){function wrapper(){for(var argsIndex=-1,argsLength=arguments.length,leftIndex=-1,leftLength=partials.length,args=Array(leftLength+argsLength),fn=this&&this!==root&&this instanceof wrapper?Ctor:func;++leftIndexstart?1:-1:toFinite(step),baseRange(start,end,step,fromRight)}}function createRelationalOperation(operator){return function(value,other){return("string"!=typeof value||"string"!=typeof other)&&(value=toNumber(value),other=toNumber(other)),operator(value,other)}}function createRecurry(func,bitmask,wrapFunc,placeholder,thisArg,partials,holders,argPos,ary,arity){var isCurry=bitmask&CURRY_FLAG,newHolders=isCurry?holders:undefined,newHoldersRight=isCurry?undefined:holders,newPartials=isCurry?partials:undefined,newPartialsRight=isCurry?undefined:partials;bitmask|=isCurry?PARTIAL_FLAG:PARTIAL_RIGHT_FLAG,bitmask&=~(isCurry?PARTIAL_RIGHT_FLAG:PARTIAL_FLAG),bitmask&CURRY_BOUND_FLAG||(bitmask&=~(BIND_FLAG|BIND_KEY_FLAG));var newData=[func,bitmask,thisArg,newPartials,newHolders,newPartialsRight,newHoldersRight,argPos,ary,arity],result=wrapFunc.apply(undefined,newData);return isLaziable(func)&&setData(result,newData),result.placeholder=placeholder,setWrapToString(result,func,bitmask)}function createRound(methodName){var func=Math[methodName];return function(number,precision){if(number=toNumber(number),precision=nativeMin(toInteger(precision),292)){var pair=(toString(number)+"e").split("e"),value=func(pair[0]+"e"+(+pair[1]+precision));return pair=(toString(value)+"e").split("e"),+(pair[0]+"e"+(+pair[1]-precision))}return func(number)}}function createToPairs(keysFunc){return function(object){var tag=getTag(object);return tag==mapTag?mapToArray(object):tag==setTag?setToPairs(object):baseToPairs(object,keysFunc(object))}}function createWrap(func,bitmask,thisArg,partials,holders,argPos,ary,arity){var isBindKey=bitmask&BIND_KEY_FLAG;if(!isBindKey&&"function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);var length=partials?partials.length:0;if(length||(bitmask&=~(PARTIAL_FLAG|PARTIAL_RIGHT_FLAG),partials=holders=undefined),ary=ary===undefined?ary:nativeMax(toInteger(ary),0),arity=arity===undefined?arity:toInteger(arity),length-=holders?holders.length:0,bitmask&PARTIAL_RIGHT_FLAG){var partialsRight=partials,holdersRight=holders;partials=holders=undefined}var data=isBindKey?undefined:getData(func),newData=[func,bitmask,thisArg,partials,holders,partialsRight,holdersRight,argPos,ary,arity];if(data&&mergeData(newData,data),func=newData[0],bitmask=newData[1],thisArg=newData[2],partials=newData[3],holders=newData[4],arity=newData[9]=null==newData[9]?isBindKey?0:func.length:nativeMax(newData[9]-length,0),!arity&&bitmask&(CURRY_FLAG|CURRY_RIGHT_FLAG)&&(bitmask&=~(CURRY_FLAG|CURRY_RIGHT_FLAG)),bitmask&&bitmask!=BIND_FLAG)result=bitmask==CURRY_FLAG||bitmask==CURRY_RIGHT_FLAG?createCurry(func,bitmask,arity):bitmask!=PARTIAL_FLAG&&bitmask!=(BIND_FLAG|PARTIAL_FLAG)||holders.length?createHybrid.apply(undefined,newData):createPartial(func,bitmask,thisArg,partials);else var result=createBind(func,bitmask,thisArg);var setter=data?baseSetData:setData;return setWrapToString(setter(result,newData),func,bitmask)}function equalArrays(array,other,equalFunc,customizer,bitmask,stack){var isPartial=bitmask&PARTIAL_COMPARE_FLAG,arrLength=array.length,othLength=other.length;if(arrLength!=othLength&&!(isPartial&&othLength>arrLength))return!1;var stacked=stack.get(array);if(stacked&&stack.get(other))return stacked==other;var index=-1,result=!0,seen=bitmask&UNORDERED_COMPARE_FLAG?new SetCache:undefined;for(stack.set(array,other),stack.set(other,array);++index1?"& ":"")+details[lastIndex],details=details.join(length>2?", ":" "),source.replace(reWrapComment,"{\n/* [wrapped with "+details+"] */\n")}function isFlattenable(value){return isArray(value)||isArguments(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol])}function isIndex(value,length){return length=null==length?MAX_SAFE_INTEGER:length,!!length&&("number"==typeof value||reIsUint.test(value))&&value>-1&&value%1==0&&length>value}function isIterateeCall(value,index,object){if(!isObject(object))return!1;var type=typeof index;return("number"==type?isArrayLike(object)&&isIndex(index,object.length):"string"==type&&index in object)?eq(object[index],value):!1}function isKey(value,object){if(isArray(value))return!1;var type=typeof value;return"number"==type||"symbol"==type||"boolean"==type||null==value||isSymbol(value)?!0:reIsPlainProp.test(value)||!reIsDeepProp.test(value)||null!=object&&value in Object(object)}function isKeyable(value){var type=typeof value;return"string"==type||"number"==type||"symbol"==type||"boolean"==type?"__proto__"!==value:null===value}function isLaziable(func){var funcName=getFuncName(func),other=lodash[funcName];if("function"!=typeof other||!(funcName in LazyWrapper.prototype))return!1;if(func===other)return!0;var data=getData(other);return!!data&&func===data[0]}function isMasked(func){return!!maskSrcKey&&maskSrcKey in func}function isPrototype(value){var Ctor=value&&value.constructor,proto="function"==typeof Ctor&&Ctor.prototype||objectProto;return value===proto}function isStrictComparable(value){return value===value&&!isObject(value)}function matchesStrictComparable(key,srcValue){return function(object){return null==object?!1:object[key]===srcValue&&(srcValue!==undefined||key in Object(object))}}function memoizeCapped(func){var result=memoize(func,function(key){return cache.size===MAX_MEMOIZE_SIZE&&cache.clear(),key}),cache=result.cache;return result}function mergeData(data,source){var bitmask=data[1],srcBitmask=source[1],newBitmask=bitmask|srcBitmask,isCommon=(BIND_FLAG|BIND_KEY_FLAG|ARY_FLAG)>newBitmask,isCombo=srcBitmask==ARY_FLAG&&bitmask==CURRY_FLAG||srcBitmask==ARY_FLAG&&bitmask==REARG_FLAG&&data[7].length<=source[8]||srcBitmask==(ARY_FLAG|REARG_FLAG)&&source[7].length<=source[8]&&bitmask==CURRY_FLAG;if(!isCommon&&!isCombo)return data;srcBitmask&BIND_FLAG&&(data[2]=source[2],newBitmask|=bitmask&BIND_FLAG?0:CURRY_BOUND_FLAG);var value=source[3];if(value){var partials=data[3];data[3]=partials?composeArgs(partials,value,source[4]):value,data[4]=partials?replaceHolders(data[3],PLACEHOLDER):source[4]}return value=source[5],value&&(partials=data[5],data[5]=partials?composeArgsRight(partials,value,source[6]):value,data[6]=partials?replaceHolders(data[5],PLACEHOLDER):source[6]),value=source[7],value&&(data[7]=value),srcBitmask&ARY_FLAG&&(data[8]=null==data[8]?source[8]:nativeMin(data[8],source[8])),null==data[9]&&(data[9]=source[9]),data[0]=source[0],data[1]=newBitmask,data}function mergeDefaults(objValue,srcValue,key,object,source,stack){return isObject(objValue)&&isObject(srcValue)&&(stack.set(srcValue,objValue),baseMerge(objValue,srcValue,undefined,mergeDefaults,stack),stack["delete"](srcValue)),objValue}function nativeKeysIn(object){var result=[];if(null!=object)for(var key in Object(object))result.push(key);return result}function overRest(func,start,transform){return start=nativeMax(start===undefined?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index0){if(++count>=HOT_COUNT)return arguments[0]}else count=0;return func.apply(undefined,arguments)}}function shuffleSelf(array,size){var index=-1,length=array.length,lastIndex=length-1;for(size=size===undefined?length:size;++indexsize)return[];for(var index=0,resIndex=0,result=Array(nativeCeil(length/size));length>index;)result[resIndex++]=baseSlice(array,index,index+=size);return result}function compact(array){for(var index=-1,length=array?array.length:0,resIndex=0,result=[];++indexn?0:n,length)):[]}function dropRight(array,n,guard){var length=array?array.length:0;return length?(n=guard||n===undefined?1:toInteger(n),n=length-n,baseSlice(array,0,0>n?0:n)):[]}function dropRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!0,!0):[]}function dropWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!0):[]}function fill(array,value,start,end){var length=array?array.length:0;return length?(start&&"number"!=typeof start&&isIterateeCall(array,value,start)&&(start=0,end=length),baseFill(array,value,start,end)):[]}function findIndex(array,predicate,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=null==fromIndex?0:toInteger(fromIndex);return 0>index&&(index=nativeMax(length+index,0)),baseFindIndex(array,getIteratee(predicate,3),index)}function findLastIndex(array,predicate,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=length-1;return fromIndex!==undefined&&(index=toInteger(fromIndex),index=0>fromIndex?nativeMax(length+index,0):nativeMin(index,length-1)),baseFindIndex(array,getIteratee(predicate,3),index,!0)}function flatten(array){var length=array?array.length:0;return length?baseFlatten(array,1):[]}function flattenDeep(array){var length=array?array.length:0;return length?baseFlatten(array,INFINITY):[]}function flattenDepth(array,depth){var length=array?array.length:0;return length?(depth=depth===undefined?1:toInteger(depth),baseFlatten(array,depth)):[]}function fromPairs(pairs){for(var index=-1,length=pairs?pairs.length:0,result={};++indexindex&&(index=nativeMax(length+index,0)),baseIndexOf(array,value,index)}function initial(array){var length=array?array.length:0;return length?baseSlice(array,0,-1):[]}function join(array,separator){return array?nativeJoin.call(array,separator):""}function last(array){var length=array?array.length:0;return length?array[length-1]:undefined}function lastIndexOf(array,value,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=length;return fromIndex!==undefined&&(index=toInteger(fromIndex),index=0>index?nativeMax(length+index,0):nativeMin(index,length-1)),value===value?strictLastIndexOf(array,value,index):baseFindIndex(array,baseIsNaN,index,!0)}function nth(array,n){return array&&array.length?baseNth(array,toInteger(n)):undefined}function pullAll(array,values){return array&&array.length&&values&&values.length?basePullAll(array,values):array}function pullAllBy(array,values,iteratee){return array&&array.length&&values&&values.length?basePullAll(array,values,getIteratee(iteratee,2)):array}function pullAllWith(array,values,comparator){return array&&array.length&&values&&values.length?basePullAll(array,values,undefined,comparator):array}function remove(array,predicate){var result=[];if(!array||!array.length)return result;var index=-1,indexes=[],length=array.length;for(predicate=getIteratee(predicate,3);++indexindex&&eq(array[index],value))return index}return-1}function sortedLastIndex(array,value){return baseSortedIndex(array,value,!0)}function sortedLastIndexBy(array,value,iteratee){return baseSortedIndexBy(array,value,getIteratee(iteratee,2),!0)}function sortedLastIndexOf(array,value){var length=array?array.length:0;if(length){var index=baseSortedIndex(array,value,!0)-1;if(eq(array[index],value))return index}return-1}function sortedUniq(array){return array&&array.length?baseSortedUniq(array):[]}function sortedUniqBy(array,iteratee){return array&&array.length?baseSortedUniq(array,getIteratee(iteratee,2)):[]}function tail(array){var length=array?array.length:0;return length?baseSlice(array,1,length):[]}function take(array,n,guard){return array&&array.length?(n=guard||n===undefined?1:toInteger(n),baseSlice(array,0,0>n?0:n)):[]}function takeRight(array,n,guard){var length=array?array.length:0;return length?(n=guard||n===undefined?1:toInteger(n),n=length-n,baseSlice(array,0>n?0:n,length)):[]}function takeRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!1,!0):[]}function takeWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3)):[]}function uniq(array){return array&&array.length?baseUniq(array):[]}function uniqBy(array,iteratee){return array&&array.length?baseUniq(array,getIteratee(iteratee,2)):[]}function uniqWith(array,comparator){return array&&array.length?baseUniq(array,undefined,comparator):[]}function unzip(array){if(!array||!array.length)return[];var length=0;return array=arrayFilter(array,function(group){return isArrayLikeObject(group)?(length=nativeMax(group.length,length),!0):void 0}),baseTimes(length,function(index){return arrayMap(array,baseProperty(index))})}function unzipWith(array,iteratee){if(!array||!array.length)return[];var result=unzip(array);return null==iteratee?result:arrayMap(result,function(group){return apply(iteratee,undefined,group)})}function zipObject(props,values){return baseZipObject(props||[],values||[],assignValue)}function zipObjectDeep(props,values){return baseZipObject(props||[],values||[],baseSet)}function chain(value){var result=lodash(value);return result.__chain__=!0,result}function tap(value,interceptor){return interceptor(value),value}function thru(value,interceptor){return interceptor(value)}function wrapperChain(){return chain(this)}function wrapperCommit(){return new LodashWrapper(this.value(),this.__chain__)}function wrapperNext(){this.__values__===undefined&&(this.__values__=toArray(this.value()));var done=this.__index__>=this.__values__.length,value=done?undefined:this.__values__[this.__index__++];return{done:done,value:value}}function wrapperToIterator(){return this}function wrapperPlant(value){for(var result,parent=this;parent instanceof baseLodash;){var clone=wrapperClone(parent);clone.__index__=0,clone.__values__=undefined,result?previous.__wrapped__=clone:result=clone;var previous=clone;parent=parent.__wrapped__}return previous.__wrapped__=value,result}function wrapperReverse(){var value=this.__wrapped__;if(value instanceof LazyWrapper){var wrapped=value;return this.__actions__.length&&(wrapped=new LazyWrapper(this)),wrapped=wrapped.reverse(),wrapped.__actions__.push({func:thru,args:[reverse],thisArg:undefined}),new LodashWrapper(wrapped,this.__chain__)}return this.thru(reverse)}function wrapperValue(){return baseWrapperValue(this.__wrapped__,this.__actions__)}function every(collection,predicate,guard){var func=isArray(collection)?arrayEvery:baseEvery;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=undefined),func(collection,getIteratee(predicate,3))}function filter(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,getIteratee(predicate,3))}function flatMap(collection,iteratee){return baseFlatten(map(collection,iteratee),1)}function flatMapDeep(collection,iteratee){return baseFlatten(map(collection,iteratee),INFINITY)}function flatMapDepth(collection,iteratee,depth){return depth=depth===undefined?1:toInteger(depth),baseFlatten(map(collection,iteratee),depth)}function forEach(collection,iteratee){var func=isArray(collection)?arrayEach:baseEach;return func(collection,getIteratee(iteratee,3))}function forEachRight(collection,iteratee){var func=isArray(collection)?arrayEachRight:baseEachRight;return func(collection,getIteratee(iteratee,3))}function includes(collection,value,fromIndex,guard){collection=isArrayLike(collection)?collection:values(collection),fromIndex=fromIndex&&!guard?toInteger(fromIndex):0;var length=collection.length;return 0>fromIndex&&(fromIndex=nativeMax(length+fromIndex,0)),isString(collection)?length>=fromIndex&&collection.indexOf(value,fromIndex)>-1:!!length&&baseIndexOf(collection,value,fromIndex)>-1}function map(collection,iteratee){var func=isArray(collection)?arrayMap:baseMap;return func(collection,getIteratee(iteratee,3))}function orderBy(collection,iteratees,orders,guard){return null==collection?[]:(isArray(iteratees)||(iteratees=null==iteratees?[]:[iteratees]),orders=guard?undefined:orders,isArray(orders)||(orders=null==orders?[]:[orders]),baseOrderBy(collection,iteratees,orders))}function reduce(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduce:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEach)}function reduceRight(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduceRight:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEachRight)}function reject(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,negate(getIteratee(predicate,3)))}function sample(collection){var func=isArray(collection)?arraySample:baseSample;return func(collection)}function sampleSize(collection,n,guard){n=(guard?isIterateeCall(collection,n,guard):n===undefined)?1:toInteger(n);var func=isArray(collection)?arraySampleSize:baseSampleSize;return func(collection,n)}function shuffle(collection){var func=isArray(collection)?arrayShuffle:baseShuffle;return func(collection)}function size(collection){if(null==collection)return 0;if(isArrayLike(collection))return isString(collection)?stringSize(collection):collection.length;var tag=getTag(collection);return tag==mapTag||tag==setTag?collection.size:baseKeys(collection).length}function some(collection,predicate,guard){var func=isArray(collection)?arraySome:baseSome;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=undefined),func(collection,getIteratee(predicate,3))}function after(n,func){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return n=toInteger(n),function(){return--n<1?func.apply(this,arguments):void 0}}function ary(func,n,guard){return n=guard?undefined:n,n=func&&null==n?func.length:n,createWrap(func,ARY_FLAG,undefined,undefined,undefined,undefined,n)}function before(n,func){var result;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return n=toInteger(n),function(){return--n>0&&(result=func.apply(this,arguments)),1>=n&&(func=undefined),result}}function curry(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,CURRY_FLAG,undefined,undefined,undefined,undefined,undefined,arity);return result.placeholder=curry.placeholder,result}function curryRight(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,CURRY_RIGHT_FLAG,undefined,undefined,undefined,undefined,undefined,arity);return result.placeholder=curryRight.placeholder,result}function debounce(func,wait,options){function invokeFunc(time){var args=lastArgs,thisArg=lastThis;return lastArgs=lastThis=undefined,lastInvokeTime=time,result=func.apply(thisArg,args)}function leadingEdge(time){return lastInvokeTime=time,timerId=setTimeout(timerExpired,wait),leading?invokeFunc(time):result}function remainingWait(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime,result=wait-timeSinceLastCall;return maxing?nativeMin(result,maxWait-timeSinceLastInvoke):result}function shouldInvoke(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime;return lastCallTime===undefined||timeSinceLastCall>=wait||0>timeSinceLastCall||maxing&&timeSinceLastInvoke>=maxWait}function timerExpired(){var time=now();return shouldInvoke(time)?trailingEdge(time):void(timerId=setTimeout(timerExpired,remainingWait(time)))}function trailingEdge(time){return timerId=undefined,trailing&&lastArgs?invokeFunc(time):(lastArgs=lastThis=undefined,result)}function cancel(){timerId!==undefined&&clearTimeout(timerId),lastInvokeTime=0,lastArgs=lastCallTime=lastThis=timerId=undefined}function flush(){return timerId===undefined?result:trailingEdge(now())}function debounced(){var time=now(),isInvoking=shouldInvoke(time);if(lastArgs=arguments,lastThis=this,lastCallTime=time,isInvoking){if(timerId===undefined)return leadingEdge(lastCallTime);if(maxing)return timerId=setTimeout(timerExpired,wait),invokeFunc(lastCallTime)}return timerId===undefined&&(timerId=setTimeout(timerExpired,wait)),result}var lastArgs,lastThis,maxWait,result,timerId,lastCallTime,lastInvokeTime=0,leading=!1,maxing=!1,trailing=!0;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return wait=toNumber(wait)||0,isObject(options)&&(leading=!!options.leading,maxing="maxWait"in options,maxWait=maxing?nativeMax(toNumber(options.maxWait)||0,wait):maxWait,trailing="trailing"in options?!!options.trailing:trailing),debounced.cancel=cancel,debounced.flush=flush,debounced}function flip(func){return createWrap(func,FLIP_FLAG)}function memoize(func,resolver){if("function"!=typeof func||resolver&&"function"!=typeof resolver)throw new TypeError(FUNC_ERROR_TEXT);var memoized=function(){var args=arguments,key=resolver?resolver.apply(this,args):args[0],cache=memoized.cache;if(cache.has(key))return cache.get(key);var result=func.apply(this,args);return memoized.cache=cache.set(key,result)||cache,result};return memoized.cache=new(memoize.Cache||MapCache),memoized}function negate(predicate){if("function"!=typeof predicate)throw new TypeError(FUNC_ERROR_TEXT);return function(){var args=arguments;switch(args.length){case 0:return!predicate.call(this);case 1:return!predicate.call(this,args[0]);case 2:return!predicate.call(this,args[0],args[1]);case 3:return!predicate.call(this,args[0],args[1],args[2])}return!predicate.apply(this,args)}}function once(func){return before(2,func)}function rest(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=start===undefined?start:toInteger(start),baseRest(func,start)}function spread(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=start===undefined?0:nativeMax(toInteger(start),0),baseRest(function(args){var array=args[start],otherArgs=castSlice(args,0,start);return array&&arrayPush(otherArgs,array),apply(func,this,otherArgs)})}function throttle(func,wait,options){var leading=!0,trailing=!0;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return isObject(options)&&(leading="leading"in options?!!options.leading:leading,trailing="trailing"in options?!!options.trailing:trailing),debounce(func,wait,{leading:leading,maxWait:wait,trailing:trailing})}function unary(func){return ary(func,1)}function wrap(value,wrapper){return wrapper=null==wrapper?identity:wrapper,partial(wrapper,value)}function castArray(){if(!arguments.length)return[];var value=arguments[0];return isArray(value)?value:[value]}function clone(value){return baseClone(value,!1,!0)}function cloneWith(value,customizer){return baseClone(value,!1,!0,customizer)}function cloneDeep(value){return baseClone(value,!0,!0)}function cloneDeepWith(value,customizer){return baseClone(value,!0,!0,customizer)}function conformsTo(object,source){return null==source||baseConformsTo(object,source,keys(source))}function eq(value,other){return value===other||value!==value&&other!==other}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value)}function isBoolean(value){return value===!0||value===!1||isObjectLike(value)&&objectToString.call(value)==boolTag}function isElement(value){return null!=value&&1===value.nodeType&&isObjectLike(value)&&!isPlainObject(value)}function isEmpty(value){if(isArrayLike(value)&&(isArray(value)||"string"==typeof value||"function"==typeof value.splice||isBuffer(value)||isTypedArray(value)||isArguments(value)))return!value.length;var tag=getTag(value);if(tag==mapTag||tag==setTag)return!value.size;if(isPrototype(value))return!baseKeys(value).length;for(var key in value)if(hasOwnProperty.call(value,key))return!1;return!0}function isEqual(value,other){return baseIsEqual(value,other)}function isEqualWith(value,other,customizer){customizer="function"==typeof customizer?customizer:undefined;var result=customizer?customizer(value,other):undefined;return result===undefined?baseIsEqual(value,other,customizer):!!result}function isError(value){return isObjectLike(value)?objectToString.call(value)==errorTag||"string"==typeof value.message&&"string"==typeof value.name:!1}function isFinite(value){return"number"==typeof value&&nativeIsFinite(value)}function isFunction(value){var tag=isObject(value)?objectToString.call(value):"";return tag==funcTag||tag==genTag||tag==proxyTag}function isInteger(value){return"number"==typeof value&&value==toInteger(value)}function isLength(value){return"number"==typeof value&&value>-1&&value%1==0&&MAX_SAFE_INTEGER>=value}function isObject(value){var type=typeof value;return null!=value&&("object"==type||"function"==type)}function isObjectLike(value){return null!=value&&"object"==typeof value}function isMatch(object,source){return object===source||baseIsMatch(object,source,getMatchData(source))}function isMatchWith(object,source,customizer){return customizer="function"==typeof customizer?customizer:undefined,baseIsMatch(object,source,getMatchData(source),customizer)}function isNaN(value){return isNumber(value)&&value!=+value}function isNative(value){if(isMaskable(value))throw new Error(CORE_ERROR_TEXT);return baseIsNative(value)}function isNull(value){return null===value}function isNil(value){return null==value}function isNumber(value){return"number"==typeof value||isObjectLike(value)&&objectToString.call(value)==numberTag}function isPlainObject(value){if(!isObjectLike(value)||objectToString.call(value)!=objectTag)return!1;var proto=getPrototype(value);if(null===proto)return!0;var Ctor=hasOwnProperty.call(proto,"constructor")&&proto.constructor;return"function"==typeof Ctor&&Ctor instanceof Ctor&&funcToString.call(Ctor)==objectCtorString}function isSafeInteger(value){return isInteger(value)&&value>=-MAX_SAFE_INTEGER&&MAX_SAFE_INTEGER>=value}function isString(value){return"string"==typeof value||!isArray(value)&&isObjectLike(value)&&objectToString.call(value)==stringTag}function isSymbol(value){return"symbol"==typeof value||isObjectLike(value)&&objectToString.call(value)==symbolTag}function isUndefined(value){return value===undefined}function isWeakMap(value){return isObjectLike(value)&&getTag(value)==weakMapTag}function isWeakSet(value){return isObjectLike(value)&&objectToString.call(value)==weakSetTag}function toArray(value){if(!value)return[];if(isArrayLike(value))return isString(value)?stringToArray(value):copyArray(value);if(iteratorSymbol&&value[iteratorSymbol])return iteratorToArray(value[iteratorSymbol]());var tag=getTag(value),func=tag==mapTag?mapToArray:tag==setTag?setToArray:values;return func(value)}function toFinite(value){if(!value)return 0===value?value:0;if(value=toNumber(value),value===INFINITY||value===-INFINITY){var sign=0>value?-1:1;return sign*MAX_INTEGER}return value===value?value:0}function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0}function toLength(value){return value?baseClamp(toInteger(value),0,MAX_ARRAY_LENGTH):0}function toNumber(value){if("number"==typeof value)return value;if(isSymbol(value))return NAN;if(isObject(value)){var other="function"==typeof value.valueOf?value.valueOf():value;value=isObject(other)?other+"":other}if("string"!=typeof value)return 0===value?value:+value;value=value.replace(reTrim,"");var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value}function toPlainObject(value){return copyObject(value,keysIn(value))}function toSafeInteger(value){return baseClamp(toInteger(value),-MAX_SAFE_INTEGER,MAX_SAFE_INTEGER)}function toString(value){return null==value?"":baseToString(value)}function create(prototype,properties){var result=baseCreate(prototype);return properties?baseAssign(result,properties):result}function findKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwn)}function findLastKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwnRight)}function forIn(object,iteratee){return null==object?object:baseFor(object,getIteratee(iteratee,3),keysIn)}function forInRight(object,iteratee){return null==object?object:baseForRight(object,getIteratee(iteratee,3),keysIn)}function forOwn(object,iteratee){return object&&baseForOwn(object,getIteratee(iteratee,3))}function forOwnRight(object,iteratee){return object&&baseForOwnRight(object,getIteratee(iteratee,3))}function functions(object){return null==object?[]:baseFunctions(object,keys(object))}function functionsIn(object){return null==object?[]:baseFunctions(object,keysIn(object))}function get(object,path,defaultValue){var result=null==object?undefined:baseGet(object,path);return result===undefined?defaultValue:result}function has(object,path){return null!=object&&hasPath(object,path,baseHas)}function hasIn(object,path){return null!=object&&hasPath(object,path,baseHasIn)}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function keysIn(object){return isArrayLike(object)?arrayLikeKeys(object,!0):baseKeysIn(object)}function mapKeys(object,iteratee){var result={};return iteratee=getIteratee(iteratee,3), baseForOwn(object,function(value,key,object){baseAssignValue(result,iteratee(value,key,object),value)}),result}function mapValues(object,iteratee){var result={};return iteratee=getIteratee(iteratee,3),baseForOwn(object,function(value,key,object){baseAssignValue(result,key,iteratee(value,key,object))}),result}function omitBy(object,predicate){return pickBy(object,negate(getIteratee(predicate)))}function pickBy(object,predicate){return null==object?{}:basePickBy(object,getAllKeysIn(object),getIteratee(predicate))}function result(object,path,defaultValue){path=isKey(path,object)?[path]:castPath(path);var index=-1,length=path.length;for(length||(object=undefined,length=1);++indexupper){var temp=lower;lower=upper,upper=temp}if(floating||lower%1||upper%1){var rand=nativeRandom();return nativeMin(lower+rand*(upper-lower+freeParseFloat("1e-"+((rand+"").length-1))),upper)}return baseRandom(lower,upper)}function capitalize(string){return upperFirst(toString(string).toLowerCase())}function deburr(string){return string=toString(string),string&&string.replace(reLatin,deburrLetter).replace(reComboMark,"")}function endsWith(string,target,position){string=toString(string),target=baseToString(target);var length=string.length;position=position===undefined?length:baseClamp(toInteger(position),0,length);var end=position;return position-=target.length,position>=0&&string.slice(position,end)==target}function escape(string){return string=toString(string),string&&reHasUnescapedHtml.test(string)?string.replace(reUnescapedHtml,escapeHtmlChar):string}function escapeRegExp(string){return string=toString(string),string&&reHasRegExpChar.test(string)?string.replace(reRegExpChar,"\\$&"):string}function pad(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;if(!length||strLength>=length)return string;var mid=(length-strLength)/2;return createPadding(nativeFloor(mid),chars)+string+createPadding(nativeCeil(mid),chars)}function padEnd(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;return length&&length>strLength?string+createPadding(length-strLength,chars):string}function padStart(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;return length&&length>strLength?createPadding(length-strLength,chars)+string:string}function parseInt(string,radix,guard){return guard||null==radix?radix=0:radix&&(radix=+radix),nativeParseInt(toString(string).replace(reTrimStart,""),radix||0)}function repeat(string,n,guard){return n=(guard?isIterateeCall(string,n,guard):n===undefined)?1:toInteger(n),baseRepeat(toString(string),n)}function replace(){var args=arguments,string=toString(args[0]);return args.length<3?string:string.replace(args[1],args[2])}function split(string,separator,limit){return limit&&"number"!=typeof limit&&isIterateeCall(string,separator,limit)&&(separator=limit=undefined),(limit=limit===undefined?MAX_ARRAY_LENGTH:limit>>>0)?(string=toString(string),string&&("string"==typeof separator||null!=separator&&!isRegExp(separator))&&(separator=baseToString(separator),!separator&&hasUnicode(string))?castSlice(stringToArray(string),0,limit):string.split(separator,limit)):[]}function startsWith(string,target,position){return string=toString(string),position=baseClamp(toInteger(position),0,string.length),target=baseToString(target),string.slice(position,position+target.length)==target}function template(string,options,guard){var settings=lodash.templateSettings;guard&&isIterateeCall(string,options,guard)&&(options=undefined),string=toString(string),options=assignInWith({},options,settings,assignInDefaults);var isEscaping,isEvaluating,imports=assignInWith({},options.imports,settings.imports,assignInDefaults),importsKeys=keys(imports),importsValues=baseValues(imports,importsKeys),index=0,interpolate=options.interpolate||reNoMatch,source="__p += '",reDelimiters=RegExp((options.escape||reNoMatch).source+"|"+interpolate.source+"|"+(interpolate===reInterpolate?reEsTemplate:reNoMatch).source+"|"+(options.evaluate||reNoMatch).source+"|$","g"),sourceURL="//# sourceURL="+("sourceURL"in options?options.sourceURL:"lodash.templateSources["+ ++templateCounter+"]")+"\n";string.replace(reDelimiters,function(match,escapeValue,interpolateValue,esTemplateValue,evaluateValue,offset){return interpolateValue||(interpolateValue=esTemplateValue),source+=string.slice(index,offset).replace(reUnescapedString,escapeStringChar),escapeValue&&(isEscaping=!0,source+="' +\n__e("+escapeValue+") +\n'"),evaluateValue&&(isEvaluating=!0,source+="';\n"+evaluateValue+";\n__p += '"),interpolateValue&&(source+="' +\n((__t = ("+interpolateValue+")) == null ? '' : __t) +\n'"),index=offset+match.length,match}),source+="';\n";var variable=options.variable;variable||(source="with (obj) {\n"+source+"\n}\n"),source=(isEvaluating?source.replace(reEmptyStringLeading,""):source).replace(reEmptyStringMiddle,"$1").replace(reEmptyStringTrailing,"$1;"),source="function("+(variable||"obj")+") {\n"+(variable?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(isEscaping?", __e = _.escape":"")+(isEvaluating?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+source+"return __p\n}";var result=attempt(function(){return Function(importsKeys,sourceURL+"return "+source).apply(undefined,importsValues)});if(result.source=source,isError(result))throw result;return result}function toLower(value){return toString(value).toLowerCase()}function toUpper(value){return toString(value).toUpperCase()}function trim(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrim,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),chrSymbols=stringToArray(chars),start=charsStartIndex(strSymbols,chrSymbols),end=charsEndIndex(strSymbols,chrSymbols)+1;return castSlice(strSymbols,start,end).join("")}function trimEnd(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrimEnd,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),end=charsEndIndex(strSymbols,stringToArray(chars))+1;return castSlice(strSymbols,0,end).join("")}function trimStart(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrimStart,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),start=charsStartIndex(strSymbols,stringToArray(chars));return castSlice(strSymbols,start).join("")}function truncate(string,options){var length=DEFAULT_TRUNC_LENGTH,omission=DEFAULT_TRUNC_OMISSION;if(isObject(options)){var separator="separator"in options?options.separator:separator;length="length"in options?toInteger(options.length):length,omission="omission"in options?baseToString(options.omission):omission}string=toString(string);var strLength=string.length;if(hasUnicode(string)){var strSymbols=stringToArray(string);strLength=strSymbols.length}if(length>=strLength)return string;var end=length-stringSize(omission);if(1>end)return omission;var result=strSymbols?castSlice(strSymbols,0,end).join(""):string.slice(0,end);if(separator===undefined)return result+omission;if(strSymbols&&(end+=result.length-end),isRegExp(separator)){if(string.slice(end).search(separator)){var match,substring=result;for(separator.global||(separator=RegExp(separator.source,toString(reFlags.exec(separator))+"g")),separator.lastIndex=0;match=separator.exec(substring);)var newEnd=match.index;result=result.slice(0,newEnd===undefined?end:newEnd)}}else if(string.indexOf(baseToString(separator),end)!=end){var index=result.lastIndexOf(separator);index>-1&&(result=result.slice(0,index))}return result+omission}function unescape(string){return string=toString(string),string&&reHasEscapedHtml.test(string)?string.replace(reEscapedHtml,unescapeHtmlChar):string}function words(string,pattern,guard){return string=toString(string),pattern=guard?undefined:pattern,pattern===undefined?hasUnicodeWord(string)?unicodeWords(string):asciiWords(string):string.match(pattern)||[]}function cond(pairs){var length=pairs?pairs.length:0,toIteratee=getIteratee();return pairs=length?arrayMap(pairs,function(pair){if("function"!=typeof pair[1])throw new TypeError(FUNC_ERROR_TEXT);return[toIteratee(pair[0]),pair[1]]}):[],baseRest(function(args){for(var index=-1;++indexn||n>MAX_SAFE_INTEGER)return[];var index=MAX_ARRAY_LENGTH,length=nativeMin(n,MAX_ARRAY_LENGTH);iteratee=getIteratee(iteratee),n-=MAX_ARRAY_LENGTH;for(var result=baseTimes(length,iteratee);++index1?arrays[length-1]:undefined;return iteratee="function"==typeof iteratee?(arrays.pop(),iteratee):undefined,unzipWith(arrays,iteratee)}),wrapperAt=flatRest(function(paths){var length=paths.length,start=length?paths[0]:0,value=this.__wrapped__,interceptor=function(object){return baseAt(object,paths)};return!(length>1||this.__actions__.length)&&value instanceof LazyWrapper&&isIndex(start)?(value=value.slice(start,+start+(length?1:0)),value.__actions__.push({func:thru,args:[interceptor],thisArg:undefined}),new LodashWrapper(value,this.__chain__).thru(function(array){return length&&!array.length&&array.push(undefined),array})):this.thru(interceptor)}),countBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?++result[key]:baseAssignValue(result,key,1)}),find=createFind(findIndex),findLast=createFind(findLastIndex),groupBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?result[key].push(value):baseAssignValue(result,key,[value])}),invokeMap=baseRest(function(collection,path,args){var index=-1,isFunc="function"==typeof path,isProp=isKey(path),result=isArrayLike(collection)?Array(collection.length):[];return baseEach(collection,function(value){var func=isFunc?path:isProp&&null!=value?value[path]:undefined;result[++index]=func?apply(func,value,args):baseInvoke(value,path,args)}),result}),keyBy=createAggregator(function(result,value,key){baseAssignValue(result,key,value)}),partition=createAggregator(function(result,value,key){result[key?0:1].push(value)},function(){return[[],[]]}),sortBy=baseRest(function(collection,iteratees){if(null==collection)return[];var length=iteratees.length;return length>1&&isIterateeCall(collection,iteratees[0],iteratees[1])?iteratees=[]:length>2&&isIterateeCall(iteratees[0],iteratees[1],iteratees[2])&&(iteratees=[iteratees[0]]),baseOrderBy(collection,baseFlatten(iteratees,1),[])}),now=ctxNow||function(){return root.Date.now()},bind=baseRest(function(func,thisArg,partials){var bitmask=BIND_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bind));bitmask|=PARTIAL_FLAG}return createWrap(func,bitmask,thisArg,partials,holders)}),bindKey=baseRest(function(object,key,partials){var bitmask=BIND_FLAG|BIND_KEY_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bindKey));bitmask|=PARTIAL_FLAG}return createWrap(key,bitmask,object,partials,holders)}),defer=baseRest(function(func,args){return baseDelay(func,1,args)}),delay=baseRest(function(func,wait,args){return baseDelay(func,toNumber(wait)||0,args)});memoize.Cache=MapCache;var overArgs=castRest(function(func,transforms){transforms=1==transforms.length&&isArray(transforms[0])?arrayMap(transforms[0],baseUnary(getIteratee())):arrayMap(baseFlatten(transforms,1),baseUnary(getIteratee()));var funcsLength=transforms.length;return baseRest(function(args){for(var index=-1,length=nativeMin(args.length,funcsLength);++index=other}),isArguments=baseIsArguments(function(){return arguments}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty.call(value,"callee")&&!propertyIsEnumerable.call(value,"callee")},isArray=Array.isArray,isArrayBuffer=nodeIsArrayBuffer?baseUnary(nodeIsArrayBuffer):baseIsArrayBuffer,isBuffer=nativeIsBuffer||stubFalse,isDate=nodeIsDate?baseUnary(nodeIsDate):baseIsDate,isMap=nodeIsMap?baseUnary(nodeIsMap):baseIsMap,isRegExp=nodeIsRegExp?baseUnary(nodeIsRegExp):baseIsRegExp,isSet=nodeIsSet?baseUnary(nodeIsSet):baseIsSet,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray,lt=createRelationalOperation(baseLt),lte=createRelationalOperation(function(value,other){return other>=value}),assign=createAssigner(function(object,source){if(isPrototype(source)||isArrayLike(source))return void copyObject(source,keys(source),object);for(var key in source)hasOwnProperty.call(source,key)&&assignValue(object,key,source[key])}),assignIn=createAssigner(function(object,source){copyObject(source,keysIn(source),object)}),assignInWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keysIn(source),object,customizer)}),assignWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keys(source),object,customizer)}),at=flatRest(baseAt),defaults=baseRest(function(args){return args.push(undefined,assignInDefaults),apply(assignInWith,undefined,args)}),defaultsDeep=baseRest(function(args){return args.push(undefined,mergeDefaults),apply(mergeWith,undefined,args)}),invert=createInverter(function(result,value,key){result[value]=key},constant(identity)),invertBy=createInverter(function(result,value,key){hasOwnProperty.call(result,value)?result[value].push(key):result[value]=[key]},getIteratee),invoke=baseRest(baseInvoke),merge=createAssigner(function(object,source,srcIndex){baseMerge(object,source,srcIndex)}),mergeWith=createAssigner(function(object,source,srcIndex,customizer){baseMerge(object,source,srcIndex,customizer)}),omit=flatRest(function(object,props){return null==object?{}:(props=arrayMap(props,toKey),basePick(object,baseDifference(getAllKeysIn(object),props)))}),pick=flatRest(function(object,props){return null==object?{}:basePick(object,arrayMap(props,toKey))}),toPairs=createToPairs(keys),toPairsIn=createToPairs(keysIn),camelCase=createCompounder(function(result,word,index){return word=word.toLowerCase(),result+(index?capitalize(word):word)}),kebabCase=createCompounder(function(result,word,index){return result+(index?"-":"")+word.toLowerCase()}),lowerCase=createCompounder(function(result,word,index){return result+(index?" ":"")+word.toLowerCase()}),lowerFirst=createCaseFirst("toLowerCase"),snakeCase=createCompounder(function(result,word,index){return result+(index?"_":"")+word.toLowerCase()}),startCase=createCompounder(function(result,word,index){return result+(index?" ":"")+upperFirst(word)}),upperCase=createCompounder(function(result,word,index){return result+(index?" ":"")+word.toUpperCase()}),upperFirst=createCaseFirst("toUpperCase"),attempt=baseRest(function(func,args){try{return apply(func,undefined,args)}catch(e){return isError(e)?e:new Error(e)}}),bindAll=flatRest(function(object,methodNames){return arrayEach(methodNames,function(key){key=toKey(key),baseAssignValue(object,key,bind(object[key],object))}),object}),flow=createFlow(),flowRight=createFlow(!0),method=baseRest(function(path,args){return function(object){return baseInvoke(object,path,args)}}),methodOf=baseRest(function(object,args){return function(path){return baseInvoke(object,path,args)}}),over=createOver(arrayMap),overEvery=createOver(arrayEvery),overSome=createOver(arraySome),range=createRange(),rangeRight=createRange(!0),add=createMathOperation(function(augend,addend){return augend+addend},0),ceil=createRound("ceil"),divide=createMathOperation(function(dividend,divisor){return dividend/divisor},1),floor=createRound("floor"),multiply=createMathOperation(function(multiplier,multiplicand){return multiplier*multiplicand},1),round=createRound("round"),subtract=createMathOperation(function(minuend,subtrahend){return minuend-subtrahend},0);return lodash.after=after,lodash.ary=ary,lodash.assign=assign,lodash.assignIn=assignIn,lodash.assignInWith=assignInWith,lodash.assignWith=assignWith,lodash.at=at,lodash.before=before,lodash.bind=bind,lodash.bindAll=bindAll,lodash.bindKey=bindKey,lodash.castArray=castArray,lodash.chain=chain,lodash.chunk=chunk,lodash.compact=compact,lodash.concat=concat,lodash.cond=cond,lodash.conforms=conforms,lodash.constant=constant,lodash.countBy=countBy,lodash.create=create,lodash.curry=curry,lodash.curryRight=curryRight,lodash.debounce=debounce,lodash.defaults=defaults,lodash.defaultsDeep=defaultsDeep,lodash.defer=defer,lodash.delay=delay,lodash.difference=difference,lodash.differenceBy=differenceBy,lodash.differenceWith=differenceWith,lodash.drop=drop,lodash.dropRight=dropRight,lodash.dropRightWhile=dropRightWhile,lodash.dropWhile=dropWhile,lodash.fill=fill,lodash.filter=filter,lodash.flatMap=flatMap,lodash.flatMapDeep=flatMapDeep,lodash.flatMapDepth=flatMapDepth,lodash.flatten=flatten,lodash.flattenDeep=flattenDeep,lodash.flattenDepth=flattenDepth,lodash.flip=flip,lodash.flow=flow,lodash.flowRight=flowRight,lodash.fromPairs=fromPairs,lodash.functions=functions,lodash.functionsIn=functionsIn,lodash.groupBy=groupBy,lodash.initial=initial,lodash.intersection=intersection,lodash.intersectionBy=intersectionBy,lodash.intersectionWith=intersectionWith,lodash.invert=invert,lodash.invertBy=invertBy,lodash.invokeMap=invokeMap,lodash.iteratee=iteratee,lodash.keyBy=keyBy,lodash.keys=keys,lodash.keysIn=keysIn,lodash.map=map,lodash.mapKeys=mapKeys,lodash.mapValues=mapValues,lodash.matches=matches,lodash.matchesProperty=matchesProperty, -lodash.memoize=memoize,lodash.merge=merge,lodash.mergeWith=mergeWith,lodash.method=method,lodash.methodOf=methodOf,lodash.mixin=mixin,lodash.negate=negate,lodash.nthArg=nthArg,lodash.omit=omit,lodash.omitBy=omitBy,lodash.once=once,lodash.orderBy=orderBy,lodash.over=over,lodash.overArgs=overArgs,lodash.overEvery=overEvery,lodash.overSome=overSome,lodash.partial=partial,lodash.partialRight=partialRight,lodash.partition=partition,lodash.pick=pick,lodash.pickBy=pickBy,lodash.property=property,lodash.propertyOf=propertyOf,lodash.pull=pull,lodash.pullAll=pullAll,lodash.pullAllBy=pullAllBy,lodash.pullAllWith=pullAllWith,lodash.pullAt=pullAt,lodash.range=range,lodash.rangeRight=rangeRight,lodash.rearg=rearg,lodash.reject=reject,lodash.remove=remove,lodash.rest=rest,lodash.reverse=reverse,lodash.sampleSize=sampleSize,lodash.set=set,lodash.setWith=setWith,lodash.shuffle=shuffle,lodash.slice=slice,lodash.sortBy=sortBy,lodash.sortedUniq=sortedUniq,lodash.sortedUniqBy=sortedUniqBy,lodash.split=split,lodash.spread=spread,lodash.tail=tail,lodash.take=take,lodash.takeRight=takeRight,lodash.takeRightWhile=takeRightWhile,lodash.takeWhile=takeWhile,lodash.tap=tap,lodash.throttle=throttle,lodash.thru=thru,lodash.toArray=toArray,lodash.toPairs=toPairs,lodash.toPairsIn=toPairsIn,lodash.toPath=toPath,lodash.toPlainObject=toPlainObject,lodash.transform=transform,lodash.unary=unary,lodash.union=union,lodash.unionBy=unionBy,lodash.unionWith=unionWith,lodash.uniq=uniq,lodash.uniqBy=uniqBy,lodash.uniqWith=uniqWith,lodash.unset=unset,lodash.unzip=unzip,lodash.unzipWith=unzipWith,lodash.update=update,lodash.updateWith=updateWith,lodash.values=values,lodash.valuesIn=valuesIn,lodash.without=without,lodash.words=words,lodash.wrap=wrap,lodash.xor=xor,lodash.xorBy=xorBy,lodash.xorWith=xorWith,lodash.zip=zip,lodash.zipObject=zipObject,lodash.zipObjectDeep=zipObjectDeep,lodash.zipWith=zipWith,lodash.entries=toPairs,lodash.entriesIn=toPairsIn,lodash.extend=assignIn,lodash.extendWith=assignInWith,mixin(lodash,lodash),lodash.add=add,lodash.attempt=attempt,lodash.camelCase=camelCase,lodash.capitalize=capitalize,lodash.ceil=ceil,lodash.clamp=clamp,lodash.clone=clone,lodash.cloneDeep=cloneDeep,lodash.cloneDeepWith=cloneDeepWith,lodash.cloneWith=cloneWith,lodash.conformsTo=conformsTo,lodash.deburr=deburr,lodash.defaultTo=defaultTo,lodash.divide=divide,lodash.endsWith=endsWith,lodash.eq=eq,lodash.escape=escape,lodash.escapeRegExp=escapeRegExp,lodash.every=every,lodash.find=find,lodash.findIndex=findIndex,lodash.findKey=findKey,lodash.findLast=findLast,lodash.findLastIndex=findLastIndex,lodash.findLastKey=findLastKey,lodash.floor=floor,lodash.forEach=forEach,lodash.forEachRight=forEachRight,lodash.forIn=forIn,lodash.forInRight=forInRight,lodash.forOwn=forOwn,lodash.forOwnRight=forOwnRight,lodash.get=get,lodash.gt=gt,lodash.gte=gte,lodash.has=has,lodash.hasIn=hasIn,lodash.head=head,lodash.identity=identity,lodash.includes=includes,lodash.indexOf=indexOf,lodash.inRange=inRange,lodash.invoke=invoke,lodash.isArguments=isArguments,lodash.isArray=isArray,lodash.isArrayBuffer=isArrayBuffer,lodash.isArrayLike=isArrayLike,lodash.isArrayLikeObject=isArrayLikeObject,lodash.isBoolean=isBoolean,lodash.isBuffer=isBuffer,lodash.isDate=isDate,lodash.isElement=isElement,lodash.isEmpty=isEmpty,lodash.isEqual=isEqual,lodash.isEqualWith=isEqualWith,lodash.isError=isError,lodash.isFinite=isFinite,lodash.isFunction=isFunction,lodash.isInteger=isInteger,lodash.isLength=isLength,lodash.isMap=isMap,lodash.isMatch=isMatch,lodash.isMatchWith=isMatchWith,lodash.isNaN=isNaN,lodash.isNative=isNative,lodash.isNil=isNil,lodash.isNull=isNull,lodash.isNumber=isNumber,lodash.isObject=isObject,lodash.isObjectLike=isObjectLike,lodash.isPlainObject=isPlainObject,lodash.isRegExp=isRegExp,lodash.isSafeInteger=isSafeInteger,lodash.isSet=isSet,lodash.isString=isString,lodash.isSymbol=isSymbol,lodash.isTypedArray=isTypedArray,lodash.isUndefined=isUndefined,lodash.isWeakMap=isWeakMap,lodash.isWeakSet=isWeakSet,lodash.join=join,lodash.kebabCase=kebabCase,lodash.last=last,lodash.lastIndexOf=lastIndexOf,lodash.lowerCase=lowerCase,lodash.lowerFirst=lowerFirst,lodash.lt=lt,lodash.lte=lte,lodash.max=max,lodash.maxBy=maxBy,lodash.mean=mean,lodash.meanBy=meanBy,lodash.min=min,lodash.minBy=minBy,lodash.stubArray=stubArray,lodash.stubFalse=stubFalse,lodash.stubObject=stubObject,lodash.stubString=stubString,lodash.stubTrue=stubTrue,lodash.multiply=multiply,lodash.nth=nth,lodash.noConflict=noConflict,lodash.noop=noop,lodash.now=now,lodash.pad=pad,lodash.padEnd=padEnd,lodash.padStart=padStart,lodash.parseInt=parseInt,lodash.random=random,lodash.reduce=reduce,lodash.reduceRight=reduceRight,lodash.repeat=repeat,lodash.replace=replace,lodash.result=result,lodash.round=round,lodash.runInContext=runInContext,lodash.sample=sample,lodash.size=size,lodash.snakeCase=snakeCase,lodash.some=some,lodash.sortedIndex=sortedIndex,lodash.sortedIndexBy=sortedIndexBy,lodash.sortedIndexOf=sortedIndexOf,lodash.sortedLastIndex=sortedLastIndex,lodash.sortedLastIndexBy=sortedLastIndexBy,lodash.sortedLastIndexOf=sortedLastIndexOf,lodash.startCase=startCase,lodash.startsWith=startsWith,lodash.subtract=subtract,lodash.sum=sum,lodash.sumBy=sumBy,lodash.template=template,lodash.times=times,lodash.toFinite=toFinite,lodash.toInteger=toInteger,lodash.toLength=toLength,lodash.toLower=toLower,lodash.toNumber=toNumber,lodash.toSafeInteger=toSafeInteger,lodash.toString=toString,lodash.toUpper=toUpper,lodash.trim=trim,lodash.trimEnd=trimEnd,lodash.trimStart=trimStart,lodash.truncate=truncate,lodash.unescape=unescape,lodash.uniqueId=uniqueId,lodash.upperCase=upperCase,lodash.upperFirst=upperFirst,lodash.each=forEach,lodash.eachRight=forEachRight,lodash.first=head,mixin(lodash,function(){var source={};return baseForOwn(lodash,function(func,methodName){hasOwnProperty.call(lodash.prototype,methodName)||(source[methodName]=func)}),source}(),{chain:!1}),lodash.VERSION=VERSION,arrayEach(["bind","bindKey","curry","curryRight","partial","partialRight"],function(methodName){lodash[methodName].placeholder=lodash}),arrayEach(["drop","take"],function(methodName,index){LazyWrapper.prototype[methodName]=function(n){var filtered=this.__filtered__;if(filtered&&!index)return new LazyWrapper(this);n=n===undefined?1:nativeMax(toInteger(n),0);var result=this.clone();return filtered?result.__takeCount__=nativeMin(n,result.__takeCount__):result.__views__.push({size:nativeMin(n,MAX_ARRAY_LENGTH),type:methodName+(result.__dir__<0?"Right":"")}),result},LazyWrapper.prototype[methodName+"Right"]=function(n){return this.reverse()[methodName](n).reverse()}}),arrayEach(["filter","map","takeWhile"],function(methodName,index){var type=index+1,isFilter=type==LAZY_FILTER_FLAG||type==LAZY_WHILE_FLAG;LazyWrapper.prototype[methodName]=function(iteratee){var result=this.clone();return result.__iteratees__.push({iteratee:getIteratee(iteratee,3),type:type}),result.__filtered__=result.__filtered__||isFilter,result}}),arrayEach(["head","last"],function(methodName,index){var takeName="take"+(index?"Right":"");LazyWrapper.prototype[methodName]=function(){return this[takeName](1).value()[0]}}),arrayEach(["initial","tail"],function(methodName,index){var dropName="drop"+(index?"":"Right");LazyWrapper.prototype[methodName]=function(){return this.__filtered__?new LazyWrapper(this):this[dropName](1)}}),LazyWrapper.prototype.compact=function(){return this.filter(identity)},LazyWrapper.prototype.find=function(predicate){return this.filter(predicate).head()},LazyWrapper.prototype.findLast=function(predicate){return this.reverse().find(predicate)},LazyWrapper.prototype.invokeMap=baseRest(function(path,args){return"function"==typeof path?new LazyWrapper(this):this.map(function(value){return baseInvoke(value,path,args)})}),LazyWrapper.prototype.reject=function(predicate){return this.filter(negate(getIteratee(predicate)))},LazyWrapper.prototype.slice=function(start,end){start=toInteger(start);var result=this;return result.__filtered__&&(start>0||0>end)?new LazyWrapper(result):(0>start?result=result.takeRight(-start):start&&(result=result.drop(start)),end!==undefined&&(end=toInteger(end),result=0>end?result.dropRight(-end):result.take(end-start)),result)},LazyWrapper.prototype.takeRightWhile=function(predicate){return this.reverse().takeWhile(predicate).reverse()},LazyWrapper.prototype.toArray=function(){return this.take(MAX_ARRAY_LENGTH)},baseForOwn(LazyWrapper.prototype,function(func,methodName){var checkIteratee=/^(?:filter|find|map|reject)|While$/.test(methodName),isTaker=/^(?:head|last)$/.test(methodName),lodashFunc=lodash[isTaker?"take"+("last"==methodName?"Right":""):methodName],retUnwrapped=isTaker||/^find/.test(methodName);lodashFunc&&(lodash.prototype[methodName]=function(){var value=this.__wrapped__,args=isTaker?[1]:arguments,isLazy=value instanceof LazyWrapper,iteratee=args[0],useLazy=isLazy||isArray(value),interceptor=function(value){var result=lodashFunc.apply(lodash,arrayPush([value],args));return isTaker&&chainAll?result[0]:result};useLazy&&checkIteratee&&"function"==typeof iteratee&&1!=iteratee.length&&(isLazy=useLazy=!1);var chainAll=this.__chain__,isHybrid=!!this.__actions__.length,isUnwrapped=retUnwrapped&&!chainAll,onlyLazy=isLazy&&!isHybrid;if(!retUnwrapped&&useLazy){value=onlyLazy?value:new LazyWrapper(this);var result=func.apply(value,args);return result.__actions__.push({func:thru,args:[interceptor],thisArg:undefined}),new LodashWrapper(result,chainAll)}return isUnwrapped&&onlyLazy?func.apply(this,args):(result=this.thru(interceptor),isUnwrapped?isTaker?result.value()[0]:result.value():result)})}),arrayEach(["pop","push","shift","sort","splice","unshift"],function(methodName){var func=arrayProto[methodName],chainName=/^(?:push|sort|unshift)$/.test(methodName)?"tap":"thru",retUnwrapped=/^(?:pop|shift)$/.test(methodName);lodash.prototype[methodName]=function(){var args=arguments;if(retUnwrapped&&!this.__chain__){var value=this.value();return func.apply(isArray(value)?value:[],args)}return this[chainName](function(value){return func.apply(isArray(value)?value:[],args)})}}),baseForOwn(LazyWrapper.prototype,function(func,methodName){var lodashFunc=lodash[methodName];if(lodashFunc){var key=lodashFunc.name+"",names=realNames[key]||(realNames[key]=[]);names.push({name:methodName,func:lodashFunc})}}),realNames[createHybrid(undefined,BIND_KEY_FLAG).name]=[{name:"wrapper",func:undefined}],LazyWrapper.prototype.clone=lazyClone,LazyWrapper.prototype.reverse=lazyReverse,LazyWrapper.prototype.value=lazyValue,lodash.prototype.at=wrapperAt,lodash.prototype.chain=wrapperChain,lodash.prototype.commit=wrapperCommit,lodash.prototype.next=wrapperNext,lodash.prototype.plant=wrapperPlant,lodash.prototype.reverse=wrapperReverse,lodash.prototype.toJSON=lodash.prototype.valueOf=lodash.prototype.value=wrapperValue,lodash.prototype.first=lodash.prototype.head,iteratorSymbol&&(lodash.prototype[iteratorSymbol]=wrapperToIterator),lodash},_=runInContext();"function"==typeof define&&"object"==typeof define.amd&&define.amd?(root._=_,define(function(){return _})):freeModule?((freeModule.exports=_)._=_,freeExports._=_):root._=_}.call(this);var UsergridAuthMode=Object.freeze({NONE:"none",USER:"user",APP:"app"}),UsergridDirection=Object.freeze({IN:"connecting",OUT:"connections"}),UsergridHttpMethod=Object.freeze({GET:"GET",PUT:"PUT",POST:"POST",DELETE:"DELETE"}),UsergridQueryOperator=Object.freeze({EQUAL:"=",GREATER_THAN:">",GREATER_THAN_EQUAL_TO:">=",LESS_THAN:"<",LESS_THAN_EQUAL_TO:"<="}),UsergridQuerySortOrder=Object.freeze({ASC:"asc",DESC:"desc"}),UsergridApplicationJSONHeaderValue="application/json";!function(global){function UsergridHelpers(){}var name="UsergridHelpers",overwrittenName=global[name];UsergridHelpers.DefaultHeaders=Object.freeze({"Content-Type":UsergridApplicationJSONHeaderValue,Accept:UsergridApplicationJSONHeaderValue}),UsergridHelpers.validateAndRetrieveClient=function(args){var client=void 0;if(args instanceof UsergridClient)client=args;else if(args[0]instanceof UsergridClient)client=args[0];else if(_.get(args,"client"))client=args.client;else{if(!Usergrid.isInitialized)throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument");client=Usergrid}return client},UsergridHelpers.inherits=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})},UsergridHelpers.flattenArgs=function(args){return _.flattenDeep(Array.prototype.slice.call(args))},UsergridHelpers.callback=function(){var args=UsergridHelpers.flattenArgs(arguments).reverse(),emptyFunc=function(){};return _.first(_.flattenDeep([args,_.get(args,"0.callback"),emptyFunc]).filter(_.isFunction))},UsergridHelpers.authForRequests=function(client){var authForRequests=void 0;return _.get(client,"tempAuth.isValid")?(authForRequests=client.tempAuth,client.tempAuth=void 0):_.get(client,"currentUser.auth.isValid")&&client.authMode===UsergridAuthMode.USER?authForRequests=client.currentUser.auth:_.get(client,"appAuth.isValid")&&client.authMode===UsergridAuthMode.APP&&(authForRequests=client.appAuth),authForRequests},UsergridHelpers.userLoginBody=function(options){var body={grant_type:"password",password:options.password};return options.tokenTtl&&(body.ttl=options.tokenTtl),body[options.username?"username":"email"]=options.username?options.username:options.email,body},UsergridHelpers.appLoginBody=function(options){var body={grant_type:"client_credentials",client_id:options.clientId,client_secret:options.clientSecret};return options.tokenTtl&&(body.ttl=options.tokenTtl),body},UsergridHelpers.calculateExpiry=function(expires_in){return Date.now()+1e3*(expires_in?expires_in-5:0)};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;return UsergridHelpers.isUUID=function(uuid){return uuid?uuidValueRegex.test(uuid):!1},UsergridHelpers.useQuotesIfRequired=function(value){return _.isFinite(value)||UsergridHelpers.isUUID(value)||_.isBoolean(value)||_.isObject(value)&&!_.isFunction(value)||_.isArray(value)?value:"'"+value+"'"},UsergridHelpers.setReadOnly=function(obj,key){return _.isArray(key)?key.forEach(function(k){UsergridHelpers.setReadOnly(obj,k)}):_.isPlainObject(obj[key])?Object.freeze(obj[key]):_.isPlainObject(obj)&&void 0===key?Object.freeze(obj):_.has(obj,key)?Object.defineProperty(obj,key,{writable:!1}):obj},UsergridHelpers.setWritable=function(obj,key){return _.isArray(key)?key.forEach(function(k){UsergridHelpers.setWritable(obj,k)}):_.isPlainObject(obj[key])?_.clone(obj[key]):_.isPlainObject(obj)&&void 0===key?_.clone(obj):_.has(obj,key)?Object.defineProperty(obj,key,{writable:!0}):obj},UsergridHelpers.assignPrefabOptions=function(args){return _.isObject(args[0])&&!_.isFunction(args[0])&&_.has(args,"method")&&_.assign(this,args[0]),this},UsergridHelpers.normalize=function(str){return str=str.replace(/\/+/g,"/"),str=str.replace(/:\//g,"://"),str=str.replace(/\/(\?|&|#[^!])/g,"$1"),str=str.replace(/(\?.+)\?/g,"$1&")},UsergridHelpers.urljoin=function(){var input=arguments,options={};"object"==typeof arguments[0]&&(input=arguments[0],options=arguments[1]||{});var joined=[].slice.call(input,0).join("/");return UsergridHelpers.normalize(joined,options)},UsergridHelpers.parseResponseHeaders=function(headerStr){var headers={};if(headerStr)for(var headerPairs=headerStr.split("\r\n"),i=0;i0){var key=headerPair.substring(0,index).toLowerCase();headers[key]=headerPair.substring(index+2)}}return headers},UsergridHelpers.uri=function(client,options){var path="";path=options instanceof UsergridEntity?options.type:options instanceof UsergridQuery?options._type:_.isString(options)?options:_.isArray(options)?_.get(options,"0.type")||_.get(options,"0.path"):options.path||options.type||_.get(options,"entity.type")||_.get(options,"query._type")||_.get(options,"body.type")||_.get(options,"body.path");var uuidOrName="";return options.method!==UsergridHttpMethod.POST&&(uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,_.get(options,"entity.uuid"),_.get(options,"entity.name"),_.get(options,"body.uuid"),_.get(options,"body.name"),""].filter(_.isString))),UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,path,uuidOrName)},UsergridHelpers.updateEntityFromRemote=function(entity,usergridResponse){UsergridHelpers.setWritable(entity,["uuid","name","type","created"]),_.assign(entity,usergridResponse.entity),UsergridHelpers.setReadOnly(entity,["uuid","name","type","created"])},UsergridHelpers.headers=function(client,options,defaultHeaders){var returnHeaders={};_.defaults(returnHeaders,options.headers,defaultHeaders),_.assign(returnHeaders,{"User-Agent":"usergrid-js/v"+UsergridSDKVersion});var authForRequests=UsergridHelpers.authForRequests(client);return authForRequests&&_.assign(returnHeaders,{authorization:"Bearer "+authForRequests.token}),returnHeaders},UsergridHelpers.setEntity=function(options,args){return options.entity=_.first([options.entity,args[0]].filter(function(property){return property instanceof UsergridEntity})),void 0!==options.entity&&(options.type=options.entity.type),options},UsergridHelpers.setAsset=function(options,args){return options.asset=_.first([options.asset,_.get(options,"entity.asset"),args[1],args[0]].filter(function(property){return property instanceof UsergridAsset})),options},UsergridHelpers.setUuidOrName=function(options,args){return options.uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,_.get(options,"entity.uuid"),_.get(options,"body.uuid"),_.get(options,"entity.name"),_.get(options,"body.name"),_.get(args,"0.uuid"),_.get(args,"0.name"),_.get(args,"2"),_.get(args,"1")].filter(_.isString)),options},UsergridHelpers.setPathOrType=function(options,args){var pathOrType=_.first([args.type,_.get(args,"0.type"),_.get(options,"entity.type"),_.get(args,"body.type"),_.get(options,"body.0.type"),_.isArray(args)?args[0]:void 0].filter(_.isString));return options[/\//.test(pathOrType)?"path":"type"]=pathOrType,options},UsergridHelpers.setQs=function(options,args){return options.path&&(options.qs=_.first([options.qs,args[2],args[1],args[0]].filter(_.isPlainObject))),options},UsergridHelpers.setQuery=function(options,args){return options.query=_.first([options,options.query,args[0]].filter(function(property){return property instanceof UsergridQuery})),options},UsergridHelpers.setAsset=function(options,args){return options.asset=_.first([options.asset,_.get(options,"entity.asset"),args[1],args[0]].filter(function(property){return property instanceof UsergridAsset})),options},UsergridHelpers.setBody=function(options,args){if(options.body=_.first([args.entity,args.body,args[0].entity,args[0].body,args[2],args[1],args[0]].filter(function(property){return _.isObject(property)&&!_.isFunction(property)&&!(property instanceof UsergridQuery)&&!(property instanceof UsergridAsset)})),void 0===options.body&&void 0===options.asset)throw new Error('"body" is required when making a '+options.method+" request");return options.body instanceof UsergridEntity?options.body=options.body.jsonValue():options.body instanceof Array&&options.body[0]instanceof UsergridEntity&&(options.body=_.map(options.body,function(entity){return entity.jsonValue()})),options},UsergridHelpers.buildReqest=function(client,method,args){var options={client:client,method:method,queryParams:args.queryParams||_.get(args,"0.queryParams"),callback:UsergridHelpers.callback(args)};return UsergridHelpers.assignPrefabOptions(options,args),UsergridHelpers.setEntity(options,args),(method===UsergridHttpMethod.POST||method===UsergridHttpMethod.PUT)&&(UsergridHelpers.setAsset(options,args),void 0===options.asset&&UsergridHelpers.setBody(options,args)),UsergridHelpers.setUuidOrName(options,args),UsergridHelpers.setPathOrType(options,args),UsergridHelpers.setQs(options,args),UsergridHelpers.setQuery(options,args),options.uri=UsergridHelpers.uri(client,options),new UsergridRequest(options)},UsergridHelpers.buildAppAuthRequest=function(client,auth,callback){var requestOptions={client:client,method:UsergridHttpMethod.POST,uri:UsergridHelpers.uri(client,{path:"token"}),body:UsergridHelpers.appLoginBody(auth),callback:callback};return new UsergridRequest(requestOptions)},UsergridHelpers.buildConnectionRequest=function(client,method,args){var options={client:client,method:method,entity:{},to:{},callback:UsergridHelpers.callback(args)};if(UsergridHelpers.assignPrefabOptions.call(options,args),_.isObject(options.from)&&(options.to=options.from),_.isObject(args[0])&&_.has(args[0],"entity")&&_.has(args[0],"to")&&(_.assign(options.entity,args[0].entity),options.relationship=_.get(args,"0.relationship"),_.assign(options.to,args[0].to)),_.isObject(args[0])&&!_.isFunction(args[0])&&_.isString(args[1])&&(_.assign(options.entity,args[0]),options.relationship=_.first([options.relationship,args[1]].filter(_.isString))),_.isObject(args[2])&&!_.isFunction(args[2])&&_.assign(options.to,args[2]),options.entity.uuidOrName=_.first([options.entity.uuidOrName,options.entity.uuid,options.entity.name,args[1]].filter(_.isString)),options.entity.type||(options.entity.type=_.first([options.entity.type,args[0]].filter(_.isString))),options.relationship=_.first([options.relationship,args[2]].filter(_.isString)),_.isString(args[3])&&!UsergridHelpers.isUUID(args[3])&&_.isString(args[4])?options.to.type=args[3]:_.isString(args[2])&&!UsergridHelpers.isUUID(args[2])&&_.isString(args[3])&&_.isObject(args[0])&&!_.isFunction(args[0])&&(options.to.type=args[2]),options.to.uuidOrName=_.first([options.to.uuidOrName,options.to.uuid,options.to.name,args[4],args[3],args[2]].filter(function(property){return _.isString(options.to.type)&&_.isString(property)||UsergridHelpers.isUUID(property)})),!_.isString(options.entity.uuidOrName))throw new Error('source entity "uuidOrName" is required when connecting or disconnecting entities');if(!_.isString(options.to.uuidOrName))throw new Error('target entity "uuidOrName" is required when connecting or disconnecting entities');if(!_.isString(options.to.type)&&!UsergridHelpers.isUUID(options.to.uuidOrName))throw new Error('target "type" (collection name) parameter is required connecting or disconnecting entities by name');return options.uri=UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,_.isString(options.entity.type)?options.entity.type:"",_.isString(options.entity.uuidOrName)?options.entity.uuidOrName:"",options.relationship,_.isString(options.to.type)?options.to.type:"",_.isString(options.to.uuidOrName)?options.to.uuidOrName:""),new UsergridRequest(options)},UsergridHelpers.buildGetConnectionRequest=function(client,args){var options={client:client,method:"GET",callback:UsergridHelpers.callback(args)};if(UsergridHelpers.assignPrefabOptions.call(options,args),_.isObject(args[1])&&!_.isFunction(args[1])&&_.assign(options,args[1]),options.direction=_.first([options.direction,args[0]].filter(function(property){return property===UsergridDirection.IN||property===UsergridDirection.OUT})),options.relationship=_.first([options.relationship,args[3],args[2]].filter(_.isString)),options.uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,args[2]].filter(_.isString)),options.type=_.first([options.type,args[1]].filter(_.isString)),!_.isString(options.type))throw new Error('"type" (collection name) parameter is required when retrieving connections');if(!_.isString(options.uuidOrName))throw new Error('target entity "uuidOrName" is required when retrieving connections');return options.uri=UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,_.isString(options.type)?options.type:"",_.isString(options.uuidOrName)?options.uuidOrName:"",options.direction,options.relationship),new UsergridRequest(options)},global[name]=UsergridHelpers,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),UsergridHelpers},global[name]}(this);var UsergridClientDefaultOptions={baseUrl:"https://api.usergrid.com",authMode:UsergridAuthMode.USER},UsergridClient=function(options){var __appAuth,self=this;if(self.tempAuth=void 0,self.isSharedInstance=!1,2===arguments.length&&(self.orgId=arguments[0],self.appId=arguments[1]),_.defaults(self,options,UsergridClientDefaultOptions),!self.orgId||!self.appId)throw new Error('"orgId" and "appId" parameters are required when instantiating UsergridClient');return Object.defineProperty(self,"clientId",{enumerable:!1}),Object.defineProperty(self,"clientSecret",{enumerable:!1}),Object.defineProperty(self,"appAuth",{get:function(){return __appAuth},set:function(options){options instanceof UsergridAppAuth?__appAuth=options:"undefined"!=typeof options&&(__appAuth=new UsergridAppAuth(options))}}),self.clientId&&self.clientSecret&&self.setAppAuth(self.clientId,self.clientSecret),self};UsergridClient.prototype={sendRequest:function(usergridRequest){return usergridRequest.sendRequest()},GET:function(){var usergridRequest=UsergridHelpers.buildReqest(this,UsergridHttpMethod.GET,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},PUT:function(){var usergridRequest=UsergridHelpers.buildReqest(this,UsergridHttpMethod.PUT,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},POST:function(){var usergridRequest=UsergridHelpers.buildReqest(this,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},DELETE:function(){var usergridRequest=UsergridHelpers.buildReqest(this,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},connect:function(){var usergridRequest=UsergridHelpers.buildConnectionRequest(this,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},disconnect:function(){var usergridRequest=UsergridHelpers.buildConnectionRequest(this,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},getConnections:function(){var usergridRequest=UsergridHelpers.buildGetConnectionRequest(this,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},usingAuth:function(auth){var self=this;return _.isString(auth)?self.tempAuth=new UsergridAuth(auth):auth instanceof UsergridAuth?self.tempAuth=auth:self.tempAuth=void 0,self},setAppAuth:function(){this.appAuth=new UsergridAppAuth(UsergridHelpers.flattenArgs(arguments))},authenticateApp:function(options){var self=this,authenticateAppCallback=UsergridHelpers.callback(UsergridHelpers.flattenArgs(arguments)),auth=_.first([options,self.appAuth,new UsergridAppAuth(options),new UsergridAppAuth(self.clientId,self.clientSecret)].filter(function(p){return p instanceof UsergridAppAuth}));if(!(auth instanceof UsergridAppAuth))throw new Error("App auth context was not defined when attempting to call .authenticateApp()");if(!auth.clientId||!auth.clientSecret)throw new Error("authenticateApp() failed because clientId or clientSecret are missing");var callback=function(error,usergridResponse){var token=_.get(usergridResponse.responseJSON,"access_token"),expiresIn=_.get(usergridResponse.responseJSON,"expires_in");usergridResponse.ok&&(self.appAuth||(self.appAuth=auth),self.appAuth.token=token,self.appAuth.expiry=UsergridHelpers.calculateExpiry(expiresIn),self.appAuth.tokenTtl=expiresIn),authenticateAppCallback(error,usergridResponse,token)},usergridRequest=UsergridHelpers.buildAppAuthRequest(self,auth,callback);return self.sendRequest(usergridRequest)},authenticateUser:function(options){var self=this,args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args),setAsCurrentUser=void 0!==_.last(args.filter(_.isBoolean))?_.last(args.filter(_.isBoolean)):!0,userToAuthenticate=new UsergridUser(options);userToAuthenticate.login(self,function(error,usergridResponse,token){usergridResponse.ok&&setAsCurrentUser&&(self.currentUser=userToAuthenticate),callback(usergridResponse.error,usergridResponse,token)})},downloadAsset:function(){var self=this,usergridRequest=UsergridHelpers.buildReqest(self,UsergridHttpMethod.GET,UsergridHelpers.flattenArgs(arguments)),assetContentType=_.get(usergridRequest,"entity.file-metadata.content-type");void 0!==assetContentType&&_.assign(usergridRequest.headers,{Accept:assetContentType});var realDownloadAssetCallback=usergridRequest.callback;return usergridRequest.callback=function(error,usergridResponse){var entity=usergridRequest.entity;entity.asset=usergridResponse.asset,realDownloadAssetCallback(error,usergridResponse,entity)},self.sendRequest(usergridRequest)},uploadAsset:function(){var self=this,usergridRequest=UsergridHelpers.buildReqest(self,UsergridHttpMethod.PUT,UsergridHelpers.flattenArgs(arguments));if(void 0===usergridRequest.asset)throw new Error("An UsergridAsset was not defined when attempting to call .uploadAsset()");var realUploadAssetCallback=usergridRequest.callback;return usergridRequest.callback=function(error,usergridResponse){var requestEntity=usergridRequest.entity,responseEntity=usergridResponse.entity,requestAsset=usergridRequest.asset;usergridResponse.ok&&void 0!==responseEntity&&(UsergridHelpers.updateEntityFromRemote(requestEntity,usergridResponse),requestEntity.asset=requestAsset,responseEntity&&(responseEntity.asset=requestAsset)),realUploadAssetCallback(error,usergridResponse,requestEntity)},self.sendRequest(usergridRequest)}};var UsergridSDKVersion="2.0.0",UsergridClientSharedInstance=function(){var self=this;return self.isInitialized=!1,self.isSharedInstance=!0,self};UsergridHelpers.inherits(UsergridClientSharedInstance,UsergridClient);var Usergrid=new UsergridClientSharedInstance;Usergrid.initSharedInstance=function(options){return Usergrid.isInitialized?console.log("Usergrid shared instance is already initialized"):(_.assign(Usergrid,new UsergridClient(options)),Usergrid.isInitialized=!0,Usergrid.isSharedInstance=!0),Usergrid},Usergrid.init=Usergrid.initSharedInstance;var UsergridQuery=function(type){var queryString,sort,self=this,query="",urlTerms={},__nextIsNot=!1;return self._type=type,_.assign(self,{type:function(value){return self._type=value,self},collection:function(value){return self._type=value,self},limit:function(value){return self._limit=value,self},cursor:function(value){return self._cursor=value,self},eq:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.EQUAL+" "+UsergridHelpers.useQuotesIfRequired(value)),self},equal:this.eq,gt:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.GREATER_THAN+" "+UsergridHelpers.useQuotesIfRequired(value)),self},greaterThan:this.gt,gte:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.GREATER_THAN_EQUAL_TO+" "+UsergridHelpers.useQuotesIfRequired(value)),self},greaterThanOrEqual:this.gte,lt:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.LESS_THAN+" "+UsergridHelpers.useQuotesIfRequired(value)),self},lessThan:this.lt,lte:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.LESS_THAN_EQUAL_TO+" "+UsergridHelpers.useQuotesIfRequired(value)),self},lessThanOrEqual:this.lte,contains:function(key,value){return query=self.andJoin(key+" contains "+UsergridHelpers.useQuotesIfRequired(value)),self},locationWithin:function(distanceInMeters,lat,lng){return query=self.andJoin("location within "+distanceInMeters+" of "+lat+", "+lng),self},asc:function(key){return self.sort(key,UsergridQuerySortOrder.ASC),self},desc:function(key){return self.sort(key,UsergridQuerySortOrder.DESC),self},sort:function(key,order){return sort=key&&order?" order by "+key+" "+order:"",self},fromString:function(string){return queryString=string,self},urlTerm:function(key,value){return"ql"===key?self.fromString():urlTerms[key]=value,self},andJoin:function(append){ -return __nextIsNot&&(append="not "+append,__nextIsNot=!1),append?0===query.length?append:_.endsWith(query,"and")||_.endsWith(query,"or")?query+" "+append:query+" and "+append:query},orJoin:function(){return query.length>0&&!_.endsWith(query,"or")?query+" or":query}}),Object.defineProperty(self,"_ql",{get:function(){var ql="select * ";return void 0!==queryString?ql=queryString:(ql+=query.length>0?"where "+(query||""):"",ql+=void 0!==sort?sort:""),ql}}),Object.defineProperty(self,"encodedStringValue",{get:function(){var self=this,limit=self._limit,cursor=self._cursor,requirementsString=self._ql,returnString=void 0;if(void 0!==limit&&(returnString="limit"+UsergridQueryOperator.EQUAL+limit),!_.isEmpty(cursor)){var cursorString="cursor"+UsergridQueryOperator.EQUAL+cursor;_.isEmpty(returnString)?returnString=cursorString:returnString+="&"+cursorString}if(_.forEach(urlTerms,function(value,key){var encodedURLTermString=encodeURIComponent(key)+UsergridQueryOperator.EQUAL+encodeURIComponent(value);_.isEmpty(returnString)?returnString=encodedURLTermString:returnString+="&"+encodedURLTermString}),!_.isEmpty(requirementsString)){var qLString="ql="+encodeURIComponent(requirementsString);_.isEmpty(returnString)?returnString=qLString:returnString+="&"+qLString}return _.isEmpty(returnString)||(returnString="?"+returnString),_.isEmpty(returnString)?void 0:returnString}}),Object.defineProperty(self,"and",{get:function(){return query=self.andJoin(""),self}}),Object.defineProperty(self,"or",{get:function(){return query=self.orJoin(),self}}),Object.defineProperty(self,"not",{get:function(){return __nextIsNot=!0,self}}),self},UsergridRequest=function(options){var self=this,client=UsergridHelpers.validateAndRetrieveClient(options);if(!_.isString(options.type)&&!_.isString(options.path)&&!_.isString(options.uri))throw new Error('one of "type" (collection name), "path", or "uri" parameters are required when initializing a UsergridRequest');if(!_.includes(["GET","PUT","POST","DELETE"],options.method))throw new Error('"method" parameter is required when initializing a UsergridRequest');self.method=options.method,self.callback=options.callback,self.uri=options.uri||UsergridHelpers.uri(client,options),self.entity=options.entity,self.body=options.body||void 0,self.asset=options.asset||void 0,self.query=options.query,self.queryParams=options.queryParams||options.qs;var defaultHeadersToUse=void 0===self.asset?UsergridHelpers.DefaultHeaders:{};if(self.headers=UsergridHelpers.headers(client,options,defaultHeadersToUse),void 0!==self.query&&(self.uri+=UsergridHelpers.normalize(self.query.encodedStringValue,{})),void 0!==self.queryParams&&(_.forOwn(self.queryParams,function(value,key){self.uri+="?"+encodeURIComponent(key)+UsergridQueryOperator.EQUAL+encodeURIComponent(value)}),self.uri=UsergridHelpers.normalize(self.uri,{})),void 0!==self.asset)self.body=new FormData,self.body.append(self.asset.filename,self.asset.data);else try{_.isPlainObject(self.body)?self.body=JSON.stringify(self.body):_.isArray(self.body)&&(self.body=JSON.stringify(self.body))}catch(exception){}return self};UsergridRequest.prototype.sendRequest=function(){var self=this,requestPromise=function(){var promise=new Promise,xmlHttpRequest=new XMLHttpRequest;return xmlHttpRequest.open(self.method,self.uri,!0),xmlHttpRequest.onload=function(){promise.done(xmlHttpRequest)},_.forOwn(self.headers,function(value,key){xmlHttpRequest.setRequestHeader(key,value)}),self.method===UsergridHttpMethod.GET&&_.get(self.headers,"Accept")!==UsergridApplicationJSONHeaderValue&&(xmlHttpRequest.responseType="blob"),xmlHttpRequest.send(self.body),promise},responsePromise=function(xmlRequest){var promise=new Promise,usergridResponse=new UsergridResponse(xmlRequest,self);return promise.done(usergridResponse),promise},onCompletePromise=function(usergridResponse){self.callback(usergridResponse.error,usergridResponse)};return Promise.chain([requestPromise,responsePromise]).then(onCompletePromise),self};var UsergridAuth=function(token,expiry){var self=this;self.token=token,self.expiry=expiry||0;var usingToken=token?!0:!1;return Object.defineProperty(self,"hasToken",{get:function(){return void 0!==self.token},configurable:!0}),Object.defineProperty(self,"isExpired",{get:function(){return usingToken?!1:Date.now()>=self.expiry},configurable:!0}),Object.defineProperty(self,"isValid",{get:function(){return!self.isExpired&&self.hasToken},configurable:!0}),Object.defineProperty(self,"tokenTtl",{configurable:!0,writable:!0}),_.assign(self,{destroy:function(){self.token=void 0,self.expiry=0,self.tokenTtl=void 0}}),self},UsergridAppAuth=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments);return _.isPlainObject(args[0])?(self.clientId=args[0].clientId,self.clientSecret=args[0].clientSecret,self.tokenTtl=args[0].tokenTtl):(self.clientId=args[0],self.clientSecret=args[1],self.tokenTtl=args[2]),UsergridAuth.call(self),_.assign(self,UsergridAuth),self};UsergridHelpers.inherits(UsergridAppAuth,UsergridAuth);var UsergridUserAuth=function(options){var self=this,args=_.flattenDeep(UsergridHelpers.flattenArgs(arguments));return _.isPlainObject(args[0])&&(options=args[0]),self.username=options.username||args[0],self.email=options.email,(options.password||args[1])&&(self.password=options.password||args[1]),self.tokenTtl=options.tokenTtl||args[2],UsergridAuth.call(self),_.assign(self,UsergridAuth),self};UsergridHelpers.inherits(UsergridUserAuth,UsergridAuth);var UsergridEntity=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments);if(0===args.length)throw new Error("A UsergridEntity object cannot be initialized without passing one or more arguments");if(self.asset=void 0,_.isPlainObject(args[0])?_.assign(self,args[0]):(self.type||(self.type=_.isString(args[0])?args[0]:void 0),self.name||(self.name=_.isString(args[1])?args[1]:void 0)),!_.isString(self.type))throw new Error('"type" (or "collection") parameter is required when initializing a UsergridEntity object');return Object.defineProperty(self,"isUser",{get:function(){return"user"===self.type.toLowerCase()}}),Object.defineProperty(self,"hasAsset",{get:function(){return _.has(self,"file-metadata")}}),UsergridHelpers.setReadOnly(self,["uuid","name","type","created"]),self};UsergridEntity.prototype={jsonValue:function(){var jsonValue={};return _.forOwn(this,function(value,key){jsonValue[key]=value}),jsonValue},putProperty:function(key,value){this[key]=value},putProperties:function(obj){_.assign(this,obj)},removeProperty:function(key){this.removeProperties([key])},removeProperties:function(keys){var self=this;keys.forEach(function(key){delete self[key]})},insert:function(key,value,idx){_.isArray(this[key])||(this[key]=this[key]?[this[key]]:[]),this[key].splice.apply(this[key],[idx,0].concat(value))},append:function(key,value){this.insert(key,value,Number.MAX_VALUE)},prepend:function(key,value){this.insert(key,value,0)},pop:function(key){_.isArray(this[key])&&this[key].pop()},shift:function(key){_.isArray(this[key])&&this[key].shift()},reload:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.GET(self,function(error,usergridResponse){UsergridHelpers.updateEntityFromRemote(self,usergridResponse),callback(error,usergridResponse,self)}.bind(self))},save:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args),currentAsset=self.asset;client.PUT(self,function(error,usergridResponse){UsergridHelpers.updateEntityFromRemote(self,usergridResponse),self.hasAsset&&(self.asset=currentAsset),callback(error,usergridResponse,self)}.bind(self))},remove:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.DELETE(self,function(error,usergridResponse){callback(error,usergridResponse,self)}.bind(self))},attachAsset:function(asset){this.asset=asset},uploadAsset:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(_.has(self,"asset.contentType"))client.uploadAsset(self,callback);else{var response=new UsergridResponse.responseWithError({name:"asset_not_found",description:"The specified entity does not have a valid asset attached"});callback(response.error,response,self)}},downloadAsset:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(_.has(self,"asset.contentType"))client.downloadAsset(self,callback);else{var response=new UsergridResponse.responseWithError({name:"asset_not_found",description:"The specified entity does not have a valid asset attached"});callback(response.error,response,self)}},connect:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args[0]=this,client.connect.apply(client,args)},disconnect:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args[0]=this,client.disconnect.apply(client,args)},getConnections:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args.shift(),args.splice(1,0,this),client.getConnections.apply(client,args)}};var UsergridUser=function(obj){if(!_.has(obj,"email")&&!_.has(obj,"username"))throw new Error('"email" or "username" property is required when initializing a UsergridUser object');var self=this;return _.assign(self,obj,UsergridEntity),UsergridEntity.call(self,"user"),UsergridHelpers.setWritable(self,"name"),self};UsergridUser.CheckAvailable=function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);args[0]instanceof UsergridClient&&args.shift();var checkQuery,callback=UsergridHelpers.callback(args);if(args[0].username&&args[0].email)checkQuery=new UsergridQuery("users").eq("username",args[0].username).or.eq("email",args[0].email);else if(args[0].username)checkQuery=new UsergridQuery("users").eq("username",args[0].username);else{if(!args[0].email)throw new Error("'username' or 'email' property is required when checking for available users");checkQuery=new UsergridQuery("users").eq("email",args[0].email)}client.GET(checkQuery,function(error,usergridResponse){callback(error,usergridResponse,usergridResponse.entities.length>0)})},UsergridHelpers.inherits(UsergridUser,UsergridEntity),UsergridUser.prototype.uniqueId=function(){var self=this;return _.first([self.uuid,self.username,self.email].filter(_.isString))},UsergridUser.prototype.create=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.POST(self,function(error,usergridResponse){delete self.password,_.assign(self,usergridResponse.user),callback(error,usergridResponse,self)}.bind(self))},UsergridUser.prototype.login=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.POST("token",UsergridHelpers.userLoginBody(self),function(error,usergridResponse){delete self.password;var responseJSON=usergridResponse.responseJSON,token=_.get(responseJSON,"access_token"),expiresIn=_.get(responseJSON,"expires_in");usergridResponse.ok&&(self.auth=new UsergridUserAuth(self),self.auth.token=token,self.auth.expiry=UsergridHelpers.calculateExpiry(expiresIn),self.auth.tokenTtl=expiresIn),callback(error,usergridResponse,token)})},UsergridUser.prototype.logout=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(self.auth&&self.auth.isValid){var revokeAll=_.first(args.filter(_.isBoolean))||!1,queryParams=void 0;revokeAll||(queryParams={token:self.auth.token});var requestOptions={client:client,path:["users",self.uniqueId(),"revoketoken"+(revokeAll?"s":"")].join("/"),method:UsergridHttpMethod.PUT,queryParams:queryParams,callback:function(error,usergridResponse){self.auth.destroy(),callback(error,usergridResponse,usergridResponse.ok)}.bind(self)},request=new UsergridRequest(requestOptions);client.sendRequest(request)}else{var response=new UsergridResponse.responseWithError({name:"no_valid_token",description:"this user does not have a valid token"});callback(response.error,response)}},UsergridUser.prototype.logoutAllSessions=function(){var args=UsergridHelpers.flattenArgs(arguments);return args=_.concat([UsergridHelpers.validateAndRetrieveClient(args),!0],args),this.logout.apply(this,args)},UsergridUser.prototype.resetPassword=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);args[0]instanceof UsergridClient&&args.shift();var body={oldpassword:_.isPlainObject(args[0])?args[0].oldPassword:_.isString(args[0])?args[0]:void 0,newpassword:_.isPlainObject(args[0])?args[0].newPassword:_.isString(args[1])?args[1]:void 0};if(!body.oldpassword||!body.newpassword)throw new Error('"oldPassword" and "newPassword" properties are required when resetting a user password');client.PUT(["users",self.uniqueId(),"password"].join("/"),body,callback)};var UsergridResponseError=function(options){var self=this;return _.assign(self,options),self};UsergridResponseError.fromJSON=function(responseErrorObject){var usergridResponseError=void 0,error={name:_.get(responseErrorObject,"error")};return void 0!==error.name&&(_.assign(error,{exception:_.get(responseErrorObject,"exception"),description:_.get(responseErrorObject,"error_description")||_.get(responseErrorObject,"description")}),usergridResponseError=new UsergridResponseError(error)),usergridResponseError};var UsergridResponse=function(xmlRequest,usergridRequest){var self=this;if(self.ok=!1,self.request=usergridRequest,xmlRequest){self.statusCode=parseInt(xmlRequest.status),self.ok=self.statusCode<400,self.headers=UsergridHelpers.parseResponseHeaders(xmlRequest.getAllResponseHeaders());var responseContentType=_.get(self.headers,"content-type");if("application/json"===responseContentType){try{var responseJSON=JSON.parse(xmlRequest.responseText)}catch(e){responseJSON={}}self.parseResponseJSON(responseJSON),Object.defineProperty(self,"cursor",{get:function(){return _.get(self,"responseJSON.cursor")}}),Object.defineProperty(self,"hasNextPage",{get:function(){return void 0!==self.cursor}})}else self.asset=new UsergridAsset(xmlRequest.response)}return self};UsergridResponse.responseWithError=function(options){var usergridResponse=new UsergridResponse;return usergridResponse.error=new UsergridResponseError(options),usergridResponse},UsergridResponse.prototype={parseResponseJSON:function(responseJSON){var self=this;if(void 0!==responseJSON)if(_.assign(self,{responseJSON:_.cloneDeep(responseJSON)}),self.ok){var entitiesJSON=_.get(responseJSON,"entities");if(entitiesJSON){var entities=_.map(entitiesJSON,function(entityJSON){var entity=new UsergridEntity(entityJSON);return entity.isUser&&(entity=new UsergridUser(entity)),entity});_.assign(self,{entities:entities}),delete self.responseJSON.entities,self.first=_.first(entities)||void 0,self.entity=self.first,self.last=_.last(entities)||void 0,"/users"===_.get(responseJSON,"path")&&(self.user=self.first,self.users=self.entities),UsergridHelpers.setReadOnly(self.responseJSON)}}else self.error=UsergridResponseError.fromJSON(responseJSON)},loadNextPage:function(){var self=this,cursor=self.cursor;if(cursor){var args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args),client=UsergridHelpers.validateAndRetrieveClient(args),type=_.last(_.get(self,"responseJSON.path").split("/")),limit=_.first(_.get(self,"responseJSON.params.limit")),ql=_.first(_.get(self,"responseJSON.params.ql")),query=new UsergridQuery(type).fromString(ql).cursor(cursor).limit(limit);client.GET(query,callback)}else callback(UsergridResponse.responseWithError({name:"cursor_not_found",description:"Cursor must be present in order perform loadNextPage()."}))}};var UsergridAssetDefaultFileName="file",UsergridAsset=function(fileOrBlob){if(!fileOrBlob instanceof File||!fileOrBlob instanceof Blob)throw new Error("UsergridAsset must be initialized with a 'File' or 'Blob'");var self=this;return self.data=fileOrBlob,self.filename=fileOrBlob.name||UsergridAssetDefaultFileName,self.contentLength=fileOrBlob.size,self.contentType=fileOrBlob.type,self}; \ No newline at end of file +lodash.memoize=memoize,lodash.merge=merge,lodash.mergeWith=mergeWith,lodash.method=method,lodash.methodOf=methodOf,lodash.mixin=mixin,lodash.negate=negate,lodash.nthArg=nthArg,lodash.omit=omit,lodash.omitBy=omitBy,lodash.once=once,lodash.orderBy=orderBy,lodash.over=over,lodash.overArgs=overArgs,lodash.overEvery=overEvery,lodash.overSome=overSome,lodash.partial=partial,lodash.partialRight=partialRight,lodash.partition=partition,lodash.pick=pick,lodash.pickBy=pickBy,lodash.property=property,lodash.propertyOf=propertyOf,lodash.pull=pull,lodash.pullAll=pullAll,lodash.pullAllBy=pullAllBy,lodash.pullAllWith=pullAllWith,lodash.pullAt=pullAt,lodash.range=range,lodash.rangeRight=rangeRight,lodash.rearg=rearg,lodash.reject=reject,lodash.remove=remove,lodash.rest=rest,lodash.reverse=reverse,lodash.sampleSize=sampleSize,lodash.set=set,lodash.setWith=setWith,lodash.shuffle=shuffle,lodash.slice=slice,lodash.sortBy=sortBy,lodash.sortedUniq=sortedUniq,lodash.sortedUniqBy=sortedUniqBy,lodash.split=split,lodash.spread=spread,lodash.tail=tail,lodash.take=take,lodash.takeRight=takeRight,lodash.takeRightWhile=takeRightWhile,lodash.takeWhile=takeWhile,lodash.tap=tap,lodash.throttle=throttle,lodash.thru=thru,lodash.toArray=toArray,lodash.toPairs=toPairs,lodash.toPairsIn=toPairsIn,lodash.toPath=toPath,lodash.toPlainObject=toPlainObject,lodash.transform=transform,lodash.unary=unary,lodash.union=union,lodash.unionBy=unionBy,lodash.unionWith=unionWith,lodash.uniq=uniq,lodash.uniqBy=uniqBy,lodash.uniqWith=uniqWith,lodash.unset=unset,lodash.unzip=unzip,lodash.unzipWith=unzipWith,lodash.update=update,lodash.updateWith=updateWith,lodash.values=values,lodash.valuesIn=valuesIn,lodash.without=without,lodash.words=words,lodash.wrap=wrap,lodash.xor=xor,lodash.xorBy=xorBy,lodash.xorWith=xorWith,lodash.zip=zip,lodash.zipObject=zipObject,lodash.zipObjectDeep=zipObjectDeep,lodash.zipWith=zipWith,lodash.entries=toPairs,lodash.entriesIn=toPairsIn,lodash.extend=assignIn,lodash.extendWith=assignInWith,mixin(lodash,lodash),lodash.add=add,lodash.attempt=attempt,lodash.camelCase=camelCase,lodash.capitalize=capitalize,lodash.ceil=ceil,lodash.clamp=clamp,lodash.clone=clone,lodash.cloneDeep=cloneDeep,lodash.cloneDeepWith=cloneDeepWith,lodash.cloneWith=cloneWith,lodash.conformsTo=conformsTo,lodash.deburr=deburr,lodash.defaultTo=defaultTo,lodash.divide=divide,lodash.endsWith=endsWith,lodash.eq=eq,lodash.escape=escape,lodash.escapeRegExp=escapeRegExp,lodash.every=every,lodash.find=find,lodash.findIndex=findIndex,lodash.findKey=findKey,lodash.findLast=findLast,lodash.findLastIndex=findLastIndex,lodash.findLastKey=findLastKey,lodash.floor=floor,lodash.forEach=forEach,lodash.forEachRight=forEachRight,lodash.forIn=forIn,lodash.forInRight=forInRight,lodash.forOwn=forOwn,lodash.forOwnRight=forOwnRight,lodash.get=get,lodash.gt=gt,lodash.gte=gte,lodash.has=has,lodash.hasIn=hasIn,lodash.head=head,lodash.identity=identity,lodash.includes=includes,lodash.indexOf=indexOf,lodash.inRange=inRange,lodash.invoke=invoke,lodash.isArguments=isArguments,lodash.isArray=isArray,lodash.isArrayBuffer=isArrayBuffer,lodash.isArrayLike=isArrayLike,lodash.isArrayLikeObject=isArrayLikeObject,lodash.isBoolean=isBoolean,lodash.isBuffer=isBuffer,lodash.isDate=isDate,lodash.isElement=isElement,lodash.isEmpty=isEmpty,lodash.isEqual=isEqual,lodash.isEqualWith=isEqualWith,lodash.isError=isError,lodash.isFinite=isFinite,lodash.isFunction=isFunction,lodash.isInteger=isInteger,lodash.isLength=isLength,lodash.isMap=isMap,lodash.isMatch=isMatch,lodash.isMatchWith=isMatchWith,lodash.isNaN=isNaN,lodash.isNative=isNative,lodash.isNil=isNil,lodash.isNull=isNull,lodash.isNumber=isNumber,lodash.isObject=isObject,lodash.isObjectLike=isObjectLike,lodash.isPlainObject=isPlainObject,lodash.isRegExp=isRegExp,lodash.isSafeInteger=isSafeInteger,lodash.isSet=isSet,lodash.isString=isString,lodash.isSymbol=isSymbol,lodash.isTypedArray=isTypedArray,lodash.isUndefined=isUndefined,lodash.isWeakMap=isWeakMap,lodash.isWeakSet=isWeakSet,lodash.join=join,lodash.kebabCase=kebabCase,lodash.last=last,lodash.lastIndexOf=lastIndexOf,lodash.lowerCase=lowerCase,lodash.lowerFirst=lowerFirst,lodash.lt=lt,lodash.lte=lte,lodash.max=max,lodash.maxBy=maxBy,lodash.mean=mean,lodash.meanBy=meanBy,lodash.min=min,lodash.minBy=minBy,lodash.stubArray=stubArray,lodash.stubFalse=stubFalse,lodash.stubObject=stubObject,lodash.stubString=stubString,lodash.stubTrue=stubTrue,lodash.multiply=multiply,lodash.nth=nth,lodash.noConflict=noConflict,lodash.noop=noop,lodash.now=now,lodash.pad=pad,lodash.padEnd=padEnd,lodash.padStart=padStart,lodash.parseInt=parseInt,lodash.random=random,lodash.reduce=reduce,lodash.reduceRight=reduceRight,lodash.repeat=repeat,lodash.replace=replace,lodash.result=result,lodash.round=round,lodash.runInContext=runInContext,lodash.sample=sample,lodash.size=size,lodash.snakeCase=snakeCase,lodash.some=some,lodash.sortedIndex=sortedIndex,lodash.sortedIndexBy=sortedIndexBy,lodash.sortedIndexOf=sortedIndexOf,lodash.sortedLastIndex=sortedLastIndex,lodash.sortedLastIndexBy=sortedLastIndexBy,lodash.sortedLastIndexOf=sortedLastIndexOf,lodash.startCase=startCase,lodash.startsWith=startsWith,lodash.subtract=subtract,lodash.sum=sum,lodash.sumBy=sumBy,lodash.template=template,lodash.times=times,lodash.toFinite=toFinite,lodash.toInteger=toInteger,lodash.toLength=toLength,lodash.toLower=toLower,lodash.toNumber=toNumber,lodash.toSafeInteger=toSafeInteger,lodash.toString=toString,lodash.toUpper=toUpper,lodash.trim=trim,lodash.trimEnd=trimEnd,lodash.trimStart=trimStart,lodash.truncate=truncate,lodash.unescape=unescape,lodash.uniqueId=uniqueId,lodash.upperCase=upperCase,lodash.upperFirst=upperFirst,lodash.each=forEach,lodash.eachRight=forEachRight,lodash.first=head,mixin(lodash,function(){var source={};return baseForOwn(lodash,function(func,methodName){hasOwnProperty.call(lodash.prototype,methodName)||(source[methodName]=func)}),source}(),{chain:!1}),lodash.VERSION=VERSION,arrayEach(["bind","bindKey","curry","curryRight","partial","partialRight"],function(methodName){lodash[methodName].placeholder=lodash}),arrayEach(["drop","take"],function(methodName,index){LazyWrapper.prototype[methodName]=function(n){var filtered=this.__filtered__;if(filtered&&!index)return new LazyWrapper(this);n=n===undefined?1:nativeMax(toInteger(n),0);var result=this.clone();return filtered?result.__takeCount__=nativeMin(n,result.__takeCount__):result.__views__.push({size:nativeMin(n,MAX_ARRAY_LENGTH),type:methodName+(result.__dir__<0?"Right":"")}),result},LazyWrapper.prototype[methodName+"Right"]=function(n){return this.reverse()[methodName](n).reverse()}}),arrayEach(["filter","map","takeWhile"],function(methodName,index){var type=index+1,isFilter=type==LAZY_FILTER_FLAG||type==LAZY_WHILE_FLAG;LazyWrapper.prototype[methodName]=function(iteratee){var result=this.clone();return result.__iteratees__.push({iteratee:getIteratee(iteratee,3),type:type}),result.__filtered__=result.__filtered__||isFilter,result}}),arrayEach(["head","last"],function(methodName,index){var takeName="take"+(index?"Right":"");LazyWrapper.prototype[methodName]=function(){return this[takeName](1).value()[0]}}),arrayEach(["initial","tail"],function(methodName,index){var dropName="drop"+(index?"":"Right");LazyWrapper.prototype[methodName]=function(){return this.__filtered__?new LazyWrapper(this):this[dropName](1)}}),LazyWrapper.prototype.compact=function(){return this.filter(identity)},LazyWrapper.prototype.find=function(predicate){return this.filter(predicate).head()},LazyWrapper.prototype.findLast=function(predicate){return this.reverse().find(predicate)},LazyWrapper.prototype.invokeMap=baseRest(function(path,args){return"function"==typeof path?new LazyWrapper(this):this.map(function(value){return baseInvoke(value,path,args)})}),LazyWrapper.prototype.reject=function(predicate){return this.filter(negate(getIteratee(predicate)))},LazyWrapper.prototype.slice=function(start,end){start=toInteger(start);var result=this;return result.__filtered__&&(start>0||0>end)?new LazyWrapper(result):(0>start?result=result.takeRight(-start):start&&(result=result.drop(start)),end!==undefined&&(end=toInteger(end),result=0>end?result.dropRight(-end):result.take(end-start)),result)},LazyWrapper.prototype.takeRightWhile=function(predicate){return this.reverse().takeWhile(predicate).reverse()},LazyWrapper.prototype.toArray=function(){return this.take(MAX_ARRAY_LENGTH)},baseForOwn(LazyWrapper.prototype,function(func,methodName){var checkIteratee=/^(?:filter|find|map|reject)|While$/.test(methodName),isTaker=/^(?:head|last)$/.test(methodName),lodashFunc=lodash[isTaker?"take"+("last"==methodName?"Right":""):methodName],retUnwrapped=isTaker||/^find/.test(methodName);lodashFunc&&(lodash.prototype[methodName]=function(){var value=this.__wrapped__,args=isTaker?[1]:arguments,isLazy=value instanceof LazyWrapper,iteratee=args[0],useLazy=isLazy||isArray(value),interceptor=function(value){var result=lodashFunc.apply(lodash,arrayPush([value],args));return isTaker&&chainAll?result[0]:result};useLazy&&checkIteratee&&"function"==typeof iteratee&&1!=iteratee.length&&(isLazy=useLazy=!1);var chainAll=this.__chain__,isHybrid=!!this.__actions__.length,isUnwrapped=retUnwrapped&&!chainAll,onlyLazy=isLazy&&!isHybrid;if(!retUnwrapped&&useLazy){value=onlyLazy?value:new LazyWrapper(this);var result=func.apply(value,args);return result.__actions__.push({func:thru,args:[interceptor],thisArg:undefined}),new LodashWrapper(result,chainAll)}return isUnwrapped&&onlyLazy?func.apply(this,args):(result=this.thru(interceptor),isUnwrapped?isTaker?result.value()[0]:result.value():result)})}),arrayEach(["pop","push","shift","sort","splice","unshift"],function(methodName){var func=arrayProto[methodName],chainName=/^(?:push|sort|unshift)$/.test(methodName)?"tap":"thru",retUnwrapped=/^(?:pop|shift)$/.test(methodName);lodash.prototype[methodName]=function(){var args=arguments;if(retUnwrapped&&!this.__chain__){var value=this.value();return func.apply(isArray(value)?value:[],args)}return this[chainName](function(value){return func.apply(isArray(value)?value:[],args)})}}),baseForOwn(LazyWrapper.prototype,function(func,methodName){var lodashFunc=lodash[methodName];if(lodashFunc){var key=lodashFunc.name+"",names=realNames[key]||(realNames[key]=[]);names.push({name:methodName,func:lodashFunc})}}),realNames[createHybrid(undefined,BIND_KEY_FLAG).name]=[{name:"wrapper",func:undefined}],LazyWrapper.prototype.clone=lazyClone,LazyWrapper.prototype.reverse=lazyReverse,LazyWrapper.prototype.value=lazyValue,lodash.prototype.at=wrapperAt,lodash.prototype.chain=wrapperChain,lodash.prototype.commit=wrapperCommit,lodash.prototype.next=wrapperNext,lodash.prototype.plant=wrapperPlant,lodash.prototype.reverse=wrapperReverse,lodash.prototype.toJSON=lodash.prototype.valueOf=lodash.prototype.value=wrapperValue,lodash.prototype.first=lodash.prototype.head,iteratorSymbol&&(lodash.prototype[iteratorSymbol]=wrapperToIterator),lodash},_=runInContext();"function"==typeof define&&"object"==typeof define.amd&&define.amd?(root._=_,define(function(){return _})):freeModule?((freeModule.exports=_)._=_,freeExports._=_):root._=_}.call(this);var UsergridAuthMode=Object.freeze({NONE:"none",USER:"user",APP:"app"}),UsergridDirection=Object.freeze({IN:"connecting",OUT:"connections"}),UsergridHttpMethod=Object.freeze({GET:"GET",PUT:"PUT",POST:"POST",DELETE:"DELETE"}),UsergridQueryOperator=Object.freeze({EQUAL:"=",GREATER_THAN:">",GREATER_THAN_EQUAL_TO:">=",LESS_THAN:"<",LESS_THAN_EQUAL_TO:"<="}),UsergridQuerySortOrder=Object.freeze({ASC:"asc",DESC:"desc"}),UsergridApplicationJSONHeaderValue="application/json";!function(global){function UsergridHelpers(){}var name="UsergridHelpers",overwrittenName=global[name];UsergridHelpers.DefaultHeaders=Object.freeze({"Content-Type":UsergridApplicationJSONHeaderValue,Accept:UsergridApplicationJSONHeaderValue}),UsergridHelpers.validateAndRetrieveClient=function(args){var client=_.first([args,args[0],_.get(args,"client"),Usergrid.isInitialized?Usergrid:void 0].filter(function(client){return client instanceof UsergridClient}));if(!client)throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument");return client},UsergridHelpers.inherits=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})},UsergridHelpers.flattenArgs=function(args){return _.flattenDeep(Array.prototype.slice.call(args))},UsergridHelpers.callback=function(){var args=UsergridHelpers.flattenArgs(arguments).reverse(),emptyFunc=function(){};return _.first(_.flattenDeep([args,_.get(args,"0.callback"),emptyFunc]).filter(_.isFunction))},UsergridHelpers.authForRequests=function(client){var authForRequests=void 0;return _.get(client,"tempAuth.isValid")?(authForRequests=client.tempAuth,client.tempAuth=void 0):_.get(client,"currentUser.auth.isValid")&&client.authMode===UsergridAuthMode.USER?authForRequests=client.currentUser.auth:_.get(client,"appAuth.isValid")&&client.authMode===UsergridAuthMode.APP&&(authForRequests=client.appAuth),authForRequests},UsergridHelpers.userLoginBody=function(options){var body={grant_type:"password",password:options.password};return options.tokenTtl&&(body.ttl=options.tokenTtl),body[options.username?"username":"email"]=options.username?options.username:options.email,body},UsergridHelpers.appLoginBody=function(options){var body={grant_type:"client_credentials",client_id:options.clientId,client_secret:options.clientSecret};return options.tokenTtl&&(body.ttl=options.tokenTtl),body},UsergridHelpers.userResetPasswordBody=function(args){return{oldpassword:_.isPlainObject(args[0])?args[0].oldPassword:_.isString(args[0])?args[0]:void 0,newpassword:_.isPlainObject(args[0])?args[0].newPassword:_.isString(args[1])?args[1]:void 0}},UsergridHelpers.calculateExpiry=function(expires_in){return Date.now()+1e3*(expires_in?expires_in-5:0)};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;return UsergridHelpers.isUUID=function(uuid){return uuid?uuidValueRegex.test(uuid):!1},UsergridHelpers.useQuotesIfRequired=function(value){return _.isFinite(value)||UsergridHelpers.isUUID(value)||_.isBoolean(value)||_.isObject(value)&&!_.isFunction(value)||_.isArray(value)?value:"'"+value+"'"},UsergridHelpers.setReadOnly=function(obj,key){return _.isArray(key)?key.forEach(function(k){UsergridHelpers.setReadOnly(obj,k)}):_.isPlainObject(obj[key])?Object.freeze(obj[key]):_.isPlainObject(obj)&&void 0===key?Object.freeze(obj):_.has(obj,key)?Object.defineProperty(obj,key,{writable:!1}):obj},UsergridHelpers.setWritable=function(obj,key){return _.isArray(key)?key.forEach(function(k){UsergridHelpers.setWritable(obj,k)}):_.isPlainObject(obj[key])?_.clone(obj[key]):_.isPlainObject(obj)&&void 0===key?_.clone(obj):_.has(obj,key)?Object.defineProperty(obj,key,{writable:!0}):obj},UsergridHelpers.assignPrefabOptions=function(args){return _.isObject(args[0])&&!_.isFunction(args[0])&&_.has(args,"method")&&_.assign(this,args[0]),this},UsergridHelpers.normalize=function(str){return str=str.replace(/\/+/g,"/"),str=str.replace(/:\//g,"://"),str=str.replace(/\/(\?|&|#[^!])/g,"$1"),str=str.replace(/(\?.+)\?/g,"$1&")},UsergridHelpers.urljoin=function(){var input=arguments,options={};"object"==typeof arguments[0]&&(input=arguments[0],options=arguments[1]||{});var joined=[].slice.call(input,0).join("/");return UsergridHelpers.normalize(joined,options)},UsergridHelpers.parseResponseHeaders=function(headerStr){var headers={};if(headerStr)for(var headerPairs=headerStr.split("\r\n"),i=0;i0){var key=headerPair.substring(0,index).toLowerCase();headers[key]=headerPair.substring(index+2)}}return headers},UsergridHelpers.uri=function(client,options){var path="";path=options instanceof UsergridEntity?options.type:options instanceof UsergridQuery?options._type:_.isString(options)?options:_.isArray(options)?_.get(options,"0.type")||_.get(options,"0.path"):options.path||options.type||_.get(options,"entity.type")||_.get(options,"query._type")||_.get(options,"body.type")||_.get(options,"body.path");var uuidOrName="";return options.method!==UsergridHttpMethod.POST&&(uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,_.get(options,"entity.uuid"),_.get(options,"entity.name"),_.get(options,"body.uuid"),_.get(options,"body.name"),""].filter(_.isString))),UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,path,uuidOrName)},UsergridHelpers.updateEntityFromRemote=function(entity,usergridResponse){UsergridHelpers.setWritable(entity,["uuid","name","type","created"]),_.assign(entity,usergridResponse.entity),UsergridHelpers.setReadOnly(entity,["uuid","name","type","created"])},UsergridHelpers.headers=function(client,options,defaultHeaders){var returnHeaders={};_.defaults(returnHeaders,options.headers,defaultHeaders),_.assign(returnHeaders,{"User-Agent":"usergrid-js/v"+UsergridSDKVersion});var authForRequests=UsergridHelpers.authForRequests(client);return authForRequests&&_.assign(returnHeaders,{authorization:"Bearer "+authForRequests.token}),returnHeaders},UsergridHelpers.setEntity=function(options,args){return options.entity=_.first([options.entity,args[0]].filter(function(property){return property instanceof UsergridEntity})),void 0!==options.entity&&(options.type=options.entity.type),options},UsergridHelpers.setAsset=function(options,args){return options.asset=_.first([options.asset,_.get(options,"entity.asset"),args[1],args[0]].filter(function(property){return property instanceof UsergridAsset})),options},UsergridHelpers.setUuidOrName=function(options,args){return options.uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,_.get(options,"entity.uuid"),_.get(options,"body.uuid"),_.get(options,"entity.name"),_.get(options,"body.name"),_.get(args,"0.uuid"),_.get(args,"0.name"),_.get(args,"2"),_.get(args,"1")].filter(_.isString)),options},UsergridHelpers.setPathOrType=function(options,args){var pathOrType=_.first([args.type,_.get(args,"0.type"),_.get(options,"entity.type"),_.get(args,"body.type"),_.get(options,"body.0.type"),_.isArray(args)?args[0]:void 0].filter(_.isString));return options[/\//.test(pathOrType)?"path":"type"]=pathOrType,options},UsergridHelpers.setQs=function(options,args){return options.path&&(options.qs=_.first([options.qs,args[2],args[1],args[0]].filter(_.isPlainObject))),options},UsergridHelpers.setQuery=function(options,args){return options.query=_.first([options,options.query,args[0]].filter(function(property){return property instanceof UsergridQuery})),options},UsergridHelpers.setAsset=function(options,args){return options.asset=_.first([options.asset,_.get(options,"entity.asset"),args[1],args[0]].filter(function(property){return property instanceof UsergridAsset})),options},UsergridHelpers.setBody=function(options,args){var body=_.first([args.entity,args.body,args[0].entity,args[0].body,args[2],args[1],args[0]].filter(function(property){return _.isObject(property)&&!_.isFunction(property)&&!(property instanceof UsergridQuery)&&!(property instanceof UsergridAsset)}));return body instanceof UsergridEntity?body=body.jsonValue():_.isArray(body)&&body[0]instanceof UsergridEntity&&(body=_.map(body,function(entity){return entity.jsonValue()})),options.body=body,options},UsergridHelpers.buildRequest=function(client,method,args){var options={client:client,method:method,queryParams:args.queryParams||_.get(args,"0.queryParams"),callback:UsergridHelpers.callback(args)};if(UsergridHelpers.assignPrefabOptions(options,args),UsergridHelpers.setEntity(options,args),!(method!==UsergridHttpMethod.POST&&method!==UsergridHttpMethod.PUT||(UsergridHelpers.setAsset(options,args),options.asset||(UsergridHelpers.setBody(options,args),options.body))))throw new Error("'body' is required when making a "+options.method+" request");return UsergridHelpers.setUuidOrName(options,args),UsergridHelpers.setPathOrType(options,args),UsergridHelpers.setQs(options,args),UsergridHelpers.setQuery(options,args),options.uri=UsergridHelpers.uri(client,options),new UsergridRequest(options)},UsergridHelpers.buildAppAuthRequest=function(client,auth,callback){var requestOptions={client:client,method:UsergridHttpMethod.POST,uri:UsergridHelpers.uri(client,{path:"token"}),body:UsergridHelpers.appLoginBody(auth),callback:callback};return new UsergridRequest(requestOptions)},UsergridHelpers.buildConnectionRequest=function(client,method,args){var options={client:client,method:method,entity:{},to:{},callback:UsergridHelpers.callback(args)};if(UsergridHelpers.assignPrefabOptions.call(options,args),_.isObject(options.from)&&(options.to=options.from),_.isObject(args[0])&&_.has(args[0],"entity")&&_.has(args[0],"to")&&(_.assign(options.entity,args[0].entity),options.relationship=_.get(args,"0.relationship"),_.assign(options.to,args[0].to)),_.isObject(args[0])&&!_.isFunction(args[0])&&_.isString(args[1])&&(_.assign(options.entity,args[0]),options.relationship=_.first([options.relationship,args[1]].filter(_.isString))),_.isObject(args[2])&&!_.isFunction(args[2])&&_.assign(options.to,args[2]),options.entity.uuidOrName=_.first([options.entity.uuidOrName,options.entity.uuid,options.entity.name,args[1]].filter(_.isString)),options.entity.type||(options.entity.type=_.first([options.entity.type,args[0]].filter(_.isString))),options.relationship=_.first([options.relationship,args[2]].filter(_.isString)),_.isString(args[3])&&!UsergridHelpers.isUUID(args[3])&&_.isString(args[4])?options.to.type=args[3]:_.isString(args[2])&&!UsergridHelpers.isUUID(args[2])&&_.isString(args[3])&&_.isObject(args[0])&&!_.isFunction(args[0])&&(options.to.type=args[2]),options.to.uuidOrName=_.first([options.to.uuidOrName,options.to.uuid,options.to.name,args[4],args[3],args[2]].filter(function(property){return _.isString(options.to.type)&&_.isString(property)||UsergridHelpers.isUUID(property)})),!_.isString(options.entity.uuidOrName))throw new Error("source entity 'uuidOrName' is required when connecting or disconnecting entities");if(!_.isString(options.to.uuidOrName))throw new Error("target entity 'uuidOrName' is required when connecting or disconnecting entities");if(!_.isString(options.to.type)&&!UsergridHelpers.isUUID(options.to.uuidOrName))throw new Error("target 'type' (collection name) parameter is required connecting or disconnecting entities by name");return options.uri=UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,_.isString(options.entity.type)?options.entity.type:"",_.isString(options.entity.uuidOrName)?options.entity.uuidOrName:"",options.relationship,_.isString(options.to.type)?options.to.type:"",_.isString(options.to.uuidOrName)?options.to.uuidOrName:""),new UsergridRequest(options)},UsergridHelpers.buildGetConnectionRequest=function(client,args){var options={client:client,method:"GET",callback:UsergridHelpers.callback(args)};if(UsergridHelpers.assignPrefabOptions.call(options,args),_.isObject(args[1])&&!_.isFunction(args[1])&&_.assign(options,args[1]),options.direction=_.first([options.direction,args[0]].filter(function(property){return property===UsergridDirection.IN||property===UsergridDirection.OUT})),options.relationship=_.first([options.relationship,args[3],args[2]].filter(_.isString)),options.uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,args[2]].filter(_.isString)),options.type=_.first([options.type,args[1]].filter(_.isString)),!_.isString(options.type))throw new Error("'type' (collection name) parameter is required when retrieving connections");if(!_.isString(options.uuidOrName))throw new Error("target entity 'uuidOrName' is required when retrieving connections");return options.uri=UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,_.isString(options.type)?options.type:"",_.isString(options.uuidOrName)?options.uuidOrName:"",options.direction,options.relationship),new UsergridRequest(options)},global[name]=UsergridHelpers,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),UsergridHelpers},global[name]}(this);var UsergridClientDefaultOptions={baseUrl:"https://api.usergrid.com",authMode:UsergridAuthMode.USER},UsergridClient=function(options){var __appAuth,self=this;if(self.tempAuth=void 0,self.isSharedInstance=!1,2===arguments.length&&(self.orgId=arguments[0],self.appId=arguments[1]),_.defaults(self,options,UsergridClientDefaultOptions),!self.orgId||!self.appId)throw new Error("'orgId' and 'appId' parameters are required when instantiating UsergridClient");return Object.defineProperty(self,"clientId",{enumerable:!1}),Object.defineProperty(self,"clientSecret",{enumerable:!1}),Object.defineProperty(self,"appAuth",{get:function(){return __appAuth},set:function(options){options instanceof UsergridAppAuth?__appAuth=options:"undefined"!=typeof options&&(__appAuth=new UsergridAppAuth(options))}}),self.clientId&&self.clientSecret&&self.setAppAuth(self.clientId,self.clientSecret),self};UsergridClient.prototype={sendRequest:function(usergridRequest){return usergridRequest.sendRequest()},GET:function(){var usergridRequest=UsergridHelpers.buildRequest(this,UsergridHttpMethod.GET,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},PUT:function(){var usergridRequest=UsergridHelpers.buildRequest(this,UsergridHttpMethod.PUT,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},POST:function(){var usergridRequest=UsergridHelpers.buildRequest(this,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},DELETE:function(){var usergridRequest=UsergridHelpers.buildRequest(this,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},connect:function(){var usergridRequest=UsergridHelpers.buildConnectionRequest(this,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},disconnect:function(){var usergridRequest=UsergridHelpers.buildConnectionRequest(this,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},getConnections:function(){var usergridRequest=UsergridHelpers.buildGetConnectionRequest(this,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},usingAuth:function(auth){var self=this;return _.isString(auth)?self.tempAuth=new UsergridAuth(auth):auth instanceof UsergridAuth?self.tempAuth=auth:self.tempAuth=void 0,self},setAppAuth:function(){this.appAuth=new UsergridAppAuth(UsergridHelpers.flattenArgs(arguments))},authenticateApp:function(options){var self=this,authenticateAppCallback=UsergridHelpers.callback(UsergridHelpers.flattenArgs(arguments)),auth=_.first([options,self.appAuth,new UsergridAppAuth(options),new UsergridAppAuth(self.clientId,self.clientSecret)].filter(function(p){return p instanceof UsergridAppAuth}));if(!(auth instanceof UsergridAppAuth))throw new Error("App auth context was not defined when attempting to call .authenticateApp()");if(!auth.clientId||!auth.clientSecret)throw new Error("authenticateApp() failed because clientId or clientSecret are missing");var callback=function(error,usergridResponse){var token=_.get(usergridResponse.responseJSON,"access_token"),expiresIn=_.get(usergridResponse.responseJSON,"expires_in");usergridResponse.ok&&(self.appAuth||(self.appAuth=auth),self.appAuth.token=token,self.appAuth.expiry=UsergridHelpers.calculateExpiry(expiresIn),self.appAuth.tokenTtl=expiresIn),authenticateAppCallback(error,usergridResponse,token)},usergridRequest=UsergridHelpers.buildAppAuthRequest(self,auth,callback);return self.sendRequest(usergridRequest)},authenticateUser:function(options){var self=this,args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args),setAsCurrentUser=void 0!==_.last(args.filter(_.isBoolean))?_.last(args.filter(_.isBoolean)):!0,userToAuthenticate=new UsergridUser(options);userToAuthenticate.login(self,function(error,usergridResponse,token){usergridResponse.ok&&setAsCurrentUser&&(self.currentUser=userToAuthenticate),callback(usergridResponse.error,usergridResponse,token)})},downloadAsset:function(){var self=this,usergridRequest=UsergridHelpers.buildRequest(self,UsergridHttpMethod.GET,UsergridHelpers.flattenArgs(arguments)),assetContentType=_.get(usergridRequest,"entity.file-metadata.content-type");void 0!==assetContentType&&_.assign(usergridRequest.headers,{Accept:assetContentType});var realDownloadAssetCallback=usergridRequest.callback;return usergridRequest.callback=function(error,usergridResponse){var entity=usergridRequest.entity;entity.asset=usergridResponse.asset,realDownloadAssetCallback(error,usergridResponse,entity)},self.sendRequest(usergridRequest)},uploadAsset:function(){var self=this,usergridRequest=UsergridHelpers.buildRequest(self,UsergridHttpMethod.PUT,UsergridHelpers.flattenArgs(arguments));if(void 0===usergridRequest.asset)throw new Error("An UsergridAsset was not defined when attempting to call .uploadAsset()");var realUploadAssetCallback=usergridRequest.callback;return usergridRequest.callback=function(error,usergridResponse){var requestEntity=usergridRequest.entity,responseEntity=usergridResponse.entity,requestAsset=usergridRequest.asset;usergridResponse.ok&&void 0!==responseEntity&&(UsergridHelpers.updateEntityFromRemote(requestEntity,usergridResponse),requestEntity.asset=requestAsset,responseEntity&&(responseEntity.asset=requestAsset)),realUploadAssetCallback(error,usergridResponse,requestEntity)},self.sendRequest(usergridRequest)}};var UsergridSDKVersion="2.0.0",UsergridClientSharedInstance=function(){var self=this;return self.isInitialized=!1,self.isSharedInstance=!0,self};UsergridHelpers.inherits(UsergridClientSharedInstance,UsergridClient);var Usergrid=new UsergridClientSharedInstance;Usergrid.initSharedInstance=function(options){return Usergrid.isInitialized?console.log("Usergrid shared instance is already initialized"):(_.assign(Usergrid,new UsergridClient(options)),Usergrid.isInitialized=!0,Usergrid.isSharedInstance=!0),Usergrid},Usergrid.init=Usergrid.initSharedInstance;var UsergridQuery=function(type){var queryString,sort,self=this,query="",urlTerms={},__nextIsNot=!1;return self._type=type,_.assign(self,{type:function(value){return self._type=value,self},collection:function(value){return self._type=value,self},limit:function(value){return self._limit=value,self},cursor:function(value){return self._cursor=value,self},eq:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.EQUAL+" "+UsergridHelpers.useQuotesIfRequired(value)),self},equal:this.eq,gt:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.GREATER_THAN+" "+UsergridHelpers.useQuotesIfRequired(value)),self},greaterThan:this.gt,gte:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.GREATER_THAN_EQUAL_TO+" "+UsergridHelpers.useQuotesIfRequired(value)),self},greaterThanOrEqual:this.gte,lt:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.LESS_THAN+" "+UsergridHelpers.useQuotesIfRequired(value)),self},lessThan:this.lt,lte:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.LESS_THAN_EQUAL_TO+" "+UsergridHelpers.useQuotesIfRequired(value)),self},lessThanOrEqual:this.lte,contains:function(key,value){return query=self.andJoin(key+" contains "+UsergridHelpers.useQuotesIfRequired(value)),self},locationWithin:function(distanceInMeters,lat,lng){return query=self.andJoin("location within "+distanceInMeters+" of "+lat+", "+lng),self},asc:function(key){return self.sort(key,UsergridQuerySortOrder.ASC),self},desc:function(key){return self.sort(key,UsergridQuerySortOrder.DESC),self},sort:function(key,order){return sort=key&&order?" order by "+key+" "+order:"",self},fromString:function(string){return queryString=string, +self},urlTerm:function(key,value){return"ql"===key?self.fromString():urlTerms[key]=value,self},andJoin:function(append){return __nextIsNot&&(append="not "+append,__nextIsNot=!1),append?0===query.length?append:_.endsWith(query,"and")||_.endsWith(query,"or")?query+" "+append:query+" and "+append:query},orJoin:function(){return query.length>0&&!_.endsWith(query,"or")?query+" or":query}}),Object.defineProperty(self,"_ql",{get:function(){var ql="select * ";return void 0!==queryString?ql=queryString:(ql+=query.length>0?"where "+(query||""):"",ql+=void 0!==sort?sort:""),ql}}),Object.defineProperty(self,"encodedStringValue",{get:function(){var self=this,limit=self._limit,cursor=self._cursor,requirementsString=self._ql,returnString=void 0;if(void 0!==limit&&(returnString="limit"+UsergridQueryOperator.EQUAL+limit),!_.isEmpty(cursor)){var cursorString="cursor"+UsergridQueryOperator.EQUAL+cursor;_.isEmpty(returnString)?returnString=cursorString:returnString+="&"+cursorString}if(_.forEach(urlTerms,function(value,key){var encodedURLTermString=encodeURIComponent(key)+UsergridQueryOperator.EQUAL+encodeURIComponent(value);_.isEmpty(returnString)?returnString=encodedURLTermString:returnString+="&"+encodedURLTermString}),!_.isEmpty(requirementsString)){var qLString="ql="+encodeURIComponent(requirementsString);_.isEmpty(returnString)?returnString=qLString:returnString+="&"+qLString}return _.isEmpty(returnString)||(returnString="?"+returnString),_.isEmpty(returnString)?void 0:returnString}}),Object.defineProperty(self,"and",{get:function(){return query=self.andJoin(""),self}}),Object.defineProperty(self,"or",{get:function(){return query=self.orJoin(),self}}),Object.defineProperty(self,"not",{get:function(){return __nextIsNot=!0,self}}),self},UsergridRequest=function(options){var self=this,client=UsergridHelpers.validateAndRetrieveClient(options);if(!_.isString(options.type)&&!_.isString(options.path)&&!_.isString(options.uri))throw new Error("one of 'type' (collection name), 'path', or 'uri' parameters are required when initializing a UsergridRequest");if(!_.includes(["GET","PUT","POST","DELETE"],options.method))throw new Error("'method' parameter is required when initializing a UsergridRequest");self.method=options.method,self.callback=options.callback,self.uri=options.uri||UsergridHelpers.uri(client,options),self.entity=options.entity,self.body=options.body,self.asset=options.asset,self.query=options.query,self.queryParams=options.queryParams||options.qs;var defaultHeadersToUse=self.asset?{}:UsergridHelpers.DefaultHeaders;if(self.headers=UsergridHelpers.headers(client,options,defaultHeadersToUse),void 0!==self.query&&(self.uri+=UsergridHelpers.normalize(self.query.encodedStringValue,{})),self.queryParams&&(_.forOwn(self.queryParams,function(value,key){self.uri+="?"+encodeURIComponent(key)+UsergridQueryOperator.EQUAL+encodeURIComponent(value)}),self.uri=UsergridHelpers.normalize(self.uri,{})),self.asset)self.body=new FormData,self.body.append(self.asset.filename,self.asset.data);else try{_.isPlainObject(self.body)?self.body=JSON.stringify(self.body):_.isArray(self.body)&&(self.body=JSON.stringify(self.body))}catch(exception){console.warn("Unable to convert 'UsergridRequest.body' to a JSON String: "+exception)}return self};UsergridRequest.prototype.sendRequest=function(){var self=this,requestPromise=function(){var promise=new Promise,xmlHttpRequest=new XMLHttpRequest;return xmlHttpRequest.open(self.method,self.uri,!0),xmlHttpRequest.onload=function(){promise.done(xmlHttpRequest)},_.forOwn(self.headers,function(value,key){xmlHttpRequest.setRequestHeader(key,value)}),self.method===UsergridHttpMethod.GET&&_.get(self.headers,"Accept")!==UsergridApplicationJSONHeaderValue&&(xmlHttpRequest.responseType="blob"),xmlHttpRequest.send(self.body),promise},responsePromise=function(xmlRequest){var promise=new Promise,usergridResponse=new UsergridResponse(xmlRequest,self);return promise.done(usergridResponse),promise},onCompletePromise=function(usergridResponse){self.callback(usergridResponse.error,usergridResponse)};return Promise.chain([requestPromise,responsePromise]).then(onCompletePromise),self};var UsergridAuth=function(token,expiry){var self=this;self.token=token,self.expiry=expiry||0;var usingToken=token?!0:!1;return Object.defineProperty(self,"hasToken",{get:function(){return void 0!==self.token},configurable:!0}),Object.defineProperty(self,"isExpired",{get:function(){return usingToken?!1:Date.now()>=self.expiry},configurable:!0}),Object.defineProperty(self,"isValid",{get:function(){return!self.isExpired&&self.hasToken},configurable:!0}),Object.defineProperty(self,"tokenTtl",{configurable:!0,writable:!0}),_.assign(self,{destroy:function(){self.token=void 0,self.expiry=0,self.tokenTtl=void 0}}),self},UsergridAppAuth=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments);return _.isPlainObject(args[0])?(self.clientId=args[0].clientId,self.clientSecret=args[0].clientSecret,self.tokenTtl=args[0].tokenTtl):(self.clientId=args[0],self.clientSecret=args[1],self.tokenTtl=args[2]),UsergridAuth.call(self),_.assign(self,UsergridAuth),self};UsergridHelpers.inherits(UsergridAppAuth,UsergridAuth);var UsergridUserAuth=function(options){var self=this,args=_.flattenDeep(UsergridHelpers.flattenArgs(arguments));return _.isPlainObject(args[0])&&(options=args[0]),self.username=options.username||args[0],self.email=options.email,(options.password||args[1])&&(self.password=options.password||args[1]),self.tokenTtl=options.tokenTtl||args[2],UsergridAuth.call(self),_.assign(self,UsergridAuth),self};UsergridHelpers.inherits(UsergridUserAuth,UsergridAuth);var UsergridEntity=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments);if(0===args.length)throw new Error("A UsergridEntity object cannot be initialized without passing one or more arguments");if(self.asset=void 0,_.isPlainObject(args[0])?_.assign(self,args[0]):(self.type||(self.type=_.isString(args[0])?args[0]:void 0),self.name||(self.name=_.isString(args[1])?args[1]:void 0)),!_.isString(self.type))throw new Error('"type" (or "collection") parameter is required when initializing a UsergridEntity object');return Object.defineProperty(self,"isUser",{get:function(){return"user"===self.type.toLowerCase()}}),Object.defineProperty(self,"hasAsset",{get:function(){return _.has(self,"file-metadata")}}),UsergridHelpers.setReadOnly(self,["uuid","name","type","created"]),self};UsergridEntity.prototype={jsonValue:function(){var jsonValue={};return _.forOwn(this,function(value,key){jsonValue[key]=value}),jsonValue},putProperty:function(key,value){this[key]=value},putProperties:function(obj){_.assign(this,obj)},removeProperty:function(key){this.removeProperties([key])},removeProperties:function(keys){var self=this;keys.forEach(function(key){delete self[key]})},insert:function(key,value,idx){_.isArray(this[key])||(this[key]=this[key]?[this[key]]:[]),this[key].splice.apply(this[key],[idx,0].concat(value))},append:function(key,value){this.insert(key,value,Number.MAX_VALUE)},prepend:function(key,value){this.insert(key,value,0)},pop:function(key){_.isArray(this[key])&&this[key].pop()},shift:function(key){_.isArray(this[key])&&this[key].shift()},reload:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.GET(self,function(error,usergridResponse){UsergridHelpers.updateEntityFromRemote(self,usergridResponse),callback(error,usergridResponse,self)}.bind(self))},save:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args),currentAsset=self.asset;client.PUT(self,function(error,usergridResponse){UsergridHelpers.updateEntityFromRemote(self,usergridResponse),self.hasAsset&&(self.asset=currentAsset),callback(error,usergridResponse,self)}.bind(self))},remove:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.DELETE(self,function(error,usergridResponse){callback(error,usergridResponse,self)}.bind(self))},attachAsset:function(asset){this.asset=asset},uploadAsset:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(_.has(self,"asset.contentType"))client.uploadAsset(self,callback);else{var response=UsergridResponse.responseWithError({name:"asset_not_found",description:"The specified entity does not have a valid asset attached"});callback(response.error,response,self)}},downloadAsset:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(_.has(self,"asset.contentType"))client.downloadAsset(self,callback);else{var response=UsergridResponse.responseWithError({name:"asset_not_found",description:"The specified entity does not have a valid asset attached"});callback(response.error,response,self)}},connect:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args[0]=this,client.connect.apply(client,args)},disconnect:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args[0]=this,client.disconnect.apply(client,args)},getConnections:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args.shift(),args.splice(1,0,this),client.getConnections.apply(client,args)}};var UsergridUser=function(obj){if(!_.has(obj,"email")&&!_.has(obj,"username"))throw new Error("'email' or 'username' property is required when initializing a UsergridUser object");var self=this;return _.assign(self,obj,UsergridEntity),UsergridEntity.call(self,"user"),UsergridHelpers.setWritable(self,"name"),self};UsergridUser.CheckAvailable=function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args),username=args[0].username||args[1].username,email=args[0].email||args[1].email;if(!username&&!email)throw new Error("'username' or 'email' property is required when checking for available users");var checkQuery=new UsergridQuery("users");username&&checkQuery.eq("username",username),email&&checkQuery.or.eq("email",email),client.GET(checkQuery,function(error,usergridResponse){callback(error,usergridResponse,usergridResponse.entities.length>0)})},UsergridHelpers.inherits(UsergridUser,UsergridEntity),UsergridUser.prototype.uniqueId=function(){var self=this;return _.first([self.uuid,self.username,self.email].filter(_.isString))},UsergridUser.prototype.create=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.POST(self,function(error,usergridResponse){delete self.password,_.assign(self,usergridResponse.user),callback(error,usergridResponse,self)}.bind(self))},UsergridUser.prototype.login=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.POST("token",UsergridHelpers.userLoginBody(self),function(error,usergridResponse){delete self.password;var responseJSON=usergridResponse.responseJSON,token=_.get(responseJSON,"access_token"),expiresIn=_.get(responseJSON,"expires_in");usergridResponse.ok&&(self.auth=new UsergridUserAuth(self),self.auth.token=token,self.auth.expiry=UsergridHelpers.calculateExpiry(expiresIn),self.auth.tokenTtl=expiresIn),callback(error,usergridResponse,token)})},UsergridUser.prototype.logout=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(self.auth&&self.auth.isValid){var revokeAll=_.first(args.filter(_.isBoolean))||!1,requestOptions={client:client,path:["users",self.uniqueId(),"revoketoken"+(revokeAll?"s":"")].join("/"),method:UsergridHttpMethod.PUT,callback:function(error,usergridResponse){self.auth.destroy(),callback(error,usergridResponse,usergridResponse.ok)}.bind(self)};revokeAll||(requestOptions.queryParams={token:self.auth.token});var request=new UsergridRequest(requestOptions);client.sendRequest(request)}else{var response=UsergridResponse.responseWithError({name:"no_valid_token",description:"this user does not have a valid token"});callback(response.error,response)}},UsergridUser.prototype.logoutAllSessions=function(){var args=UsergridHelpers.flattenArgs(arguments);return args=_.concat([UsergridHelpers.validateAndRetrieveClient(args),!0],args),this.logout.apply(this,args)},UsergridUser.prototype.resetPassword=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);args[0]instanceof UsergridClient&&args.shift();var body=UsergridHelpers.userResetPasswordBody(args);if(!body.oldpassword||!body.newpassword)throw new Error("'oldPassword' and 'newPassword' properties are required when resetting a user password");client.PUT(["users",self.uniqueId(),"password"].join("/"),body,callback)};var UsergridResponseError=function(options){var self=this;return _.assign(self,options),self};UsergridResponseError.fromJSON=function(responseErrorObject){var usergridResponseError,error={name:_.get(responseErrorObject,"error")};return error.name&&(_.assign(error,{exception:_.get(responseErrorObject,"exception"),description:_.get(responseErrorObject,"error_description")||_.get(responseErrorObject,"description")}),usergridResponseError=new UsergridResponseError(error)),usergridResponseError};var UsergridResponse=function(xmlRequest,usergridRequest){var self=this;if(self.ok=!1,self.request=usergridRequest,xmlRequest){self.statusCode=parseInt(xmlRequest.status),self.ok=self.statusCode<400,self.headers=UsergridHelpers.parseResponseHeaders(xmlRequest.getAllResponseHeaders());var responseContentType=_.get(self.headers,"content-type");if(responseContentType===UsergridApplicationJSONHeaderValue)try{var responseJSON=JSON.parse(xmlRequest.responseText);responseJSON&&self.parseResponseJSON(responseJSON)}catch(e){}else self.asset=new UsergridAsset(xmlRequest.response)}return self};UsergridResponse.responseWithError=function(options){var usergridResponse=new UsergridResponse;return usergridResponse.error=new UsergridResponseError(options),usergridResponse},UsergridResponse.prototype={parseResponseJSON:function(responseJSON){var self=this;if(self.responseJSON=_.cloneDeep(responseJSON),self.ok){self.cursor=_.get(self,"responseJSON.cursor"),self.hasNextPage=!_.isNil(self.cursor);var entitiesJSON=_.get(responseJSON,"entities");entitiesJSON&&(self.parseResponseEntities(entitiesJSON),delete self.responseJSON.entities)}else self.error=UsergridResponseError.fromJSON(responseJSON);UsergridHelpers.setReadOnly(self.responseJSON)},parseResponseEntities:function(entitiesJSON){var self=this;self.entities=_.map(entitiesJSON,function(entityJSON){var entity=new UsergridEntity(entityJSON);return entity.isUser&&(entity=new UsergridUser(entity)),entity}),self.first=_.first(self.entities),self.entity=self.first,self.last=_.last(self.entities),"/users"===_.get(self,"responseJSON.path")&&(self.user=self.first,self.users=self.entities)},loadNextPage:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args),cursor=self.cursor;if(cursor){var client=UsergridHelpers.validateAndRetrieveClient(args),type=_.last(_.get(self,"responseJSON.path").split("/")),limit=_.first(_.get(self,"responseJSON.params.limit")),ql=_.first(_.get(self,"responseJSON.params.ql")),query=new UsergridQuery(type).fromString(ql).cursor(cursor).limit(limit);client.GET(query,callback)}else callback(UsergridResponse.responseWithError({name:"cursor_not_found",description:"Cursor must be present in order perform loadNextPage()."}))}};var UsergridAssetDefaultFileName="file",UsergridAsset=function(fileOrBlob){if(!fileOrBlob instanceof File||!fileOrBlob instanceof Blob)throw new Error("UsergridAsset must be initialized with a 'File' or 'Blob'");var self=this;return self.data=fileOrBlob,self.filename=fileOrBlob.name||UsergridAssetDefaultFileName,self.contentLength=fileOrBlob.size,self.contentType=fileOrBlob.type,self}; \ No newline at end of file From c4e7d22c4f2c28c4fcbdf607360a9bcda65a21c6 Mon Sep 17 00:00:00 2001 From: Robert Walsh Date: Fri, 14 Oct 2016 14:06:58 -0500 Subject: [PATCH 36/36] Fixed examples and minor cleanup. --- examples/all-calls/app.js | 23 +++++++++-------------- examples/dogs/app.js | 24 ++++++++++++------------ lib/Usergrid.js | 6 +++--- lib/modules/UsergridClient.js | 2 +- lib/modules/UsergridEntity.js | 29 ++++++++++++++--------------- lib/modules/UsergridResponse.js | 2 +- lib/modules/util/Promise.js | 6 +++--- usergrid.js | 2 +- usergrid.min.js | 2 +- 9 files changed, 45 insertions(+), 51 deletions(-) diff --git a/examples/all-calls/app.js b/examples/all-calls/app.js index 0c72c0b..8d6720d 100755 --- a/examples/all-calls/app.js +++ b/examples/all-calls/app.js @@ -102,8 +102,7 @@ $(document).ready(function () { function _get() { var endpoint = $("#get-path").val(); - client.GET(endpoint, function(usergridResponse) { - var err = usergridResponse.error; + client.GET(endpoint, function(err,usergridResponse) { if (err) { $("#response").html('
    ERROR: '+JSON.stringify(err,null,2)+'
    '); } else { @@ -116,12 +115,11 @@ $(document).ready(function () { var endpoint = $("#post-path").val(); var data = $("#post-data").val(); data = JSON.parse(data); - client.POST(endpoint, data, function (usergridResponse) { - var err = usergridResponse.error; + client.POST(endpoint, data, function (err,usergridResponse) { if (err) { $("#response").html('
    ERROR: '+JSON.stringify(err,null,2)+'
    '); } else { - $("#response").html('
    '+JSON.stringify(usergridResponse.entities,null,2)+'
    '); + $("#response").html('
    '+JSON.stringify(usergridResponse.entity,null,2)+'
    '); } }); } @@ -130,24 +128,22 @@ $(document).ready(function () { var endpoint = $("#put-path").val(); var data = $("#put-data").val(); data = JSON.parse(data); - client.PUT(endpoint, data, function (usergridResponse) { - var err = usergridResponse.error; + client.PUT(endpoint, data, function (err,usergridResponse) { if (err) { $("#response").html('
    ERROR: '+JSON.stringify(err,null,2)+'
    '); } else { - $("#response").html('
    '+JSON.stringify(usergridResponse.entities,null,2)+'
    '); + $("#response").html('
    '+JSON.stringify(usergridResponse.entity,null,2)+'
    '); } }); } function _delete() { var endpoint = $("#delete-path").val(); - client.DELETE(endpoint, function (usergridResponse) { - var err = usergridResponse.error; + client.DELETE(endpoint, function (err,usergridResponse) { if (err) { $("#response").html('
    ERROR: '+JSON.stringify(err,null,2)+'
    '); } else { - $("#response").html('
    '+JSON.stringify(usergridResponse.entities,null,2)+'
    '); + $("#response").html('
    '+JSON.stringify(usergridResponse.entity,null,2)+'
    '); } }); } @@ -155,12 +151,11 @@ $(document).ready(function () { function _login() { var username = $("#username").val(); var password = $("#password").val(); - client.authenticateUser({username:username, password:password}, function (auth,user,usergridResponse) { - var err = usergridResponse.error; + client.authenticateUser({username:username, password:password}, function (err,usergridResponse,token) { if (err) { $("#response").html('
    ERROR: '+JSON.stringify(err,null,2)+'
    '); } else { - $("#response").html('
    '+JSON.stringify(usergridResponse.responseJSON,null,2)+'
    '); + $("#response").html('
    '+JSON.stringify(usergridResponse,null,2)+'
    '); } }); } diff --git a/examples/dogs/app.js b/examples/dogs/app.js index b8ad732..69565d9 100755 --- a/examples/dogs/app.js +++ b/examples/dogs/app.js @@ -33,8 +33,8 @@ $(document).ready(function () { message.html(''); previousCursors.push(lastQueryUsed._cursor); lastQueryUsed = new UsergridQuery('dogs').desc('created').cursor(_.get(lastResponse,'responseJSON.cursor')); - lastResponse.loadNextPage(client,function(usergridResponse) { - handleGETDogResponse(usergridResponse) + lastResponse.loadNextPage(client,function(error,usergridResponse) { + handleGETDogResponse(error,usergridResponse) }) }); @@ -71,14 +71,14 @@ $(document).ready(function () { if( cursor !== undefined && !_.isEmpty(cursor) ) { lastQueryUsed.cursor(cursor) } - client.GET(lastQueryUsed,function(usergridResponse) { - handleGETDogResponse(usergridResponse) + client.GET(lastQueryUsed,function(error,usergridResponse) { + handleGETDogResponse(error,usergridResponse) }); } - function handleGETDogResponse(usergridResponse) { + function handleGETDogResponse(error,usergridResponse) { lastResponse = usergridResponse; - if(lastResponse.error) { + if(error) { alert('there was an error getting the dogs'); } else { myDogList.empty(); @@ -101,23 +101,23 @@ $(document).ready(function () { function newdog() { createDogButton.addClass("disabled"); - var name = $("#name").val(), + var nameInput = $("#name"), nameHelp = $("#name-help"), nameControl = $("#name-control"); nameHelp.hide(); nameControl.removeClass('error'); - if (Usergrid.validation.validateName(name, function (){ - name.focus(); + if (Usergrid.validation.validateName(nameInput.val(), function (){ + nameInput.focus(); nameHelp.show(); nameControl.addClass('error'); nameHelp.html(Usergrid.validation.getNameAllowedChars()); createDogButton.removeClass("disabled");}) ) { - client.POST('dogs',{ name:name }, function(usergridResponse) { - if (usergridResponse.error) { - alert('Oops! There was an error creating the dog. \n' + JSON.stringify(usergridResponse.error,null,2)); + client.POST('dogs',{ name:nameInput.val() }, function(error,usergridResponse) { + if (error) { + alert('Oops! There was an error creating the dog. \n' + JSON.stringify(error,null,2)); createDogButton.removeClass("disabled"); } else { message.html('New dog created!'); diff --git a/lib/Usergrid.js b/lib/Usergrid.js index 885f337..819c1b9 100644 --- a/lib/Usergrid.js +++ b/lib/Usergrid.js @@ -17,9 +17,9 @@ * under the License. */ -'use strict'; +"use strict"; -var UsergridSDKVersion = '2.0.0'; +var UsergridSDKVersion = "2.0.0"; var UsergridClientSharedInstance = function() { var self = this; @@ -32,7 +32,7 @@ UsergridHelpers.inherits(UsergridClientSharedInstance, UsergridClient); var Usergrid = new UsergridClientSharedInstance(); Usergrid.initSharedInstance = function(options) { if (Usergrid.isInitialized) { - console.log('Usergrid shared instance is already initialized'); + console.log("Usergrid shared instance is already initialized"); } else { _.assign(Usergrid, new UsergridClient(options)); Usergrid.isInitialized = true; diff --git a/lib/modules/UsergridClient.js b/lib/modules/UsergridClient.js index 04ccd05..255925e 100644 --- a/lib/modules/UsergridClient.js +++ b/lib/modules/UsergridClient.js @@ -149,7 +149,7 @@ UsergridClient.prototype = { self.currentUser = userToAuthenticate; } callback(usergridResponse.error,usergridResponse,token); - }) + }); }, downloadAsset: function() { var self = this; diff --git a/lib/modules/UsergridEntity.js b/lib/modules/UsergridEntity.js index 9ac8dea..98f3c36 100644 --- a/lib/modules/UsergridEntity.js +++ b/lib/modules/UsergridEntity.js @@ -11,15 +11,14 @@ See the License for the specific language governing permissions and limitations under the License. */ - -'use strict'; +"use strict"; var UsergridEntity = function() { var self = this; var args = UsergridHelpers.flattenArgs(arguments); if (args.length === 0) { - throw new Error('A UsergridEntity object cannot be initialized without passing one or more arguments'); + throw new Error("A UsergridEntity object cannot be initialized without passing one or more arguments"); } self.asset = undefined; @@ -36,22 +35,22 @@ var UsergridEntity = function() { } if (!_.isString(self.type)) { - throw new Error('"type" (or "collection") parameter is required when initializing a UsergridEntity object'); + throw new Error("'type' (or 'collection') parameter is required when initializing a UsergridEntity object"); } - Object.defineProperty(self, 'isUser', { + Object.defineProperty(self, "isUser", { get: function() { - return (self.type.toLowerCase() === 'user'); + return (self.type.toLowerCase() === "user"); } }); - Object.defineProperty(self, 'hasAsset', { + Object.defineProperty(self, "hasAsset", { get: function() { - return _.has(self, 'file-metadata'); + return _.has(self, "file-metadata"); } }); - UsergridHelpers.setReadOnly(self, ['uuid', 'name', 'type', 'created']); + UsergridHelpers.setReadOnly(self, ["uuid", "name", "type", "created"]); return self; }; @@ -146,12 +145,12 @@ UsergridEntity.prototype = { var client = UsergridHelpers.validateAndRetrieveClient(args); var callback = UsergridHelpers.callback(args); - if( _.has(self,'asset.contentType') ) { + if( _.has(self,"asset.contentType") ) { client.uploadAsset(self,callback); } else { var response = UsergridResponse.responseWithError({ - name: 'asset_not_found', - description: 'The specified entity does not have a valid asset attached' + name: "asset_not_found", + description: "The specified entity does not have a valid asset attached" }); callback(response.error,response,self); } @@ -163,12 +162,12 @@ UsergridEntity.prototype = { var client = UsergridHelpers.validateAndRetrieveClient(args); var callback = UsergridHelpers.callback(args); - if( _.has(self,'asset.contentType') ) { + if( _.has(self,"asset.contentType") ) { client.downloadAsset(self,callback); } else { var response = UsergridResponse.responseWithError({ - name: 'asset_not_found', - description: 'The specified entity does not have a valid asset attached' + name: "asset_not_found", + description: "The specified entity does not have a valid asset attached" }); callback(response.error,response,self); } diff --git a/lib/modules/UsergridResponse.js b/lib/modules/UsergridResponse.js index 6c45b8b..41d6038 100644 --- a/lib/modules/UsergridResponse.js +++ b/lib/modules/UsergridResponse.js @@ -48,7 +48,7 @@ var UsergridResponse = function(xmlRequest,usergridRequest) { try { var responseJSON = JSON.parse(xmlRequest.responseText); if( responseJSON ) { - self.parseResponseJSON(responseJSON) + self.parseResponseJSON(responseJSON); } } catch (e) {} } else { diff --git a/lib/modules/util/Promise.js b/lib/modules/util/Promise.js index 2c56433..a4e1b21 100644 --- a/lib/modules/util/Promise.js +++ b/lib/modules/util/Promise.js @@ -19,10 +19,10 @@ * @author ryan bridges (rbridges@apigee.com) */ -'use strict'; +"use strict"; (function(global) { - var name = 'Promise', overwrittenName = global[name]; + var name = "Promise", overwrittenName = global[name]; function Promise() { this.complete = false; @@ -44,7 +44,7 @@ this.result = result; if(this.callbacks){ _.forEach(this.callbacks,function(callback){ - callback(result) + callback(result); }); this.callbacks.length = 0; } diff --git a/usergrid.js b/usergrid.js index c62d62d..132f0f1 100644 --- a/usergrid.js +++ b/usergrid.js @@ -6298,7 +6298,7 @@ var UsergridEntity = function() { } } if (!_.isString(self.type)) { - throw new Error('"type" (or "collection") parameter is required when initializing a UsergridEntity object'); + throw new Error("'type' (or 'collection') parameter is required when initializing a UsergridEntity object"); } Object.defineProperty(self, "isUser", { get: function() { diff --git a/usergrid.min.js b/usergrid.min.js index acbbb54..b6659c6 100644 --- a/usergrid.min.js +++ b/usergrid.min.js @@ -24,4 +24,4 @@ return value===other?!0:null==value||null==other||!isObject(value)&&!isObjectLik }return stack["delete"](object),stack["delete"](other),result}function flatRest(func){return setToString(overRest(func,undefined,flatten),func+"")}function getAllKeys(object){return baseGetAllKeys(object,keys,getSymbols)}function getAllKeysIn(object){return baseGetAllKeys(object,keysIn,getSymbolsIn)}function getFuncName(func){for(var result=func.name+"",array=realNames[result],length=hasOwnProperty.call(realNames,result)?array.length:0;length--;){var data=array[length],otherFunc=data.func;if(null==otherFunc||otherFunc==func)return data.name}return result}function getHolder(func){var object=hasOwnProperty.call(lodash,"placeholder")?lodash:func;return object.placeholder}function getIteratee(){var result=lodash.iteratee||iteratee;return result=result===iteratee?baseIteratee:result,arguments.length?result(arguments[0],arguments[1]):result}function getMapData(map,key){var data=map.__data__;return isKeyable(key)?data["string"==typeof key?"string":"hash"]:data.map}function getMatchData(object){for(var result=keys(object),length=result.length;length--;){var key=result[length],value=object[key];result[length]=[key,value,isStrictComparable(value)]}return result}function getNative(object,key){var value=getValue(object,key);return baseIsNative(value)?value:undefined}function getView(start,end,transforms){for(var index=-1,length=transforms.length;++index1?"& ":"")+details[lastIndex],details=details.join(length>2?", ":" "),source.replace(reWrapComment,"{\n/* [wrapped with "+details+"] */\n")}function isFlattenable(value){return isArray(value)||isArguments(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol])}function isIndex(value,length){return length=null==length?MAX_SAFE_INTEGER:length,!!length&&("number"==typeof value||reIsUint.test(value))&&value>-1&&value%1==0&&length>value}function isIterateeCall(value,index,object){if(!isObject(object))return!1;var type=typeof index;return("number"==type?isArrayLike(object)&&isIndex(index,object.length):"string"==type&&index in object)?eq(object[index],value):!1}function isKey(value,object){if(isArray(value))return!1;var type=typeof value;return"number"==type||"symbol"==type||"boolean"==type||null==value||isSymbol(value)?!0:reIsPlainProp.test(value)||!reIsDeepProp.test(value)||null!=object&&value in Object(object)}function isKeyable(value){var type=typeof value;return"string"==type||"number"==type||"symbol"==type||"boolean"==type?"__proto__"!==value:null===value}function isLaziable(func){var funcName=getFuncName(func),other=lodash[funcName];if("function"!=typeof other||!(funcName in LazyWrapper.prototype))return!1;if(func===other)return!0;var data=getData(other);return!!data&&func===data[0]}function isMasked(func){return!!maskSrcKey&&maskSrcKey in func}function isPrototype(value){var Ctor=value&&value.constructor,proto="function"==typeof Ctor&&Ctor.prototype||objectProto;return value===proto}function isStrictComparable(value){return value===value&&!isObject(value)}function matchesStrictComparable(key,srcValue){return function(object){return null==object?!1:object[key]===srcValue&&(srcValue!==undefined||key in Object(object))}}function memoizeCapped(func){var result=memoize(func,function(key){return cache.size===MAX_MEMOIZE_SIZE&&cache.clear(),key}),cache=result.cache;return result}function mergeData(data,source){var bitmask=data[1],srcBitmask=source[1],newBitmask=bitmask|srcBitmask,isCommon=(BIND_FLAG|BIND_KEY_FLAG|ARY_FLAG)>newBitmask,isCombo=srcBitmask==ARY_FLAG&&bitmask==CURRY_FLAG||srcBitmask==ARY_FLAG&&bitmask==REARG_FLAG&&data[7].length<=source[8]||srcBitmask==(ARY_FLAG|REARG_FLAG)&&source[7].length<=source[8]&&bitmask==CURRY_FLAG;if(!isCommon&&!isCombo)return data;srcBitmask&BIND_FLAG&&(data[2]=source[2],newBitmask|=bitmask&BIND_FLAG?0:CURRY_BOUND_FLAG);var value=source[3];if(value){var partials=data[3];data[3]=partials?composeArgs(partials,value,source[4]):value,data[4]=partials?replaceHolders(data[3],PLACEHOLDER):source[4]}return value=source[5],value&&(partials=data[5],data[5]=partials?composeArgsRight(partials,value,source[6]):value,data[6]=partials?replaceHolders(data[5],PLACEHOLDER):source[6]),value=source[7],value&&(data[7]=value),srcBitmask&ARY_FLAG&&(data[8]=null==data[8]?source[8]:nativeMin(data[8],source[8])),null==data[9]&&(data[9]=source[9]),data[0]=source[0],data[1]=newBitmask,data}function mergeDefaults(objValue,srcValue,key,object,source,stack){return isObject(objValue)&&isObject(srcValue)&&(stack.set(srcValue,objValue),baseMerge(objValue,srcValue,undefined,mergeDefaults,stack),stack["delete"](srcValue)),objValue}function nativeKeysIn(object){var result=[];if(null!=object)for(var key in Object(object))result.push(key);return result}function overRest(func,start,transform){return start=nativeMax(start===undefined?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index0){if(++count>=HOT_COUNT)return arguments[0]}else count=0;return func.apply(undefined,arguments)}}function shuffleSelf(array,size){var index=-1,length=array.length,lastIndex=length-1;for(size=size===undefined?length:size;++indexsize)return[];for(var index=0,resIndex=0,result=Array(nativeCeil(length/size));length>index;)result[resIndex++]=baseSlice(array,index,index+=size);return result}function compact(array){for(var index=-1,length=array?array.length:0,resIndex=0,result=[];++indexn?0:n,length)):[]}function dropRight(array,n,guard){var length=array?array.length:0;return length?(n=guard||n===undefined?1:toInteger(n),n=length-n,baseSlice(array,0,0>n?0:n)):[]}function dropRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!0,!0):[]}function dropWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!0):[]}function fill(array,value,start,end){var length=array?array.length:0;return length?(start&&"number"!=typeof start&&isIterateeCall(array,value,start)&&(start=0,end=length),baseFill(array,value,start,end)):[]}function findIndex(array,predicate,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=null==fromIndex?0:toInteger(fromIndex);return 0>index&&(index=nativeMax(length+index,0)),baseFindIndex(array,getIteratee(predicate,3),index)}function findLastIndex(array,predicate,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=length-1;return fromIndex!==undefined&&(index=toInteger(fromIndex),index=0>fromIndex?nativeMax(length+index,0):nativeMin(index,length-1)),baseFindIndex(array,getIteratee(predicate,3),index,!0)}function flatten(array){var length=array?array.length:0;return length?baseFlatten(array,1):[]}function flattenDeep(array){var length=array?array.length:0;return length?baseFlatten(array,INFINITY):[]}function flattenDepth(array,depth){var length=array?array.length:0;return length?(depth=depth===undefined?1:toInteger(depth),baseFlatten(array,depth)):[]}function fromPairs(pairs){for(var index=-1,length=pairs?pairs.length:0,result={};++indexindex&&(index=nativeMax(length+index,0)),baseIndexOf(array,value,index)}function initial(array){var length=array?array.length:0;return length?baseSlice(array,0,-1):[]}function join(array,separator){return array?nativeJoin.call(array,separator):""}function last(array){var length=array?array.length:0;return length?array[length-1]:undefined}function lastIndexOf(array,value,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=length;return fromIndex!==undefined&&(index=toInteger(fromIndex),index=0>index?nativeMax(length+index,0):nativeMin(index,length-1)),value===value?strictLastIndexOf(array,value,index):baseFindIndex(array,baseIsNaN,index,!0)}function nth(array,n){return array&&array.length?baseNth(array,toInteger(n)):undefined}function pullAll(array,values){return array&&array.length&&values&&values.length?basePullAll(array,values):array}function pullAllBy(array,values,iteratee){return array&&array.length&&values&&values.length?basePullAll(array,values,getIteratee(iteratee,2)):array}function pullAllWith(array,values,comparator){return array&&array.length&&values&&values.length?basePullAll(array,values,undefined,comparator):array}function remove(array,predicate){var result=[];if(!array||!array.length)return result;var index=-1,indexes=[],length=array.length;for(predicate=getIteratee(predicate,3);++indexindex&&eq(array[index],value))return index}return-1}function sortedLastIndex(array,value){return baseSortedIndex(array,value,!0)}function sortedLastIndexBy(array,value,iteratee){return baseSortedIndexBy(array,value,getIteratee(iteratee,2),!0)}function sortedLastIndexOf(array,value){var length=array?array.length:0;if(length){var index=baseSortedIndex(array,value,!0)-1;if(eq(array[index],value))return index}return-1}function sortedUniq(array){return array&&array.length?baseSortedUniq(array):[]}function sortedUniqBy(array,iteratee){return array&&array.length?baseSortedUniq(array,getIteratee(iteratee,2)):[]}function tail(array){var length=array?array.length:0;return length?baseSlice(array,1,length):[]}function take(array,n,guard){return array&&array.length?(n=guard||n===undefined?1:toInteger(n),baseSlice(array,0,0>n?0:n)):[]}function takeRight(array,n,guard){var length=array?array.length:0;return length?(n=guard||n===undefined?1:toInteger(n),n=length-n,baseSlice(array,0>n?0:n,length)):[]}function takeRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!1,!0):[]}function takeWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3)):[]}function uniq(array){return array&&array.length?baseUniq(array):[]}function uniqBy(array,iteratee){return array&&array.length?baseUniq(array,getIteratee(iteratee,2)):[]}function uniqWith(array,comparator){return array&&array.length?baseUniq(array,undefined,comparator):[]}function unzip(array){if(!array||!array.length)return[];var length=0;return array=arrayFilter(array,function(group){return isArrayLikeObject(group)?(length=nativeMax(group.length,length),!0):void 0}),baseTimes(length,function(index){return arrayMap(array,baseProperty(index))})}function unzipWith(array,iteratee){if(!array||!array.length)return[];var result=unzip(array);return null==iteratee?result:arrayMap(result,function(group){return apply(iteratee,undefined,group)})}function zipObject(props,values){return baseZipObject(props||[],values||[],assignValue)}function zipObjectDeep(props,values){return baseZipObject(props||[],values||[],baseSet)}function chain(value){var result=lodash(value);return result.__chain__=!0,result}function tap(value,interceptor){return interceptor(value),value}function thru(value,interceptor){return interceptor(value)}function wrapperChain(){return chain(this)}function wrapperCommit(){return new LodashWrapper(this.value(),this.__chain__)}function wrapperNext(){this.__values__===undefined&&(this.__values__=toArray(this.value()));var done=this.__index__>=this.__values__.length,value=done?undefined:this.__values__[this.__index__++];return{done:done,value:value}}function wrapperToIterator(){return this}function wrapperPlant(value){for(var result,parent=this;parent instanceof baseLodash;){var clone=wrapperClone(parent);clone.__index__=0,clone.__values__=undefined,result?previous.__wrapped__=clone:result=clone;var previous=clone;parent=parent.__wrapped__}return previous.__wrapped__=value,result}function wrapperReverse(){var value=this.__wrapped__;if(value instanceof LazyWrapper){var wrapped=value;return this.__actions__.length&&(wrapped=new LazyWrapper(this)),wrapped=wrapped.reverse(),wrapped.__actions__.push({func:thru,args:[reverse],thisArg:undefined}),new LodashWrapper(wrapped,this.__chain__)}return this.thru(reverse)}function wrapperValue(){return baseWrapperValue(this.__wrapped__,this.__actions__)}function every(collection,predicate,guard){var func=isArray(collection)?arrayEvery:baseEvery;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=undefined),func(collection,getIteratee(predicate,3))}function filter(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,getIteratee(predicate,3))}function flatMap(collection,iteratee){return baseFlatten(map(collection,iteratee),1)}function flatMapDeep(collection,iteratee){return baseFlatten(map(collection,iteratee),INFINITY)}function flatMapDepth(collection,iteratee,depth){return depth=depth===undefined?1:toInteger(depth),baseFlatten(map(collection,iteratee),depth)}function forEach(collection,iteratee){var func=isArray(collection)?arrayEach:baseEach;return func(collection,getIteratee(iteratee,3))}function forEachRight(collection,iteratee){var func=isArray(collection)?arrayEachRight:baseEachRight;return func(collection,getIteratee(iteratee,3))}function includes(collection,value,fromIndex,guard){collection=isArrayLike(collection)?collection:values(collection),fromIndex=fromIndex&&!guard?toInteger(fromIndex):0;var length=collection.length;return 0>fromIndex&&(fromIndex=nativeMax(length+fromIndex,0)),isString(collection)?length>=fromIndex&&collection.indexOf(value,fromIndex)>-1:!!length&&baseIndexOf(collection,value,fromIndex)>-1}function map(collection,iteratee){var func=isArray(collection)?arrayMap:baseMap;return func(collection,getIteratee(iteratee,3))}function orderBy(collection,iteratees,orders,guard){return null==collection?[]:(isArray(iteratees)||(iteratees=null==iteratees?[]:[iteratees]),orders=guard?undefined:orders,isArray(orders)||(orders=null==orders?[]:[orders]),baseOrderBy(collection,iteratees,orders))}function reduce(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduce:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEach)}function reduceRight(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduceRight:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEachRight)}function reject(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,negate(getIteratee(predicate,3)))}function sample(collection){var func=isArray(collection)?arraySample:baseSample;return func(collection)}function sampleSize(collection,n,guard){n=(guard?isIterateeCall(collection,n,guard):n===undefined)?1:toInteger(n);var func=isArray(collection)?arraySampleSize:baseSampleSize;return func(collection,n)}function shuffle(collection){var func=isArray(collection)?arrayShuffle:baseShuffle;return func(collection)}function size(collection){if(null==collection)return 0;if(isArrayLike(collection))return isString(collection)?stringSize(collection):collection.length;var tag=getTag(collection);return tag==mapTag||tag==setTag?collection.size:baseKeys(collection).length}function some(collection,predicate,guard){var func=isArray(collection)?arraySome:baseSome;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=undefined),func(collection,getIteratee(predicate,3))}function after(n,func){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return n=toInteger(n),function(){return--n<1?func.apply(this,arguments):void 0}}function ary(func,n,guard){return n=guard?undefined:n,n=func&&null==n?func.length:n,createWrap(func,ARY_FLAG,undefined,undefined,undefined,undefined,n)}function before(n,func){var result;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return n=toInteger(n),function(){return--n>0&&(result=func.apply(this,arguments)),1>=n&&(func=undefined),result}}function curry(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,CURRY_FLAG,undefined,undefined,undefined,undefined,undefined,arity);return result.placeholder=curry.placeholder,result}function curryRight(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,CURRY_RIGHT_FLAG,undefined,undefined,undefined,undefined,undefined,arity);return result.placeholder=curryRight.placeholder,result}function debounce(func,wait,options){function invokeFunc(time){var args=lastArgs,thisArg=lastThis;return lastArgs=lastThis=undefined,lastInvokeTime=time,result=func.apply(thisArg,args)}function leadingEdge(time){return lastInvokeTime=time,timerId=setTimeout(timerExpired,wait),leading?invokeFunc(time):result}function remainingWait(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime,result=wait-timeSinceLastCall;return maxing?nativeMin(result,maxWait-timeSinceLastInvoke):result}function shouldInvoke(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime;return lastCallTime===undefined||timeSinceLastCall>=wait||0>timeSinceLastCall||maxing&&timeSinceLastInvoke>=maxWait}function timerExpired(){var time=now();return shouldInvoke(time)?trailingEdge(time):void(timerId=setTimeout(timerExpired,remainingWait(time)))}function trailingEdge(time){return timerId=undefined,trailing&&lastArgs?invokeFunc(time):(lastArgs=lastThis=undefined,result)}function cancel(){timerId!==undefined&&clearTimeout(timerId),lastInvokeTime=0,lastArgs=lastCallTime=lastThis=timerId=undefined}function flush(){return timerId===undefined?result:trailingEdge(now())}function debounced(){var time=now(),isInvoking=shouldInvoke(time);if(lastArgs=arguments,lastThis=this,lastCallTime=time,isInvoking){if(timerId===undefined)return leadingEdge(lastCallTime);if(maxing)return timerId=setTimeout(timerExpired,wait),invokeFunc(lastCallTime)}return timerId===undefined&&(timerId=setTimeout(timerExpired,wait)),result}var lastArgs,lastThis,maxWait,result,timerId,lastCallTime,lastInvokeTime=0,leading=!1,maxing=!1,trailing=!0;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return wait=toNumber(wait)||0,isObject(options)&&(leading=!!options.leading,maxing="maxWait"in options,maxWait=maxing?nativeMax(toNumber(options.maxWait)||0,wait):maxWait,trailing="trailing"in options?!!options.trailing:trailing),debounced.cancel=cancel,debounced.flush=flush,debounced}function flip(func){return createWrap(func,FLIP_FLAG)}function memoize(func,resolver){if("function"!=typeof func||resolver&&"function"!=typeof resolver)throw new TypeError(FUNC_ERROR_TEXT);var memoized=function(){var args=arguments,key=resolver?resolver.apply(this,args):args[0],cache=memoized.cache;if(cache.has(key))return cache.get(key);var result=func.apply(this,args);return memoized.cache=cache.set(key,result)||cache,result};return memoized.cache=new(memoize.Cache||MapCache),memoized}function negate(predicate){if("function"!=typeof predicate)throw new TypeError(FUNC_ERROR_TEXT);return function(){var args=arguments;switch(args.length){case 0:return!predicate.call(this);case 1:return!predicate.call(this,args[0]);case 2:return!predicate.call(this,args[0],args[1]);case 3:return!predicate.call(this,args[0],args[1],args[2])}return!predicate.apply(this,args)}}function once(func){return before(2,func)}function rest(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=start===undefined?start:toInteger(start),baseRest(func,start)}function spread(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=start===undefined?0:nativeMax(toInteger(start),0),baseRest(function(args){var array=args[start],otherArgs=castSlice(args,0,start);return array&&arrayPush(otherArgs,array),apply(func,this,otherArgs)})}function throttle(func,wait,options){var leading=!0,trailing=!0;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return isObject(options)&&(leading="leading"in options?!!options.leading:leading,trailing="trailing"in options?!!options.trailing:trailing),debounce(func,wait,{leading:leading,maxWait:wait,trailing:trailing})}function unary(func){return ary(func,1)}function wrap(value,wrapper){return wrapper=null==wrapper?identity:wrapper,partial(wrapper,value)}function castArray(){if(!arguments.length)return[];var value=arguments[0];return isArray(value)?value:[value]}function clone(value){return baseClone(value,!1,!0)}function cloneWith(value,customizer){return baseClone(value,!1,!0,customizer)}function cloneDeep(value){return baseClone(value,!0,!0)}function cloneDeepWith(value,customizer){return baseClone(value,!0,!0,customizer)}function conformsTo(object,source){return null==source||baseConformsTo(object,source,keys(source))}function eq(value,other){return value===other||value!==value&&other!==other}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value)}function isBoolean(value){return value===!0||value===!1||isObjectLike(value)&&objectToString.call(value)==boolTag}function isElement(value){return null!=value&&1===value.nodeType&&isObjectLike(value)&&!isPlainObject(value)}function isEmpty(value){if(isArrayLike(value)&&(isArray(value)||"string"==typeof value||"function"==typeof value.splice||isBuffer(value)||isTypedArray(value)||isArguments(value)))return!value.length;var tag=getTag(value);if(tag==mapTag||tag==setTag)return!value.size;if(isPrototype(value))return!baseKeys(value).length;for(var key in value)if(hasOwnProperty.call(value,key))return!1;return!0}function isEqual(value,other){return baseIsEqual(value,other)}function isEqualWith(value,other,customizer){customizer="function"==typeof customizer?customizer:undefined;var result=customizer?customizer(value,other):undefined;return result===undefined?baseIsEqual(value,other,customizer):!!result}function isError(value){return isObjectLike(value)?objectToString.call(value)==errorTag||"string"==typeof value.message&&"string"==typeof value.name:!1}function isFinite(value){return"number"==typeof value&&nativeIsFinite(value)}function isFunction(value){var tag=isObject(value)?objectToString.call(value):"";return tag==funcTag||tag==genTag||tag==proxyTag}function isInteger(value){return"number"==typeof value&&value==toInteger(value)}function isLength(value){return"number"==typeof value&&value>-1&&value%1==0&&MAX_SAFE_INTEGER>=value}function isObject(value){var type=typeof value;return null!=value&&("object"==type||"function"==type)}function isObjectLike(value){return null!=value&&"object"==typeof value}function isMatch(object,source){return object===source||baseIsMatch(object,source,getMatchData(source))}function isMatchWith(object,source,customizer){return customizer="function"==typeof customizer?customizer:undefined,baseIsMatch(object,source,getMatchData(source),customizer)}function isNaN(value){return isNumber(value)&&value!=+value}function isNative(value){if(isMaskable(value))throw new Error(CORE_ERROR_TEXT);return baseIsNative(value)}function isNull(value){return null===value}function isNil(value){return null==value}function isNumber(value){return"number"==typeof value||isObjectLike(value)&&objectToString.call(value)==numberTag}function isPlainObject(value){if(!isObjectLike(value)||objectToString.call(value)!=objectTag)return!1;var proto=getPrototype(value);if(null===proto)return!0;var Ctor=hasOwnProperty.call(proto,"constructor")&&proto.constructor;return"function"==typeof Ctor&&Ctor instanceof Ctor&&funcToString.call(Ctor)==objectCtorString}function isSafeInteger(value){return isInteger(value)&&value>=-MAX_SAFE_INTEGER&&MAX_SAFE_INTEGER>=value}function isString(value){return"string"==typeof value||!isArray(value)&&isObjectLike(value)&&objectToString.call(value)==stringTag}function isSymbol(value){return"symbol"==typeof value||isObjectLike(value)&&objectToString.call(value)==symbolTag}function isUndefined(value){return value===undefined}function isWeakMap(value){return isObjectLike(value)&&getTag(value)==weakMapTag}function isWeakSet(value){return isObjectLike(value)&&objectToString.call(value)==weakSetTag}function toArray(value){if(!value)return[];if(isArrayLike(value))return isString(value)?stringToArray(value):copyArray(value);if(iteratorSymbol&&value[iteratorSymbol])return iteratorToArray(value[iteratorSymbol]());var tag=getTag(value),func=tag==mapTag?mapToArray:tag==setTag?setToArray:values;return func(value)}function toFinite(value){if(!value)return 0===value?value:0;if(value=toNumber(value),value===INFINITY||value===-INFINITY){var sign=0>value?-1:1;return sign*MAX_INTEGER}return value===value?value:0}function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0}function toLength(value){return value?baseClamp(toInteger(value),0,MAX_ARRAY_LENGTH):0}function toNumber(value){if("number"==typeof value)return value;if(isSymbol(value))return NAN;if(isObject(value)){var other="function"==typeof value.valueOf?value.valueOf():value;value=isObject(other)?other+"":other}if("string"!=typeof value)return 0===value?value:+value;value=value.replace(reTrim,"");var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value}function toPlainObject(value){return copyObject(value,keysIn(value))}function toSafeInteger(value){return baseClamp(toInteger(value),-MAX_SAFE_INTEGER,MAX_SAFE_INTEGER)}function toString(value){return null==value?"":baseToString(value)}function create(prototype,properties){var result=baseCreate(prototype);return properties?baseAssign(result,properties):result}function findKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwn)}function findLastKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwnRight)}function forIn(object,iteratee){return null==object?object:baseFor(object,getIteratee(iteratee,3),keysIn)}function forInRight(object,iteratee){return null==object?object:baseForRight(object,getIteratee(iteratee,3),keysIn)}function forOwn(object,iteratee){return object&&baseForOwn(object,getIteratee(iteratee,3))}function forOwnRight(object,iteratee){return object&&baseForOwnRight(object,getIteratee(iteratee,3))}function functions(object){return null==object?[]:baseFunctions(object,keys(object))}function functionsIn(object){return null==object?[]:baseFunctions(object,keysIn(object))}function get(object,path,defaultValue){var result=null==object?undefined:baseGet(object,path);return result===undefined?defaultValue:result}function has(object,path){return null!=object&&hasPath(object,path,baseHas)}function hasIn(object,path){return null!=object&&hasPath(object,path,baseHasIn)}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function keysIn(object){return isArrayLike(object)?arrayLikeKeys(object,!0):baseKeysIn(object)}function mapKeys(object,iteratee){var result={};return iteratee=getIteratee(iteratee,3), baseForOwn(object,function(value,key,object){baseAssignValue(result,iteratee(value,key,object),value)}),result}function mapValues(object,iteratee){var result={};return iteratee=getIteratee(iteratee,3),baseForOwn(object,function(value,key,object){baseAssignValue(result,key,iteratee(value,key,object))}),result}function omitBy(object,predicate){return pickBy(object,negate(getIteratee(predicate)))}function pickBy(object,predicate){return null==object?{}:basePickBy(object,getAllKeysIn(object),getIteratee(predicate))}function result(object,path,defaultValue){path=isKey(path,object)?[path]:castPath(path);var index=-1,length=path.length;for(length||(object=undefined,length=1);++indexupper){var temp=lower;lower=upper,upper=temp}if(floating||lower%1||upper%1){var rand=nativeRandom();return nativeMin(lower+rand*(upper-lower+freeParseFloat("1e-"+((rand+"").length-1))),upper)}return baseRandom(lower,upper)}function capitalize(string){return upperFirst(toString(string).toLowerCase())}function deburr(string){return string=toString(string),string&&string.replace(reLatin,deburrLetter).replace(reComboMark,"")}function endsWith(string,target,position){string=toString(string),target=baseToString(target);var length=string.length;position=position===undefined?length:baseClamp(toInteger(position),0,length);var end=position;return position-=target.length,position>=0&&string.slice(position,end)==target}function escape(string){return string=toString(string),string&&reHasUnescapedHtml.test(string)?string.replace(reUnescapedHtml,escapeHtmlChar):string}function escapeRegExp(string){return string=toString(string),string&&reHasRegExpChar.test(string)?string.replace(reRegExpChar,"\\$&"):string}function pad(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;if(!length||strLength>=length)return string;var mid=(length-strLength)/2;return createPadding(nativeFloor(mid),chars)+string+createPadding(nativeCeil(mid),chars)}function padEnd(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;return length&&length>strLength?string+createPadding(length-strLength,chars):string}function padStart(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;return length&&length>strLength?createPadding(length-strLength,chars)+string:string}function parseInt(string,radix,guard){return guard||null==radix?radix=0:radix&&(radix=+radix),nativeParseInt(toString(string).replace(reTrimStart,""),radix||0)}function repeat(string,n,guard){return n=(guard?isIterateeCall(string,n,guard):n===undefined)?1:toInteger(n),baseRepeat(toString(string),n)}function replace(){var args=arguments,string=toString(args[0]);return args.length<3?string:string.replace(args[1],args[2])}function split(string,separator,limit){return limit&&"number"!=typeof limit&&isIterateeCall(string,separator,limit)&&(separator=limit=undefined),(limit=limit===undefined?MAX_ARRAY_LENGTH:limit>>>0)?(string=toString(string),string&&("string"==typeof separator||null!=separator&&!isRegExp(separator))&&(separator=baseToString(separator),!separator&&hasUnicode(string))?castSlice(stringToArray(string),0,limit):string.split(separator,limit)):[]}function startsWith(string,target,position){return string=toString(string),position=baseClamp(toInteger(position),0,string.length),target=baseToString(target),string.slice(position,position+target.length)==target}function template(string,options,guard){var settings=lodash.templateSettings;guard&&isIterateeCall(string,options,guard)&&(options=undefined),string=toString(string),options=assignInWith({},options,settings,assignInDefaults);var isEscaping,isEvaluating,imports=assignInWith({},options.imports,settings.imports,assignInDefaults),importsKeys=keys(imports),importsValues=baseValues(imports,importsKeys),index=0,interpolate=options.interpolate||reNoMatch,source="__p += '",reDelimiters=RegExp((options.escape||reNoMatch).source+"|"+interpolate.source+"|"+(interpolate===reInterpolate?reEsTemplate:reNoMatch).source+"|"+(options.evaluate||reNoMatch).source+"|$","g"),sourceURL="//# sourceURL="+("sourceURL"in options?options.sourceURL:"lodash.templateSources["+ ++templateCounter+"]")+"\n";string.replace(reDelimiters,function(match,escapeValue,interpolateValue,esTemplateValue,evaluateValue,offset){return interpolateValue||(interpolateValue=esTemplateValue),source+=string.slice(index,offset).replace(reUnescapedString,escapeStringChar),escapeValue&&(isEscaping=!0,source+="' +\n__e("+escapeValue+") +\n'"),evaluateValue&&(isEvaluating=!0,source+="';\n"+evaluateValue+";\n__p += '"),interpolateValue&&(source+="' +\n((__t = ("+interpolateValue+")) == null ? '' : __t) +\n'"),index=offset+match.length,match}),source+="';\n";var variable=options.variable;variable||(source="with (obj) {\n"+source+"\n}\n"),source=(isEvaluating?source.replace(reEmptyStringLeading,""):source).replace(reEmptyStringMiddle,"$1").replace(reEmptyStringTrailing,"$1;"),source="function("+(variable||"obj")+") {\n"+(variable?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(isEscaping?", __e = _.escape":"")+(isEvaluating?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+source+"return __p\n}";var result=attempt(function(){return Function(importsKeys,sourceURL+"return "+source).apply(undefined,importsValues)});if(result.source=source,isError(result))throw result;return result}function toLower(value){return toString(value).toLowerCase()}function toUpper(value){return toString(value).toUpperCase()}function trim(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrim,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),chrSymbols=stringToArray(chars),start=charsStartIndex(strSymbols,chrSymbols),end=charsEndIndex(strSymbols,chrSymbols)+1;return castSlice(strSymbols,start,end).join("")}function trimEnd(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrimEnd,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),end=charsEndIndex(strSymbols,stringToArray(chars))+1;return castSlice(strSymbols,0,end).join("")}function trimStart(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrimStart,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),start=charsStartIndex(strSymbols,stringToArray(chars));return castSlice(strSymbols,start).join("")}function truncate(string,options){var length=DEFAULT_TRUNC_LENGTH,omission=DEFAULT_TRUNC_OMISSION;if(isObject(options)){var separator="separator"in options?options.separator:separator;length="length"in options?toInteger(options.length):length,omission="omission"in options?baseToString(options.omission):omission}string=toString(string);var strLength=string.length;if(hasUnicode(string)){var strSymbols=stringToArray(string);strLength=strSymbols.length}if(length>=strLength)return string;var end=length-stringSize(omission);if(1>end)return omission;var result=strSymbols?castSlice(strSymbols,0,end).join(""):string.slice(0,end);if(separator===undefined)return result+omission;if(strSymbols&&(end+=result.length-end),isRegExp(separator)){if(string.slice(end).search(separator)){var match,substring=result;for(separator.global||(separator=RegExp(separator.source,toString(reFlags.exec(separator))+"g")),separator.lastIndex=0;match=separator.exec(substring);)var newEnd=match.index;result=result.slice(0,newEnd===undefined?end:newEnd)}}else if(string.indexOf(baseToString(separator),end)!=end){var index=result.lastIndexOf(separator);index>-1&&(result=result.slice(0,index))}return result+omission}function unescape(string){return string=toString(string),string&&reHasEscapedHtml.test(string)?string.replace(reEscapedHtml,unescapeHtmlChar):string}function words(string,pattern,guard){return string=toString(string),pattern=guard?undefined:pattern,pattern===undefined?hasUnicodeWord(string)?unicodeWords(string):asciiWords(string):string.match(pattern)||[]}function cond(pairs){var length=pairs?pairs.length:0,toIteratee=getIteratee();return pairs=length?arrayMap(pairs,function(pair){if("function"!=typeof pair[1])throw new TypeError(FUNC_ERROR_TEXT);return[toIteratee(pair[0]),pair[1]]}):[],baseRest(function(args){for(var index=-1;++indexn||n>MAX_SAFE_INTEGER)return[];var index=MAX_ARRAY_LENGTH,length=nativeMin(n,MAX_ARRAY_LENGTH);iteratee=getIteratee(iteratee),n-=MAX_ARRAY_LENGTH;for(var result=baseTimes(length,iteratee);++index1?arrays[length-1]:undefined;return iteratee="function"==typeof iteratee?(arrays.pop(),iteratee):undefined,unzipWith(arrays,iteratee)}),wrapperAt=flatRest(function(paths){var length=paths.length,start=length?paths[0]:0,value=this.__wrapped__,interceptor=function(object){return baseAt(object,paths)};return!(length>1||this.__actions__.length)&&value instanceof LazyWrapper&&isIndex(start)?(value=value.slice(start,+start+(length?1:0)),value.__actions__.push({func:thru,args:[interceptor],thisArg:undefined}),new LodashWrapper(value,this.__chain__).thru(function(array){return length&&!array.length&&array.push(undefined),array})):this.thru(interceptor)}),countBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?++result[key]:baseAssignValue(result,key,1)}),find=createFind(findIndex),findLast=createFind(findLastIndex),groupBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?result[key].push(value):baseAssignValue(result,key,[value])}),invokeMap=baseRest(function(collection,path,args){var index=-1,isFunc="function"==typeof path,isProp=isKey(path),result=isArrayLike(collection)?Array(collection.length):[];return baseEach(collection,function(value){var func=isFunc?path:isProp&&null!=value?value[path]:undefined;result[++index]=func?apply(func,value,args):baseInvoke(value,path,args)}),result}),keyBy=createAggregator(function(result,value,key){baseAssignValue(result,key,value)}),partition=createAggregator(function(result,value,key){result[key?0:1].push(value)},function(){return[[],[]]}),sortBy=baseRest(function(collection,iteratees){if(null==collection)return[];var length=iteratees.length;return length>1&&isIterateeCall(collection,iteratees[0],iteratees[1])?iteratees=[]:length>2&&isIterateeCall(iteratees[0],iteratees[1],iteratees[2])&&(iteratees=[iteratees[0]]),baseOrderBy(collection,baseFlatten(iteratees,1),[])}),now=ctxNow||function(){return root.Date.now()},bind=baseRest(function(func,thisArg,partials){var bitmask=BIND_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bind));bitmask|=PARTIAL_FLAG}return createWrap(func,bitmask,thisArg,partials,holders)}),bindKey=baseRest(function(object,key,partials){var bitmask=BIND_FLAG|BIND_KEY_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bindKey));bitmask|=PARTIAL_FLAG}return createWrap(key,bitmask,object,partials,holders)}),defer=baseRest(function(func,args){return baseDelay(func,1,args)}),delay=baseRest(function(func,wait,args){return baseDelay(func,toNumber(wait)||0,args)});memoize.Cache=MapCache;var overArgs=castRest(function(func,transforms){transforms=1==transforms.length&&isArray(transforms[0])?arrayMap(transforms[0],baseUnary(getIteratee())):arrayMap(baseFlatten(transforms,1),baseUnary(getIteratee()));var funcsLength=transforms.length;return baseRest(function(args){for(var index=-1,length=nativeMin(args.length,funcsLength);++index=other}),isArguments=baseIsArguments(function(){return arguments}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty.call(value,"callee")&&!propertyIsEnumerable.call(value,"callee")},isArray=Array.isArray,isArrayBuffer=nodeIsArrayBuffer?baseUnary(nodeIsArrayBuffer):baseIsArrayBuffer,isBuffer=nativeIsBuffer||stubFalse,isDate=nodeIsDate?baseUnary(nodeIsDate):baseIsDate,isMap=nodeIsMap?baseUnary(nodeIsMap):baseIsMap,isRegExp=nodeIsRegExp?baseUnary(nodeIsRegExp):baseIsRegExp,isSet=nodeIsSet?baseUnary(nodeIsSet):baseIsSet,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray,lt=createRelationalOperation(baseLt),lte=createRelationalOperation(function(value,other){return other>=value}),assign=createAssigner(function(object,source){if(isPrototype(source)||isArrayLike(source))return void copyObject(source,keys(source),object);for(var key in source)hasOwnProperty.call(source,key)&&assignValue(object,key,source[key])}),assignIn=createAssigner(function(object,source){copyObject(source,keysIn(source),object)}),assignInWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keysIn(source),object,customizer)}),assignWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keys(source),object,customizer)}),at=flatRest(baseAt),defaults=baseRest(function(args){return args.push(undefined,assignInDefaults),apply(assignInWith,undefined,args)}),defaultsDeep=baseRest(function(args){return args.push(undefined,mergeDefaults),apply(mergeWith,undefined,args)}),invert=createInverter(function(result,value,key){result[value]=key},constant(identity)),invertBy=createInverter(function(result,value,key){hasOwnProperty.call(result,value)?result[value].push(key):result[value]=[key]},getIteratee),invoke=baseRest(baseInvoke),merge=createAssigner(function(object,source,srcIndex){baseMerge(object,source,srcIndex)}),mergeWith=createAssigner(function(object,source,srcIndex,customizer){baseMerge(object,source,srcIndex,customizer)}),omit=flatRest(function(object,props){return null==object?{}:(props=arrayMap(props,toKey),basePick(object,baseDifference(getAllKeysIn(object),props)))}),pick=flatRest(function(object,props){return null==object?{}:basePick(object,arrayMap(props,toKey))}),toPairs=createToPairs(keys),toPairsIn=createToPairs(keysIn),camelCase=createCompounder(function(result,word,index){return word=word.toLowerCase(),result+(index?capitalize(word):word)}),kebabCase=createCompounder(function(result,word,index){return result+(index?"-":"")+word.toLowerCase()}),lowerCase=createCompounder(function(result,word,index){return result+(index?" ":"")+word.toLowerCase()}),lowerFirst=createCaseFirst("toLowerCase"),snakeCase=createCompounder(function(result,word,index){return result+(index?"_":"")+word.toLowerCase()}),startCase=createCompounder(function(result,word,index){return result+(index?" ":"")+upperFirst(word)}),upperCase=createCompounder(function(result,word,index){return result+(index?" ":"")+word.toUpperCase()}),upperFirst=createCaseFirst("toUpperCase"),attempt=baseRest(function(func,args){try{return apply(func,undefined,args)}catch(e){return isError(e)?e:new Error(e)}}),bindAll=flatRest(function(object,methodNames){return arrayEach(methodNames,function(key){key=toKey(key),baseAssignValue(object,key,bind(object[key],object))}),object}),flow=createFlow(),flowRight=createFlow(!0),method=baseRest(function(path,args){return function(object){return baseInvoke(object,path,args)}}),methodOf=baseRest(function(object,args){return function(path){return baseInvoke(object,path,args)}}),over=createOver(arrayMap),overEvery=createOver(arrayEvery),overSome=createOver(arraySome),range=createRange(),rangeRight=createRange(!0),add=createMathOperation(function(augend,addend){return augend+addend},0),ceil=createRound("ceil"),divide=createMathOperation(function(dividend,divisor){return dividend/divisor},1),floor=createRound("floor"),multiply=createMathOperation(function(multiplier,multiplicand){return multiplier*multiplicand},1),round=createRound("round"),subtract=createMathOperation(function(minuend,subtrahend){return minuend-subtrahend},0);return lodash.after=after,lodash.ary=ary,lodash.assign=assign,lodash.assignIn=assignIn,lodash.assignInWith=assignInWith,lodash.assignWith=assignWith,lodash.at=at,lodash.before=before,lodash.bind=bind,lodash.bindAll=bindAll,lodash.bindKey=bindKey,lodash.castArray=castArray,lodash.chain=chain,lodash.chunk=chunk,lodash.compact=compact,lodash.concat=concat,lodash.cond=cond,lodash.conforms=conforms,lodash.constant=constant,lodash.countBy=countBy,lodash.create=create,lodash.curry=curry,lodash.curryRight=curryRight,lodash.debounce=debounce,lodash.defaults=defaults,lodash.defaultsDeep=defaultsDeep,lodash.defer=defer,lodash.delay=delay,lodash.difference=difference,lodash.differenceBy=differenceBy,lodash.differenceWith=differenceWith,lodash.drop=drop,lodash.dropRight=dropRight,lodash.dropRightWhile=dropRightWhile,lodash.dropWhile=dropWhile,lodash.fill=fill,lodash.filter=filter,lodash.flatMap=flatMap,lodash.flatMapDeep=flatMapDeep,lodash.flatMapDepth=flatMapDepth,lodash.flatten=flatten,lodash.flattenDeep=flattenDeep,lodash.flattenDepth=flattenDepth,lodash.flip=flip,lodash.flow=flow,lodash.flowRight=flowRight,lodash.fromPairs=fromPairs,lodash.functions=functions,lodash.functionsIn=functionsIn,lodash.groupBy=groupBy,lodash.initial=initial,lodash.intersection=intersection,lodash.intersectionBy=intersectionBy,lodash.intersectionWith=intersectionWith,lodash.invert=invert,lodash.invertBy=invertBy,lodash.invokeMap=invokeMap,lodash.iteratee=iteratee,lodash.keyBy=keyBy,lodash.keys=keys,lodash.keysIn=keysIn,lodash.map=map,lodash.mapKeys=mapKeys,lodash.mapValues=mapValues,lodash.matches=matches,lodash.matchesProperty=matchesProperty, lodash.memoize=memoize,lodash.merge=merge,lodash.mergeWith=mergeWith,lodash.method=method,lodash.methodOf=methodOf,lodash.mixin=mixin,lodash.negate=negate,lodash.nthArg=nthArg,lodash.omit=omit,lodash.omitBy=omitBy,lodash.once=once,lodash.orderBy=orderBy,lodash.over=over,lodash.overArgs=overArgs,lodash.overEvery=overEvery,lodash.overSome=overSome,lodash.partial=partial,lodash.partialRight=partialRight,lodash.partition=partition,lodash.pick=pick,lodash.pickBy=pickBy,lodash.property=property,lodash.propertyOf=propertyOf,lodash.pull=pull,lodash.pullAll=pullAll,lodash.pullAllBy=pullAllBy,lodash.pullAllWith=pullAllWith,lodash.pullAt=pullAt,lodash.range=range,lodash.rangeRight=rangeRight,lodash.rearg=rearg,lodash.reject=reject,lodash.remove=remove,lodash.rest=rest,lodash.reverse=reverse,lodash.sampleSize=sampleSize,lodash.set=set,lodash.setWith=setWith,lodash.shuffle=shuffle,lodash.slice=slice,lodash.sortBy=sortBy,lodash.sortedUniq=sortedUniq,lodash.sortedUniqBy=sortedUniqBy,lodash.split=split,lodash.spread=spread,lodash.tail=tail,lodash.take=take,lodash.takeRight=takeRight,lodash.takeRightWhile=takeRightWhile,lodash.takeWhile=takeWhile,lodash.tap=tap,lodash.throttle=throttle,lodash.thru=thru,lodash.toArray=toArray,lodash.toPairs=toPairs,lodash.toPairsIn=toPairsIn,lodash.toPath=toPath,lodash.toPlainObject=toPlainObject,lodash.transform=transform,lodash.unary=unary,lodash.union=union,lodash.unionBy=unionBy,lodash.unionWith=unionWith,lodash.uniq=uniq,lodash.uniqBy=uniqBy,lodash.uniqWith=uniqWith,lodash.unset=unset,lodash.unzip=unzip,lodash.unzipWith=unzipWith,lodash.update=update,lodash.updateWith=updateWith,lodash.values=values,lodash.valuesIn=valuesIn,lodash.without=without,lodash.words=words,lodash.wrap=wrap,lodash.xor=xor,lodash.xorBy=xorBy,lodash.xorWith=xorWith,lodash.zip=zip,lodash.zipObject=zipObject,lodash.zipObjectDeep=zipObjectDeep,lodash.zipWith=zipWith,lodash.entries=toPairs,lodash.entriesIn=toPairsIn,lodash.extend=assignIn,lodash.extendWith=assignInWith,mixin(lodash,lodash),lodash.add=add,lodash.attempt=attempt,lodash.camelCase=camelCase,lodash.capitalize=capitalize,lodash.ceil=ceil,lodash.clamp=clamp,lodash.clone=clone,lodash.cloneDeep=cloneDeep,lodash.cloneDeepWith=cloneDeepWith,lodash.cloneWith=cloneWith,lodash.conformsTo=conformsTo,lodash.deburr=deburr,lodash.defaultTo=defaultTo,lodash.divide=divide,lodash.endsWith=endsWith,lodash.eq=eq,lodash.escape=escape,lodash.escapeRegExp=escapeRegExp,lodash.every=every,lodash.find=find,lodash.findIndex=findIndex,lodash.findKey=findKey,lodash.findLast=findLast,lodash.findLastIndex=findLastIndex,lodash.findLastKey=findLastKey,lodash.floor=floor,lodash.forEach=forEach,lodash.forEachRight=forEachRight,lodash.forIn=forIn,lodash.forInRight=forInRight,lodash.forOwn=forOwn,lodash.forOwnRight=forOwnRight,lodash.get=get,lodash.gt=gt,lodash.gte=gte,lodash.has=has,lodash.hasIn=hasIn,lodash.head=head,lodash.identity=identity,lodash.includes=includes,lodash.indexOf=indexOf,lodash.inRange=inRange,lodash.invoke=invoke,lodash.isArguments=isArguments,lodash.isArray=isArray,lodash.isArrayBuffer=isArrayBuffer,lodash.isArrayLike=isArrayLike,lodash.isArrayLikeObject=isArrayLikeObject,lodash.isBoolean=isBoolean,lodash.isBuffer=isBuffer,lodash.isDate=isDate,lodash.isElement=isElement,lodash.isEmpty=isEmpty,lodash.isEqual=isEqual,lodash.isEqualWith=isEqualWith,lodash.isError=isError,lodash.isFinite=isFinite,lodash.isFunction=isFunction,lodash.isInteger=isInteger,lodash.isLength=isLength,lodash.isMap=isMap,lodash.isMatch=isMatch,lodash.isMatchWith=isMatchWith,lodash.isNaN=isNaN,lodash.isNative=isNative,lodash.isNil=isNil,lodash.isNull=isNull,lodash.isNumber=isNumber,lodash.isObject=isObject,lodash.isObjectLike=isObjectLike,lodash.isPlainObject=isPlainObject,lodash.isRegExp=isRegExp,lodash.isSafeInteger=isSafeInteger,lodash.isSet=isSet,lodash.isString=isString,lodash.isSymbol=isSymbol,lodash.isTypedArray=isTypedArray,lodash.isUndefined=isUndefined,lodash.isWeakMap=isWeakMap,lodash.isWeakSet=isWeakSet,lodash.join=join,lodash.kebabCase=kebabCase,lodash.last=last,lodash.lastIndexOf=lastIndexOf,lodash.lowerCase=lowerCase,lodash.lowerFirst=lowerFirst,lodash.lt=lt,lodash.lte=lte,lodash.max=max,lodash.maxBy=maxBy,lodash.mean=mean,lodash.meanBy=meanBy,lodash.min=min,lodash.minBy=minBy,lodash.stubArray=stubArray,lodash.stubFalse=stubFalse,lodash.stubObject=stubObject,lodash.stubString=stubString,lodash.stubTrue=stubTrue,lodash.multiply=multiply,lodash.nth=nth,lodash.noConflict=noConflict,lodash.noop=noop,lodash.now=now,lodash.pad=pad,lodash.padEnd=padEnd,lodash.padStart=padStart,lodash.parseInt=parseInt,lodash.random=random,lodash.reduce=reduce,lodash.reduceRight=reduceRight,lodash.repeat=repeat,lodash.replace=replace,lodash.result=result,lodash.round=round,lodash.runInContext=runInContext,lodash.sample=sample,lodash.size=size,lodash.snakeCase=snakeCase,lodash.some=some,lodash.sortedIndex=sortedIndex,lodash.sortedIndexBy=sortedIndexBy,lodash.sortedIndexOf=sortedIndexOf,lodash.sortedLastIndex=sortedLastIndex,lodash.sortedLastIndexBy=sortedLastIndexBy,lodash.sortedLastIndexOf=sortedLastIndexOf,lodash.startCase=startCase,lodash.startsWith=startsWith,lodash.subtract=subtract,lodash.sum=sum,lodash.sumBy=sumBy,lodash.template=template,lodash.times=times,lodash.toFinite=toFinite,lodash.toInteger=toInteger,lodash.toLength=toLength,lodash.toLower=toLower,lodash.toNumber=toNumber,lodash.toSafeInteger=toSafeInteger,lodash.toString=toString,lodash.toUpper=toUpper,lodash.trim=trim,lodash.trimEnd=trimEnd,lodash.trimStart=trimStart,lodash.truncate=truncate,lodash.unescape=unescape,lodash.uniqueId=uniqueId,lodash.upperCase=upperCase,lodash.upperFirst=upperFirst,lodash.each=forEach,lodash.eachRight=forEachRight,lodash.first=head,mixin(lodash,function(){var source={};return baseForOwn(lodash,function(func,methodName){hasOwnProperty.call(lodash.prototype,methodName)||(source[methodName]=func)}),source}(),{chain:!1}),lodash.VERSION=VERSION,arrayEach(["bind","bindKey","curry","curryRight","partial","partialRight"],function(methodName){lodash[methodName].placeholder=lodash}),arrayEach(["drop","take"],function(methodName,index){LazyWrapper.prototype[methodName]=function(n){var filtered=this.__filtered__;if(filtered&&!index)return new LazyWrapper(this);n=n===undefined?1:nativeMax(toInteger(n),0);var result=this.clone();return filtered?result.__takeCount__=nativeMin(n,result.__takeCount__):result.__views__.push({size:nativeMin(n,MAX_ARRAY_LENGTH),type:methodName+(result.__dir__<0?"Right":"")}),result},LazyWrapper.prototype[methodName+"Right"]=function(n){return this.reverse()[methodName](n).reverse()}}),arrayEach(["filter","map","takeWhile"],function(methodName,index){var type=index+1,isFilter=type==LAZY_FILTER_FLAG||type==LAZY_WHILE_FLAG;LazyWrapper.prototype[methodName]=function(iteratee){var result=this.clone();return result.__iteratees__.push({iteratee:getIteratee(iteratee,3),type:type}),result.__filtered__=result.__filtered__||isFilter,result}}),arrayEach(["head","last"],function(methodName,index){var takeName="take"+(index?"Right":"");LazyWrapper.prototype[methodName]=function(){return this[takeName](1).value()[0]}}),arrayEach(["initial","tail"],function(methodName,index){var dropName="drop"+(index?"":"Right");LazyWrapper.prototype[methodName]=function(){return this.__filtered__?new LazyWrapper(this):this[dropName](1)}}),LazyWrapper.prototype.compact=function(){return this.filter(identity)},LazyWrapper.prototype.find=function(predicate){return this.filter(predicate).head()},LazyWrapper.prototype.findLast=function(predicate){return this.reverse().find(predicate)},LazyWrapper.prototype.invokeMap=baseRest(function(path,args){return"function"==typeof path?new LazyWrapper(this):this.map(function(value){return baseInvoke(value,path,args)})}),LazyWrapper.prototype.reject=function(predicate){return this.filter(negate(getIteratee(predicate)))},LazyWrapper.prototype.slice=function(start,end){start=toInteger(start);var result=this;return result.__filtered__&&(start>0||0>end)?new LazyWrapper(result):(0>start?result=result.takeRight(-start):start&&(result=result.drop(start)),end!==undefined&&(end=toInteger(end),result=0>end?result.dropRight(-end):result.take(end-start)),result)},LazyWrapper.prototype.takeRightWhile=function(predicate){return this.reverse().takeWhile(predicate).reverse()},LazyWrapper.prototype.toArray=function(){return this.take(MAX_ARRAY_LENGTH)},baseForOwn(LazyWrapper.prototype,function(func,methodName){var checkIteratee=/^(?:filter|find|map|reject)|While$/.test(methodName),isTaker=/^(?:head|last)$/.test(methodName),lodashFunc=lodash[isTaker?"take"+("last"==methodName?"Right":""):methodName],retUnwrapped=isTaker||/^find/.test(methodName);lodashFunc&&(lodash.prototype[methodName]=function(){var value=this.__wrapped__,args=isTaker?[1]:arguments,isLazy=value instanceof LazyWrapper,iteratee=args[0],useLazy=isLazy||isArray(value),interceptor=function(value){var result=lodashFunc.apply(lodash,arrayPush([value],args));return isTaker&&chainAll?result[0]:result};useLazy&&checkIteratee&&"function"==typeof iteratee&&1!=iteratee.length&&(isLazy=useLazy=!1);var chainAll=this.__chain__,isHybrid=!!this.__actions__.length,isUnwrapped=retUnwrapped&&!chainAll,onlyLazy=isLazy&&!isHybrid;if(!retUnwrapped&&useLazy){value=onlyLazy?value:new LazyWrapper(this);var result=func.apply(value,args);return result.__actions__.push({func:thru,args:[interceptor],thisArg:undefined}),new LodashWrapper(result,chainAll)}return isUnwrapped&&onlyLazy?func.apply(this,args):(result=this.thru(interceptor),isUnwrapped?isTaker?result.value()[0]:result.value():result)})}),arrayEach(["pop","push","shift","sort","splice","unshift"],function(methodName){var func=arrayProto[methodName],chainName=/^(?:push|sort|unshift)$/.test(methodName)?"tap":"thru",retUnwrapped=/^(?:pop|shift)$/.test(methodName);lodash.prototype[methodName]=function(){var args=arguments;if(retUnwrapped&&!this.__chain__){var value=this.value();return func.apply(isArray(value)?value:[],args)}return this[chainName](function(value){return func.apply(isArray(value)?value:[],args)})}}),baseForOwn(LazyWrapper.prototype,function(func,methodName){var lodashFunc=lodash[methodName];if(lodashFunc){var key=lodashFunc.name+"",names=realNames[key]||(realNames[key]=[]);names.push({name:methodName,func:lodashFunc})}}),realNames[createHybrid(undefined,BIND_KEY_FLAG).name]=[{name:"wrapper",func:undefined}],LazyWrapper.prototype.clone=lazyClone,LazyWrapper.prototype.reverse=lazyReverse,LazyWrapper.prototype.value=lazyValue,lodash.prototype.at=wrapperAt,lodash.prototype.chain=wrapperChain,lodash.prototype.commit=wrapperCommit,lodash.prototype.next=wrapperNext,lodash.prototype.plant=wrapperPlant,lodash.prototype.reverse=wrapperReverse,lodash.prototype.toJSON=lodash.prototype.valueOf=lodash.prototype.value=wrapperValue,lodash.prototype.first=lodash.prototype.head,iteratorSymbol&&(lodash.prototype[iteratorSymbol]=wrapperToIterator),lodash},_=runInContext();"function"==typeof define&&"object"==typeof define.amd&&define.amd?(root._=_,define(function(){return _})):freeModule?((freeModule.exports=_)._=_,freeExports._=_):root._=_}.call(this);var UsergridAuthMode=Object.freeze({NONE:"none",USER:"user",APP:"app"}),UsergridDirection=Object.freeze({IN:"connecting",OUT:"connections"}),UsergridHttpMethod=Object.freeze({GET:"GET",PUT:"PUT",POST:"POST",DELETE:"DELETE"}),UsergridQueryOperator=Object.freeze({EQUAL:"=",GREATER_THAN:">",GREATER_THAN_EQUAL_TO:">=",LESS_THAN:"<",LESS_THAN_EQUAL_TO:"<="}),UsergridQuerySortOrder=Object.freeze({ASC:"asc",DESC:"desc"}),UsergridApplicationJSONHeaderValue="application/json";!function(global){function UsergridHelpers(){}var name="UsergridHelpers",overwrittenName=global[name];UsergridHelpers.DefaultHeaders=Object.freeze({"Content-Type":UsergridApplicationJSONHeaderValue,Accept:UsergridApplicationJSONHeaderValue}),UsergridHelpers.validateAndRetrieveClient=function(args){var client=_.first([args,args[0],_.get(args,"client"),Usergrid.isInitialized?Usergrid:void 0].filter(function(client){return client instanceof UsergridClient}));if(!client)throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument");return client},UsergridHelpers.inherits=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})},UsergridHelpers.flattenArgs=function(args){return _.flattenDeep(Array.prototype.slice.call(args))},UsergridHelpers.callback=function(){var args=UsergridHelpers.flattenArgs(arguments).reverse(),emptyFunc=function(){};return _.first(_.flattenDeep([args,_.get(args,"0.callback"),emptyFunc]).filter(_.isFunction))},UsergridHelpers.authForRequests=function(client){var authForRequests=void 0;return _.get(client,"tempAuth.isValid")?(authForRequests=client.tempAuth,client.tempAuth=void 0):_.get(client,"currentUser.auth.isValid")&&client.authMode===UsergridAuthMode.USER?authForRequests=client.currentUser.auth:_.get(client,"appAuth.isValid")&&client.authMode===UsergridAuthMode.APP&&(authForRequests=client.appAuth),authForRequests},UsergridHelpers.userLoginBody=function(options){var body={grant_type:"password",password:options.password};return options.tokenTtl&&(body.ttl=options.tokenTtl),body[options.username?"username":"email"]=options.username?options.username:options.email,body},UsergridHelpers.appLoginBody=function(options){var body={grant_type:"client_credentials",client_id:options.clientId,client_secret:options.clientSecret};return options.tokenTtl&&(body.ttl=options.tokenTtl),body},UsergridHelpers.userResetPasswordBody=function(args){return{oldpassword:_.isPlainObject(args[0])?args[0].oldPassword:_.isString(args[0])?args[0]:void 0,newpassword:_.isPlainObject(args[0])?args[0].newPassword:_.isString(args[1])?args[1]:void 0}},UsergridHelpers.calculateExpiry=function(expires_in){return Date.now()+1e3*(expires_in?expires_in-5:0)};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;return UsergridHelpers.isUUID=function(uuid){return uuid?uuidValueRegex.test(uuid):!1},UsergridHelpers.useQuotesIfRequired=function(value){return _.isFinite(value)||UsergridHelpers.isUUID(value)||_.isBoolean(value)||_.isObject(value)&&!_.isFunction(value)||_.isArray(value)?value:"'"+value+"'"},UsergridHelpers.setReadOnly=function(obj,key){return _.isArray(key)?key.forEach(function(k){UsergridHelpers.setReadOnly(obj,k)}):_.isPlainObject(obj[key])?Object.freeze(obj[key]):_.isPlainObject(obj)&&void 0===key?Object.freeze(obj):_.has(obj,key)?Object.defineProperty(obj,key,{writable:!1}):obj},UsergridHelpers.setWritable=function(obj,key){return _.isArray(key)?key.forEach(function(k){UsergridHelpers.setWritable(obj,k)}):_.isPlainObject(obj[key])?_.clone(obj[key]):_.isPlainObject(obj)&&void 0===key?_.clone(obj):_.has(obj,key)?Object.defineProperty(obj,key,{writable:!0}):obj},UsergridHelpers.assignPrefabOptions=function(args){return _.isObject(args[0])&&!_.isFunction(args[0])&&_.has(args,"method")&&_.assign(this,args[0]),this},UsergridHelpers.normalize=function(str){return str=str.replace(/\/+/g,"/"),str=str.replace(/:\//g,"://"),str=str.replace(/\/(\?|&|#[^!])/g,"$1"),str=str.replace(/(\?.+)\?/g,"$1&")},UsergridHelpers.urljoin=function(){var input=arguments,options={};"object"==typeof arguments[0]&&(input=arguments[0],options=arguments[1]||{});var joined=[].slice.call(input,0).join("/");return UsergridHelpers.normalize(joined,options)},UsergridHelpers.parseResponseHeaders=function(headerStr){var headers={};if(headerStr)for(var headerPairs=headerStr.split("\r\n"),i=0;i0){var key=headerPair.substring(0,index).toLowerCase();headers[key]=headerPair.substring(index+2)}}return headers},UsergridHelpers.uri=function(client,options){var path="";path=options instanceof UsergridEntity?options.type:options instanceof UsergridQuery?options._type:_.isString(options)?options:_.isArray(options)?_.get(options,"0.type")||_.get(options,"0.path"):options.path||options.type||_.get(options,"entity.type")||_.get(options,"query._type")||_.get(options,"body.type")||_.get(options,"body.path");var uuidOrName="";return options.method!==UsergridHttpMethod.POST&&(uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,_.get(options,"entity.uuid"),_.get(options,"entity.name"),_.get(options,"body.uuid"),_.get(options,"body.name"),""].filter(_.isString))),UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,path,uuidOrName)},UsergridHelpers.updateEntityFromRemote=function(entity,usergridResponse){UsergridHelpers.setWritable(entity,["uuid","name","type","created"]),_.assign(entity,usergridResponse.entity),UsergridHelpers.setReadOnly(entity,["uuid","name","type","created"])},UsergridHelpers.headers=function(client,options,defaultHeaders){var returnHeaders={};_.defaults(returnHeaders,options.headers,defaultHeaders),_.assign(returnHeaders,{"User-Agent":"usergrid-js/v"+UsergridSDKVersion});var authForRequests=UsergridHelpers.authForRequests(client);return authForRequests&&_.assign(returnHeaders,{authorization:"Bearer "+authForRequests.token}),returnHeaders},UsergridHelpers.setEntity=function(options,args){return options.entity=_.first([options.entity,args[0]].filter(function(property){return property instanceof UsergridEntity})),void 0!==options.entity&&(options.type=options.entity.type),options},UsergridHelpers.setAsset=function(options,args){return options.asset=_.first([options.asset,_.get(options,"entity.asset"),args[1],args[0]].filter(function(property){return property instanceof UsergridAsset})),options},UsergridHelpers.setUuidOrName=function(options,args){return options.uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,_.get(options,"entity.uuid"),_.get(options,"body.uuid"),_.get(options,"entity.name"),_.get(options,"body.name"),_.get(args,"0.uuid"),_.get(args,"0.name"),_.get(args,"2"),_.get(args,"1")].filter(_.isString)),options},UsergridHelpers.setPathOrType=function(options,args){var pathOrType=_.first([args.type,_.get(args,"0.type"),_.get(options,"entity.type"),_.get(args,"body.type"),_.get(options,"body.0.type"),_.isArray(args)?args[0]:void 0].filter(_.isString));return options[/\//.test(pathOrType)?"path":"type"]=pathOrType,options},UsergridHelpers.setQs=function(options,args){return options.path&&(options.qs=_.first([options.qs,args[2],args[1],args[0]].filter(_.isPlainObject))),options},UsergridHelpers.setQuery=function(options,args){return options.query=_.first([options,options.query,args[0]].filter(function(property){return property instanceof UsergridQuery})),options},UsergridHelpers.setAsset=function(options,args){return options.asset=_.first([options.asset,_.get(options,"entity.asset"),args[1],args[0]].filter(function(property){return property instanceof UsergridAsset})),options},UsergridHelpers.setBody=function(options,args){var body=_.first([args.entity,args.body,args[0].entity,args[0].body,args[2],args[1],args[0]].filter(function(property){return _.isObject(property)&&!_.isFunction(property)&&!(property instanceof UsergridQuery)&&!(property instanceof UsergridAsset)}));return body instanceof UsergridEntity?body=body.jsonValue():_.isArray(body)&&body[0]instanceof UsergridEntity&&(body=_.map(body,function(entity){return entity.jsonValue()})),options.body=body,options},UsergridHelpers.buildRequest=function(client,method,args){var options={client:client,method:method,queryParams:args.queryParams||_.get(args,"0.queryParams"),callback:UsergridHelpers.callback(args)};if(UsergridHelpers.assignPrefabOptions(options,args),UsergridHelpers.setEntity(options,args),!(method!==UsergridHttpMethod.POST&&method!==UsergridHttpMethod.PUT||(UsergridHelpers.setAsset(options,args),options.asset||(UsergridHelpers.setBody(options,args),options.body))))throw new Error("'body' is required when making a "+options.method+" request");return UsergridHelpers.setUuidOrName(options,args),UsergridHelpers.setPathOrType(options,args),UsergridHelpers.setQs(options,args),UsergridHelpers.setQuery(options,args),options.uri=UsergridHelpers.uri(client,options),new UsergridRequest(options)},UsergridHelpers.buildAppAuthRequest=function(client,auth,callback){var requestOptions={client:client,method:UsergridHttpMethod.POST,uri:UsergridHelpers.uri(client,{path:"token"}),body:UsergridHelpers.appLoginBody(auth),callback:callback};return new UsergridRequest(requestOptions)},UsergridHelpers.buildConnectionRequest=function(client,method,args){var options={client:client,method:method,entity:{},to:{},callback:UsergridHelpers.callback(args)};if(UsergridHelpers.assignPrefabOptions.call(options,args),_.isObject(options.from)&&(options.to=options.from),_.isObject(args[0])&&_.has(args[0],"entity")&&_.has(args[0],"to")&&(_.assign(options.entity,args[0].entity),options.relationship=_.get(args,"0.relationship"),_.assign(options.to,args[0].to)),_.isObject(args[0])&&!_.isFunction(args[0])&&_.isString(args[1])&&(_.assign(options.entity,args[0]),options.relationship=_.first([options.relationship,args[1]].filter(_.isString))),_.isObject(args[2])&&!_.isFunction(args[2])&&_.assign(options.to,args[2]),options.entity.uuidOrName=_.first([options.entity.uuidOrName,options.entity.uuid,options.entity.name,args[1]].filter(_.isString)),options.entity.type||(options.entity.type=_.first([options.entity.type,args[0]].filter(_.isString))),options.relationship=_.first([options.relationship,args[2]].filter(_.isString)),_.isString(args[3])&&!UsergridHelpers.isUUID(args[3])&&_.isString(args[4])?options.to.type=args[3]:_.isString(args[2])&&!UsergridHelpers.isUUID(args[2])&&_.isString(args[3])&&_.isObject(args[0])&&!_.isFunction(args[0])&&(options.to.type=args[2]),options.to.uuidOrName=_.first([options.to.uuidOrName,options.to.uuid,options.to.name,args[4],args[3],args[2]].filter(function(property){return _.isString(options.to.type)&&_.isString(property)||UsergridHelpers.isUUID(property)})),!_.isString(options.entity.uuidOrName))throw new Error("source entity 'uuidOrName' is required when connecting or disconnecting entities");if(!_.isString(options.to.uuidOrName))throw new Error("target entity 'uuidOrName' is required when connecting or disconnecting entities");if(!_.isString(options.to.type)&&!UsergridHelpers.isUUID(options.to.uuidOrName))throw new Error("target 'type' (collection name) parameter is required connecting or disconnecting entities by name");return options.uri=UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,_.isString(options.entity.type)?options.entity.type:"",_.isString(options.entity.uuidOrName)?options.entity.uuidOrName:"",options.relationship,_.isString(options.to.type)?options.to.type:"",_.isString(options.to.uuidOrName)?options.to.uuidOrName:""),new UsergridRequest(options)},UsergridHelpers.buildGetConnectionRequest=function(client,args){var options={client:client,method:"GET",callback:UsergridHelpers.callback(args)};if(UsergridHelpers.assignPrefabOptions.call(options,args),_.isObject(args[1])&&!_.isFunction(args[1])&&_.assign(options,args[1]),options.direction=_.first([options.direction,args[0]].filter(function(property){return property===UsergridDirection.IN||property===UsergridDirection.OUT})),options.relationship=_.first([options.relationship,args[3],args[2]].filter(_.isString)),options.uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,args[2]].filter(_.isString)),options.type=_.first([options.type,args[1]].filter(_.isString)),!_.isString(options.type))throw new Error("'type' (collection name) parameter is required when retrieving connections");if(!_.isString(options.uuidOrName))throw new Error("target entity 'uuidOrName' is required when retrieving connections");return options.uri=UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,_.isString(options.type)?options.type:"",_.isString(options.uuidOrName)?options.uuidOrName:"",options.direction,options.relationship),new UsergridRequest(options)},global[name]=UsergridHelpers,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),UsergridHelpers},global[name]}(this);var UsergridClientDefaultOptions={baseUrl:"https://api.usergrid.com",authMode:UsergridAuthMode.USER},UsergridClient=function(options){var __appAuth,self=this;if(self.tempAuth=void 0,self.isSharedInstance=!1,2===arguments.length&&(self.orgId=arguments[0],self.appId=arguments[1]),_.defaults(self,options,UsergridClientDefaultOptions),!self.orgId||!self.appId)throw new Error("'orgId' and 'appId' parameters are required when instantiating UsergridClient");return Object.defineProperty(self,"clientId",{enumerable:!1}),Object.defineProperty(self,"clientSecret",{enumerable:!1}),Object.defineProperty(self,"appAuth",{get:function(){return __appAuth},set:function(options){options instanceof UsergridAppAuth?__appAuth=options:"undefined"!=typeof options&&(__appAuth=new UsergridAppAuth(options))}}),self.clientId&&self.clientSecret&&self.setAppAuth(self.clientId,self.clientSecret),self};UsergridClient.prototype={sendRequest:function(usergridRequest){return usergridRequest.sendRequest()},GET:function(){var usergridRequest=UsergridHelpers.buildRequest(this,UsergridHttpMethod.GET,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},PUT:function(){var usergridRequest=UsergridHelpers.buildRequest(this,UsergridHttpMethod.PUT,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},POST:function(){var usergridRequest=UsergridHelpers.buildRequest(this,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},DELETE:function(){var usergridRequest=UsergridHelpers.buildRequest(this,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},connect:function(){var usergridRequest=UsergridHelpers.buildConnectionRequest(this,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},disconnect:function(){var usergridRequest=UsergridHelpers.buildConnectionRequest(this,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},getConnections:function(){var usergridRequest=UsergridHelpers.buildGetConnectionRequest(this,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},usingAuth:function(auth){var self=this;return _.isString(auth)?self.tempAuth=new UsergridAuth(auth):auth instanceof UsergridAuth?self.tempAuth=auth:self.tempAuth=void 0,self},setAppAuth:function(){this.appAuth=new UsergridAppAuth(UsergridHelpers.flattenArgs(arguments))},authenticateApp:function(options){var self=this,authenticateAppCallback=UsergridHelpers.callback(UsergridHelpers.flattenArgs(arguments)),auth=_.first([options,self.appAuth,new UsergridAppAuth(options),new UsergridAppAuth(self.clientId,self.clientSecret)].filter(function(p){return p instanceof UsergridAppAuth}));if(!(auth instanceof UsergridAppAuth))throw new Error("App auth context was not defined when attempting to call .authenticateApp()");if(!auth.clientId||!auth.clientSecret)throw new Error("authenticateApp() failed because clientId or clientSecret are missing");var callback=function(error,usergridResponse){var token=_.get(usergridResponse.responseJSON,"access_token"),expiresIn=_.get(usergridResponse.responseJSON,"expires_in");usergridResponse.ok&&(self.appAuth||(self.appAuth=auth),self.appAuth.token=token,self.appAuth.expiry=UsergridHelpers.calculateExpiry(expiresIn),self.appAuth.tokenTtl=expiresIn),authenticateAppCallback(error,usergridResponse,token)},usergridRequest=UsergridHelpers.buildAppAuthRequest(self,auth,callback);return self.sendRequest(usergridRequest)},authenticateUser:function(options){var self=this,args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args),setAsCurrentUser=void 0!==_.last(args.filter(_.isBoolean))?_.last(args.filter(_.isBoolean)):!0,userToAuthenticate=new UsergridUser(options);userToAuthenticate.login(self,function(error,usergridResponse,token){usergridResponse.ok&&setAsCurrentUser&&(self.currentUser=userToAuthenticate),callback(usergridResponse.error,usergridResponse,token)})},downloadAsset:function(){var self=this,usergridRequest=UsergridHelpers.buildRequest(self,UsergridHttpMethod.GET,UsergridHelpers.flattenArgs(arguments)),assetContentType=_.get(usergridRequest,"entity.file-metadata.content-type");void 0!==assetContentType&&_.assign(usergridRequest.headers,{Accept:assetContentType});var realDownloadAssetCallback=usergridRequest.callback;return usergridRequest.callback=function(error,usergridResponse){var entity=usergridRequest.entity;entity.asset=usergridResponse.asset,realDownloadAssetCallback(error,usergridResponse,entity)},self.sendRequest(usergridRequest)},uploadAsset:function(){var self=this,usergridRequest=UsergridHelpers.buildRequest(self,UsergridHttpMethod.PUT,UsergridHelpers.flattenArgs(arguments));if(void 0===usergridRequest.asset)throw new Error("An UsergridAsset was not defined when attempting to call .uploadAsset()");var realUploadAssetCallback=usergridRequest.callback;return usergridRequest.callback=function(error,usergridResponse){var requestEntity=usergridRequest.entity,responseEntity=usergridResponse.entity,requestAsset=usergridRequest.asset;usergridResponse.ok&&void 0!==responseEntity&&(UsergridHelpers.updateEntityFromRemote(requestEntity,usergridResponse),requestEntity.asset=requestAsset,responseEntity&&(responseEntity.asset=requestAsset)),realUploadAssetCallback(error,usergridResponse,requestEntity)},self.sendRequest(usergridRequest)}};var UsergridSDKVersion="2.0.0",UsergridClientSharedInstance=function(){var self=this;return self.isInitialized=!1,self.isSharedInstance=!0,self};UsergridHelpers.inherits(UsergridClientSharedInstance,UsergridClient);var Usergrid=new UsergridClientSharedInstance;Usergrid.initSharedInstance=function(options){return Usergrid.isInitialized?console.log("Usergrid shared instance is already initialized"):(_.assign(Usergrid,new UsergridClient(options)),Usergrid.isInitialized=!0,Usergrid.isSharedInstance=!0),Usergrid},Usergrid.init=Usergrid.initSharedInstance;var UsergridQuery=function(type){var queryString,sort,self=this,query="",urlTerms={},__nextIsNot=!1;return self._type=type,_.assign(self,{type:function(value){return self._type=value,self},collection:function(value){return self._type=value,self},limit:function(value){return self._limit=value,self},cursor:function(value){return self._cursor=value,self},eq:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.EQUAL+" "+UsergridHelpers.useQuotesIfRequired(value)),self},equal:this.eq,gt:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.GREATER_THAN+" "+UsergridHelpers.useQuotesIfRequired(value)),self},greaterThan:this.gt,gte:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.GREATER_THAN_EQUAL_TO+" "+UsergridHelpers.useQuotesIfRequired(value)),self},greaterThanOrEqual:this.gte,lt:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.LESS_THAN+" "+UsergridHelpers.useQuotesIfRequired(value)),self},lessThan:this.lt,lte:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.LESS_THAN_EQUAL_TO+" "+UsergridHelpers.useQuotesIfRequired(value)),self},lessThanOrEqual:this.lte,contains:function(key,value){return query=self.andJoin(key+" contains "+UsergridHelpers.useQuotesIfRequired(value)),self},locationWithin:function(distanceInMeters,lat,lng){return query=self.andJoin("location within "+distanceInMeters+" of "+lat+", "+lng),self},asc:function(key){return self.sort(key,UsergridQuerySortOrder.ASC),self},desc:function(key){return self.sort(key,UsergridQuerySortOrder.DESC),self},sort:function(key,order){return sort=key&&order?" order by "+key+" "+order:"",self},fromString:function(string){return queryString=string, -self},urlTerm:function(key,value){return"ql"===key?self.fromString():urlTerms[key]=value,self},andJoin:function(append){return __nextIsNot&&(append="not "+append,__nextIsNot=!1),append?0===query.length?append:_.endsWith(query,"and")||_.endsWith(query,"or")?query+" "+append:query+" and "+append:query},orJoin:function(){return query.length>0&&!_.endsWith(query,"or")?query+" or":query}}),Object.defineProperty(self,"_ql",{get:function(){var ql="select * ";return void 0!==queryString?ql=queryString:(ql+=query.length>0?"where "+(query||""):"",ql+=void 0!==sort?sort:""),ql}}),Object.defineProperty(self,"encodedStringValue",{get:function(){var self=this,limit=self._limit,cursor=self._cursor,requirementsString=self._ql,returnString=void 0;if(void 0!==limit&&(returnString="limit"+UsergridQueryOperator.EQUAL+limit),!_.isEmpty(cursor)){var cursorString="cursor"+UsergridQueryOperator.EQUAL+cursor;_.isEmpty(returnString)?returnString=cursorString:returnString+="&"+cursorString}if(_.forEach(urlTerms,function(value,key){var encodedURLTermString=encodeURIComponent(key)+UsergridQueryOperator.EQUAL+encodeURIComponent(value);_.isEmpty(returnString)?returnString=encodedURLTermString:returnString+="&"+encodedURLTermString}),!_.isEmpty(requirementsString)){var qLString="ql="+encodeURIComponent(requirementsString);_.isEmpty(returnString)?returnString=qLString:returnString+="&"+qLString}return _.isEmpty(returnString)||(returnString="?"+returnString),_.isEmpty(returnString)?void 0:returnString}}),Object.defineProperty(self,"and",{get:function(){return query=self.andJoin(""),self}}),Object.defineProperty(self,"or",{get:function(){return query=self.orJoin(),self}}),Object.defineProperty(self,"not",{get:function(){return __nextIsNot=!0,self}}),self},UsergridRequest=function(options){var self=this,client=UsergridHelpers.validateAndRetrieveClient(options);if(!_.isString(options.type)&&!_.isString(options.path)&&!_.isString(options.uri))throw new Error("one of 'type' (collection name), 'path', or 'uri' parameters are required when initializing a UsergridRequest");if(!_.includes(["GET","PUT","POST","DELETE"],options.method))throw new Error("'method' parameter is required when initializing a UsergridRequest");self.method=options.method,self.callback=options.callback,self.uri=options.uri||UsergridHelpers.uri(client,options),self.entity=options.entity,self.body=options.body,self.asset=options.asset,self.query=options.query,self.queryParams=options.queryParams||options.qs;var defaultHeadersToUse=self.asset?{}:UsergridHelpers.DefaultHeaders;if(self.headers=UsergridHelpers.headers(client,options,defaultHeadersToUse),void 0!==self.query&&(self.uri+=UsergridHelpers.normalize(self.query.encodedStringValue,{})),self.queryParams&&(_.forOwn(self.queryParams,function(value,key){self.uri+="?"+encodeURIComponent(key)+UsergridQueryOperator.EQUAL+encodeURIComponent(value)}),self.uri=UsergridHelpers.normalize(self.uri,{})),self.asset)self.body=new FormData,self.body.append(self.asset.filename,self.asset.data);else try{_.isPlainObject(self.body)?self.body=JSON.stringify(self.body):_.isArray(self.body)&&(self.body=JSON.stringify(self.body))}catch(exception){console.warn("Unable to convert 'UsergridRequest.body' to a JSON String: "+exception)}return self};UsergridRequest.prototype.sendRequest=function(){var self=this,requestPromise=function(){var promise=new Promise,xmlHttpRequest=new XMLHttpRequest;return xmlHttpRequest.open(self.method,self.uri,!0),xmlHttpRequest.onload=function(){promise.done(xmlHttpRequest)},_.forOwn(self.headers,function(value,key){xmlHttpRequest.setRequestHeader(key,value)}),self.method===UsergridHttpMethod.GET&&_.get(self.headers,"Accept")!==UsergridApplicationJSONHeaderValue&&(xmlHttpRequest.responseType="blob"),xmlHttpRequest.send(self.body),promise},responsePromise=function(xmlRequest){var promise=new Promise,usergridResponse=new UsergridResponse(xmlRequest,self);return promise.done(usergridResponse),promise},onCompletePromise=function(usergridResponse){self.callback(usergridResponse.error,usergridResponse)};return Promise.chain([requestPromise,responsePromise]).then(onCompletePromise),self};var UsergridAuth=function(token,expiry){var self=this;self.token=token,self.expiry=expiry||0;var usingToken=token?!0:!1;return Object.defineProperty(self,"hasToken",{get:function(){return void 0!==self.token},configurable:!0}),Object.defineProperty(self,"isExpired",{get:function(){return usingToken?!1:Date.now()>=self.expiry},configurable:!0}),Object.defineProperty(self,"isValid",{get:function(){return!self.isExpired&&self.hasToken},configurable:!0}),Object.defineProperty(self,"tokenTtl",{configurable:!0,writable:!0}),_.assign(self,{destroy:function(){self.token=void 0,self.expiry=0,self.tokenTtl=void 0}}),self},UsergridAppAuth=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments);return _.isPlainObject(args[0])?(self.clientId=args[0].clientId,self.clientSecret=args[0].clientSecret,self.tokenTtl=args[0].tokenTtl):(self.clientId=args[0],self.clientSecret=args[1],self.tokenTtl=args[2]),UsergridAuth.call(self),_.assign(self,UsergridAuth),self};UsergridHelpers.inherits(UsergridAppAuth,UsergridAuth);var UsergridUserAuth=function(options){var self=this,args=_.flattenDeep(UsergridHelpers.flattenArgs(arguments));return _.isPlainObject(args[0])&&(options=args[0]),self.username=options.username||args[0],self.email=options.email,(options.password||args[1])&&(self.password=options.password||args[1]),self.tokenTtl=options.tokenTtl||args[2],UsergridAuth.call(self),_.assign(self,UsergridAuth),self};UsergridHelpers.inherits(UsergridUserAuth,UsergridAuth);var UsergridEntity=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments);if(0===args.length)throw new Error("A UsergridEntity object cannot be initialized without passing one or more arguments");if(self.asset=void 0,_.isPlainObject(args[0])?_.assign(self,args[0]):(self.type||(self.type=_.isString(args[0])?args[0]:void 0),self.name||(self.name=_.isString(args[1])?args[1]:void 0)),!_.isString(self.type))throw new Error('"type" (or "collection") parameter is required when initializing a UsergridEntity object');return Object.defineProperty(self,"isUser",{get:function(){return"user"===self.type.toLowerCase()}}),Object.defineProperty(self,"hasAsset",{get:function(){return _.has(self,"file-metadata")}}),UsergridHelpers.setReadOnly(self,["uuid","name","type","created"]),self};UsergridEntity.prototype={jsonValue:function(){var jsonValue={};return _.forOwn(this,function(value,key){jsonValue[key]=value}),jsonValue},putProperty:function(key,value){this[key]=value},putProperties:function(obj){_.assign(this,obj)},removeProperty:function(key){this.removeProperties([key])},removeProperties:function(keys){var self=this;keys.forEach(function(key){delete self[key]})},insert:function(key,value,idx){_.isArray(this[key])||(this[key]=this[key]?[this[key]]:[]),this[key].splice.apply(this[key],[idx,0].concat(value))},append:function(key,value){this.insert(key,value,Number.MAX_VALUE)},prepend:function(key,value){this.insert(key,value,0)},pop:function(key){_.isArray(this[key])&&this[key].pop()},shift:function(key){_.isArray(this[key])&&this[key].shift()},reload:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.GET(self,function(error,usergridResponse){UsergridHelpers.updateEntityFromRemote(self,usergridResponse),callback(error,usergridResponse,self)}.bind(self))},save:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args),currentAsset=self.asset;client.PUT(self,function(error,usergridResponse){UsergridHelpers.updateEntityFromRemote(self,usergridResponse),self.hasAsset&&(self.asset=currentAsset),callback(error,usergridResponse,self)}.bind(self))},remove:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.DELETE(self,function(error,usergridResponse){callback(error,usergridResponse,self)}.bind(self))},attachAsset:function(asset){this.asset=asset},uploadAsset:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(_.has(self,"asset.contentType"))client.uploadAsset(self,callback);else{var response=UsergridResponse.responseWithError({name:"asset_not_found",description:"The specified entity does not have a valid asset attached"});callback(response.error,response,self)}},downloadAsset:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(_.has(self,"asset.contentType"))client.downloadAsset(self,callback);else{var response=UsergridResponse.responseWithError({name:"asset_not_found",description:"The specified entity does not have a valid asset attached"});callback(response.error,response,self)}},connect:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args[0]=this,client.connect.apply(client,args)},disconnect:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args[0]=this,client.disconnect.apply(client,args)},getConnections:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args.shift(),args.splice(1,0,this),client.getConnections.apply(client,args)}};var UsergridUser=function(obj){if(!_.has(obj,"email")&&!_.has(obj,"username"))throw new Error("'email' or 'username' property is required when initializing a UsergridUser object");var self=this;return _.assign(self,obj,UsergridEntity),UsergridEntity.call(self,"user"),UsergridHelpers.setWritable(self,"name"),self};UsergridUser.CheckAvailable=function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args),username=args[0].username||args[1].username,email=args[0].email||args[1].email;if(!username&&!email)throw new Error("'username' or 'email' property is required when checking for available users");var checkQuery=new UsergridQuery("users");username&&checkQuery.eq("username",username),email&&checkQuery.or.eq("email",email),client.GET(checkQuery,function(error,usergridResponse){callback(error,usergridResponse,usergridResponse.entities.length>0)})},UsergridHelpers.inherits(UsergridUser,UsergridEntity),UsergridUser.prototype.uniqueId=function(){var self=this;return _.first([self.uuid,self.username,self.email].filter(_.isString))},UsergridUser.prototype.create=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.POST(self,function(error,usergridResponse){delete self.password,_.assign(self,usergridResponse.user),callback(error,usergridResponse,self)}.bind(self))},UsergridUser.prototype.login=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.POST("token",UsergridHelpers.userLoginBody(self),function(error,usergridResponse){delete self.password;var responseJSON=usergridResponse.responseJSON,token=_.get(responseJSON,"access_token"),expiresIn=_.get(responseJSON,"expires_in");usergridResponse.ok&&(self.auth=new UsergridUserAuth(self),self.auth.token=token,self.auth.expiry=UsergridHelpers.calculateExpiry(expiresIn),self.auth.tokenTtl=expiresIn),callback(error,usergridResponse,token)})},UsergridUser.prototype.logout=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(self.auth&&self.auth.isValid){var revokeAll=_.first(args.filter(_.isBoolean))||!1,requestOptions={client:client,path:["users",self.uniqueId(),"revoketoken"+(revokeAll?"s":"")].join("/"),method:UsergridHttpMethod.PUT,callback:function(error,usergridResponse){self.auth.destroy(),callback(error,usergridResponse,usergridResponse.ok)}.bind(self)};revokeAll||(requestOptions.queryParams={token:self.auth.token});var request=new UsergridRequest(requestOptions);client.sendRequest(request)}else{var response=UsergridResponse.responseWithError({name:"no_valid_token",description:"this user does not have a valid token"});callback(response.error,response)}},UsergridUser.prototype.logoutAllSessions=function(){var args=UsergridHelpers.flattenArgs(arguments);return args=_.concat([UsergridHelpers.validateAndRetrieveClient(args),!0],args),this.logout.apply(this,args)},UsergridUser.prototype.resetPassword=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);args[0]instanceof UsergridClient&&args.shift();var body=UsergridHelpers.userResetPasswordBody(args);if(!body.oldpassword||!body.newpassword)throw new Error("'oldPassword' and 'newPassword' properties are required when resetting a user password");client.PUT(["users",self.uniqueId(),"password"].join("/"),body,callback)};var UsergridResponseError=function(options){var self=this;return _.assign(self,options),self};UsergridResponseError.fromJSON=function(responseErrorObject){var usergridResponseError,error={name:_.get(responseErrorObject,"error")};return error.name&&(_.assign(error,{exception:_.get(responseErrorObject,"exception"),description:_.get(responseErrorObject,"error_description")||_.get(responseErrorObject,"description")}),usergridResponseError=new UsergridResponseError(error)),usergridResponseError};var UsergridResponse=function(xmlRequest,usergridRequest){var self=this;if(self.ok=!1,self.request=usergridRequest,xmlRequest){self.statusCode=parseInt(xmlRequest.status),self.ok=self.statusCode<400,self.headers=UsergridHelpers.parseResponseHeaders(xmlRequest.getAllResponseHeaders());var responseContentType=_.get(self.headers,"content-type");if(responseContentType===UsergridApplicationJSONHeaderValue)try{var responseJSON=JSON.parse(xmlRequest.responseText);responseJSON&&self.parseResponseJSON(responseJSON)}catch(e){}else self.asset=new UsergridAsset(xmlRequest.response)}return self};UsergridResponse.responseWithError=function(options){var usergridResponse=new UsergridResponse;return usergridResponse.error=new UsergridResponseError(options),usergridResponse},UsergridResponse.prototype={parseResponseJSON:function(responseJSON){var self=this;if(self.responseJSON=_.cloneDeep(responseJSON),self.ok){self.cursor=_.get(self,"responseJSON.cursor"),self.hasNextPage=!_.isNil(self.cursor);var entitiesJSON=_.get(responseJSON,"entities");entitiesJSON&&(self.parseResponseEntities(entitiesJSON),delete self.responseJSON.entities)}else self.error=UsergridResponseError.fromJSON(responseJSON);UsergridHelpers.setReadOnly(self.responseJSON)},parseResponseEntities:function(entitiesJSON){var self=this;self.entities=_.map(entitiesJSON,function(entityJSON){var entity=new UsergridEntity(entityJSON);return entity.isUser&&(entity=new UsergridUser(entity)),entity}),self.first=_.first(self.entities),self.entity=self.first,self.last=_.last(self.entities),"/users"===_.get(self,"responseJSON.path")&&(self.user=self.first,self.users=self.entities)},loadNextPage:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args),cursor=self.cursor;if(cursor){var client=UsergridHelpers.validateAndRetrieveClient(args),type=_.last(_.get(self,"responseJSON.path").split("/")),limit=_.first(_.get(self,"responseJSON.params.limit")),ql=_.first(_.get(self,"responseJSON.params.ql")),query=new UsergridQuery(type).fromString(ql).cursor(cursor).limit(limit);client.GET(query,callback)}else callback(UsergridResponse.responseWithError({name:"cursor_not_found",description:"Cursor must be present in order perform loadNextPage()."}))}};var UsergridAssetDefaultFileName="file",UsergridAsset=function(fileOrBlob){if(!fileOrBlob instanceof File||!fileOrBlob instanceof Blob)throw new Error("UsergridAsset must be initialized with a 'File' or 'Blob'");var self=this;return self.data=fileOrBlob,self.filename=fileOrBlob.name||UsergridAssetDefaultFileName,self.contentLength=fileOrBlob.size,self.contentType=fileOrBlob.type,self}; \ No newline at end of file +self},urlTerm:function(key,value){return"ql"===key?self.fromString():urlTerms[key]=value,self},andJoin:function(append){return __nextIsNot&&(append="not "+append,__nextIsNot=!1),append?0===query.length?append:_.endsWith(query,"and")||_.endsWith(query,"or")?query+" "+append:query+" and "+append:query},orJoin:function(){return query.length>0&&!_.endsWith(query,"or")?query+" or":query}}),Object.defineProperty(self,"_ql",{get:function(){var ql="select * ";return void 0!==queryString?ql=queryString:(ql+=query.length>0?"where "+(query||""):"",ql+=void 0!==sort?sort:""),ql}}),Object.defineProperty(self,"encodedStringValue",{get:function(){var self=this,limit=self._limit,cursor=self._cursor,requirementsString=self._ql,returnString=void 0;if(void 0!==limit&&(returnString="limit"+UsergridQueryOperator.EQUAL+limit),!_.isEmpty(cursor)){var cursorString="cursor"+UsergridQueryOperator.EQUAL+cursor;_.isEmpty(returnString)?returnString=cursorString:returnString+="&"+cursorString}if(_.forEach(urlTerms,function(value,key){var encodedURLTermString=encodeURIComponent(key)+UsergridQueryOperator.EQUAL+encodeURIComponent(value);_.isEmpty(returnString)?returnString=encodedURLTermString:returnString+="&"+encodedURLTermString}),!_.isEmpty(requirementsString)){var qLString="ql="+encodeURIComponent(requirementsString);_.isEmpty(returnString)?returnString=qLString:returnString+="&"+qLString}return _.isEmpty(returnString)||(returnString="?"+returnString),_.isEmpty(returnString)?void 0:returnString}}),Object.defineProperty(self,"and",{get:function(){return query=self.andJoin(""),self}}),Object.defineProperty(self,"or",{get:function(){return query=self.orJoin(),self}}),Object.defineProperty(self,"not",{get:function(){return __nextIsNot=!0,self}}),self},UsergridRequest=function(options){var self=this,client=UsergridHelpers.validateAndRetrieveClient(options);if(!_.isString(options.type)&&!_.isString(options.path)&&!_.isString(options.uri))throw new Error("one of 'type' (collection name), 'path', or 'uri' parameters are required when initializing a UsergridRequest");if(!_.includes(["GET","PUT","POST","DELETE"],options.method))throw new Error("'method' parameter is required when initializing a UsergridRequest");self.method=options.method,self.callback=options.callback,self.uri=options.uri||UsergridHelpers.uri(client,options),self.entity=options.entity,self.body=options.body,self.asset=options.asset,self.query=options.query,self.queryParams=options.queryParams||options.qs;var defaultHeadersToUse=self.asset?{}:UsergridHelpers.DefaultHeaders;if(self.headers=UsergridHelpers.headers(client,options,defaultHeadersToUse),void 0!==self.query&&(self.uri+=UsergridHelpers.normalize(self.query.encodedStringValue,{})),self.queryParams&&(_.forOwn(self.queryParams,function(value,key){self.uri+="?"+encodeURIComponent(key)+UsergridQueryOperator.EQUAL+encodeURIComponent(value)}),self.uri=UsergridHelpers.normalize(self.uri,{})),self.asset)self.body=new FormData,self.body.append(self.asset.filename,self.asset.data);else try{_.isPlainObject(self.body)?self.body=JSON.stringify(self.body):_.isArray(self.body)&&(self.body=JSON.stringify(self.body))}catch(exception){console.warn("Unable to convert 'UsergridRequest.body' to a JSON String: "+exception)}return self};UsergridRequest.prototype.sendRequest=function(){var self=this,requestPromise=function(){var promise=new Promise,xmlHttpRequest=new XMLHttpRequest;return xmlHttpRequest.open(self.method,self.uri,!0),xmlHttpRequest.onload=function(){promise.done(xmlHttpRequest)},_.forOwn(self.headers,function(value,key){xmlHttpRequest.setRequestHeader(key,value)}),self.method===UsergridHttpMethod.GET&&_.get(self.headers,"Accept")!==UsergridApplicationJSONHeaderValue&&(xmlHttpRequest.responseType="blob"),xmlHttpRequest.send(self.body),promise},responsePromise=function(xmlRequest){var promise=new Promise,usergridResponse=new UsergridResponse(xmlRequest,self);return promise.done(usergridResponse),promise},onCompletePromise=function(usergridResponse){self.callback(usergridResponse.error,usergridResponse)};return Promise.chain([requestPromise,responsePromise]).then(onCompletePromise),self};var UsergridAuth=function(token,expiry){var self=this;self.token=token,self.expiry=expiry||0;var usingToken=token?!0:!1;return Object.defineProperty(self,"hasToken",{get:function(){return void 0!==self.token},configurable:!0}),Object.defineProperty(self,"isExpired",{get:function(){return usingToken?!1:Date.now()>=self.expiry},configurable:!0}),Object.defineProperty(self,"isValid",{get:function(){return!self.isExpired&&self.hasToken},configurable:!0}),Object.defineProperty(self,"tokenTtl",{configurable:!0,writable:!0}),_.assign(self,{destroy:function(){self.token=void 0,self.expiry=0,self.tokenTtl=void 0}}),self},UsergridAppAuth=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments);return _.isPlainObject(args[0])?(self.clientId=args[0].clientId,self.clientSecret=args[0].clientSecret,self.tokenTtl=args[0].tokenTtl):(self.clientId=args[0],self.clientSecret=args[1],self.tokenTtl=args[2]),UsergridAuth.call(self),_.assign(self,UsergridAuth),self};UsergridHelpers.inherits(UsergridAppAuth,UsergridAuth);var UsergridUserAuth=function(options){var self=this,args=_.flattenDeep(UsergridHelpers.flattenArgs(arguments));return _.isPlainObject(args[0])&&(options=args[0]),self.username=options.username||args[0],self.email=options.email,(options.password||args[1])&&(self.password=options.password||args[1]),self.tokenTtl=options.tokenTtl||args[2],UsergridAuth.call(self),_.assign(self,UsergridAuth),self};UsergridHelpers.inherits(UsergridUserAuth,UsergridAuth);var UsergridEntity=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments);if(0===args.length)throw new Error("A UsergridEntity object cannot be initialized without passing one or more arguments");if(self.asset=void 0,_.isPlainObject(args[0])?_.assign(self,args[0]):(self.type||(self.type=_.isString(args[0])?args[0]:void 0),self.name||(self.name=_.isString(args[1])?args[1]:void 0)),!_.isString(self.type))throw new Error("'type' (or 'collection') parameter is required when initializing a UsergridEntity object");return Object.defineProperty(self,"isUser",{get:function(){return"user"===self.type.toLowerCase()}}),Object.defineProperty(self,"hasAsset",{get:function(){return _.has(self,"file-metadata")}}),UsergridHelpers.setReadOnly(self,["uuid","name","type","created"]),self};UsergridEntity.prototype={jsonValue:function(){var jsonValue={};return _.forOwn(this,function(value,key){jsonValue[key]=value}),jsonValue},putProperty:function(key,value){this[key]=value},putProperties:function(obj){_.assign(this,obj)},removeProperty:function(key){this.removeProperties([key])},removeProperties:function(keys){var self=this;keys.forEach(function(key){delete self[key]})},insert:function(key,value,idx){_.isArray(this[key])||(this[key]=this[key]?[this[key]]:[]),this[key].splice.apply(this[key],[idx,0].concat(value))},append:function(key,value){this.insert(key,value,Number.MAX_VALUE)},prepend:function(key,value){this.insert(key,value,0)},pop:function(key){_.isArray(this[key])&&this[key].pop()},shift:function(key){_.isArray(this[key])&&this[key].shift()},reload:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.GET(self,function(error,usergridResponse){UsergridHelpers.updateEntityFromRemote(self,usergridResponse),callback(error,usergridResponse,self)}.bind(self))},save:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args),currentAsset=self.asset;client.PUT(self,function(error,usergridResponse){UsergridHelpers.updateEntityFromRemote(self,usergridResponse),self.hasAsset&&(self.asset=currentAsset),callback(error,usergridResponse,self)}.bind(self))},remove:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.DELETE(self,function(error,usergridResponse){callback(error,usergridResponse,self)}.bind(self))},attachAsset:function(asset){this.asset=asset},uploadAsset:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(_.has(self,"asset.contentType"))client.uploadAsset(self,callback);else{var response=UsergridResponse.responseWithError({name:"asset_not_found",description:"The specified entity does not have a valid asset attached"});callback(response.error,response,self)}},downloadAsset:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(_.has(self,"asset.contentType"))client.downloadAsset(self,callback);else{var response=UsergridResponse.responseWithError({name:"asset_not_found",description:"The specified entity does not have a valid asset attached"});callback(response.error,response,self)}},connect:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args[0]=this,client.connect.apply(client,args)},disconnect:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args[0]=this,client.disconnect.apply(client,args)},getConnections:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args.shift(),args.splice(1,0,this),client.getConnections.apply(client,args)}};var UsergridUser=function(obj){if(!_.has(obj,"email")&&!_.has(obj,"username"))throw new Error("'email' or 'username' property is required when initializing a UsergridUser object");var self=this;return _.assign(self,obj,UsergridEntity),UsergridEntity.call(self,"user"),UsergridHelpers.setWritable(self,"name"),self};UsergridUser.CheckAvailable=function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args),username=args[0].username||args[1].username,email=args[0].email||args[1].email;if(!username&&!email)throw new Error("'username' or 'email' property is required when checking for available users");var checkQuery=new UsergridQuery("users");username&&checkQuery.eq("username",username),email&&checkQuery.or.eq("email",email),client.GET(checkQuery,function(error,usergridResponse){callback(error,usergridResponse,usergridResponse.entities.length>0)})},UsergridHelpers.inherits(UsergridUser,UsergridEntity),UsergridUser.prototype.uniqueId=function(){var self=this;return _.first([self.uuid,self.username,self.email].filter(_.isString))},UsergridUser.prototype.create=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.POST(self,function(error,usergridResponse){delete self.password,_.assign(self,usergridResponse.user),callback(error,usergridResponse,self)}.bind(self))},UsergridUser.prototype.login=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.POST("token",UsergridHelpers.userLoginBody(self),function(error,usergridResponse){delete self.password;var responseJSON=usergridResponse.responseJSON,token=_.get(responseJSON,"access_token"),expiresIn=_.get(responseJSON,"expires_in");usergridResponse.ok&&(self.auth=new UsergridUserAuth(self),self.auth.token=token,self.auth.expiry=UsergridHelpers.calculateExpiry(expiresIn),self.auth.tokenTtl=expiresIn),callback(error,usergridResponse,token)})},UsergridUser.prototype.logout=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(self.auth&&self.auth.isValid){var revokeAll=_.first(args.filter(_.isBoolean))||!1,requestOptions={client:client,path:["users",self.uniqueId(),"revoketoken"+(revokeAll?"s":"")].join("/"),method:UsergridHttpMethod.PUT,callback:function(error,usergridResponse){self.auth.destroy(),callback(error,usergridResponse,usergridResponse.ok)}.bind(self)};revokeAll||(requestOptions.queryParams={token:self.auth.token});var request=new UsergridRequest(requestOptions);client.sendRequest(request)}else{var response=UsergridResponse.responseWithError({name:"no_valid_token",description:"this user does not have a valid token"});callback(response.error,response)}},UsergridUser.prototype.logoutAllSessions=function(){var args=UsergridHelpers.flattenArgs(arguments);return args=_.concat([UsergridHelpers.validateAndRetrieveClient(args),!0],args),this.logout.apply(this,args)},UsergridUser.prototype.resetPassword=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);args[0]instanceof UsergridClient&&args.shift();var body=UsergridHelpers.userResetPasswordBody(args);if(!body.oldpassword||!body.newpassword)throw new Error("'oldPassword' and 'newPassword' properties are required when resetting a user password");client.PUT(["users",self.uniqueId(),"password"].join("/"),body,callback)};var UsergridResponseError=function(options){var self=this;return _.assign(self,options),self};UsergridResponseError.fromJSON=function(responseErrorObject){var usergridResponseError,error={name:_.get(responseErrorObject,"error")};return error.name&&(_.assign(error,{exception:_.get(responseErrorObject,"exception"),description:_.get(responseErrorObject,"error_description")||_.get(responseErrorObject,"description")}),usergridResponseError=new UsergridResponseError(error)),usergridResponseError};var UsergridResponse=function(xmlRequest,usergridRequest){var self=this;if(self.ok=!1,self.request=usergridRequest,xmlRequest){self.statusCode=parseInt(xmlRequest.status),self.ok=self.statusCode<400,self.headers=UsergridHelpers.parseResponseHeaders(xmlRequest.getAllResponseHeaders());var responseContentType=_.get(self.headers,"content-type");if(responseContentType===UsergridApplicationJSONHeaderValue)try{var responseJSON=JSON.parse(xmlRequest.responseText);responseJSON&&self.parseResponseJSON(responseJSON)}catch(e){}else self.asset=new UsergridAsset(xmlRequest.response)}return self};UsergridResponse.responseWithError=function(options){var usergridResponse=new UsergridResponse;return usergridResponse.error=new UsergridResponseError(options),usergridResponse},UsergridResponse.prototype={parseResponseJSON:function(responseJSON){var self=this;if(self.responseJSON=_.cloneDeep(responseJSON),self.ok){self.cursor=_.get(self,"responseJSON.cursor"),self.hasNextPage=!_.isNil(self.cursor);var entitiesJSON=_.get(responseJSON,"entities");entitiesJSON&&(self.parseResponseEntities(entitiesJSON),delete self.responseJSON.entities)}else self.error=UsergridResponseError.fromJSON(responseJSON);UsergridHelpers.setReadOnly(self.responseJSON)},parseResponseEntities:function(entitiesJSON){var self=this;self.entities=_.map(entitiesJSON,function(entityJSON){var entity=new UsergridEntity(entityJSON);return entity.isUser&&(entity=new UsergridUser(entity)),entity}),self.first=_.first(self.entities),self.entity=self.first,self.last=_.last(self.entities),"/users"===_.get(self,"responseJSON.path")&&(self.user=self.first,self.users=self.entities)},loadNextPage:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args),cursor=self.cursor;if(cursor){var client=UsergridHelpers.validateAndRetrieveClient(args),type=_.last(_.get(self,"responseJSON.path").split("/")),limit=_.first(_.get(self,"responseJSON.params.limit")),ql=_.first(_.get(self,"responseJSON.params.ql")),query=new UsergridQuery(type).fromString(ql).cursor(cursor).limit(limit);client.GET(query,callback)}else callback(UsergridResponse.responseWithError({name:"cursor_not_found",description:"Cursor must be present in order perform loadNextPage()."}))}};var UsergridAssetDefaultFileName="file",UsergridAsset=function(fileOrBlob){if(!fileOrBlob instanceof File||!fileOrBlob instanceof Blob)throw new Error("UsergridAsset must be initialized with a 'File' or 'Blob'");var self=this;return self.data=fileOrBlob,self.filename=fileOrBlob.name||UsergridAssetDefaultFileName,self.contentLength=fileOrBlob.size,self.contentType=fileOrBlob.type,self}; \ No newline at end of file