react-native-onyx 1.0.73 → 1.0.75

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"web.min.js","mappings":";CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,EAAQG,QAAQ,eAAgBA,QAAQ,cAAeA,QAAQ,cAAeA,QAAQ,oBAAqBA,QAAQ,UAC3G,mBAAXC,QAAyBA,OAAOC,IAC9CD,OAAO,CAAC,cAAe,aAAc,aAAc,mBAAoB,SAAUJ,GACvD,iBAAZC,QACdA,QAAQ,yBAA2BD,EAAQG,QAAQ,eAAgBA,QAAQ,cAAeA,QAAQ,cAAeA,QAAQ,oBAAqBA,QAAQ,UAEtJJ,EAAK,yBAA2BC,EAAQD,EAAK,eAAgBA,EAAiB,WAAGA,EAAK,cAAeA,EAAK,oBAAqBA,EAAY,MAC5I,CATD,CASGO,MAAM,CAACC,EAAkCC,EAAkCC,EAAkCC,EAAkCC,4CCPlJ,SAASC,EAAoBC,GAAQ,OAAOA,CAAM,CAClD,SAASC,IAAc,CACvB,SAASC,IAAgB,CACzB,SAASC,IAAgB,uHCLzB,iBACE,SAASjB,GAGV,IAQIkB,GAL0Cf,GAC7CA,EAAOD,QAI0B,iBAAV,EAAAiB,GAAsB,EAAAA,GAC1CD,EAAWE,SAAWF,GAAcA,EAAWG,OAMnD,IAAIC,EAAwB,SAASC,GACpCC,KAAKD,QAAUA,CAChB,GACAD,EAAsBG,UAAY,IAAIC,OACNC,KAAO,wBAEvC,IAAIC,EAAQ,SAASL,GAGpB,MAAM,IAAID,EAAsBC,EACjC,EAEIM,EAAQ,mEAERC,EAAyB,eAuGzBC,EAAS,CACZ,OA5DY,SAASC,GACrBA,EAAQC,OAAOD,GACX,aAAaE,KAAKF,IAGrBJ,EACC,6EAeF,IAXA,IAGIO,EACAC,EACAC,EAEAC,EAPAC,EAAUP,E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iBAAkBzzB,KAClB6sB,eAER,CAEA2N,SACI,GAAIx6B,KAAKsM,MAAMwtB,QACX,OAAO,KAKX,IAAIW,EAAc3X,IAAAA,KAAO9iB,KAAKsM,MAAO,WACrCmuB,EAAc3X,IAAAA,KAAO2X,GAAax4B,GAAS6gB,IAAAA,OAAS7gB,KAGpD,MAAMy4B,EAAc5X,IAAAA,KAAO9iB,KAAKyJ,OAAOxH,GAAS6gB,IAAAA,OAAS7gB,KAGzD,OACIw3B,KAAAA,cAACH,EACGqB,GAAA,GACID,EAEAD,EAAW,CACfG,IAAK56B,KAAKyJ,MAAMoxB,eAG5B,EAcJ,OAXArB,EAASsB,UAAY,CACjBD,aAAczvB,KAAAA,UAAoB,CAC9BA,KAAAA,KAEAA,KAAAA,MAAgB,CAAC2vB,QAAS3vB,KAAAA,YAGlCouB,EAASwB,aAAe,CACpBH,kBAAc52B,GAElBu1B,EAAS3M,YAAe,YAAWA,KAC5B4M,KAAAA,YAAiB,CAAChwB,EAAOmxB,KAC5B,MAAMK,EAAYzB,EAElB,OAAOC,KAAAA,cAACwB,EAASN,GAAA,GAAKlxB,EAAK,CAAEoxB,aAAcD,IAAO,GACpD,CAEV,CC9OA","sources":["webpack://react-native-onyx/web/webpack/universalModuleDefinition","webpack://react-native-onyx/web/./lib/metrics/index.web.js","webpack://react-native-onyx/web/./node_modules/base-64/base64.js","webpack://react-native-onyx/web/./node_modules/jsan/index.js","webpack://react-native-onyx/web/./node_modules/jsan/lib/cycle.js","webpack://react-native-onyx/web/./node_modules/jsan/lib/index.js","webpack://react-native-onyx/web/./node_modules/jsan/lib/path-getter.js","webpack://react-native-onyx/web/./node_modules/jsan/lib/utils.js","webpack://react-native-onyx/web/./node_modules/linked-list/_source/linked-list.js","webpack://react-native-onyx/web/./node_modules/linked-list/index.js","webpack://react-native-onyx/web/./node_modules/prop-types/factoryWithThrowingShims.js","webpack://react-native-onyx/web/./node_modules/prop-types/index.js","webpack://react-native-onyx/web/./node_modules/prop-types/lib/ReactPropTypesSecret.js","webpack://react-native-onyx/web/./node_modules/remotedev/lib/constants.js","webpack://react-native-onyx/web/./node_modules/remotedev/lib/devTools.js","webpack://react-native-onyx/web/./node_modules/remotedev/lib/index.js","webpack://react-native-onyx/web/./node_modules/rn-host-detect/index.js","webpack://react-native-onyx/web/./node_modules/sc-channel/index.js","webpack://react-native-onyx/web/./node_modules/sc-channel/node_modules/component-emitter/index.js","webpack://react-native-onyx/web/./node_modules/sc-errors/decycle.js","webpack://react-native-onyx/web/./node_modules/sc-errors/index.js","webpack://react-native-onyx/web/./node_modules/sc-formatter/index.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/index.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/lib/auth.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/lib/factory.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/lib/response.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/lib/scclientsocket.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/lib/sctransport.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/lib/ws-browser.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/node_modules/clone/clone.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/node_modules/component-emitter/index.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/node_modules/querystring/decode.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/node_modules/querystring/encode.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/node_modules/querystring/index.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/node_modules/uuid/index.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/node_modules/uuid/lib/bytesToUuid.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/node_modules/uuid/lib/rng-browser.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/node_modules/uuid/v1.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/node_modules/uuid/v4.js","webpack://react-native-onyx/web/external umd \"fast-equals\"","webpack://react-native-onyx/web/external umd \"idb-keyval\"","webpack://react-native-onyx/web/external umd \"lodash/transform\"","webpack://react-native-onyx/web/external umd \"react\"","webpack://react-native-onyx/web/external umd \"underscore\"","webpack://react-native-onyx/web/webpack/bootstrap","webpack://react-native-onyx/web/webpack/runtime/compat get default export","webpack://react-native-onyx/web/webpack/runtime/define property getters","webpack://react-native-onyx/web/webpack/runtime/global","webpack://react-native-onyx/web/webpack/runtime/hasOwnProperty shorthand","webpack://react-native-onyx/web/webpack/runtime/make namespace object","webpack://react-native-onyx/web/webpack/runtime/node module decorator","webpack://react-native-onyx/web/./lib/Logger.js","webpack://react-native-onyx/web/./lib/fastMerge.js","webpack://react-native-onyx/web/./lib/OnyxCache.js","webpack://react-native-onyx/web/./lib/Str.js","webpack://react-native-onyx/web/./lib/metrics/PerformanceUtils.js","webpack://react-native-onyx/web/./lib/storage/providers/IDBKeyVal.js","webpack://react-native-onyx/web/./lib/storage/WebStorage.js","webpack://react-native-onyx/web/./lib/storage/index.web.js","webpack://react-native-onyx/web/./lib/DevTools.js","webpack://react-native-onyx/web/./lib/Onyx.js","webpack://react-native-onyx/web/./lib/createDeferredTask.js","webpack://react-native-onyx/web/./lib/withOnyx.js","webpack://react-native-onyx/web/./lib/index.js"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory(require(\"fast-equals\"), require(\"underscore\"), require(\"idb-keyval\"), require(\"lodash/transform\"), require(\"react\"));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([\"fast-equals\", \"underscore\", \"idb-keyval\", \"lodash/transform\", \"react\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"react-native-onyx/web\"] = factory(require(\"fast-equals\"), require(\"underscore\"), require(\"idb-keyval\"), require(\"lodash/transform\"), require(\"react\"));\n\telse\n\t\troot[\"react-native-onyx/web\"] = factory(root[\"fast-equals\"], root[\"underscore\"], root[\"idb-keyval\"], root[\"lodash/transform\"], root[\"react\"]);\n})(self, (__WEBPACK_EXTERNAL_MODULE__746__, __WEBPACK_EXTERNAL_MODULE__952__, __WEBPACK_EXTERNAL_MODULE__802__, __WEBPACK_EXTERNAL_MODULE__407__, __WEBPACK_EXTERNAL_MODULE__156__) => {\nreturn ","// For web-only implementations of Onyx, this module will just be a no-op\n\nfunction decorateWithMetrics(func) { return func; }\nfunction getMetrics() {}\nfunction printMetrics() {}\nfunction resetMetrics() {}\n\nexport {\n decorateWithMetrics,\n getMetrics,\n resetMetrics,\n printMetrics,\n};\n","/*! http://mths.be/base64 v0.1.0 by @mathias | MIT license */\n;(function(root) {\n\n\t// Detect free variables `exports`.\n\tvar freeExports = typeof exports == 'object' && exports;\n\n\t// Detect free variable `module`.\n\tvar freeModule = typeof module == 'object' && module &&\n\t\tmodule.exports == freeExports && module;\n\n\t// Detect free variable `global`, from Node.js or Browserified code, and use\n\t// it as `root`.\n\tvar freeGlobal = typeof global == 'object' && global;\n\tif (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {\n\t\troot = freeGlobal;\n\t}\n\n\t/*--------------------------------------------------------------------------*/\n\n\tvar InvalidCharacterError = function(message) {\n\t\tthis.message = message;\n\t};\n\tInvalidCharacterError.prototype = new Error;\n\tInvalidCharacterError.prototype.name = 'InvalidCharacterError';\n\n\tvar error = function(message) {\n\t\t// Note: the error messages used throughout this file match those used by\n\t\t// the native `atob`/`btoa` implementation in Chromium.\n\t\tthrow new InvalidCharacterError(message);\n\t};\n\n\tvar TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\t// http://whatwg.org/html/common-microsyntaxes.html#space-character\n\tvar REGEX_SPACE_CHARACTERS = /[\\t\\n\\f\\r ]/g;\n\n\t// `decode` is designed to be fully compatible with `atob` as described in the\n\t// HTML Standard. http://whatwg.org/html/webappapis.html#dom-windowbase64-atob\n\t// The optimized base64-decoding algorithm used is based on @atk’s excellent\n\t// implementation. https://gist.github.com/atk/1020396\n\tvar decode = function(input) {\n\t\tinput = String(input)\n\t\t\t.replace(REGEX_SPACE_CHARACTERS, '');\n\t\tvar length = input.length;\n\t\tif (length % 4 == 0) {\n\t\t\tinput = input.replace(/==?$/, '');\n\t\t\tlength = input.length;\n\t\t}\n\t\tif (\n\t\t\tlength % 4 == 1 ||\n\t\t\t// http://whatwg.org/C#alphanumeric-ascii-characters\n\t\t\t/[^+a-zA-Z0-9/]/.test(input)\n\t\t) {\n\t\t\terror(\n\t\t\t\t'Invalid character: the string to be decoded is not correctly encoded.'\n\t\t\t);\n\t\t}\n\t\tvar bitCounter = 0;\n\t\tvar bitStorage;\n\t\tvar buffer;\n\t\tvar output = '';\n\t\tvar position = -1;\n\t\twhile (++position < length) {\n\t\t\tbuffer = TABLE.indexOf(input.charAt(position));\n\t\t\tbitStorage = bitCounter % 4 ? bitStorage * 64 + buffer : buffer;\n\t\t\t// Unless this is the first of a group of 4 characters…\n\t\t\tif (bitCounter++ % 4) {\n\t\t\t\t// …convert the first 8 bits to a single ASCII character.\n\t\t\t\toutput += String.fromCharCode(\n\t\t\t\t\t0xFF & bitStorage >> (-2 * bitCounter & 6)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn output;\n\t};\n\n\t// `encode` is designed to be fully compatible with `btoa` as described in the\n\t// HTML Standard: http://whatwg.org/html/webappapis.html#dom-windowbase64-btoa\n\tvar encode = function(input) {\n\t\tinput = String(input);\n\t\tif (/[^\\0-\\xFF]/.test(input)) {\n\t\t\t// Note: no need to special-case astral symbols here, as surrogates are\n\t\t\t// matched, and the input is supposed to only contain ASCII anyway.\n\t\t\terror(\n\t\t\t\t'The string to be encoded contains characters outside of the ' +\n\t\t\t\t'Latin1 range.'\n\t\t\t);\n\t\t}\n\t\tvar padding = input.length % 3;\n\t\tvar output = '';\n\t\tvar position = -1;\n\t\tvar a;\n\t\tvar b;\n\t\tvar c;\n\t\tvar d;\n\t\tvar buffer;\n\t\t// Make sure any padding is handled outside of the loop.\n\t\tvar length = input.length - padding;\n\n\t\twhile (++position < length) {\n\t\t\t// Read three bytes, i.e. 24 bits.\n\t\t\ta = input.charCodeAt(position) << 16;\n\t\t\tb = input.charCodeAt(++position) << 8;\n\t\t\tc = input.charCodeAt(++position);\n\t\t\tbuffer = a + b + c;\n\t\t\t// Turn the 24 bits into four chunks of 6 bits each, and append the\n\t\t\t// matching character for each of them to the output.\n\t\t\toutput += (\n\t\t\t\tTABLE.charAt(buffer >> 18 & 0x3F) +\n\t\t\t\tTABLE.charAt(buffer >> 12 & 0x3F) +\n\t\t\t\tTABLE.charAt(buffer >> 6 & 0x3F) +\n\t\t\t\tTABLE.charAt(buffer & 0x3F)\n\t\t\t);\n\t\t}\n\n\t\tif (padding == 2) {\n\t\t\ta = input.charCodeAt(position) << 8;\n\t\t\tb = input.charCodeAt(++position);\n\t\t\tbuffer = a + b;\n\t\t\toutput += (\n\t\t\t\tTABLE.charAt(buffer >> 10) +\n\t\t\t\tTABLE.charAt((buffer >> 4) & 0x3F) +\n\t\t\t\tTABLE.charAt((buffer << 2) & 0x3F) +\n\t\t\t\t'='\n\t\t\t);\n\t\t} else if (padding == 1) {\n\t\t\tbuffer = input.charCodeAt(position);\n\t\t\toutput += (\n\t\t\t\tTABLE.charAt(buffer >> 2) +\n\t\t\t\tTABLE.charAt((buffer << 4) & 0x3F) +\n\t\t\t\t'=='\n\t\t\t);\n\t\t}\n\n\t\treturn output;\n\t};\n\n\tvar base64 = {\n\t\t'encode': encode,\n\t\t'decode': decode,\n\t\t'version': '0.1.0'\n\t};\n\n\t// Some AMD build optimizers, like r.js, check for specific condition patterns\n\t// like the following:\n\tif (\n\t\ttypeof define == 'function' &&\n\t\ttypeof define.amd == 'object' &&\n\t\tdefine.amd\n\t) {\n\t\tdefine(function() {\n\t\t\treturn base64;\n\t\t});\n\t}\telse if (freeExports && !freeExports.nodeType) {\n\t\tif (freeModule) { // in Node.js or RingoJS v0.8.0+\n\t\t\tfreeModule.exports = base64;\n\t\t} else { // in Narwhal or RingoJS v0.7.0-\n\t\t\tfor (var key in base64) {\n\t\t\t\tbase64.hasOwnProperty(key) && (freeExports[key] = base64[key]);\n\t\t\t}\n\t\t}\n\t} else { // in Rhino or a web browser\n\t\troot.base64 = base64;\n\t}\n\n}(this));\n","module.exports = require('./lib');\n","var pathGetter = require('./path-getter');\nvar utils = require('./utils');\n\nvar WMap = typeof WeakMap !== 'undefined'?\n WeakMap:\n function() {\n var keys = [];\n var values = [];\n return {\n set: function(key, value) {\n keys.push(key);\n values.push(value);\n },\n get: function(key) {\n for (var i = 0; i < keys.length; i++) {\n if (keys[i] === key) {\n return values[i];\n }\n }\n }\n }\n };\n\n// Based on https://github.com/douglascrockford/JSON-js/blob/master/cycle.js\n\nexports.decycle = function decycle(object, options, replacer, map) {\n 'use strict';\n\n map = map || new WMap();\n\n var noCircularOption = !Object.prototype.hasOwnProperty.call(options, 'circular');\n var withRefs = options.refs !== false;\n\n return (function derez(_value, path, key) {\n\n // The derez recurses through the object, producing the deep copy.\n\n var i, // The loop counter\n name, // Property name\n nu; // The new object or array\n\n // typeof null === 'object', so go on if this value is really an object but not\n // one of the weird builtin objects.\n\n var value = typeof replacer === 'function' ? replacer(key || '', _value) : _value;\n\n if (options.date && value instanceof Date) {\n return {$jsan: 'd' + value.getTime()};\n }\n if (options.regex && value instanceof RegExp) {\n return {$jsan: 'r' + utils.getRegexFlags(value) + ',' + value.source};\n }\n if (options['function'] && typeof value === 'function') {\n return {$jsan: 'f' + utils.stringifyFunction(value, options['function'])}\n }\n if (options['nan'] && typeof value === 'number' && isNaN(value)) {\n return {$jsan: 'n'}\n }\n if (options['infinity']) {\n if (Number.POSITIVE_INFINITY === value) return {$jsan: 'i'}\n if (Number.NEGATIVE_INFINITY === value) return {$jsan: 'y'}\n }\n if (options['undefined'] && value === undefined) {\n return {$jsan: 'u'}\n }\n if (options['error'] && value instanceof Error) {\n return {$jsan: 'e' + value.message}\n }\n if (options['symbol'] && typeof value === 'symbol') {\n var symbolKey = Symbol.keyFor(value)\n if (symbolKey !== undefined) {\n return {$jsan: 'g' + symbolKey}\n }\n\n // 'Symbol(foo)'.slice(7, -1) === 'foo'\n return {$jsan: 's' + value.toString().slice(7, -1)}\n }\n\n if (options['map'] && typeof Map === 'function' && value instanceof Map && typeof Array.from === 'function') {\n return {$jsan: 'm' + JSON.stringify(decycle(Array.from(value), options, replacer, map))}\n }\n\n if (options['set'] && typeof Set === 'function' && value instanceof Set && typeof Array.from === 'function') {\n return {$jsan: 'l' + JSON.stringify(decycle(Array.from(value), options, replacer, map))}\n }\n\n if (value && typeof value.toJSON === 'function') {\n try {\n value = value.toJSON(key);\n } catch (error) {\n var keyString = (key || '$');\n return \"toJSON failed for '\" + (map.get(value) || keyString) + \"'\";\n }\n }\n\n if (typeof value === 'object' && value !== null &&\n !(value instanceof Boolean) &&\n !(value instanceof Date) &&\n !(value instanceof Number) &&\n !(value instanceof RegExp) &&\n !(value instanceof String) &&\n !(typeof value === 'symbol') &&\n !(value instanceof Error)) {\n\n // If the value is an object or array, look to see if we have already\n // encountered it. If so, return a $ref/path object.\n\n if (typeof value === 'object') {\n var foundPath = map.get(value);\n if (foundPath) {\n if (noCircularOption && withRefs) {\n return {$jsan: foundPath};\n }\n \n // This is only a true circular reference if the parent path is inside of foundPath\n // drop the last component of the current path and check if it starts with foundPath\n var parentPath = path.split('.').slice(0, -1).join('.');\n if (parentPath.indexOf(foundPath) === 0) {\n if (!noCircularOption) {\n return typeof options.circular === 'function'?\n options.circular(value, path, foundPath):\n options.circular;\n }\n return {$jsan: foundPath};\n }\n if (withRefs) return {$jsan: foundPath};\n }\n map.set(value, path);\n }\n\n\n // If it is an array, replicate the array.\n\n if (Object.prototype.toString.apply(value) === '[object Array]') {\n nu = [];\n for (i = 0; i < value.length; i += 1) {\n nu[i] = derez(value[i], path + '[' + i + ']', i);\n }\n } else {\n\n // If it is an object, replicate the object.\n\n nu = {};\n for (name in value) {\n if (Object.prototype.hasOwnProperty.call(value, name)) {\n var nextPath = /^\\w+$/.test(name) ?\n '.' + name :\n '[' + JSON.stringify(name) + ']';\n nu[name] = name === '$jsan' ? [derez(value[name], path + nextPath)] : derez(value[name], path + nextPath, name);\n }\n }\n }\n return nu;\n }\n return value;\n }(object, '$'));\n};\n\n\nexports.retrocycle = function retrocycle($) {\n 'use strict';\n\n\n return (function rez(value) {\n\n // The rez function walks recursively through the object looking for $jsan\n // properties. When it finds one that has a value that is a path, then it\n // replaces the $jsan object with a reference to the value that is found by\n // the path.\n\n var i, item, name, path;\n\n if (value && typeof value === 'object') {\n if (Object.prototype.toString.apply(value) === '[object Array]') {\n for (i = 0; i < value.length; i += 1) {\n item = value[i];\n if (item && typeof item === 'object') {\n if (item.$jsan) {\n value[i] = utils.restore(item.$jsan, $);\n } else {\n rez(item);\n }\n }\n }\n } else {\n for (name in value) {\n // base case passed raw object\n if(typeof value[name] === 'string' && name === '$jsan'){\n return utils.restore(value.$jsan, $);\n break;\n }\n else {\n if (name === '$jsan') {\n value[name] = value[name][0];\n }\n if (typeof value[name] === 'object') {\n item = value[name];\n if (item && typeof item === 'object') {\n if (item.$jsan) {\n value[name] = utils.restore(item.$jsan, $);\n } else {\n rez(item);\n }\n }\n }\n }\n }\n }\n }\n return value;\n }($));\n};\n","var cycle = require('./cycle');\n\nexports.stringify = function stringify(value, replacer, space, _options) {\n\n if (arguments.length < 4) {\n try {\n if (arguments.length === 1) {\n return JSON.stringify(value);\n } else {\n return JSON.stringify.apply(JSON, arguments);\n }\n } catch (e) {}\n }\n\n var options = _options || false;\n if (typeof options === 'boolean') {\n options = {\n 'date': options,\n 'function': options,\n 'regex': options,\n 'undefined': options,\n 'error': options,\n 'symbol': options,\n 'map': options,\n 'set': options,\n 'nan': options,\n 'infinity': options\n }\n }\n\n var decycled = cycle.decycle(value, options, replacer);\n if (arguments.length === 1) {\n return JSON.stringify(decycled);\n } else {\n // decycle already handles when replacer is a function.\n return JSON.stringify(decycled, Array.isArray(replacer) ? replacer : null, space);\n }\n}\n\nexports.parse = function parse(text, reviver) {\n var needsRetrocycle = /\"\\$jsan\"/.test(text);\n var parsed;\n if (arguments.length === 1) {\n parsed = JSON.parse(text);\n } else {\n parsed = JSON.parse(text, reviver);\n }\n if (needsRetrocycle) {\n parsed = cycle.retrocycle(parsed);\n }\n return parsed;\n}\n","module.exports = pathGetter;\n\nfunction pathGetter(obj, path) {\n if (path !== '$') {\n var paths = getPaths(path);\n for (var i = 0; i < paths.length; i++) {\n path = paths[i].toString().replace(/\\\\\"/g, '\"');\n if (typeof obj[path] === 'undefined' && i !== paths.length - 1) continue;\n obj = obj[path];\n }\n }\n return obj;\n}\n\nfunction getPaths(pathString) {\n var regex = /(?:\\.(\\w+))|(?:\\[(\\d+)\\])|(?:\\[\"((?:[^\\\\\"]|\\\\.)*)\"\\])/g;\n var matches = [];\n var match;\n while (match = regex.exec(pathString)) {\n matches.push( match[1] || match[2] || match[3] );\n }\n return matches;\n}\n","var pathGetter = require('./path-getter');\nvar jsan = require('./');\n\nexports.getRegexFlags = function getRegexFlags(regex) {\n var flags = '';\n if (regex.ignoreCase) flags += 'i';\n if (regex.global) flags += 'g';\n if (regex.multiline) flags += 'm';\n return flags;\n};\n\nexports.stringifyFunction = function stringifyFunction(fn, customToString) {\n if (typeof customToString === 'function') {\n return customToString(fn);\n }\n var str = fn.toString();\n var match = str.match(/^[^{]*{|^[^=]*=>/);\n var start = match ? match[0] : '<function> ';\n var end = str[str.length - 1] === '}' ? '}' : '';\n return start.replace(/\\r\\n|\\n/g, ' ').replace(/\\s+/g, ' ') + ' /* ... */ ' + end;\n};\n\nexports.restore = function restore(obj, root) {\n var type = obj[0];\n var rest = obj.slice(1);\n switch(type) {\n case '$':\n return pathGetter(root, obj);\n case 'r':\n var comma = rest.indexOf(',');\n var flags = rest.slice(0, comma);\n var source = rest.slice(comma + 1);\n return RegExp(source, flags);\n case 'd':\n return new Date(+rest);\n case 'f':\n var fn = function() { throw new Error(\"can't run jsan parsed function\") };\n fn.toString = function() { return rest; };\n return fn;\n case 'u':\n return undefined;\n case 'e':\n var error = new Error(rest);\n error.stack = 'Stack is unavailable for jsan parsed errors';\n return error;\n case 's':\n return Symbol(rest);\n case 'g':\n return Symbol.for(rest);\n case 'm':\n return new Map(jsan.parse(rest));\n case 'l':\n return new Set(jsan.parse(rest));\n case 'n':\n return NaN;\n case 'i':\n return Infinity;\n case 'y':\n return -Infinity;\n default:\n console.warn('unknown type', obj);\n return obj;\n }\n}\n","'use strict';\n\n/**\n * Constants.\n */\n\nvar errorMessage;\n\nerrorMessage = 'An argument without append, prepend, ' +\n 'or detach methods was given to `List';\n\n/**\n * Creates a new List: A linked list is a bit like an Array, but\n * knows nothing about how many items are in it, and knows only about its\n * first (`head`) and last (`tail`) items. Each item (e.g. `head`, `tail`,\n * &c.) knows which item comes before or after it (its more like the\n * implementation of the DOM in JavaScript).\n * @global\n * @private\n * @constructor\n * @class Represents an instance of List.\n */\n\nfunction List(/*items...*/) {\n if (arguments.length) {\n return List.from(arguments);\n }\n}\n\nvar ListPrototype;\n\nListPrototype = List.prototype;\n\n/**\n * Creates a new list from the arguments (each a list item) passed in.\n * @name List.of\n * @param {...ListItem} [items] - Zero or more items to attach.\n * @returns {list} - A new instance of List.\n */\n\nList.of = function (/*items...*/) {\n return List.from.call(this, arguments);\n};\n\n/**\n * Creates a new list from the given array-like object (each a list item)\n * passed in.\n * @name List.from\n * @param {ListItem[]} [items] - The items to append.\n * @returns {list} - A new instance of List.\n */\nList.from = function (items) {\n var list = new this(), length, iterator, item;\n\n if (items && (length = items.length)) {\n iterator = -1;\n\n while (++iterator < length) {\n item = items[iterator];\n\n if (item !== null && item !== undefined) {\n list.append(item);\n }\n }\n }\n\n return list;\n};\n\n/**\n * List#head\n * Default to `null`.\n */\nListPrototype.head = null;\n\n/**\n * List#tail\n * Default to `null`.\n */\nListPrototype.tail = null;\n\n/**\n * Returns the list's items as an array. This does *not* detach the items.\n * @name List#toArray\n * @returns {ListItem[]} - An array of (still attached) ListItems.\n */\nListPrototype.toArray = function () {\n var item = this.head,\n result = [];\n\n while (item) {\n result.push(item);\n item = item.next;\n }\n\n return result;\n};\n\n/**\n * Prepends the given item to the list: Item will be the new first item\n * (`head`).\n * @name List#prepend\n * @param {ListItem} item - The item to prepend.\n * @returns {ListItem} - An instance of ListItem (the given item).\n */\nListPrototype.prepend = function (item) {\n if (!item) {\n return false;\n }\n\n if (!item.append || !item.prepend || !item.detach) {\n throw new Error(errorMessage + '#prepend`.');\n }\n\n var self, head;\n\n // Cache self.\n self = this;\n\n // If self has a first item, defer prepend to the first items prepend\n // method, and return the result.\n head = self.head;\n\n if (head) {\n return head.prepend(item);\n }\n\n // ...otherwise, there is no `head` (or `tail`) item yet.\n\n // Detach the prependee.\n item.detach();\n\n // Set the prependees parent list to reference self.\n item.list = self;\n\n // Set self's first item to the prependee, and return the item.\n self.head = item;\n\n return item;\n};\n\n/**\n * Appends the given item to the list: Item will be the new last item (`tail`)\n * if the list had a first item, and its first item (`head`) otherwise.\n * @name List#append\n * @param {ListItem} item - The item to append.\n * @returns {ListItem} - An instance of ListItem (the given item).\n */\n\nListPrototype.append = function (item) {\n if (!item) {\n return false;\n }\n\n if (!item.append || !item.prepend || !item.detach) {\n throw new Error(errorMessage + '#append`.');\n }\n\n var self, head, tail;\n\n // Cache self.\n self = this;\n\n // If self has a last item, defer appending to the last items append\n // method, and return the result.\n tail = self.tail;\n\n if (tail) {\n return tail.append(item);\n }\n\n // If self has a first item, defer appending to the first items append\n // method, and return the result.\n head = self.head;\n\n if (head) {\n return head.append(item);\n }\n\n // ...otherwise, there is no `tail` or `head` item yet.\n\n // Detach the appendee.\n item.detach();\n\n // Set the appendees parent list to reference self.\n item.list = self;\n\n // Set self's first item to the appendee, and return the item.\n self.head = item;\n\n return item;\n};\n\n/**\n * Creates a new ListItem: A linked list item is a bit like DOM node:\n * It knows only about its \"parent\" (`list`), the item before it (`prev`),\n * and the item after it (`next`).\n * @global\n * @private\n * @constructor\n * @class Represents an instance of ListItem.\n */\n\nfunction ListItem() {}\n\nList.Item = ListItem;\n\nvar ListItemPrototype = ListItem.prototype;\n\nListItemPrototype.next = null;\n\nListItemPrototype.prev = null;\n\nListItemPrototype.list = null;\n\n/**\n * Detaches the item operated on from its parent list.\n * @name ListItem#detach\n * @returns {ListItem} - The item operated on.\n */\nListItemPrototype.detach = function () {\n // Cache self, the parent list, and the previous and next items.\n var self = this,\n list = self.list,\n prev = self.prev,\n next = self.next;\n\n // If the item is already detached, return self.\n if (!list) {\n return self;\n }\n\n // If self is the last item in the parent list, link the lists last item\n // to the previous item.\n if (list.tail === self) {\n list.tail = prev;\n }\n\n // If self is the first item in the parent list, link the lists first item\n // to the next item.\n if (list.head === self) {\n list.head = next;\n }\n\n // If both the last and first items in the parent list are the same,\n // remove the link to the last item.\n if (list.tail === list.head) {\n list.tail = null;\n }\n\n // If a previous item exists, link its next item to selfs next item.\n if (prev) {\n prev.next = next;\n }\n\n // If a next item exists, link its previous item to selfs previous item.\n if (next) {\n next.prev = prev;\n }\n\n // Remove links from self to both the next and previous items, and to the\n // parent list.\n self.prev = self.next = self.list = null;\n\n // Return self.\n return self;\n};\n\n/**\n * Prepends the given item *before* the item operated on.\n * @name ListItem#prepend\n * @param {ListItem} item - The item to prepend.\n * @returns {ListItem} - The item operated on, or false when that item is not\n * attached.\n */\nListItemPrototype.prepend = function (item) {\n if (!item || !item.append || !item.prepend || !item.detach) {\n throw new Error(errorMessage + 'Item#prepend`.');\n }\n\n // Cache self, the parent list, and the previous item.\n var self = this,\n list = self.list,\n prev = self.prev;\n\n // If self is detached, return false.\n if (!list) {\n return false;\n }\n\n // Detach the prependee.\n item.detach();\n\n // If self has a previous item...\n if (prev) {\n // ...link the prependees previous item, to selfs previous item.\n item.prev = prev;\n\n // ...link the previous items next item, to self.\n prev.next = item;\n }\n\n // Set the prependees next item to self.\n item.next = self;\n\n // Set the prependees parent list to selfs parent list.\n item.list = list;\n\n // Set the previous item of self to the prependee.\n self.prev = item;\n\n // If self is the first item in the parent list, link the lists first item\n // to the prependee.\n if (self === list.head) {\n list.head = item;\n }\n\n // If the the parent list has no last item, link the lists last item to\n // self.\n if (!list.tail) {\n list.tail = self;\n }\n\n // Return the prependee.\n return item;\n};\n\n/**\n * Appends the given item *after* the item operated on.\n * @name ListItem#append\n * @param {ListItem} item - The item to append.\n * @returns {ListItem} - The item operated on, or false when that item is not\n * attached.\n */\nListItemPrototype.append = function (item) {\n // If item is falsey, return false.\n if (!item || !item.append || !item.prepend || !item.detach) {\n throw new Error(errorMessage + 'Item#append`.');\n }\n\n // Cache self, the parent list, and the next item.\n var self = this,\n list = self.list,\n next = self.next;\n\n // If self is detached, return false.\n if (!list) {\n return false;\n }\n\n // Detach the appendee.\n item.detach();\n\n // If self has a next item...\n if (next) {\n // ...link the appendees next item, to selfs next item.\n item.next = next;\n\n // ...link the next items previous item, to the appendee.\n next.prev = item;\n }\n\n // Set the appendees previous item to self.\n item.prev = self;\n\n // Set the appendees parent list to selfs parent list.\n item.list = list;\n\n // Set the next item of self to the appendee.\n self.next = item;\n\n // If the the parent list has no last item or if self is the parent lists\n // last item, link the lists last item to the appendee.\n if (self === list.tail || !list.tail) {\n list.tail = item;\n }\n\n // Return the appendee.\n return item;\n};\n\n/**\n * Expose `List`.\n */\n\nmodule.exports = List;\n","'use strict';\n\nmodule.exports = require('./_source/linked-list.js');\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nvar ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');\n\nfunction emptyFunction() {}\nfunction emptyFunctionWithReset() {}\nemptyFunctionWithReset.resetWarningCache = emptyFunction;\n\nmodule.exports = function() {\n function shim(props, propName, componentName, location, propFullName, secret) {\n if (secret === ReactPropTypesSecret) {\n // It is still safe when called from React.\n return;\n }\n var err = new Error(\n 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +\n 'Use PropTypes.checkPropTypes() to call them. ' +\n 'Read more at http://fb.me/use-check-prop-types'\n );\n err.name = 'Invariant Violation';\n throw err;\n };\n shim.isRequired = shim;\n function getShim() {\n return shim;\n };\n // Important!\n // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.\n var ReactPropTypes = {\n array: shim,\n bool: shim,\n func: shim,\n number: shim,\n object: shim,\n string: shim,\n symbol: shim,\n\n any: shim,\n arrayOf: getShim,\n element: shim,\n elementType: shim,\n instanceOf: getShim,\n node: shim,\n objectOf: getShim,\n oneOf: getShim,\n oneOfType: getShim,\n shape: getShim,\n exact: getShim,\n\n checkPropTypes: emptyFunctionWithReset,\n resetWarningCache: emptyFunction\n };\n\n ReactPropTypes.PropTypes = ReactPropTypes;\n\n return ReactPropTypes;\n};\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nif (process.env.NODE_ENV !== 'production') {\n var ReactIs = require('react-is');\n\n // By explicitly using `prop-types` you are opting into new development behavior.\n // http://fb.me/prop-types-in-prod\n var throwOnDirectAccess = true;\n module.exports = require('./factoryWithTypeCheckers')(ReactIs.isElement, throwOnDirectAccess);\n} else {\n // By explicitly using `prop-types` you are opting into new production behavior.\n // http://fb.me/prop-types-in-prod\n module.exports = require('./factoryWithThrowingShims')();\n}\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nvar ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';\n\nmodule.exports = ReactPropTypesSecret;\n","'use strict';\n\nexports.__esModule = true;\nvar defaultSocketOptions = exports.defaultSocketOptions = {\n secure: true,\n hostname: 'remotedev.io',\n port: 443,\n autoReconnect: true,\n autoReconnectOptions: {\n randomness: 60000\n }\n};","'use strict';\n\nexports.__esModule = true;\nexports.send = undefined;\nexports.extractState = extractState;\nexports.generateId = generateId;\nexports.start = start;\nexports.connect = connect;\nexports.connectViaExtension = connectViaExtension;\n\nvar _jsan = require('jsan');\n\nvar _socketclusterClient = require('socketcluster-client');\n\nvar _socketclusterClient2 = _interopRequireDefault(_socketclusterClient);\n\nvar _rnHostDetect = require('rn-host-detect');\n\nvar _rnHostDetect2 = _interopRequireDefault(_rnHostDetect);\n\nvar _constants = require('./constants');\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar socket = undefined;\nvar channel = undefined;\nvar listeners = {};\n\nfunction extractState(message) {\n if (!message || !message.state) return undefined;\n if (typeof message.state === 'string') return (0, _jsan.parse)(message.state);\n return message.state;\n}\n\nfunction generateId() {\n return Math.random().toString(36).substr(2);\n}\n\nfunction handleMessages(message) {\n if (!message.payload) message.payload = message.action;\n Object.keys(listeners).forEach(function (id) {\n if (message.instanceId && id !== message.instanceId) return;\n if (typeof listeners[id] === 'function') listeners[id](message);else listeners[id].forEach(function (fn) {\n fn(message);\n });\n });\n}\n\nfunction watch() {\n if (channel) return;\n socket.emit('login', 'master', function (err, channelName) {\n if (err) {\n console.log(err);return;\n }\n channel = socket.subscribe(channelName);\n channel.watch(handleMessages);\n socket.on(channelName, handleMessages);\n });\n}\n\nfunction connectToServer(options) {\n if (socket) return;\n var socketOptions = undefined;\n if (options.port) {\n socketOptions = {\n port: options.port,\n hostname: (0, _rnHostDetect2.default)(options.hostname || 'localhost'),\n secure: !!options.secure\n };\n } else socketOptions = _constants.defaultSocketOptions;\n socket = _socketclusterClient2.default.create(socketOptions);\n watch();\n}\n\nfunction start(options) {\n if (options) {\n if (options.port && !options.hostname) {\n options.hostname = 'localhost';\n }\n }\n connectToServer(options);\n}\n\nfunction transformAction(action, config) {\n if (action.action) return action;\n var liftedAction = { timestamp: Date.now() };\n if (action) {\n if (config.getActionType) liftedAction.action = config.getActionType(action);else {\n if (typeof action === 'string') liftedAction.action = { type: action };else if (!action.type) liftedAction.action = { type: 'update' };else liftedAction.action = action;\n }\n } else {\n liftedAction.action = { type: action };\n }\n return liftedAction;\n}\n\nfunction _send(action, state, options, type, instanceId) {\n start(options);\n setTimeout(function () {\n var message = {\n payload: state ? (0, _jsan.stringify)(state) : '',\n action: type === 'ACTION' ? (0, _jsan.stringify)(transformAction(action, options)) : action,\n type: type || 'ACTION',\n id: socket.id,\n instanceId: instanceId,\n name: options.name\n };\n socket.emit(socket.id ? 'log' : 'log-noid', message);\n }, 0);\n}\n\nexports.send = _send;\nfunction connect() {\n var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];\n\n var id = generateId(options.instanceId);\n start(options);\n return {\n init: function init(state, action) {\n _send(action || {}, state, options, 'INIT', id);\n },\n subscribe: function subscribe(listener) {\n if (!listener) return undefined;\n if (!listeners[id]) listeners[id] = [];\n listeners[id].push(listener);\n\n return function unsubscribe() {\n var index = listeners[id].indexOf(listener);\n listeners[id].splice(index, 1);\n };\n },\n unsubscribe: function unsubscribe() {\n delete listeners[id];\n },\n send: function send(action, payload) {\n if (action) {\n _send(action, payload, options, 'ACTION', id);\n } else {\n _send(undefined, payload, options, 'STATE', id);\n }\n },\n error: function error(payload) {\n socket.emit({ type: 'ERROR', payload: payload, id: socket.id, instanceId: id });\n }\n };\n}\n\nfunction connectViaExtension(options) {\n if (options && options.remote || typeof window === 'undefined' || !window.__REDUX_DEVTOOLS_EXTENSION__) {\n return connect(options);\n }\n return window.__REDUX_DEVTOOLS_EXTENSION__.connect(options);\n}\n\nexports.default = { connect: connect, connectViaExtension: connectViaExtension, send: _send, extractState: extractState, generateId: generateId };","'use strict';\n\nmodule.exports = require('./devTools');","'use strict'\n\n/*\n * It only for Debug Remotely mode for Android\n * When __DEV__ === false, we can't use window.require('NativeModules')\n */\nfunction getByRemoteConfig(hostname) {\n var remoteModuleConfig = typeof window !== 'undefined' &&\n window.__fbBatchedBridgeConfig &&\n window.__fbBatchedBridgeConfig.remoteModuleConfig\n\n if (\n !Array.isArray(remoteModuleConfig) ||\n hostname !== 'localhost' && hostname !== '127.0.0.1'\n ) return { hostname: hostname, passed: false }\n\n var result = hostname\n var passed = false\n remoteModuleConfig.some(function (config) {\n if (!config) return false\n \n var name = config[0]\n var content = config[1]\n if (\n (name === 'AndroidConstants' || name === 'PlatformConstants') &&\n content &&\n content.ServerHost\n ) {\n result = content.ServerHost.split(':')[0]\n passed = true\n return true\n }\n\n if (\n name === 'SourceCode' &&\n content &&\n content.scriptURL\n ) {\n result = content.scriptURL.replace(/https?:\\/\\//, '').split(':')[0]\n passed = true\n return true\n }\n return false\n })\n\n return { hostname: result, passed: passed }\n}\n\nfunction getByRNRequirePolyfill(hostname) {\n var originalWarn = console.warn\n var NativeModules\n var Constants\n var SourceCode\n if (\n typeof window === 'undefined' ||\n !window.__DEV__ ||\n typeof window.require !== 'function' ||\n // RN >= 0.56\n // TODO: Get NativeModules for RN >= 0.56\n window.require.name === 'metroRequire'\n ) {\n return hostname\n }\n console.warn = function() {\n if (\n arguments[0] &&\n typeof arguments[0].indexOf == 'function' &&\n arguments[0].indexOf(\"Requiring module 'NativeModules' by name\") > -1\n )\n return\n return originalWarn.apply(console, arguments)\n }\n try {\n NativeModules = window.require('NativeModules')\n } catch (e) {}\n console.warn = originalWarn\n if (!NativeModules) return hostname\n\n Constants = NativeModules.PlatformConstants || NativeModules.AndroidConstants\n SourceCode = NativeModules.SourceCode\n\n if (Constants && Constants.ServerHost) {\n return Constants.ServerHost.split(':')[0]\n } else if (SourceCode && SourceCode.scriptURL) {\n return SourceCode.scriptURL.replace(/https?:\\/\\//, '').split(':')[0]\n }\n return hostname\n}\n\n/*\n * Get React Native server IP if hostname is `localhost`\n * On Android emulator, the IP of host is `10.0.2.2` (Genymotion: 10.0.3.2)\n */\nmodule.exports = function (hostname) {\n // Check if it in React Native environment\n if (\n typeof __fbBatchedBridgeConfig !== 'object' ||\n hostname !== 'localhost' && hostname !== '127.0.0.1'\n ) {\n return hostname\n }\n var result = getByRemoteConfig(hostname)\n\n // Leave if get hostname by remote config successful\n if (result.passed) {\n return result.hostname\n }\n\n // Otherwise, use RN's require polyfill\n return getByRNRequirePolyfill(hostname)\n}\n","var Emitter = require('component-emitter');\n\nvar SCChannel = function (name, client, options) {\n var self = this;\n\n Emitter.call(this);\n\n this.PENDING = 'pending';\n this.SUBSCRIBED = 'subscribed';\n this.UNSUBSCRIBED = 'unsubscribed';\n\n this.name = name;\n this.state = this.UNSUBSCRIBED;\n this.client = client;\n\n this.options = options || {};\n this.setOptions(this.options);\n};\n\nSCChannel.prototype = Object.create(Emitter.prototype);\n\nSCChannel.prototype.setOptions = function (options) {\n if (!options) {\n options = {};\n }\n this.waitForAuth = options.waitForAuth || false;\n this.batch = options.batch || false;\n\n if (options.data !== undefined) {\n this.data = options.data;\n }\n};\n\nSCChannel.prototype.getState = function () {\n return this.state;\n};\n\nSCChannel.prototype.subscribe = function (options) {\n this.client.subscribe(this.name, options);\n};\n\nSCChannel.prototype.unsubscribe = function () {\n this.client.unsubscribe(this.name);\n};\n\nSCChannel.prototype.isSubscribed = function (includePending) {\n return this.client.isSubscribed(this.name, includePending);\n};\n\nSCChannel.prototype.publish = function (data, callback) {\n this.client.publish(this.name, data, callback);\n};\n\nSCChannel.prototype.watch = function (handler) {\n this.client.watch(this.name, handler);\n};\n\nSCChannel.prototype.unwatch = function (handler) {\n this.client.unwatch(this.name, handler);\n};\n\nSCChannel.prototype.watchers = function () {\n return this.client.watchers(this.name);\n};\n\nSCChannel.prototype.destroy = function () {\n this.client.destroyChannel(this.name);\n};\n\nmodule.exports.SCChannel = SCChannel;\n","\r\n/**\r\n * Expose `Emitter`.\r\n */\r\n\r\nif (typeof module !== 'undefined') {\r\n module.exports = Emitter;\r\n}\r\n\r\n/**\r\n * Initialize a new `Emitter`.\r\n *\r\n * @api public\r\n */\r\n\r\nfunction Emitter(obj) {\r\n if (obj) return mixin(obj);\r\n};\r\n\r\n/**\r\n * Mixin the emitter properties.\r\n *\r\n * @param {Object} obj\r\n * @return {Object}\r\n * @api private\r\n */\r\n\r\nfunction mixin(obj) {\r\n for (var key in Emitter.prototype) {\r\n obj[key] = Emitter.prototype[key];\r\n }\r\n return obj;\r\n}\r\n\r\n/**\r\n * Listen on the given `event` with `fn`.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.on =\r\nEmitter.prototype.addEventListener = function(event, fn){\r\n this._callbacks = this._callbacks || {};\r\n (this._callbacks['$' + event] = this._callbacks['$' + event] || [])\r\n .push(fn);\r\n return this;\r\n};\r\n\r\n/**\r\n * Adds an `event` listener that will be invoked a single\r\n * time then automatically removed.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.once = function(event, fn){\r\n function on() {\r\n this.off(event, on);\r\n fn.apply(this, arguments);\r\n }\r\n\r\n on.fn = fn;\r\n this.on(event, on);\r\n return this;\r\n};\r\n\r\n/**\r\n * Remove the given callback for `event` or all\r\n * registered callbacks.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.off =\r\nEmitter.prototype.removeListener =\r\nEmitter.prototype.removeAllListeners =\r\nEmitter.prototype.removeEventListener = function(event, fn){\r\n this._callbacks = this._callbacks || {};\r\n\r\n // all\r\n if (0 == arguments.length) {\r\n this._callbacks = {};\r\n return this;\r\n }\r\n\r\n // specific event\r\n var callbacks = this._callbacks['$' + event];\r\n if (!callbacks) return this;\r\n\r\n // remove all handlers\r\n if (1 == arguments.length) {\r\n delete this._callbacks['$' + event];\r\n return this;\r\n }\r\n\r\n // remove specific handler\r\n var cb;\r\n for (var i = 0; i < callbacks.length; i++) {\r\n cb = callbacks[i];\r\n if (cb === fn || cb.fn === fn) {\r\n callbacks.splice(i, 1);\r\n break;\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Emit `event` with the given args.\r\n *\r\n * @param {String} event\r\n * @param {Mixed} ...\r\n * @return {Emitter}\r\n */\r\n\r\nEmitter.prototype.emit = function(event){\r\n this._callbacks = this._callbacks || {};\r\n var args = [].slice.call(arguments, 1)\r\n , callbacks = this._callbacks['$' + event];\r\n\r\n if (callbacks) {\r\n callbacks = callbacks.slice(0);\r\n for (var i = 0, len = callbacks.length; i < len; ++i) {\r\n callbacks[i].apply(this, args);\r\n }\r\n }\r\n\r\n return this;\r\n};\r\n\r\n/**\r\n * Return array of callbacks for `event`.\r\n *\r\n * @param {String} event\r\n * @return {Array}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.listeners = function(event){\r\n this._callbacks = this._callbacks || {};\r\n return this._callbacks['$' + event] || [];\r\n};\r\n\r\n/**\r\n * Check if this emitter has `event` handlers.\r\n *\r\n * @param {String} event\r\n * @return {Boolean}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.hasListeners = function(event){\r\n return !! this.listeners(event).length;\r\n};\r\n","// Based on https://github.com/dscape/cycle/blob/master/cycle.js\n\nmodule.exports = function decycle(object) {\n// Make a deep copy of an object or array, assuring that there is at most\n// one instance of each object or array in the resulting structure. The\n// duplicate references (which might be forming cycles) are replaced with\n// an object of the form\n// {$ref: PATH}\n// where the PATH is a JSONPath string that locates the first occurance.\n// So,\n// var a = [];\n// a[0] = a;\n// return JSON.stringify(JSON.decycle(a));\n// produces the string '[{\"$ref\":\"$\"}]'.\n\n// JSONPath is used to locate the unique object. $ indicates the top level of\n// the object or array. [NUMBER] or [STRING] indicates a child member or\n// property.\n\n var objects = [], // Keep a reference to each unique object or array\n paths = []; // Keep the path to each unique object or array\n\n return (function derez(value, path) {\n\n// The derez recurses through the object, producing the deep copy.\n\n var i, // The loop counter\n name, // Property name\n nu; // The new object or array\n\n// typeof null === 'object', so go on if this value is really an object but not\n// one of the weird builtin objects.\n\n if (typeof value === 'object' && value !== null &&\n !(value instanceof Boolean) &&\n !(value instanceof Date) &&\n !(value instanceof Number) &&\n !(value instanceof RegExp) &&\n !(value instanceof String)) {\n\n// If the value is an object or array, look to see if we have already\n// encountered it. If so, return a $ref/path object. This is a hard way,\n// linear search that will get slower as the number of unique objects grows.\n\n for (i = 0; i < objects.length; i += 1) {\n if (objects[i] === value) {\n return {$ref: paths[i]};\n }\n }\n\n// Otherwise, accumulate the unique value and its path.\n\n objects.push(value);\n paths.push(path);\n\n// If it is an array, replicate the array.\n\n if (Object.prototype.toString.apply(value) === '[object Array]') {\n nu = [];\n for (i = 0; i < value.length; i += 1) {\n nu[i] = derez(value[i], path + '[' + i + ']');\n }\n } else {\n\n// If it is an object, replicate the object.\n\n nu = {};\n for (name in value) {\n if (Object.prototype.hasOwnProperty.call(value, name)) {\n nu[name] = derez(value[name],\n path + '[' + JSON.stringify(name) + ']');\n }\n }\n }\n return nu;\n }\n return value;\n }(object, '$'));\n};\n","var decycle = require('./decycle');\n\nvar isStrict = (function () { return !this; })();\n\nfunction AuthTokenExpiredError(message, expiry) {\n this.name = 'AuthTokenExpiredError';\n this.message = message;\n this.expiry = expiry;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nAuthTokenExpiredError.prototype = Object.create(Error.prototype);\n\n\nfunction AuthTokenInvalidError(message) {\n this.name = 'AuthTokenInvalidError';\n this.message = message;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nAuthTokenInvalidError.prototype = Object.create(Error.prototype);\n\n\nfunction AuthTokenNotBeforeError(message, date) {\n this.name = 'AuthTokenNotBeforeError';\n this.message = message;\n this.date = date;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nAuthTokenNotBeforeError.prototype = Object.create(Error.prototype);\n\n\n// For any other auth token error.\nfunction AuthTokenError(message) {\n this.name = 'AuthTokenError';\n this.message = message;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nAuthTokenError.prototype = Object.create(Error.prototype);\n\n\nfunction SilentMiddlewareBlockedError(message, type) {\n this.name = 'SilentMiddlewareBlockedError';\n this.message = message;\n this.type = type;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nSilentMiddlewareBlockedError.prototype = Object.create(Error.prototype);\n\n\nfunction InvalidActionError(message) {\n this.name = 'InvalidActionError';\n this.message = message;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nInvalidActionError.prototype = Object.create(Error.prototype);\n\nfunction InvalidArgumentsError(message) {\n this.name = 'InvalidArgumentsError';\n this.message = message;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nInvalidArgumentsError.prototype = Object.create(Error.prototype);\n\nfunction InvalidOptionsError(message) {\n this.name = 'InvalidOptionsError';\n this.message = message;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nInvalidOptionsError.prototype = Object.create(Error.prototype);\n\n\nfunction InvalidMessageError(message) {\n this.name = 'InvalidMessageError';\n this.message = message;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nInvalidMessageError.prototype = Object.create(Error.prototype);\n\n\nfunction SocketProtocolError(message, code) {\n this.name = 'SocketProtocolError';\n this.message = message;\n this.code = code;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nSocketProtocolError.prototype = Object.create(Error.prototype);\n\n\nfunction ServerProtocolError(message) {\n this.name = 'ServerProtocolError';\n this.message = message;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nServerProtocolError.prototype = Object.create(Error.prototype);\n\nfunction HTTPServerError(message) {\n this.name = 'HTTPServerError';\n this.message = message;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nHTTPServerError.prototype = Object.create(Error.prototype);\n\n\nfunction ResourceLimitError(message) {\n this.name = 'ResourceLimitError';\n this.message = message;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nResourceLimitError.prototype = Object.create(Error.prototype);\n\n\nfunction TimeoutError(message) {\n this.name = 'TimeoutError';\n this.message = message;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nTimeoutError.prototype = Object.create(Error.prototype);\n\n\nfunction BadConnectionError(message, type) {\n this.name = 'BadConnectionError';\n this.message = message;\n this.type = type;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nBadConnectionError.prototype = Object.create(Error.prototype);\n\n\nfunction BrokerError(message) {\n this.name = 'BrokerError';\n this.message = message;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nBrokerError.prototype = Object.create(Error.prototype);\n\n\nfunction ProcessExitError(message, code) {\n this.name = 'ProcessExitError';\n this.message = message;\n this.code = code;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nProcessExitError.prototype = Object.create(Error.prototype);\n\n\nfunction UnknownError(message) {\n this.name = 'UnknownError';\n this.message = message;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nUnknownError.prototype = Object.create(Error.prototype);\n\n\n// Expose all error types.\n\nmodule.exports = {\n AuthTokenExpiredError: AuthTokenExpiredError,\n AuthTokenInvalidError: AuthTokenInvalidError,\n AuthTokenNotBeforeError: AuthTokenNotBeforeError,\n AuthTokenError: AuthTokenError,\n SilentMiddlewareBlockedError: SilentMiddlewareBlockedError,\n InvalidActionError: InvalidActionError,\n InvalidArgumentsError: InvalidArgumentsError,\n InvalidOptionsError: InvalidOptionsError,\n InvalidMessageError: InvalidMessageError,\n SocketProtocolError: SocketProtocolError,\n ServerProtocolError: ServerProtocolError,\n HTTPServerError: HTTPServerError,\n ResourceLimitError: ResourceLimitError,\n TimeoutError: TimeoutError,\n BadConnectionError: BadConnectionError,\n BrokerError: BrokerError,\n ProcessExitError: ProcessExitError,\n UnknownError: UnknownError\n};\n\nmodule.exports.socketProtocolErrorStatuses = {\n 1001: 'Socket was disconnected',\n 1002: 'A WebSocket protocol error was encountered',\n 1003: 'Server terminated socket because it received invalid data',\n 1005: 'Socket closed without status code',\n 1006: 'Socket hung up',\n 1007: 'Message format was incorrect',\n 1008: 'Encountered a policy violation',\n 1009: 'Message was too big to process',\n 1010: 'Client ended the connection because the server did not comply with extension requirements',\n 1011: 'Server encountered an unexpected fatal condition',\n 4000: 'Server ping timed out',\n 4001: 'Client pong timed out',\n 4002: 'Server failed to sign auth token',\n 4003: 'Failed to complete handshake',\n 4004: 'Client failed to save auth token',\n 4005: 'Did not receive #handshake from client before timeout',\n 4006: 'Failed to bind socket to message broker',\n 4007: 'Client connection establishment timed out',\n 4008: 'Server rejected handshake from client'\n};\n\nmodule.exports.socketProtocolIgnoreStatuses = {\n 1000: 'Socket closed normally',\n 1001: 'Socket hung up'\n};\n\n// Properties related to error domains cannot be serialized.\nvar unserializableErrorProperties = {\n domain: 1,\n domainEmitter: 1,\n domainThrown: 1\n};\n\n// Convert an error into a JSON-compatible type which can later be hydrated\n// back to its *original* form.\nmodule.exports.dehydrateError = function dehydrateError(error, includeStackTrace) {\n var dehydratedError;\n\n if (error && typeof error === 'object') {\n dehydratedError = {\n message: error.message\n };\n if (includeStackTrace) {\n dehydratedError.stack = error.stack;\n }\n for (var i in error) {\n if (!unserializableErrorProperties[i]) {\n dehydratedError[i] = error[i];\n }\n }\n } else if (typeof error === 'function') {\n dehydratedError = '[function ' + (error.name || 'anonymous') + ']';\n } else {\n dehydratedError = error;\n }\n\n return decycle(dehydratedError);\n};\n\n// Convert a dehydrated error back to its *original* form.\nmodule.exports.hydrateError = function hydrateError(error) {\n var hydratedError = null;\n if (error != null) {\n if (typeof error === 'object') {\n hydratedError = new Error(error.message);\n for (var i in error) {\n if (error.hasOwnProperty(i)) {\n hydratedError[i] = error[i];\n }\n }\n } else {\n hydratedError = error;\n }\n }\n return hydratedError;\n};\n\nmodule.exports.decycle = decycle;\n","const base64Chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\nconst validJSONStartRegex = /^[ \\n\\r\\t]*[{\\[]/;\n\nlet arrayBufferToBase64 = function (arraybuffer) {\n let bytes = new Uint8Array(arraybuffer);\n let len = bytes.length;\n let base64 = '';\n\n for (let i = 0; i < len; i += 3) {\n base64 += base64Chars[bytes[i] >> 2];\n base64 += base64Chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += base64Chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];\n base64 += base64Chars[bytes[i + 2] & 63];\n }\n\n if ((len % 3) === 2) {\n base64 = base64.substring(0, base64.length - 1) + '=';\n } else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + '==';\n }\n\n return base64;\n};\n\nlet binaryToBase64Replacer = function (key, value) {\n if (global.ArrayBuffer && value instanceof global.ArrayBuffer) {\n return {\n base64: true,\n data: arrayBufferToBase64(value)\n };\n } else if (global.Buffer) {\n if (value instanceof global.Buffer){\n return {\n base64: true,\n data: value.toString('base64')\n };\n }\n // Some versions of Node.js convert Buffers to Objects before they are passed to\n // the replacer function - Because of this, we need to rehydrate Buffers\n // before we can convert them to base64 strings.\n if (value && value.type === 'Buffer' && Array.isArray(value.data)) {\n let rehydratedBuffer;\n if (global.Buffer.from) {\n rehydratedBuffer = global.Buffer.from(value.data);\n } else {\n rehydratedBuffer = new global.Buffer(value.data);\n }\n return {\n base64: true,\n data: rehydratedBuffer.toString('base64')\n };\n }\n }\n return value;\n};\n\n// Decode the data which was transmitted over the wire to a JavaScript Object in a format which SC understands.\n// See encode function below for more details.\nmodule.exports.decode = function (encodedMessage) {\n if (encodedMessage == null) {\n return null;\n }\n // Leave ping or pong message as is\n if (encodedMessage === '#1' || encodedMessage === '#2') {\n return encodedMessage;\n }\n let message = encodedMessage.toString();\n\n // Performance optimization to detect invalid JSON packet sooner.\n if (!validJSONStartRegex.test(message)) {\n return message;\n }\n\n try {\n return JSON.parse(message);\n } catch (err) {}\n return message;\n};\n\n// Encode raw data (which is in the SC protocol format) into a format for\n// transfering it over the wire. In this case, we just convert it into a simple JSON string.\n// If you want to create your own custom codec, you can encode the object into any format\n// (e.g. binary ArrayBuffer or string with any kind of compression) so long as your decode\n// function is able to rehydrate that object back into its original JavaScript Object format\n// (which adheres to the SC protocol).\n// See https://github.com/SocketCluster/socketcluster/blob/master/socketcluster-protocol.md\n// for details about the SC protocol.\nmodule.exports.encode = function (rawData) {\n // Leave ping or pong message as is\n if (rawData === '#1' || rawData === '#2') {\n return rawData;\n }\n return JSON.stringify(rawData, binaryToBase64Replacer);\n};\n","var SCClientSocket = require('./lib/scclientsocket');\r\nvar factory = require('./lib/factory');\r\n\r\nmodule.exports.factory = factory;\r\nmodule.exports.SCClientSocket = SCClientSocket;\r\n\r\nmodule.exports.Emitter = require('component-emitter');\r\n\r\nmodule.exports.create = function (options) {\r\n return factory.create(options);\r\n};\r\n\r\nmodule.exports.connect = module.exports.create;\r\n\r\nmodule.exports.destroy = function (socket) {\r\n return factory.destroy(socket);\r\n};\r\n\r\nmodule.exports.clients = factory.clients;\r\n\r\nmodule.exports.version = '13.0.1';\r\n","var AuthEngine = function () {\n this._internalStorage = {};\n this.isLocalStorageEnabled = this._checkLocalStorageEnabled();\n};\n\nAuthEngine.prototype._checkLocalStorageEnabled = function () {\n var err;\n try {\n // Some browsers will throw an error here if localStorage is disabled.\n global.localStorage;\n\n // Safari, in Private Browsing Mode, looks like it supports localStorage but all calls to setItem\n // throw QuotaExceededError. We're going to detect this and avoid hard to debug edge cases.\n global.localStorage.setItem('__scLocalStorageTest', 1);\n global.localStorage.removeItem('__scLocalStorageTest');\n } catch (e) {\n err = e;\n }\n return !err;\n};\n\nAuthEngine.prototype.saveToken = function (name, token, options, callback) {\n if (this.isLocalStorageEnabled && global.localStorage) {\n global.localStorage.setItem(name, token);\n } else {\n this._internalStorage[name] = token;\n }\n callback && callback(null, token);\n};\n\nAuthEngine.prototype.removeToken = function (name, callback) {\n var token;\n\n this.loadToken(name, function (err, authToken) {\n token = authToken;\n });\n\n if (this.isLocalStorageEnabled && global.localStorage) {\n global.localStorage.removeItem(name);\n } else {\n delete this._internalStorage[name];\n }\n\n callback && callback(null, token);\n};\n\nAuthEngine.prototype.loadToken = function (name, callback) {\n var token;\n\n if (this.isLocalStorageEnabled && global.localStorage) {\n token = global.localStorage.getItem(name);\n } else {\n token = this._internalStorage[name] || null;\n }\n callback(null, token);\n};\n\nmodule.exports.AuthEngine = AuthEngine;\n","var SCClientSocket = require('./scclientsocket');\r\nvar scErrors = require('sc-errors');\r\nvar uuid = require('uuid');\r\nvar InvalidArgumentsError = scErrors.InvalidArgumentsError;\r\n\r\nvar _clients = {};\r\n\r\nfunction getMultiplexId(options) {\r\n var protocolPrefix = options.secure ? 'https://' : 'http://';\r\n var queryString = '';\r\n if (options.query) {\r\n if (typeof options.query == 'string') {\r\n queryString = options.query;\r\n } else {\r\n var queryArray = [];\r\n var queryMap = options.query;\r\n for (var key in queryMap) {\r\n if (queryMap.hasOwnProperty(key)) {\r\n queryArray.push(key + '=' + queryMap[key]);\r\n }\r\n }\r\n if (queryArray.length) {\r\n queryString = '?' + queryArray.join('&');\r\n }\r\n }\r\n }\r\n var host;\r\n if (options.host) {\r\n host = options.host;\r\n } else {\r\n host = options.hostname + ':' + options.port;\r\n }\r\n return protocolPrefix + host + options.path + queryString;\r\n}\r\n\r\nfunction isUrlSecure() {\r\n return global.location && location.protocol == 'https:';\r\n}\r\n\r\nfunction getPort(options, isSecureDefault) {\r\n var isSecure = options.secure == null ? isSecureDefault : options.secure;\r\n return options.port || (global.location && location.port ? location.port : isSecure ? 443 : 80);\r\n}\r\n\r\nfunction create(options) {\r\n var self = this;\r\n\r\n options = options || {};\r\n\r\n if (options.host && !options.host.match(/[^:]+:\\d{2,5}/)) {\r\n throw new InvalidArgumentsError('The host option should include both' +\r\n ' the hostname and the port number in the format \"hostname:port\"');\r\n }\r\n\r\n if (options.host && options.hostname) {\r\n throw new InvalidArgumentsError('The host option should already include' +\r\n ' the hostname and the port number in the format \"hostname:port\"' +\r\n ' - Because of this, you should never use host and hostname options together');\r\n }\r\n\r\n if (options.host && options.port) {\r\n throw new InvalidArgumentsError('The host option should already include' +\r\n ' the hostname and the port number in the format \"hostname:port\"' +\r\n ' - Because of this, you should never use host and port options together');\r\n }\r\n\r\n var isSecureDefault = isUrlSecure();\r\n\r\n var opts = {\r\n port: getPort(options, isSecureDefault),\r\n hostname: global.location && location.hostname || 'localhost',\r\n path: '/socketcluster/',\r\n secure: isSecureDefault,\r\n autoConnect: true,\r\n autoReconnect: true,\r\n autoSubscribeOnConnect: true,\r\n connectTimeout: 20000,\r\n ackTimeout: 10000,\r\n timestampRequests: false,\r\n timestampParam: 't',\r\n authEngine: null,\r\n authTokenName: 'socketCluster.authToken',\r\n binaryType: 'arraybuffer',\r\n multiplex: true,\r\n pubSubBatchDuration: null,\r\n cloneData: false\r\n };\r\n for (var i in options) {\r\n if (options.hasOwnProperty(i)) {\r\n opts[i] = options[i];\r\n }\r\n }\r\n opts.clientMap = _clients;\r\n\r\n if (opts.multiplex === false) {\r\n opts.clientId = uuid.v4();\r\n var socket = new SCClientSocket(opts);\r\n _clients[opts.clientId] = socket;\r\n return socket;\r\n }\r\n opts.clientId = getMultiplexId(opts);\r\n\r\n if (_clients[opts.clientId]) {\r\n if (opts.autoConnect) {\r\n _clients[opts.clientId].connect();\r\n }\r\n } else {\r\n _clients[opts.clientId] = new SCClientSocket(opts);\r\n }\r\n return _clients[opts.clientId];\r\n}\r\n\r\nfunction destroy(socket) {\r\n socket.destroy();\r\n}\r\n\r\nmodule.exports = {\r\n create: create,\r\n destroy: destroy,\r\n clients: _clients\r\n};\r\n","var scErrors = require('sc-errors');\nvar InvalidActionError = scErrors.InvalidActionError;\n\nvar Response = function (socket, id) {\n this.socket = socket;\n this.id = id;\n this.sent = false;\n};\n\nResponse.prototype._respond = function (responseData) {\n if (this.sent) {\n throw new InvalidActionError('Response ' + this.id + ' has already been sent');\n } else {\n this.sent = true;\n this.socket.send(this.socket.encode(responseData));\n }\n};\n\nResponse.prototype.end = function (data) {\n if (this.id) {\n var responseData = {\n rid: this.id\n };\n if (data !== undefined) {\n responseData.data = data;\n }\n this._respond(responseData);\n }\n};\n\nResponse.prototype.error = function (error, data) {\n if (this.id) {\n var err = scErrors.dehydrateError(error);\n\n var responseData = {\n rid: this.id,\n error: err\n };\n if (data !== undefined) {\n responseData.data = data;\n }\n\n this._respond(responseData);\n }\n};\n\nResponse.prototype.callback = function (error, data) {\n if (error) {\n this.error(error, data);\n } else {\n this.end(data);\n }\n};\n\nmodule.exports.Response = Response;\n","var Emitter = require('component-emitter');\r\nvar SCChannel = require('sc-channel').SCChannel;\r\nvar Response = require('./response').Response;\r\nvar AuthEngine = require('./auth').AuthEngine;\r\nvar formatter = require('sc-formatter');\r\nvar SCTransport = require('./sctransport').SCTransport;\r\nvar querystring = require('querystring');\r\nvar LinkedList = require('linked-list');\r\nvar base64 = require('base-64');\r\nvar clone = require('clone');\r\n\r\nvar scErrors = require('sc-errors');\r\nvar InvalidArgumentsError = scErrors.InvalidArgumentsError;\r\nvar InvalidMessageError = scErrors.InvalidMessageError;\r\nvar InvalidActionError = scErrors.InvalidActionError;\r\nvar SocketProtocolError = scErrors.SocketProtocolError;\r\nvar TimeoutError = scErrors.TimeoutError;\r\nvar BadConnectionError = scErrors.BadConnectionError;\r\n\r\nvar isBrowser = typeof window != 'undefined';\r\n\r\n\r\nvar SCClientSocket = function (opts) {\r\n var self = this;\r\n\r\n Emitter.call(this);\r\n\r\n this.id = null;\r\n this.state = this.CLOSED;\r\n this.authState = this.UNAUTHENTICATED;\r\n this.signedAuthToken = null;\r\n this.authToken = null;\r\n this.pendingReconnect = false;\r\n this.pendingReconnectTimeout = null;\r\n this.preparingPendingSubscriptions = false;\r\n this.clientId = opts.clientId;\r\n\r\n this.connectTimeout = opts.connectTimeout;\r\n this.ackTimeout = opts.ackTimeout;\r\n this.channelPrefix = opts.channelPrefix || null;\r\n this.disconnectOnUnload = opts.disconnectOnUnload == null ? true : opts.disconnectOnUnload;\r\n this.authTokenName = opts.authTokenName;\r\n\r\n // pingTimeout will be ackTimeout at the start, but it will\r\n // be updated with values provided by the 'connect' event\r\n this.pingTimeout = this.ackTimeout;\r\n this.pingTimeoutDisabled = !!opts.pingTimeoutDisabled;\r\n this.active = true;\r\n\r\n this._clientMap = opts.clientMap || {};\r\n\r\n var maxTimeout = Math.pow(2, 31) - 1;\r\n\r\n var verifyDuration = function (propertyName) {\r\n if (self[propertyName] > maxTimeout) {\r\n throw new InvalidArgumentsError('The ' + propertyName +\r\n ' value provided exceeded the maximum amount allowed');\r\n }\r\n };\r\n\r\n verifyDuration('connectTimeout');\r\n verifyDuration('ackTimeout');\r\n\r\n this._localEvents = {\r\n 'connect': 1,\r\n 'connectAbort': 1,\r\n 'close': 1,\r\n 'disconnect': 1,\r\n 'message': 1,\r\n 'error': 1,\r\n 'raw': 1,\r\n 'kickOut': 1,\r\n 'subscribe': 1,\r\n 'unsubscribe': 1,\r\n 'subscribeStateChange': 1,\r\n 'authStateChange': 1,\r\n 'authenticate': 1,\r\n 'deauthenticate': 1,\r\n 'removeAuthToken': 1,\r\n 'subscribeRequest': 1\r\n };\r\n\r\n this.connectAttempts = 0;\r\n\r\n this._emitBuffer = new LinkedList();\r\n this.channels = {};\r\n\r\n this.options = opts;\r\n\r\n this._cid = 1;\r\n\r\n this.options.callIdGenerator = function () {\r\n return self._cid++;\r\n };\r\n\r\n if (this.options.autoReconnect) {\r\n if (this.options.autoReconnectOptions == null) {\r\n this.options.autoReconnectOptions = {};\r\n }\r\n\r\n // Add properties to the this.options.autoReconnectOptions object.\r\n // We assign the reference to a reconnectOptions variable to avoid repetition.\r\n var reconnectOptions = this.options.autoReconnectOptions;\r\n if (reconnectOptions.initialDelay == null) {\r\n reconnectOptions.initialDelay = 10000;\r\n }\r\n if (reconnectOptions.randomness == null) {\r\n reconnectOptions.randomness = 10000;\r\n }\r\n if (reconnectOptions.multiplier == null) {\r\n reconnectOptions.multiplier = 1.5;\r\n }\r\n if (reconnectOptions.maxDelay == null) {\r\n reconnectOptions.maxDelay = 60000;\r\n }\r\n }\r\n\r\n if (this.options.subscriptionRetryOptions == null) {\r\n this.options.subscriptionRetryOptions = {};\r\n }\r\n\r\n if (this.options.authEngine) {\r\n this.auth = this.options.authEngine;\r\n } else {\r\n this.auth = new AuthEngine();\r\n }\r\n\r\n if (this.options.codecEngine) {\r\n this.codec = this.options.codecEngine;\r\n } else {\r\n // Default codec engine\r\n this.codec = formatter;\r\n }\r\n\r\n this.options.path = this.options.path.replace(/\\/$/, '') + '/';\r\n\r\n this.options.query = opts.query || {};\r\n if (typeof this.options.query == 'string') {\r\n this.options.query = querystring.parse(this.options.query);\r\n }\r\n\r\n this._channelEmitter = new Emitter();\r\n\r\n this._unloadHandler = function () {\r\n self.disconnect();\r\n };\r\n\r\n if (isBrowser && this.disconnectOnUnload && global.addEventListener) {\r\n global.addEventListener('beforeunload', this._unloadHandler, false);\r\n }\r\n this._clientMap[this.clientId] = this;\r\n\r\n if (this.options.autoConnect) {\r\n this.connect();\r\n }\r\n};\r\n\r\nSCClientSocket.prototype = Object.create(Emitter.prototype);\r\n\r\nSCClientSocket.CONNECTING = SCClientSocket.prototype.CONNECTING = SCTransport.prototype.CONNECTING;\r\nSCClientSocket.OPEN = SCClientSocket.prototype.OPEN = SCTransport.prototype.OPEN;\r\nSCClientSocket.CLOSED = SCClientSocket.prototype.CLOSED = SCTransport.prototype.CLOSED;\r\n\r\nSCClientSocket.AUTHENTICATED = SCClientSocket.prototype.AUTHENTICATED = 'authenticated';\r\nSCClientSocket.UNAUTHENTICATED = SCClientSocket.prototype.UNAUTHENTICATED = 'unauthenticated';\r\n\r\nSCClientSocket.PENDING = SCClientSocket.prototype.PENDING = 'pending';\r\n\r\nSCClientSocket.ignoreStatuses = scErrors.socketProtocolIgnoreStatuses;\r\nSCClientSocket.errorStatuses = scErrors.socketProtocolErrorStatuses;\r\n\r\nSCClientSocket.prototype._privateEventHandlerMap = {\r\n '#publish': function (data) {\r\n var undecoratedChannelName = this._undecorateChannelName(data.channel);\r\n var isSubscribed = this.isSubscribed(undecoratedChannelName, true);\r\n\r\n if (isSubscribed) {\r\n this._channelEmitter.emit(undecoratedChannelName, data.data);\r\n }\r\n },\r\n '#kickOut': function (data) {\r\n var undecoratedChannelName = this._undecorateChannelName(data.channel);\r\n var channel = this.channels[undecoratedChannelName];\r\n if (channel) {\r\n Emitter.prototype.emit.call(this, 'kickOut', data.message, undecoratedChannelName);\r\n channel.emit('kickOut', data.message, undecoratedChannelName);\r\n this._triggerChannelUnsubscribe(channel);\r\n }\r\n },\r\n '#setAuthToken': function (data, response) {\r\n var self = this;\r\n\r\n if (data) {\r\n var triggerAuthenticate = function (err) {\r\n if (err) {\r\n // This is a non-fatal error, we don't want to close the connection\r\n // because of this but we do want to notify the server and throw an error\r\n // on the client.\r\n response.error(err);\r\n self._onSCError(err);\r\n } else {\r\n self._changeToAuthenticatedState(data.token);\r\n response.end();\r\n }\r\n };\r\n\r\n this.auth.saveToken(this.authTokenName, data.token, {}, triggerAuthenticate);\r\n } else {\r\n response.error(new InvalidMessageError('No token data provided by #setAuthToken event'));\r\n }\r\n },\r\n '#removeAuthToken': function (data, response) {\r\n var self = this;\r\n\r\n this.auth.removeToken(this.authTokenName, function (err, oldToken) {\r\n if (err) {\r\n // Non-fatal error - Do not close the connection\r\n response.error(err);\r\n self._onSCError(err);\r\n } else {\r\n Emitter.prototype.emit.call(self, 'removeAuthToken', oldToken);\r\n self._changeToUnauthenticatedStateAndClearTokens();\r\n response.end();\r\n }\r\n });\r\n },\r\n '#disconnect': function (data) {\r\n this.transport.close(data.code, data.data);\r\n }\r\n};\r\n\r\nSCClientSocket.prototype.getState = function () {\r\n return this.state;\r\n};\r\n\r\nSCClientSocket.prototype.getBytesReceived = function () {\r\n return this.transport.getBytesReceived();\r\n};\r\n\r\nSCClientSocket.prototype.deauthenticate = function (callback) {\r\n var self = this;\r\n\r\n this.auth.removeToken(this.authTokenName, function (err, oldToken) {\r\n if (err) {\r\n // Non-fatal error - Do not close the connection\r\n self._onSCError(err);\r\n } else {\r\n Emitter.prototype.emit.call(self, 'removeAuthToken', oldToken);\r\n if (self.state != self.CLOSED) {\r\n self.emit('#removeAuthToken');\r\n }\r\n self._changeToUnauthenticatedStateAndClearTokens();\r\n }\r\n callback && callback(err);\r\n });\r\n};\r\n\r\nSCClientSocket.prototype.connect = SCClientSocket.prototype.open = function () {\r\n var self = this;\r\n\r\n if (!this.active) {\r\n var error = new InvalidActionError('Cannot connect a destroyed client');\r\n this._onSCError(error);\r\n return;\r\n }\r\n\r\n if (this.state == this.CLOSED) {\r\n this.pendingReconnect = false;\r\n this.pendingReconnectTimeout = null;\r\n clearTimeout(this._reconnectTimeoutRef);\r\n\r\n this.state = this.CONNECTING;\r\n Emitter.prototype.emit.call(this, 'connecting');\r\n\r\n if (this.transport) {\r\n this.transport.off();\r\n }\r\n\r\n this.transport = new SCTransport(this.auth, this.codec, this.options);\r\n\r\n this.transport.on('open', function (status) {\r\n self.state = self.OPEN;\r\n self._onSCOpen(status);\r\n });\r\n\r\n this.transport.on('error', function (err) {\r\n self._onSCError(err);\r\n });\r\n\r\n this.transport.on('close', function (code, data) {\r\n self.state = self.CLOSED;\r\n self._onSCClose(code, data);\r\n });\r\n\r\n this.transport.on('openAbort', function (code, data) {\r\n self.state = self.CLOSED;\r\n self._onSCClose(code, data, true);\r\n });\r\n\r\n this.transport.on('event', function (event, data, res) {\r\n self._onSCEvent(event, data, res);\r\n });\r\n }\r\n};\r\n\r\nSCClientSocket.prototype.reconnect = function (code, data) {\r\n this.disconnect(code, data);\r\n this.connect();\r\n};\r\n\r\nSCClientSocket.prototype.disconnect = function (code, data) {\r\n code = code || 1000;\r\n\r\n if (typeof code != 'number') {\r\n throw new InvalidArgumentsError('If specified, the code argument must be a number');\r\n }\r\n\r\n if (this.state == this.OPEN || this.state == this.CONNECTING) {\r\n this.transport.close(code, data);\r\n } else {\r\n this.pendingReconnect = false;\r\n this.pendingReconnectTimeout = null;\r\n clearTimeout(this._reconnectTimeoutRef);\r\n }\r\n};\r\n\r\nSCClientSocket.prototype.destroy = function (code, data) {\r\n if (isBrowser && global.removeEventListener) {\r\n global.removeEventListener('beforeunload', this._unloadHandler, false);\r\n }\r\n this.active = false;\r\n this.disconnect(code, data);\r\n delete this._clientMap[this.clientId];\r\n};\r\n\r\nSCClientSocket.prototype._changeToUnauthenticatedStateAndClearTokens = function () {\r\n if (this.authState != this.UNAUTHENTICATED) {\r\n var oldState = this.authState;\r\n var oldSignedToken = this.signedAuthToken;\r\n this.authState = this.UNAUTHENTICATED;\r\n this.signedAuthToken = null;\r\n this.authToken = null;\r\n\r\n var stateChangeData = {\r\n oldState: oldState,\r\n newState: this.authState\r\n };\r\n Emitter.prototype.emit.call(this, 'authStateChange', stateChangeData);\r\n Emitter.prototype.emit.call(this, 'deauthenticate', oldSignedToken);\r\n }\r\n};\r\n\r\nSCClientSocket.prototype._changeToAuthenticatedState = function (signedAuthToken) {\r\n this.signedAuthToken = signedAuthToken;\r\n this.authToken = this._extractAuthTokenData(signedAuthToken);\r\n\r\n if (this.authState != this.AUTHENTICATED) {\r\n var oldState = this.authState;\r\n this.authState = this.AUTHENTICATED;\r\n var stateChangeData = {\r\n oldState: oldState,\r\n newState: this.authState,\r\n signedAuthToken: signedAuthToken,\r\n authToken: this.authToken\r\n };\r\n if (!this.preparingPendingSubscriptions) {\r\n this.processPendingSubscriptions();\r\n }\r\n\r\n Emitter.prototype.emit.call(this, 'authStateChange', stateChangeData);\r\n }\r\n Emitter.prototype.emit.call(this, 'authenticate', signedAuthToken);\r\n};\r\n\r\nSCClientSocket.prototype.decodeBase64 = function (encodedString) {\r\n var decodedString;\r\n if (typeof Buffer == 'undefined') {\r\n if (global.atob) {\r\n decodedString = global.atob(encodedString);\r\n } else {\r\n decodedString = base64.decode(encodedString);\r\n }\r\n } else {\r\n var buffer = new Buffer(encodedString, 'base64');\r\n decodedString = buffer.toString('utf8');\r\n }\r\n return decodedString;\r\n};\r\n\r\nSCClientSocket.prototype.encodeBase64 = function (decodedString) {\r\n var encodedString;\r\n if (typeof Buffer == 'undefined') {\r\n if (global.btoa) {\r\n encodedString = global.btoa(decodedString);\r\n } else {\r\n encodedString = base64.encode(decodedString);\r\n }\r\n } else {\r\n var buffer = new Buffer(decodedString, 'utf8');\r\n encodedString = buffer.toString('base64');\r\n }\r\n return encodedString;\r\n};\r\n\r\nSCClientSocket.prototype._extractAuthTokenData = function (signedAuthToken) {\r\n var tokenParts = (signedAuthToken || '').split('.');\r\n var encodedTokenData = tokenParts[1];\r\n if (encodedTokenData != null) {\r\n var tokenData = encodedTokenData;\r\n try {\r\n tokenData = this.decodeBase64(tokenData);\r\n return JSON.parse(tokenData);\r\n } catch (e) {\r\n return tokenData;\r\n }\r\n }\r\n return null;\r\n};\r\n\r\nSCClientSocket.prototype.getAuthToken = function () {\r\n return this.authToken;\r\n};\r\n\r\nSCClientSocket.prototype.getSignedAuthToken = function () {\r\n return this.signedAuthToken;\r\n};\r\n\r\n// Perform client-initiated authentication by providing an encrypted token string.\r\nSCClientSocket.prototype.authenticate = function (signedAuthToken, callback) {\r\n var self = this;\r\n\r\n this.emit('#authenticate', signedAuthToken, function (err, authStatus) {\r\n if (authStatus && authStatus.isAuthenticated != null) {\r\n // If authStatus is correctly formatted (has an isAuthenticated property),\r\n // then we will rehydrate the authError.\r\n if (authStatus.authError) {\r\n authStatus.authError = scErrors.hydrateError(authStatus.authError);\r\n }\r\n } else {\r\n // Some errors like BadConnectionError and TimeoutError will not pass a valid\r\n // authStatus object to the current function, so we need to create it ourselves.\r\n authStatus = {\r\n isAuthenticated: self.authState,\r\n authError: null\r\n };\r\n }\r\n if (err) {\r\n if (err.name != 'BadConnectionError' && err.name != 'TimeoutError') {\r\n // In case of a bad/closed connection or a timeout, we maintain the last\r\n // known auth state since those errors don't mean that the token is invalid.\r\n\r\n self._changeToUnauthenticatedStateAndClearTokens();\r\n }\r\n callback && callback(err, authStatus);\r\n } else {\r\n self.auth.saveToken(self.authTokenName, signedAuthToken, {}, function (err) {\r\n if (err) {\r\n self._onSCError(err);\r\n }\r\n if (authStatus.isAuthenticated) {\r\n self._changeToAuthenticatedState(signedAuthToken);\r\n } else {\r\n self._changeToUnauthenticatedStateAndClearTokens();\r\n }\r\n callback && callback(err, authStatus);\r\n });\r\n }\r\n });\r\n};\r\n\r\nSCClientSocket.prototype._tryReconnect = function (initialDelay) {\r\n var self = this;\r\n\r\n var exponent = this.connectAttempts++;\r\n var reconnectOptions = this.options.autoReconnectOptions;\r\n var timeout;\r\n\r\n if (initialDelay == null || exponent > 0) {\r\n var initialTimeout = Math.round(reconnectOptions.initialDelay + (reconnectOptions.randomness || 0) * Math.random());\r\n\r\n timeout = Math.round(initialTimeout * Math.pow(reconnectOptions.multiplier, exponent));\r\n } else {\r\n timeout = initialDelay;\r\n }\r\n\r\n if (timeout > reconnectOptions.maxDelay) {\r\n timeout = reconnectOptions.maxDelay;\r\n }\r\n\r\n clearTimeout(this._reconnectTimeoutRef);\r\n\r\n this.pendingReconnect = true;\r\n this.pendingReconnectTimeout = timeout;\r\n this._reconnectTimeoutRef = setTimeout(function () {\r\n self.connect();\r\n }, timeout);\r\n};\r\n\r\nSCClientSocket.prototype._onSCOpen = function (status) {\r\n var self = this;\r\n\r\n this.preparingPendingSubscriptions = true;\r\n\r\n if (status) {\r\n this.id = status.id;\r\n this.pingTimeout = status.pingTimeout;\r\n this.transport.pingTimeout = this.pingTimeout;\r\n if (status.isAuthenticated) {\r\n this._changeToAuthenticatedState(status.authToken);\r\n } else {\r\n this._changeToUnauthenticatedStateAndClearTokens();\r\n }\r\n } else {\r\n // This can happen if auth.loadToken (in sctransport.js) fails with\r\n // an error - This means that the signedAuthToken cannot be loaded by\r\n // the auth engine and therefore, we need to unauthenticate the client.\r\n this._changeToUnauthenticatedStateAndClearTokens();\r\n }\r\n\r\n this.connectAttempts = 0;\r\n\r\n if (this.options.autoSubscribeOnConnect) {\r\n this.processPendingSubscriptions();\r\n }\r\n\r\n // If the user invokes the callback while in autoSubscribeOnConnect mode, it\r\n // won't break anything.\r\n Emitter.prototype.emit.call(this, 'connect', status, function () {\r\n self.processPendingSubscriptions();\r\n });\r\n\r\n if (this.state == this.OPEN) {\r\n this._flushEmitBuffer();\r\n }\r\n};\r\n\r\nSCClientSocket.prototype._onSCError = function (err) {\r\n var self = this;\r\n\r\n // Throw error in different stack frame so that error handling\r\n // cannot interfere with a reconnect action.\r\n setTimeout(function () {\r\n if (self.listeners('error').length < 1) {\r\n throw err;\r\n } else {\r\n Emitter.prototype.emit.call(self, 'error', err);\r\n }\r\n }, 0);\r\n};\r\n\r\nSCClientSocket.prototype._suspendSubscriptions = function () {\r\n var channel, newState;\r\n for (var channelName in this.channels) {\r\n if (this.channels.hasOwnProperty(channelName)) {\r\n channel = this.channels[channelName];\r\n if (channel.state == channel.SUBSCRIBED ||\r\n channel.state == channel.PENDING) {\r\n\r\n newState = channel.PENDING;\r\n } else {\r\n newState = channel.UNSUBSCRIBED;\r\n }\r\n\r\n this._triggerChannelUnsubscribe(channel, newState);\r\n }\r\n }\r\n};\r\n\r\nSCClientSocket.prototype._abortAllPendingEventsDueToBadConnection = function (failureType) {\r\n var currentNode = this._emitBuffer.head;\r\n var nextNode;\r\n\r\n while (currentNode) {\r\n nextNode = currentNode.next;\r\n var eventObject = currentNode.data;\r\n clearTimeout(eventObject.timeout);\r\n delete eventObject.timeout;\r\n currentNode.detach();\r\n currentNode = nextNode;\r\n\r\n var callback = eventObject.callback;\r\n if (callback) {\r\n delete eventObject.callback;\r\n var errorMessage = \"Event '\" + eventObject.event +\r\n \"' was aborted due to a bad connection\";\r\n var error = new BadConnectionError(errorMessage, failureType);\r\n callback.call(eventObject, error, eventObject);\r\n }\r\n // Cleanup any pending response callback in the transport layer too.\r\n if (eventObject.cid) {\r\n this.transport.cancelPendingResponse(eventObject.cid);\r\n }\r\n }\r\n};\r\n\r\nSCClientSocket.prototype._onSCClose = function (code, data, openAbort) {\r\n var self = this;\r\n\r\n this.id = null;\r\n\r\n if (this.transport) {\r\n this.transport.off();\r\n }\r\n this.pendingReconnect = false;\r\n this.pendingReconnectTimeout = null;\r\n clearTimeout(this._reconnectTimeoutRef);\r\n\r\n this._suspendSubscriptions();\r\n this._abortAllPendingEventsDueToBadConnection(openAbort ? 'connectAbort' : 'disconnect');\r\n\r\n // Try to reconnect\r\n // on server ping timeout (4000)\r\n // or on client pong timeout (4001)\r\n // or on close without status (1005)\r\n // or on handshake failure (4003)\r\n // or on handshake rejection (4008)\r\n // or on socket hung up (1006)\r\n if (this.options.autoReconnect) {\r\n if (code == 4000 || code == 4001 || code == 1005) {\r\n // If there is a ping or pong timeout or socket closes without\r\n // status, don't wait before trying to reconnect - These could happen\r\n // if the client wakes up after a period of inactivity and in this case we\r\n // want to re-establish the connection as soon as possible.\r\n this._tryReconnect(0);\r\n\r\n // Codes 4500 and above will be treated as permanent disconnects.\r\n // Socket will not try to auto-reconnect.\r\n } else if (code != 1000 && code < 4500) {\r\n this._tryReconnect();\r\n }\r\n }\r\n\r\n if (openAbort) {\r\n Emitter.prototype.emit.call(self, 'connectAbort', code, data);\r\n } else {\r\n Emitter.prototype.emit.call(self, 'disconnect', code, data);\r\n }\r\n Emitter.prototype.emit.call(self, 'close', code, data);\r\n\r\n if (!SCClientSocket.ignoreStatuses[code]) {\r\n var closeMessage;\r\n if (data) {\r\n closeMessage = 'Socket connection closed with status code ' + code + ' and reason: ' + data;\r\n } else {\r\n closeMessage = 'Socket connection closed with status code ' + code;\r\n }\r\n var err = new SocketProtocolError(SCClientSocket.errorStatuses[code] || closeMessage, code);\r\n this._onSCError(err);\r\n }\r\n};\r\n\r\nSCClientSocket.prototype._onSCEvent = function (event, data, res) {\r\n var handler = this._privateEventHandlerMap[event];\r\n if (handler) {\r\n handler.call(this, data, res);\r\n } else {\r\n Emitter.prototype.emit.call(this, event, data, function () {\r\n res && res.callback.apply(res, arguments);\r\n });\r\n }\r\n};\r\n\r\nSCClientSocket.prototype.decode = function (message) {\r\n return this.transport.decode(message);\r\n};\r\n\r\nSCClientSocket.prototype.encode = function (object) {\r\n return this.transport.encode(object);\r\n};\r\n\r\nSCClientSocket.prototype._flushEmitBuffer = function () {\r\n var currentNode = this._emitBuffer.head;\r\n var nextNode;\r\n\r\n while (currentNode) {\r\n nextNode = currentNode.next;\r\n var eventObject = currentNode.data;\r\n currentNode.detach();\r\n this.transport.emitObject(eventObject);\r\n currentNode = nextNode;\r\n }\r\n};\r\n\r\nSCClientSocket.prototype._handleEventAckTimeout = function (eventObject, eventNode) {\r\n if (eventNode) {\r\n eventNode.detach();\r\n }\r\n delete eventObject.timeout;\r\n\r\n var callback = eventObject.callback;\r\n if (callback) {\r\n delete eventObject.callback;\r\n var error = new TimeoutError(\"Event response for '\" + eventObject.event + \"' timed out\");\r\n callback.call(eventObject, error, eventObject);\r\n }\r\n // Cleanup any pending response callback in the transport layer too.\r\n if (eventObject.cid) {\r\n this.transport.cancelPendingResponse(eventObject.cid);\r\n }\r\n};\r\n\r\nSCClientSocket.prototype._emit = function (event, data, callback) {\r\n var self = this;\r\n\r\n if (this.state == this.CLOSED) {\r\n this.connect();\r\n }\r\n var eventObject = {\r\n event: event,\r\n callback: callback\r\n };\r\n\r\n var eventNode = new LinkedList.Item();\r\n\r\n if (this.options.cloneData) {\r\n eventObject.data = clone(data);\r\n } else {\r\n eventObject.data = data;\r\n }\r\n eventNode.data = eventObject;\r\n\r\n eventObject.timeout = setTimeout(function () {\r\n self._handleEventAckTimeout(eventObject, eventNode);\r\n }, this.ackTimeout);\r\n\r\n this._emitBuffer.append(eventNode);\r\n if (this.state == this.OPEN) {\r\n this._flushEmitBuffer();\r\n }\r\n};\r\n\r\nSCClientSocket.prototype.send = function (data) {\r\n this.transport.send(data);\r\n};\r\n\r\nSCClientSocket.prototype.emit = function (event, data, callback) {\r\n if (this._localEvents[event] == null) {\r\n this._emit(event, data, callback);\r\n } else if (event == 'error') {\r\n Emitter.prototype.emit.call(this, event, data);\r\n } else {\r\n var error = new InvalidActionError('The \"' + event + '\" event is reserved and cannot be emitted on a client socket');\r\n this._onSCError(error);\r\n }\r\n};\r\n\r\nSCClientSocket.prototype.publish = function (channelName, data, callback) {\r\n var pubData = {\r\n channel: this._decorateChannelName(channelName),\r\n data: data\r\n };\r\n this.emit('#publish', pubData, callback);\r\n};\r\n\r\nSCClientSocket.prototype._triggerChannelSubscribe = function (channel, subscriptionOptions) {\r\n var channelName = channel.name;\r\n\r\n if (channel.state != channel.SUBSCRIBED) {\r\n var oldState = channel.state;\r\n channel.state = channel.SUBSCRIBED;\r\n\r\n var stateChangeData = {\r\n channel: channelName,\r\n oldState: oldState,\r\n newState: channel.state,\r\n subscriptionOptions: subscriptionOptions\r\n };\r\n channel.emit('subscribeStateChange', stateChangeData);\r\n channel.emit('subscribe', channelName, subscriptionOptions);\r\n Emitter.prototype.emit.call(this, 'subscribeStateChange', stateChangeData);\r\n Emitter.prototype.emit.call(this, 'subscribe', channelName, subscriptionOptions);\r\n }\r\n};\r\n\r\nSCClientSocket.prototype._triggerChannelSubscribeFail = function (err, channel, subscriptionOptions) {\r\n var channelName = channel.name;\r\n var meetsAuthRequirements = !channel.waitForAuth || this.authState == this.AUTHENTICATED;\r\n\r\n if (channel.state != channel.UNSUBSCRIBED && meetsAuthRequirements) {\r\n channel.state = channel.UNSUBSCRIBED;\r\n\r\n channel.emit('subscribeFail', err, channelName, subscriptionOptions);\r\n Emitter.prototype.emit.call(this, 'subscribeFail', err, channelName, subscriptionOptions);\r\n }\r\n};\r\n\r\n// Cancel any pending subscribe callback\r\nSCClientSocket.prototype._cancelPendingSubscribeCallback = function (channel) {\r\n if (channel._pendingSubscriptionCid != null) {\r\n this.transport.cancelPendingResponse(channel._pendingSubscriptionCid);\r\n delete channel._pendingSubscriptionCid;\r\n }\r\n};\r\n\r\nSCClientSocket.prototype._decorateChannelName = function (channelName) {\r\n if (this.channelPrefix) {\r\n channelName = this.channelPrefix + channelName;\r\n }\r\n return channelName;\r\n};\r\n\r\nSCClientSocket.prototype._undecorateChannelName = function (decoratedChannelName) {\r\n if (this.channelPrefix && decoratedChannelName.indexOf(this.channelPrefix) == 0) {\r\n return decoratedChannelName.replace(this.channelPrefix, '');\r\n }\r\n return decoratedChannelName;\r\n};\r\n\r\nSCClientSocket.prototype._trySubscribe = function (channel) {\r\n var self = this;\r\n\r\n var meetsAuthRequirements = !channel.waitForAuth || this.authState == this.AUTHENTICATED;\r\n\r\n // We can only ever have one pending subscribe action at any given time on a channel\r\n if (this.state == this.OPEN && !this.preparingPendingSubscriptions &&\r\n channel._pendingSubscriptionCid == null && meetsAuthRequirements) {\r\n\r\n var options = {\r\n noTimeout: true\r\n };\r\n\r\n var subscriptionOptions = {\r\n channel: this._decorateChannelName(channel.name)\r\n };\r\n if (channel.waitForAuth) {\r\n options.waitForAuth = true;\r\n subscriptionOptions.waitForAuth = options.waitForAuth;\r\n }\r\n if (channel.data) {\r\n subscriptionOptions.data = channel.data;\r\n }\r\n if (channel.batch) {\r\n options.batch = true;\r\n subscriptionOptions.batch = true;\r\n }\r\n\r\n channel._pendingSubscriptionCid = this.transport.emit(\r\n '#subscribe', subscriptionOptions, options,\r\n function (err) {\r\n delete channel._pendingSubscriptionCid;\r\n if (err) {\r\n self._triggerChannelSubscribeFail(err, channel, subscriptionOptions);\r\n } else {\r\n self._triggerChannelSubscribe(channel, subscriptionOptions);\r\n }\r\n }\r\n );\r\n Emitter.prototype.emit.call(this, 'subscribeRequest', channel.name, subscriptionOptions);\r\n }\r\n};\r\n\r\nSCClientSocket.prototype.subscribe = function (channelName, options) {\r\n var channel = this.channels[channelName];\r\n\r\n if (!channel) {\r\n channel = new SCChannel(channelName, this, options);\r\n this.channels[channelName] = channel;\r\n } else if (options) {\r\n channel.setOptions(options);\r\n }\r\n\r\n if (channel.state == channel.UNSUBSCRIBED) {\r\n channel.state = channel.PENDING;\r\n this._trySubscribe(channel);\r\n }\r\n\r\n return channel;\r\n};\r\n\r\nSCClientSocket.prototype._triggerChannelUnsubscribe = function (channel, newState) {\r\n var channelName = channel.name;\r\n var oldState = channel.state;\r\n\r\n if (newState) {\r\n channel.state = newState;\r\n } else {\r\n channel.state = channel.UNSUBSCRIBED;\r\n }\r\n this._cancelPendingSubscribeCallback(channel);\r\n\r\n if (oldState == channel.SUBSCRIBED) {\r\n var stateChangeData = {\r\n channel: channelName,\r\n oldState: oldState,\r\n newState: channel.state\r\n };\r\n channel.emit('subscribeStateChange', stateChangeData);\r\n channel.emit('unsubscribe', channelName);\r\n Emitter.prototype.emit.call(this, 'subscribeStateChange', stateChangeData);\r\n Emitter.prototype.emit.call(this, 'unsubscribe', channelName);\r\n }\r\n};\r\n\r\nSCClientSocket.prototype._tryUnsubscribe = function (channel) {\r\n var self = this;\r\n\r\n if (this.state == this.OPEN) {\r\n var options = {\r\n noTimeout: true\r\n };\r\n if (channel.batch) {\r\n options.batch = true;\r\n }\r\n // If there is a pending subscribe action, cancel the callback\r\n this._cancelPendingSubscribeCallback(channel);\r\n\r\n // This operation cannot fail because the TCP protocol guarantees delivery\r\n // so long as the connection remains open. If the connection closes,\r\n // the server will automatically unsubscribe the client and thus complete\r\n // the operation on the server side.\r\n var decoratedChannelName = this._decorateChannelName(channel.name);\r\n this.transport.emit('#unsubscribe', decoratedChannelName, options);\r\n }\r\n};\r\n\r\nSCClientSocket.prototype.unsubscribe = function (channelName) {\r\n var channel = this.channels[channelName];\r\n\r\n if (channel) {\r\n if (channel.state != channel.UNSUBSCRIBED) {\r\n\r\n this._triggerChannelUnsubscribe(channel);\r\n this._tryUnsubscribe(channel);\r\n }\r\n }\r\n};\r\n\r\nSCClientSocket.prototype.channel = function (channelName, options) {\r\n var currentChannel = this.channels[channelName];\r\n\r\n if (!currentChannel) {\r\n currentChannel = new SCChannel(channelName, this, options);\r\n this.channels[channelName] = currentChannel;\r\n }\r\n return currentChannel;\r\n};\r\n\r\nSCClientSocket.prototype.destroyChannel = function (channelName) {\r\n var channel = this.channels[channelName];\r\n\r\n if (channel) {\r\n channel.unwatch();\r\n channel.unsubscribe();\r\n delete this.channels[channelName];\r\n }\r\n};\r\n\r\nSCClientSocket.prototype.subscriptions = function (includePending) {\r\n var subs = [];\r\n var channel, includeChannel;\r\n for (var channelName in this.channels) {\r\n if (this.channels.hasOwnProperty(channelName)) {\r\n channel = this.channels[channelName];\r\n\r\n if (includePending) {\r\n includeChannel = channel && (channel.state == channel.SUBSCRIBED ||\r\n channel.state == channel.PENDING);\r\n } else {\r\n includeChannel = channel && channel.state == channel.SUBSCRIBED;\r\n }\r\n\r\n if (includeChannel) {\r\n subs.push(channelName);\r\n }\r\n }\r\n }\r\n return subs;\r\n};\r\n\r\nSCClientSocket.prototype.isSubscribed = function (channelName, includePending) {\r\n var channel = this.channels[channelName];\r\n if (includePending) {\r\n return !!channel && (channel.state == channel.SUBSCRIBED ||\r\n channel.state == channel.PENDING);\r\n }\r\n return !!channel && channel.state == channel.SUBSCRIBED;\r\n};\r\n\r\nSCClientSocket.prototype.processPendingSubscriptions = function () {\r\n var self = this;\r\n\r\n this.preparingPendingSubscriptions = false;\r\n\r\n var pendingChannels = [];\r\n\r\n for (var i in this.channels) {\r\n if (this.channels.hasOwnProperty(i)) {\r\n var channel = this.channels[i];\r\n if (channel.state == channel.PENDING) {\r\n pendingChannels.push(channel);\r\n }\r\n }\r\n }\r\n\r\n pendingChannels.sort(function (a, b) {\r\n var ap = a.priority || 0;\r\n var bp = b.priority || 0;\r\n if (ap > bp) {\r\n return -1;\r\n }\r\n if (ap < bp) {\r\n return 1;\r\n }\r\n return 0;\r\n });\r\n\r\n pendingChannels.forEach(function (channel) {\r\n self._trySubscribe(channel);\r\n });\r\n};\r\n\r\nSCClientSocket.prototype.watch = function (channelName, handler) {\r\n if (typeof handler != 'function') {\r\n throw new InvalidArgumentsError('No handler function was provided');\r\n }\r\n this._channelEmitter.on(channelName, handler);\r\n};\r\n\r\nSCClientSocket.prototype.unwatch = function (channelName, handler) {\r\n if (handler) {\r\n this._channelEmitter.removeListener(channelName, handler);\r\n } else {\r\n this._channelEmitter.removeAllListeners(channelName);\r\n }\r\n};\r\n\r\nSCClientSocket.prototype.watchers = function (channelName) {\r\n return this._channelEmitter.listeners(channelName);\r\n};\r\n\r\nmodule.exports = SCClientSocket;\r\n","var Emitter = require('component-emitter');\r\nvar Response = require('./response').Response;\r\nvar querystring = require('querystring');\r\nvar WebSocket;\r\nvar createWebSocket;\r\n\r\nif (global.WebSocket) {\r\n WebSocket = global.WebSocket;\r\n createWebSocket = function (uri, options) {\r\n return new WebSocket(uri);\r\n };\r\n} else {\r\n WebSocket = require('ws');\r\n createWebSocket = function (uri, options) {\r\n return new WebSocket(uri, null, options);\r\n };\r\n}\r\n\r\nvar scErrors = require('sc-errors');\r\nvar TimeoutError = scErrors.TimeoutError;\r\nvar BadConnectionError = scErrors.BadConnectionError;\r\n\r\n\r\nvar SCTransport = function (authEngine, codecEngine, options) {\r\n var self = this;\r\n\r\n this.state = this.CLOSED;\r\n this.auth = authEngine;\r\n this.codec = codecEngine;\r\n this.options = options;\r\n this.connectTimeout = options.connectTimeout;\r\n this.pingTimeout = options.ackTimeout;\r\n this.pingTimeoutDisabled = !!options.pingTimeoutDisabled;\r\n this.callIdGenerator = options.callIdGenerator;\r\n this.authTokenName = options.authTokenName;\r\n\r\n this._pingTimeoutTicker = null;\r\n this._callbackMap = {};\r\n this._batchSendList = [];\r\n\r\n // Open the connection.\r\n\r\n this.state = this.CONNECTING;\r\n var uri = this.uri();\r\n\r\n var wsSocket = createWebSocket(uri, this.options);\r\n wsSocket.binaryType = this.options.binaryType;\r\n\r\n this.socket = wsSocket;\r\n\r\n wsSocket.onopen = function () {\r\n self._onOpen();\r\n };\r\n\r\n wsSocket.onclose = function (event) {\r\n var code;\r\n if (event.code == null) {\r\n // This is to handle an edge case in React Native whereby\r\n // event.code is undefined when the mobile device is locked.\r\n // TODO: This is not perfect since this condition could also apply to\r\n // an abnormal close (no close control frame) which would be a 1006.\r\n code = 1005;\r\n } else {\r\n code = event.code;\r\n }\r\n self._onClose(code, event.reason);\r\n };\r\n\r\n wsSocket.onmessage = function (message, flags) {\r\n self._onMessage(message.data);\r\n };\r\n\r\n wsSocket.onerror = function (error) {\r\n // The onclose event will be called automatically after the onerror event\r\n // if the socket is connected - Otherwise, if it's in the middle of\r\n // connecting, we want to close it manually with a 1006 - This is necessary\r\n // to prevent inconsistent behavior when running the client in Node.js\r\n // vs in a browser.\r\n\r\n if (self.state === self.CONNECTING) {\r\n self._onClose(1006);\r\n }\r\n };\r\n\r\n this._connectTimeoutRef = setTimeout(function () {\r\n self._onClose(4007);\r\n self.socket.close(4007);\r\n }, this.connectTimeout);\r\n};\r\n\r\nSCTransport.prototype = Object.create(Emitter.prototype);\r\n\r\nSCTransport.CONNECTING = SCTransport.prototype.CONNECTING = 'connecting';\r\nSCTransport.OPEN = SCTransport.prototype.OPEN = 'open';\r\nSCTransport.CLOSED = SCTransport.prototype.CLOSED = 'closed';\r\n\r\nSCTransport.prototype.uri = function () {\r\n var query = this.options.query || {};\r\n var schema = this.options.secure ? 'wss' : 'ws';\r\n\r\n if (this.options.timestampRequests) {\r\n query[this.options.timestampParam] = (new Date()).getTime();\r\n }\r\n\r\n query = querystring.encode(query);\r\n\r\n if (query.length) {\r\n query = '?' + query;\r\n }\r\n\r\n var host;\r\n if (this.options.host) {\r\n host = this.options.host;\r\n } else {\r\n var port = '';\r\n\r\n if (this.options.port && ((schema == 'wss' && this.options.port != 443)\r\n || (schema == 'ws' && this.options.port != 80))) {\r\n port = ':' + this.options.port;\r\n }\r\n host = this.options.hostname + port;\r\n }\r\n\r\n return schema + '://' + host + this.options.path + query;\r\n};\r\n\r\nSCTransport.prototype._onOpen = function () {\r\n var self = this;\r\n\r\n clearTimeout(this._connectTimeoutRef);\r\n this._resetPingTimeout();\r\n\r\n this._handshake(function (err, status) {\r\n if (err) {\r\n var statusCode;\r\n if (status && status.code) {\r\n statusCode = status.code;\r\n } else {\r\n statusCode = 4003;\r\n }\r\n self._onError(err);\r\n self._onClose(statusCode, err.toString());\r\n self.socket.close(statusCode);\r\n } else {\r\n self.state = self.OPEN;\r\n Emitter.prototype.emit.call(self, 'open', status);\r\n self._resetPingTimeout();\r\n }\r\n });\r\n};\r\n\r\nSCTransport.prototype._handshake = function (callback) {\r\n var self = this;\r\n this.auth.loadToken(this.authTokenName, function (err, token) {\r\n if (err) {\r\n callback(err);\r\n } else {\r\n // Don't wait for this.state to be 'open'.\r\n // The underlying WebSocket (this.socket) is already open.\r\n var options = {\r\n force: true\r\n };\r\n self.emit('#handshake', {\r\n authToken: token\r\n }, options, function (err, status) {\r\n if (status) {\r\n // Add the token which was used as part of authentication attempt\r\n // to the status object.\r\n status.authToken = token;\r\n if (status.authError) {\r\n status.authError = scErrors.hydrateError(status.authError);\r\n }\r\n }\r\n callback(err, status);\r\n });\r\n }\r\n });\r\n};\r\n\r\nSCTransport.prototype._abortAllPendingEventsDueToBadConnection = function (failureType) {\r\n for (var i in this._callbackMap) {\r\n if (this._callbackMap.hasOwnProperty(i)) {\r\n var eventObject = this._callbackMap[i];\r\n delete this._callbackMap[i];\r\n\r\n clearTimeout(eventObject.timeout);\r\n delete eventObject.timeout;\r\n\r\n var errorMessage = \"Event '\" + eventObject.event +\r\n \"' was aborted due to a bad connection\";\r\n var badConnectionError = new BadConnectionError(errorMessage, failureType);\r\n\r\n var callback = eventObject.callback;\r\n delete eventObject.callback;\r\n callback.call(eventObject, badConnectionError, eventObject);\r\n }\r\n }\r\n};\r\n\r\nSCTransport.prototype._onClose = function (code, data) {\r\n delete this.socket.onopen;\r\n delete this.socket.onclose;\r\n delete this.socket.onmessage;\r\n delete this.socket.onerror;\r\n\r\n clearTimeout(this._connectTimeoutRef);\r\n clearTimeout(this._pingTimeoutTicker);\r\n clearTimeout(this._batchTimeout);\r\n\r\n if (this.state == this.OPEN) {\r\n this.state = this.CLOSED;\r\n Emitter.prototype.emit.call(this, 'close', code, data);\r\n this._abortAllPendingEventsDueToBadConnection('disconnect');\r\n\r\n } else if (this.state == this.CONNECTING) {\r\n this.state = this.CLOSED;\r\n Emitter.prototype.emit.call(this, 'openAbort', code, data);\r\n this._abortAllPendingEventsDueToBadConnection('connectAbort');\r\n }\r\n};\r\n\r\nSCTransport.prototype._handleEventObject = function (obj, message) {\r\n if (obj && obj.event != null) {\r\n var response = new Response(this, obj.cid);\r\n Emitter.prototype.emit.call(this, 'event', obj.event, obj.data, response);\r\n } else if (obj && obj.rid != null) {\r\n var eventObject = this._callbackMap[obj.rid];\r\n if (eventObject) {\r\n clearTimeout(eventObject.timeout);\r\n delete eventObject.timeout;\r\n delete this._callbackMap[obj.rid];\r\n\r\n if (eventObject.callback) {\r\n var rehydratedError = scErrors.hydrateError(obj.error);\r\n eventObject.callback(rehydratedError, obj.data);\r\n }\r\n }\r\n } else {\r\n Emitter.prototype.emit.call(this, 'event', 'raw', message);\r\n }\r\n};\r\n\r\nSCTransport.prototype._onMessage = function (message) {\r\n Emitter.prototype.emit.call(this, 'event', 'message', message);\r\n\r\n var obj = this.decode(message);\r\n\r\n // If ping\r\n if (obj == '#1') {\r\n this._resetPingTimeout();\r\n if (this.socket.readyState == this.socket.OPEN) {\r\n this.sendObject('#2');\r\n }\r\n } else {\r\n if (Array.isArray(obj)) {\r\n var len = obj.length;\r\n for (var i = 0; i < len; i++) {\r\n this._handleEventObject(obj[i], message);\r\n }\r\n } else {\r\n this._handleEventObject(obj, message);\r\n }\r\n }\r\n};\r\n\r\nSCTransport.prototype._onError = function (err) {\r\n Emitter.prototype.emit.call(this, 'error', err);\r\n};\r\n\r\nSCTransport.prototype._resetPingTimeout = function () {\r\n if (this.pingTimeoutDisabled) {\r\n return;\r\n }\r\n var self = this;\r\n\r\n var now = (new Date()).getTime();\r\n clearTimeout(this._pingTimeoutTicker);\r\n\r\n this._pingTimeoutTicker = setTimeout(function () {\r\n self._onClose(4000);\r\n self.socket.close(4000);\r\n }, this.pingTimeout);\r\n};\r\n\r\nSCTransport.prototype.getBytesReceived = function () {\r\n return this.socket.bytesReceived;\r\n};\r\n\r\nSCTransport.prototype.close = function (code, data) {\r\n code = code || 1000;\r\n\r\n if (this.state == this.OPEN) {\r\n var packet = {\r\n code: code,\r\n data: data\r\n };\r\n this.emit('#disconnect', packet);\r\n\r\n this._onClose(code, data);\r\n this.socket.close(code);\r\n\r\n } else if (this.state == this.CONNECTING) {\r\n this._onClose(code, data);\r\n this.socket.close(code);\r\n }\r\n};\r\n\r\nSCTransport.prototype.emitObject = function (eventObject, options) {\r\n var simpleEventObject = {\r\n event: eventObject.event,\r\n data: eventObject.data\r\n };\r\n\r\n if (eventObject.callback) {\r\n simpleEventObject.cid = eventObject.cid = this.callIdGenerator();\r\n this._callbackMap[eventObject.cid] = eventObject;\r\n }\r\n\r\n this.sendObject(simpleEventObject, options);\r\n\r\n return eventObject.cid || null;\r\n};\r\n\r\nSCTransport.prototype._handleEventAckTimeout = function (eventObject) {\r\n if (eventObject.cid) {\r\n delete this._callbackMap[eventObject.cid];\r\n }\r\n delete eventObject.timeout;\r\n\r\n var callback = eventObject.callback;\r\n if (callback) {\r\n delete eventObject.callback;\r\n var error = new TimeoutError(\"Event response for '\" + eventObject.event + \"' timed out\");\r\n callback.call(eventObject, error, eventObject);\r\n }\r\n};\r\n\r\n// The last two optional arguments (a and b) can be options and/or callback\r\nSCTransport.prototype.emit = function (event, data, a, b) {\r\n var self = this;\r\n\r\n var callback, options;\r\n\r\n if (b) {\r\n options = a;\r\n callback = b;\r\n } else {\r\n if (a instanceof Function) {\r\n options = {};\r\n callback = a;\r\n } else {\r\n options = a;\r\n }\r\n }\r\n\r\n var eventObject = {\r\n event: event,\r\n data: data,\r\n callback: callback\r\n };\r\n\r\n if (callback && !options.noTimeout) {\r\n eventObject.timeout = setTimeout(function () {\r\n self._handleEventAckTimeout(eventObject);\r\n }, this.options.ackTimeout);\r\n }\r\n\r\n var cid = null;\r\n if (this.state == this.OPEN || options.force) {\r\n cid = this.emitObject(eventObject, options);\r\n }\r\n return cid;\r\n};\r\n\r\nSCTransport.prototype.cancelPendingResponse = function (cid) {\r\n delete this._callbackMap[cid];\r\n};\r\n\r\nSCTransport.prototype.decode = function (message) {\r\n return this.codec.decode(message);\r\n};\r\n\r\nSCTransport.prototype.encode = function (object) {\r\n return this.codec.encode(object);\r\n};\r\n\r\nSCTransport.prototype.send = function (data) {\r\n if (this.socket.readyState != this.socket.OPEN) {\r\n this._onClose(1005);\r\n } else {\r\n this.socket.send(data);\r\n }\r\n};\r\n\r\nSCTransport.prototype.serializeObject = function (object) {\r\n var str, formatError;\r\n try {\r\n str = this.encode(object);\r\n } catch (err) {\r\n formatError = err;\r\n this._onError(formatError);\r\n }\r\n if (!formatError) {\r\n return str;\r\n }\r\n return null;\r\n};\r\n\r\nSCTransport.prototype.sendObjectBatch = function (object) {\r\n var self = this;\r\n\r\n this._batchSendList.push(object);\r\n if (this._batchTimeout) {\r\n return;\r\n }\r\n\r\n this._batchTimeout = setTimeout(function () {\r\n delete self._batchTimeout;\r\n if (self._batchSendList.length) {\r\n var str = self.serializeObject(self._batchSendList);\r\n if (str != null) {\r\n self.send(str);\r\n }\r\n self._batchSendList = [];\r\n }\r\n }, this.options.pubSubBatchDuration || 0);\r\n};\r\n\r\nSCTransport.prototype.sendObjectSingle = function (object) {\r\n var str = this.serializeObject(object);\r\n if (str != null) {\r\n this.send(str);\r\n }\r\n};\r\n\r\nSCTransport.prototype.sendObject = function (object, options) {\r\n if (options && options.batch) {\r\n this.sendObjectBatch(object);\r\n } else {\r\n this.sendObjectSingle(object);\r\n }\r\n};\r\n\r\nmodule.exports.SCTransport = SCTransport;\r\n","var global;\nif (typeof WorkerGlobalScope !== 'undefined') {\n global = self;\n} else {\n global = typeof window != 'undefined' && window || (function() { return this; })();\n}\n\nvar WebSocket = global.WebSocket || global.MozWebSocket;\n\n/**\n * WebSocket constructor.\n *\n * The third `opts` options object gets ignored in web browsers, since it's\n * non-standard, and throws a TypeError if passed to the constructor.\n * See: https://github.com/einaros/ws/issues/227\n *\n * @param {String} uri\n * @param {Array} protocols (optional)\n * @param {Object} opts (optional)\n * @api public\n */\n\nfunction ws(uri, protocols, opts) {\n var instance;\n if (protocols) {\n instance = new WebSocket(uri, protocols);\n } else {\n instance = new WebSocket(uri);\n }\n return instance;\n}\n\nif (WebSocket) ws.prototype = WebSocket.prototype;\n\nmodule.exports = WebSocket ? ws : null;\n","var clone = (function() {\n'use strict';\n\nfunction _instanceof(obj, type) {\n return type != null && obj instanceof type;\n}\n\nvar nativeMap;\ntry {\n nativeMap = Map;\n} catch(_) {\n // maybe a reference error because no `Map`. Give it a dummy value that no\n // value will ever be an instanceof.\n nativeMap = function() {};\n}\n\nvar nativeSet;\ntry {\n nativeSet = Set;\n} catch(_) {\n nativeSet = function() {};\n}\n\nvar nativePromise;\ntry {\n nativePromise = Promise;\n} catch(_) {\n nativePromise = function() {};\n}\n\n/**\n * Clones (copies) an Object using deep copying.\n *\n * This function supports circular references by default, but if you are certain\n * there are no circular references in your object, you can save some CPU time\n * by calling clone(obj, false).\n *\n * Caution: if `circular` is false and `parent` contains circular references,\n * your program may enter an infinite loop and crash.\n *\n * @param `parent` - the object to be cloned\n * @param `circular` - set to true if the object to be cloned may contain\n * circular references. (optional - true by default)\n * @param `depth` - set to a number if the object is only to be cloned to\n * a particular depth. (optional - defaults to Infinity)\n * @param `prototype` - sets the prototype to be used when cloning an object.\n * (optional - defaults to parent prototype).\n * @param `includeNonEnumerable` - set to true if the non-enumerable properties\n * should be cloned as well. Non-enumerable properties on the prototype\n * chain will be ignored. (optional - false by default)\n*/\nfunction clone(parent, circular, depth, prototype, includeNonEnumerable) {\n if (typeof circular === 'object') {\n depth = circular.depth;\n prototype = circular.prototype;\n includeNonEnumerable = circular.includeNonEnumerable;\n circular = circular.circular;\n }\n // maintain two arrays for circular references, where corresponding parents\n // and children have the same index\n var allParents = [];\n var allChildren = [];\n\n var useBuffer = typeof Buffer != 'undefined';\n\n if (typeof circular == 'undefined')\n circular = true;\n\n if (typeof depth == 'undefined')\n depth = Infinity;\n\n // recurse this function so we don't reset allParents and allChildren\n function _clone(parent, depth) {\n // cloning null always returns null\n if (parent === null)\n return null;\n\n if (depth === 0)\n return parent;\n\n var child;\n var proto;\n if (typeof parent != 'object') {\n return parent;\n }\n\n if (_instanceof(parent, nativeMap)) {\n child = new nativeMap();\n } else if (_instanceof(parent, nativeSet)) {\n child = new nativeSet();\n } else if (_instanceof(parent, nativePromise)) {\n child = new nativePromise(function (resolve, reject) {\n parent.then(function(value) {\n resolve(_clone(value, depth - 1));\n }, function(err) {\n reject(_clone(err, depth - 1));\n });\n });\n } else if (clone.__isArray(parent)) {\n child = [];\n } else if (clone.__isRegExp(parent)) {\n child = new RegExp(parent.source, __getRegExpFlags(parent));\n if (parent.lastIndex) child.lastIndex = parent.lastIndex;\n } else if (clone.__isDate(parent)) {\n child = new Date(parent.getTime());\n } else if (useBuffer && Buffer.isBuffer(parent)) {\n child = new Buffer(parent.length);\n parent.copy(child);\n return child;\n } else if (_instanceof(parent, Error)) {\n child = Object.create(parent);\n } else {\n if (typeof prototype == 'undefined') {\n proto = Object.getPrototypeOf(parent);\n child = Object.create(proto);\n }\n else {\n child = Object.create(prototype);\n proto = prototype;\n }\n }\n\n if (circular) {\n var index = allParents.indexOf(parent);\n\n if (index != -1) {\n return allChildren[index];\n }\n allParents.push(parent);\n allChildren.push(child);\n }\n\n if (_instanceof(parent, nativeMap)) {\n parent.forEach(function(value, key) {\n var keyChild = _clone(key, depth - 1);\n var valueChild = _clone(value, depth - 1);\n child.set(keyChild, valueChild);\n });\n }\n if (_instanceof(parent, nativeSet)) {\n parent.forEach(function(value) {\n var entryChild = _clone(value, depth - 1);\n child.add(entryChild);\n });\n }\n\n for (var i in parent) {\n var attrs;\n if (proto) {\n attrs = Object.getOwnPropertyDescriptor(proto, i);\n }\n\n if (attrs && attrs.set == null) {\n continue;\n }\n child[i] = _clone(parent[i], depth - 1);\n }\n\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(parent);\n for (var i = 0; i < symbols.length; i++) {\n // Don't need to worry about cloning a symbol because it is a primitive,\n // like a number or string.\n var symbol = symbols[i];\n var descriptor = Object.getOwnPropertyDescriptor(parent, symbol);\n if (descriptor && !descriptor.enumerable && !includeNonEnumerable) {\n continue;\n }\n child[symbol] = _clone(parent[symbol], depth - 1);\n if (!descriptor.enumerable) {\n Object.defineProperty(child, symbol, {\n enumerable: false\n });\n }\n }\n }\n\n if (includeNonEnumerable) {\n var allPropertyNames = Object.getOwnPropertyNames(parent);\n for (var i = 0; i < allPropertyNames.length; i++) {\n var propertyName = allPropertyNames[i];\n var descriptor = Object.getOwnPropertyDescriptor(parent, propertyName);\n if (descriptor && descriptor.enumerable) {\n continue;\n }\n child[propertyName] = _clone(parent[propertyName], depth - 1);\n Object.defineProperty(child, propertyName, {\n enumerable: false\n });\n }\n }\n\n return child;\n }\n\n return _clone(parent, depth);\n}\n\n/**\n * Simple flat clone using prototype, accepts only objects, usefull for property\n * override on FLAT configuration object (no nested props).\n *\n * USE WITH CAUTION! This may not behave as you wish if you do not know how this\n * works.\n */\nclone.clonePrototype = function clonePrototype(parent) {\n if (parent === null)\n return null;\n\n var c = function () {};\n c.prototype = parent;\n return new c();\n};\n\n// private utility functions\n\nfunction __objToStr(o) {\n return Object.prototype.toString.call(o);\n}\nclone.__objToStr = __objToStr;\n\nfunction __isDate(o) {\n return typeof o === 'object' && __objToStr(o) === '[object Date]';\n}\nclone.__isDate = __isDate;\n\nfunction __isArray(o) {\n return typeof o === 'object' && __objToStr(o) === '[object Array]';\n}\nclone.__isArray = __isArray;\n\nfunction __isRegExp(o) {\n return typeof o === 'object' && __objToStr(o) === '[object RegExp]';\n}\nclone.__isRegExp = __isRegExp;\n\nfunction __getRegExpFlags(re) {\n var flags = '';\n if (re.global) flags += 'g';\n if (re.ignoreCase) flags += 'i';\n if (re.multiline) flags += 'm';\n return flags;\n}\nclone.__getRegExpFlags = __getRegExpFlags;\n\nreturn clone;\n})();\n\nif (typeof module === 'object' && module.exports) {\n module.exports = clone;\n}\n","\r\n/**\r\n * Expose `Emitter`.\r\n */\r\n\r\nif (typeof module !== 'undefined') {\r\n module.exports = Emitter;\r\n}\r\n\r\n/**\r\n * Initialize a new `Emitter`.\r\n *\r\n * @api public\r\n */\r\n\r\nfunction Emitter(obj) {\r\n if (obj) return mixin(obj);\r\n};\r\n\r\n/**\r\n * Mixin the emitter properties.\r\n *\r\n * @param {Object} obj\r\n * @return {Object}\r\n * @api private\r\n */\r\n\r\nfunction mixin(obj) {\r\n for (var key in Emitter.prototype) {\r\n obj[key] = Emitter.prototype[key];\r\n }\r\n return obj;\r\n}\r\n\r\n/**\r\n * Listen on the given `event` with `fn`.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.on =\r\nEmitter.prototype.addEventListener = function(event, fn){\r\n this._callbacks = this._callbacks || {};\r\n (this._callbacks['$' + event] = this._callbacks['$' + event] || [])\r\n .push(fn);\r\n return this;\r\n};\r\n\r\n/**\r\n * Adds an `event` listener that will be invoked a single\r\n * time then automatically removed.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.once = function(event, fn){\r\n function on() {\r\n this.off(event, on);\r\n fn.apply(this, arguments);\r\n }\r\n\r\n on.fn = fn;\r\n this.on(event, on);\r\n return this;\r\n};\r\n\r\n/**\r\n * Remove the given callback for `event` or all\r\n * registered callbacks.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.off =\r\nEmitter.prototype.removeListener =\r\nEmitter.prototype.removeAllListeners =\r\nEmitter.prototype.removeEventListener = function(event, fn){\r\n this._callbacks = this._callbacks || {};\r\n\r\n // all\r\n if (0 == arguments.length) {\r\n this._callbacks = {};\r\n return this;\r\n }\r\n\r\n // specific event\r\n var callbacks = this._callbacks['$' + event];\r\n if (!callbacks) return this;\r\n\r\n // remove all handlers\r\n if (1 == arguments.length) {\r\n delete this._callbacks['$' + event];\r\n return this;\r\n }\r\n\r\n // remove specific handler\r\n var cb;\r\n for (var i = 0; i < callbacks.length; i++) {\r\n cb = callbacks[i];\r\n if (cb === fn || cb.fn === fn) {\r\n callbacks.splice(i, 1);\r\n break;\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Emit `event` with the given args.\r\n *\r\n * @param {String} event\r\n * @param {Mixed} ...\r\n * @return {Emitter}\r\n */\r\n\r\nEmitter.prototype.emit = function(event){\r\n this._callbacks = this._callbacks || {};\r\n var args = [].slice.call(arguments, 1)\r\n , callbacks = this._callbacks['$' + event];\r\n\r\n if (callbacks) {\r\n callbacks = callbacks.slice(0);\r\n for (var i = 0, len = callbacks.length; i < len; ++i) {\r\n callbacks[i].apply(this, args);\r\n }\r\n }\r\n\r\n return this;\r\n};\r\n\r\n/**\r\n * Return array of callbacks for `event`.\r\n *\r\n * @param {String} event\r\n * @return {Array}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.listeners = function(event){\r\n this._callbacks = this._callbacks || {};\r\n return this._callbacks['$' + event] || [];\r\n};\r\n\r\n/**\r\n * Check if this emitter has `event` handlers.\r\n *\r\n * @param {String} event\r\n * @return {Boolean}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.hasListeners = function(event){\r\n return !! this.listeners(event).length;\r\n};\r\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n// If obj.hasOwnProperty has been overridden, then calling\n// obj.hasOwnProperty(prop) will break.\n// See: https://github.com/joyent/node/issues/1707\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nmodule.exports = function(qs, sep, eq, options) {\n sep = sep || '&';\n eq = eq || '=';\n var obj = {};\n\n if (typeof qs !== 'string' || qs.length === 0) {\n return obj;\n }\n\n var regexp = /\\+/g;\n qs = qs.split(sep);\n\n var maxKeys = 1000;\n if (options && typeof options.maxKeys === 'number') {\n maxKeys = options.maxKeys;\n }\n\n var len = qs.length;\n // maxKeys <= 0 means that we should not limit keys count\n if (maxKeys > 0 && len > maxKeys) {\n len = maxKeys;\n }\n\n for (var i = 0; i < len; ++i) {\n var x = qs[i].replace(regexp, '%20'),\n idx = x.indexOf(eq),\n kstr, vstr, k, v;\n\n if (idx >= 0) {\n kstr = x.substr(0, idx);\n vstr = x.substr(idx + 1);\n } else {\n kstr = x;\n vstr = '';\n }\n\n k = decodeURIComponent(kstr);\n v = decodeURIComponent(vstr);\n\n if (!hasOwnProperty(obj, k)) {\n obj[k] = v;\n } else if (Array.isArray(obj[k])) {\n obj[k].push(v);\n } else {\n obj[k] = [obj[k], v];\n }\n }\n\n return obj;\n};\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar stringifyPrimitive = function(v) {\n switch (typeof v) {\n case 'string':\n return v;\n\n case 'boolean':\n return v ? 'true' : 'false';\n\n case 'number':\n return isFinite(v) ? v : '';\n\n default:\n return '';\n }\n};\n\nmodule.exports = function(obj, sep, eq, name) {\n sep = sep || '&';\n eq = eq || '=';\n if (obj === null) {\n obj = undefined;\n }\n\n if (typeof obj === 'object') {\n return Object.keys(obj).map(function(k) {\n var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;\n if (Array.isArray(obj[k])) {\n return obj[k].map(function(v) {\n return ks + encodeURIComponent(stringifyPrimitive(v));\n }).join(sep);\n } else {\n return ks + encodeURIComponent(stringifyPrimitive(obj[k]));\n }\n }).join(sep);\n\n }\n\n if (!name) return '';\n return encodeURIComponent(stringifyPrimitive(name)) + eq +\n encodeURIComponent(stringifyPrimitive(obj));\n};\n","'use strict';\n\nexports.decode = exports.parse = require('./decode');\nexports.encode = exports.stringify = require('./encode');\n","var v1 = require('./v1');\nvar v4 = require('./v4');\n\nvar uuid = v4;\nuuid.v1 = v1;\nuuid.v4 = v4;\n\nmodule.exports = uuid;\n","/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\nvar byteToHex = [];\nfor (var i = 0; i < 256; ++i) {\n byteToHex[i] = (i + 0x100).toString(16).substr(1);\n}\n\nfunction bytesToUuid(buf, offset) {\n var i = offset || 0;\n var bth = byteToHex;\n return bth[buf[i++]] + bth[buf[i++]] +\n bth[buf[i++]] + bth[buf[i++]] + '-' +\n bth[buf[i++]] + bth[buf[i++]] + '-' +\n bth[buf[i++]] + bth[buf[i++]] + '-' +\n bth[buf[i++]] + bth[buf[i++]] + '-' +\n bth[buf[i++]] + bth[buf[i++]] +\n bth[buf[i++]] + bth[buf[i++]] +\n bth[buf[i++]] + bth[buf[i++]];\n}\n\nmodule.exports = bytesToUuid;\n","// Unique ID creation requires a high quality random # generator. In the\n// browser this is a little complicated due to unknown quality of Math.random()\n// and inconsistent support for the `crypto` API. We do the best we can via\n// feature-detection\n\n// getRandomValues needs to be invoked in a context where \"this\" is a Crypto implementation.\nvar getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues.bind(crypto)) ||\n (typeof(msCrypto) != 'undefined' && msCrypto.getRandomValues.bind(msCrypto));\nif (getRandomValues) {\n // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto\n var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef\n\n module.exports = function whatwgRNG() {\n getRandomValues(rnds8);\n return rnds8;\n };\n} else {\n // Math.random()-based (RNG)\n //\n // If all else fails, use Math.random(). It's fast, but is of unspecified\n // quality.\n var rnds = new Array(16);\n\n module.exports = function mathRNG() {\n for (var i = 0, r; i < 16; i++) {\n if ((i & 0x03) === 0) r = Math.random() * 0x100000000;\n rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;\n }\n\n return rnds;\n };\n}\n","var rng = require('./lib/rng');\nvar bytesToUuid = require('./lib/bytesToUuid');\n\n// **`v1()` - Generate time-based UUID**\n//\n// Inspired by https://github.com/LiosK/UUID.js\n// and http://docs.python.org/library/uuid.html\n\nvar _nodeId;\nvar _clockseq;\n\n// Previous uuid creation time\nvar _lastMSecs = 0;\nvar _lastNSecs = 0;\n\n// See https://github.com/broofa/node-uuid for API details\nfunction v1(options, buf, offset) {\n var i = buf && offset || 0;\n var b = buf || [];\n\n options = options || {};\n var node = options.node || _nodeId;\n var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;\n\n // node and clockseq need to be initialized to random values if they're not\n // specified. We do this lazily to minimize issues related to insufficient\n // system entropy. See #189\n if (node == null || clockseq == null) {\n var seedBytes = rng();\n if (node == null) {\n // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n node = _nodeId = [\n seedBytes[0] | 0x01,\n seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]\n ];\n }\n if (clockseq == null) {\n // Per 4.2.2, randomize (14 bit) clockseq\n clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;\n }\n }\n\n // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();\n\n // Per 4.2.1.2, use count of uuid's generated during the current clock\n // cycle to simulate higher resolution clock\n var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;\n\n // Time since last uuid creation (in msecs)\n var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;\n\n // Per 4.2.1.2, Bump clockseq on clock regression\n if (dt < 0 && options.clockseq === undefined) {\n clockseq = clockseq + 1 & 0x3fff;\n }\n\n // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n // time interval\n if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {\n nsecs = 0;\n }\n\n // Per 4.2.1.2 Throw error if too many uuids are requested\n if (nsecs >= 10000) {\n throw new Error('uuid.v1(): Can\\'t create more than 10M uuids/sec');\n }\n\n _lastMSecs = msecs;\n _lastNSecs = nsecs;\n _clockseq = clockseq;\n\n // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n msecs += 12219292800000;\n\n // `time_low`\n var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n b[i++] = tl >>> 24 & 0xff;\n b[i++] = tl >>> 16 & 0xff;\n b[i++] = tl >>> 8 & 0xff;\n b[i++] = tl & 0xff;\n\n // `time_mid`\n var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;\n b[i++] = tmh >>> 8 & 0xff;\n b[i++] = tmh & 0xff;\n\n // `time_high_and_version`\n b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n b[i++] = tmh >>> 16 & 0xff;\n\n // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n b[i++] = clockseq >>> 8 | 0x80;\n\n // `clock_seq_low`\n b[i++] = clockseq & 0xff;\n\n // `node`\n for (var n = 0; n < 6; ++n) {\n b[i + n] = node[n];\n }\n\n return buf ? buf : bytesToUuid(b);\n}\n\nmodule.exports = v1;\n","var rng = require('./lib/rng');\nvar bytesToUuid = require('./lib/bytesToUuid');\n\nfunction v4(options, buf, offset) {\n var i = buf && offset || 0;\n\n if (typeof(options) == 'string') {\n buf = options === 'binary' ? new Array(16) : null;\n options = null;\n }\n options = options || {};\n\n var rnds = options.random || (options.rng || rng)();\n\n // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n rnds[6] = (rnds[6] & 0x0f) | 0x40;\n rnds[8] = (rnds[8] & 0x3f) | 0x80;\n\n // Copy bytes to buffer, if provided\n if (buf) {\n for (var ii = 0; ii < 16; ++ii) {\n buf[i + ii] = rnds[ii];\n }\n }\n\n return buf || bytesToUuid(rnds);\n}\n\nmodule.exports = v4;\n","module.exports = __WEBPACK_EXTERNAL_MODULE__746__;","module.exports = __WEBPACK_EXTERNAL_MODULE__802__;","module.exports = __WEBPACK_EXTERNAL_MODULE__407__;","module.exports = __WEBPACK_EXTERNAL_MODULE__156__;","module.exports = __WEBPACK_EXTERNAL_MODULE__952__;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","// Logging callback\nlet logger = () => {};\n\n/**\n * Register the logging callback\n *\n * @param {Function} callback\n */\nfunction registerLogger(callback) {\n logger = callback;\n}\n\n/**\n * Send an alert message to the logger\n *\n * @param {String} message\n */\nfunction logAlert(message) {\n logger({message: `[Onyx] ${message}`, level: 'alert'});\n}\n\n/**\n * Send an info message to the logger\n *\n * @param {String} message\n */\nfunction logInfo(message) {\n logger({message: `[Onyx] ${message}`, level: 'info'});\n}\n\nexport {\n registerLogger,\n logInfo,\n logAlert,\n};\n","// Mostly copied from https://medium.com/@lubaka.a/how-to-remove-lodash-performance-improvement-b306669ad0e1\n\n/**\n * @param {mixed} val\n * @returns {boolean}\n*/\nfunction isMergeableObject(val) {\n const nonNullObject = val != null ? typeof val === 'object' : false;\n return (nonNullObject\n && Object.prototype.toString.call(val) !== '[object RegExp]'\n && Object.prototype.toString.call(val) !== '[object Date]');\n}\n\n/**\n * @param {Object} target\n * @param {Object} source\n * @returns {Object}\n*/\nfunction mergeObject(target, source) {\n const destination = {};\n if (isMergeableObject(target)) {\n // lodash adds a small overhead so we don't use it here\n // eslint-disable-next-line rulesdir/prefer-underscore-method\n const targetKeys = Object.keys(target);\n for (let i = 0; i < targetKeys.length; ++i) {\n const key = targetKeys[i];\n destination[key] = target[key];\n }\n }\n\n // lodash adds a small overhead so we don't use it here\n // eslint-disable-next-line rulesdir/prefer-underscore-method\n const sourceKeys = Object.keys(source);\n for (let i = 0; i < sourceKeys.length; ++i) {\n const key = sourceKeys[i];\n if (source[key] === undefined) {\n // eslint-disable-next-line no-continue\n continue;\n }\n if (!isMergeableObject(source[key]) || !target[key]) {\n destination[key] = source[key];\n } else {\n // eslint-disable-next-line no-use-before-define\n destination[key] = fastMerge(target[key], source[key]);\n }\n }\n\n return destination;\n}\n\n/**\n * @param {Object|Array} target\n * @param {Object|Array} source\n * @returns {Object|Array}\n*/\nfunction fastMerge(target, source) {\n // lodash adds a small overhead so we don't use it here\n // eslint-disable-next-line rulesdir/prefer-underscore-method\n const array = Array.isArray(source);\n if (array) {\n return source;\n }\n return mergeObject(target, source);\n}\n\nexport default fastMerge;\n","import _ from 'underscore';\nimport {deepEqual} from 'fast-equals';\nimport fastMerge from './fastMerge';\n\nconst isDefined = _.negate(_.isUndefined);\n\n/**\n * In memory cache providing data by reference\n * Encapsulates Onyx cache related functionality\n */\nclass OnyxCache {\n constructor() {\n /**\n * @private\n * Cache of all the storage keys available in persistent storage\n * @type {Set<string>}\n */\n this.storageKeys = new Set();\n\n /**\n * @private\n * Unique list of keys maintained in access order (most recent at the end)\n * @type {Set<string>}\n */\n this.recentKeys = new Set();\n\n /**\n * @private\n * A map of cached values\n * @type {Record<string, *>}\n */\n this.storageMap = {};\n\n /**\n * @private\n * Captured pending tasks for already running storage methods\n * @type {Record<string, Promise>}\n */\n this.pendingPromises = {};\n\n // bind all public methods to prevent problems with `this`\n _.bindAll(\n this,\n 'getAllKeys', 'getValue', 'hasCacheForKey', 'addKey', 'set', 'drop', 'merge',\n 'hasPendingTask', 'getTaskPromise', 'captureTask', 'removeLeastRecentlyUsedKeys',\n 'setRecentKeysLimit',\n );\n }\n\n /**\n * Get all the storage keys\n * @returns {string[]}\n */\n getAllKeys() {\n return Array.from(this.storageKeys);\n }\n\n /**\n * Get a cached value from storage\n * @param {string} key\n * @returns {*}\n */\n getValue(key) {\n this.addToAccessedKeys(key);\n return this.storageMap[key];\n }\n\n /**\n * Check whether cache has data for the given key\n * @param {string} key\n * @returns {boolean}\n */\n hasCacheForKey(key) {\n return isDefined(this.storageMap[key]);\n }\n\n /**\n * Saves a key in the storage keys list\n * Serves to keep the result of `getAllKeys` up to date\n * @param {string} key\n */\n addKey(key) {\n this.storageKeys.add(key);\n }\n\n /**\n * Set's a key value in cache\n * Adds the key to the storage keys list as well\n * @param {string} key\n * @param {*} value\n * @returns {*} value - returns the cache value\n */\n set(key, value) {\n this.addKey(key);\n this.addToAccessedKeys(key);\n this.storageMap[key] = value;\n\n return value;\n }\n\n /**\n * Forget the cached value for the given key\n * @param {string} key\n */\n drop(key) {\n delete this.storageMap[key];\n this.storageKeys.delete(key);\n this.recentKeys.delete(key);\n }\n\n /**\n * Deep merge data to cache, any non existing keys will be created\n * @param {Record<string, *>} data - a map of (cache) key - values\n */\n merge(data) {\n if (!_.isObject(data) || _.isArray(data)) {\n throw new Error('data passed to cache.merge() must be an Object of onyx key/value pairs');\n }\n\n // lodash adds a small overhead so we don't use it here\n // eslint-disable-next-line prefer-object-spread, rulesdir/prefer-underscore-method\n this.storageMap = Object.assign({}, fastMerge(this.storageMap, data));\n\n const storageKeys = this.getAllKeys();\n const mergedKeys = _.keys(data);\n this.storageKeys = new Set([...storageKeys, ...mergedKeys]);\n _.each(mergedKeys, key => this.addToAccessedKeys(key));\n }\n\n /**\n * Check whether the given task is already running\n * @param {string} taskName - unique name given for the task\n * @returns {*}\n */\n hasPendingTask(taskName) {\n return isDefined(this.pendingPromises[taskName]);\n }\n\n /**\n * Use this method to prevent concurrent calls for the same thing\n * Instead of calling the same task again use the existing promise\n * provided from this function\n * @template T\n * @param {string} taskName - unique name given for the task\n * @returns {Promise<T>}\n */\n getTaskPromise(taskName) {\n return this.pendingPromises[taskName];\n }\n\n /**\n * Capture a promise for a given task so other caller can\n * hook up to the promise if it's still pending\n * @template T\n * @param {string} taskName - unique name for the task\n * @param {Promise<T>} promise\n * @returns {Promise<T>}\n */\n captureTask(taskName, promise) {\n this.pendingPromises[taskName] = promise.finally(() => {\n delete this.pendingPromises[taskName];\n });\n\n return this.pendingPromises[taskName];\n }\n\n /**\n * @private\n * Adds a key to the top of the recently accessed keys\n * @param {string} key\n */\n addToAccessedKeys(key) {\n // Removing and re-adding a key ensures it's at the end of the list\n this.recentKeys.delete(key);\n this.recentKeys.add(key);\n }\n\n /**\n * Remove keys that don't fall into the range of recently used keys\n */\n removeLeastRecentlyUsedKeys() {\n if (this.recentKeys.size <= this.maxRecentKeysSize) {\n return;\n }\n\n // Get the last N keys by doing a negative slice\n const recentlyAccessed = [...this.recentKeys].slice(-this.maxRecentKeysSize);\n const storageKeys = _.keys(this.storageMap);\n const keysToRemove = _.difference(storageKeys, recentlyAccessed);\n\n _.each(keysToRemove, this.drop);\n }\n\n /**\n * Set the recent keys list size\n * @param {number} limit\n */\n setRecentKeysLimit(limit) {\n this.maxRecentKeysSize = limit;\n }\n\n /**\n * @param {String} key\n * @param {*} value\n * @returns {Boolean}\n */\n hasValueChanged(key, value) {\n return !deepEqual(this.storageMap[key], value);\n }\n}\n\nconst instance = new OnyxCache();\n\nexport default instance;\n","import _ from 'underscore';\n\n/**\n * Returns true if the haystack begins with the needle\n *\n * @param {String} haystack The full string to be searched\n * @param {String} needle The case-sensitive string to search for\n * @return {Boolean} Returns true if the haystack starts with the needle.\n */\nfunction startsWith(haystack, needle) {\n return _.isString(haystack)\n && _.isString(needle)\n && haystack.startsWith(needle);\n}\n\n/**\n * Checks if parameter is a string or function.\n * If it is a string, then we will just return it.\n * If it is a function, then we will call it with\n * any additional arguments and return the result.\n *\n * @param {String|Function} parameter\n * @returns {*}\n */\nfunction result(parameter, ...args) {\n return _.isFunction(parameter) ? parameter(...args) : parameter;\n}\n\nexport {startsWith, result};\n","import lodashTransform from 'lodash/transform';\nimport _ from 'underscore';\n\nlet debugSetState = false;\n\n/**\n * @param {Boolean} debug\n */\nfunction setShouldDebugSetState(debug) {\n debugSetState = debug;\n}\n\n/**\n * Deep diff between two objects. Useful for figuring out what changed about an object from one render to the next so\n * that state and props updates can be optimized.\n *\n * @param {Object} object\n * @param {Object} base\n * @return {Object}\n */\nfunction diffObject(object, base) {\n function changes(obj, comparisonObject) {\n return lodashTransform(obj, (result, value, key) => {\n if (_.isEqual(value, comparisonObject[key])) {\n return;\n }\n\n // eslint-disable-next-line no-param-reassign\n result[key] = (_.isObject(value) && _.isObject(comparisonObject[key]))\n ? changes(value, comparisonObject[key])\n : value;\n });\n }\n return changes(object, base);\n}\n\n/**\n * Provide insights into why a setState() call occurred by diffing the before and after values.\n *\n * @param {Object} mapping\n * @param {*} previousValue\n * @param {*} newValue\n * @param {String} caller\n * @param {String} [keyThatChanged]\n */\nfunction logSetStateCall(mapping, previousValue, newValue, caller, keyThatChanged) {\n if (!debugSetState) {\n return;\n }\n\n const logParams = {};\n if (keyThatChanged) {\n logParams.keyThatChanged = keyThatChanged;\n }\n if (_.isObject(newValue) && _.isObject(previousValue)) {\n logParams.difference = diffObject(previousValue, newValue);\n } else {\n logParams.previousValue = previousValue;\n logParams.newValue = newValue;\n }\n\n console.debug(`[Onyx-Debug] ${mapping.displayName} setState() called. Subscribed to key '${mapping.key}' (${caller})`, logParams);\n}\n\nexport {\n logSetStateCall,\n setShouldDebugSetState,\n};\n","import {\n set,\n keys,\n getMany,\n setMany,\n get,\n clear,\n del,\n delMany,\n createStore,\n promisifyRequest,\n} from 'idb-keyval';\nimport _ from 'underscore';\nimport fastMerge from '../../fastMerge';\n\n// We don't want to initialize the store while the JS bundle loads as idb-keyval will try to use global.indexedDB\n// which might not be available in certain environments that load the bundle (e.g. electron main process).\nlet customStoreInstance;\nconst getCustomStore = () => {\n if (!customStoreInstance) {\n customStoreInstance = createStore('OnyxDB', 'keyvaluepairs');\n }\n return customStoreInstance;\n};\n\nconst provider = {\n /**\n * Sets the value for a given key. The only requirement is that the value should be serializable to JSON string\n * @param {String} key\n * @param {*} value\n * @return {Promise<void>}\n */\n setItem: (key, value) => set(key, value, getCustomStore()),\n\n /**\n * Get multiple key-value pairs for the give array of keys in a batch.\n * This is optimized to use only one database transaction.\n * @param {String[]} keysParam\n * @return {Promise<Array<[key, value]>>}\n */\n multiGet: keysParam => getMany(keysParam, getCustomStore())\n .then(values => _.map(values, (value, index) => [keysParam[index], value])),\n\n /**\n * Multiple merging of existing and new values in a batch\n * @param {Array<[key, value]>} pairs\n * @return {Promise<void>}\n */\n multiMerge: pairs => getCustomStore()('readwrite', (store) => {\n // Note: we are using the manual store transaction here, to fit the read and update\n // of the items in one transaction to achieve best performance.\n\n const getValues = Promise.all(_.map(pairs, ([key]) => promisifyRequest(store.get(key))));\n\n return getValues.then((values) => {\n const upsertMany = _.map(pairs, ([key, value], index) => {\n const prev = values[index];\n const newValue = _.isObject(prev) ? fastMerge(prev, value) : value;\n return promisifyRequest(store.put(newValue, key));\n });\n return Promise.all(upsertMany);\n });\n }),\n\n /**\n * Merging an existing value with a new one\n * @param {String} key\n * @param {any} _changes - not used, as we rely on the pre-merged data from the `modifiedData`\n * @param {any} modifiedData - the pre-merged data from `Onyx.applyMerge`\n * @return {Promise<void>}\n */\n mergeItem(key, _changes, modifiedData) {\n return provider.multiMerge([[key, modifiedData]]);\n },\n\n /**\n * Stores multiple key-value pairs in a batch\n * @param {Array<[key, value]>} pairs\n * @return {Promise<void>}\n */\n multiSet: pairs => setMany(pairs, getCustomStore()),\n\n /**\n * Clear everything from storage and also stops the SyncQueue from adding anything more to storage\n * @returns {Promise<void>}\n */\n clear: () => clear(getCustomStore()),\n\n // This is a noop for now in order to keep clients from crashing see https://github.com/Expensify/Expensify/issues/312438\n setMemoryOnlyKeys: () => {},\n\n /**\n * Returns all keys available in storage\n * @returns {Promise<String[]>}\n */\n getAllKeys: () => keys(getCustomStore()),\n\n /**\n * Get the value of a given key or return `null` if it's not available in storage\n * @param {String} key\n * @return {Promise<*>}\n */\n getItem: key => get(key, getCustomStore()),\n\n /**\n * Remove given key and it's value from storage\n * @param {String} key\n * @returns {Promise<void>}\n */\n removeItem: key => del(key, getCustomStore()),\n\n /**\n * Remove given keys and their values from storage\n *\n * @param {Array} keysParam\n * @returns {Promise}\n */\n removeItems: keysParam => delMany(keysParam, getCustomStore()),\n\n /**\n * Gets the total bytes of the database file\n * @returns {Promise<number>}\n */\n getDatabaseSize() {\n if (!window.navigator || !window.navigator.storage) {\n throw new Error('StorageManager browser API unavailable');\n }\n\n return window.navigator.storage.estimate()\n .then(value => ({\n bytesUsed: value.usage,\n bytesRemaining: value.quota - value.usage,\n }))\n .catch((error) => {\n throw new Error(`Unable to estimate web storage quota. Original error: ${error}`);\n });\n },\n};\n\nexport default provider;\n","/**\n * This file is here to wrap IDBKeyVal with a layer that provides data-changed events like the ones that exist\n * when using LocalStorage APIs in the browser. These events are great because multiple tabs can listen for when\n * data changes and then stay up-to-date with everything happening in Onyx.\n */\nimport _ from 'underscore';\nimport Storage from './providers/IDBKeyVal';\n\nconst SYNC_ONYX = 'SYNC_ONYX';\n\n/**\n * Raise an event thorough `localStorage` to let other tabs know a value changed\n * @param {String} onyxKey\n */\nfunction raiseStorageSyncEvent(onyxKey) {\n global.localStorage.setItem(SYNC_ONYX, onyxKey);\n global.localStorage.removeItem(SYNC_ONYX, onyxKey);\n}\n\nfunction raiseStorageSyncManyKeysEvent(onyxKeys) {\n _.each(onyxKeys, (onyxKey) => {\n raiseStorageSyncEvent(onyxKey);\n });\n}\n\nconst webStorage = {\n ...Storage,\n\n /**\n * @param {Function} onStorageKeyChanged Storage synchronization mechanism keeping all opened tabs in sync\n */\n keepInstancesSync(onStorageKeyChanged) {\n // Override set, remove and clear to raise storage events that we intercept in other tabs\n this.setItem = (key, value) => Storage.setItem(key, value)\n .then(() => raiseStorageSyncEvent(key));\n\n this.removeItem = key => Storage.removeItem(key)\n .then(() => raiseStorageSyncEvent(key));\n\n this.removeItems = keys => Storage.removeItems(keys)\n .then(() => raiseStorageSyncManyKeysEvent(keys));\n\n // If we just call Storage.clear other tabs will have no idea which keys were available previously\n // so that they can call keysChanged for them. That's why we iterate over every key and raise a storage sync\n // event for each one\n this.clear = () => {\n let allKeys;\n\n // They keys must be retreived before storage is cleared or else the list of keys would be empty\n return Storage.getAllKeys()\n .then((keys) => {\n allKeys = keys;\n })\n .then(() => Storage.clear())\n .then(() => {\n // Now that storage is cleared, the storage sync event can happen which is a more atomic action\n // for other browser tabs\n _.each(allKeys, raiseStorageSyncEvent);\n });\n };\n\n // This listener will only be triggered by events coming from other tabs\n global.addEventListener('storage', (event) => {\n // Ignore events that don't originate from the SYNC_ONYX logic\n if (event.key !== SYNC_ONYX || !event.newValue) {\n return;\n }\n\n const onyxKey = event.newValue;\n Storage.getItem(onyxKey)\n .then(value => onStorageKeyChanged(onyxKey, value));\n });\n },\n};\n\nexport default webStorage;\n","import WebStorage from './WebStorage';\n\nexport default WebStorage;\n","import {connectViaExtension} from 'remotedev';\nimport _ from 'underscore';\n\nclass DevTools {\n /**\n * @callback onStateChange\n * @param {object} state\n */\n /**\n * Creates an instance of DevTools, with an internal state that mirrors the storage.\n *\n * @param {object} initialState - initial state of the storage\n * @param {onStateChange} onStateChange - callback which is triggered when we timetravel to a different registered action\n */\n constructor(initialState = {}) {\n this.state = initialState;\n this.remotedev = connectViaExtension();\n this.remotedev.init(this.state);\n }\n\n /**\n * Registers an action that updated the current state of the storage\n *\n * @param {string} type - name of the action\n * @param {any} payload - data written to the storage\n * @param {object} stateChanges - partial state that got updated after the changes\n */\n registerAction(type, payload = undefined, stateChanges = {}) {\n const newState = {\n ...this.state,\n ...stateChanges,\n };\n\n this.remotedev.send({type, payload}, newState);\n this.state = newState;\n }\n\n /**\n * This clears the internal state of the DevTools, preserving the keys not included in `keyToBeRemoved`\n *\n * @param {string[]} keysToBeRemoved\n */\n clearState(keysToBeRemoved = []) {\n const pairs = _.map(keysToBeRemoved, key => [key, undefined]);\n this.registerAction('CLEAR', undefined, _.object((pairs)));\n }\n}\n\nexport default DevTools;\n","/* eslint-disable no-continue */\nimport {deepEqual} from 'fast-equals';\nimport _ from 'underscore';\nimport * as Logger from './Logger';\nimport cache from './OnyxCache';\nimport * as Str from './Str';\nimport createDeferredTask from './createDeferredTask';\nimport fastMerge from './fastMerge';\nimport * as PerformanceUtils from './metrics/PerformanceUtils';\nimport Storage from './storage';\nimport DevTools from './DevTools';\n\n// Method constants\nconst METHOD = {\n SET: 'set',\n MERGE: 'merge',\n MERGE_COLLECTION: 'mergecollection',\n MULTI_SET: 'multiset',\n CLEAR: 'clear',\n};\n\n// Key/value store of Onyx key and arrays of values to merge\nconst mergeQueue = {};\n\n// Keeps track of the last connectionID that was used so we can keep incrementing it\nlet lastConnectionID = 0;\n\n// Holds a mapping of all the react components that want their state subscribed to a store key\nconst callbackToStateMapping = {};\n\n// Stores all of the keys that Onyx can use. Must be defined in init().\nlet onyxKeys = {};\n\n// Holds a list of keys that have been directly subscribed to or recently modified from least to most recent\nlet recentlyAccessedKeys = [];\n\n// Holds a list of keys that are safe to remove when we reach max storage. If a key does not match with\n// whatever appears in this list it will NEVER be a candidate for eviction.\nlet evictionAllowList = [];\n\nlet devTools = {\n registerAction: () => {},\n clearState: () => {},\n};\n\n// Holds a map of keys and connectionID arrays whose keys will never be automatically evicted as\n// long as we have at least one subscriber that returns false for the canEvict property.\nconst evictionBlocklist = {};\n\n// Optional user-provided key value states set when Onyx initializes or clears\nlet defaultKeyStates = {};\n\n// Connections can be made before `Onyx.init`. They would wait for this task before resolving\nconst deferredInitTask = createDeferredTask();\n\n/**\n * Uses a selector function to return a simplified version of sourceData\n * @param {Mixed} sourceData\n * @param {Function} selector Function that takes sourceData and returns a simplified version of it\n * @param {Object} [withOnyxInstanceState]\n * @returns {Mixed}\n */\nconst getSubsetOfData = (sourceData, selector, withOnyxInstanceState) => selector(sourceData, withOnyxInstanceState);\n\n/**\n * Takes a collection of items (eg. {testKey_1:{a:'a'}, testKey_2:{b:'b'}})\n * and runs it through a reducer function to return a subset of the data according to a selector.\n * The resulting collection will only contain items that are returned by the selector.\n * @param {Object} collection\n * @param {String|Function} selector (see method docs for getSubsetOfData() for full details)\n * @param {Object} [withOnyxInstanceState]\n * @returns {Object}\n */\nconst reduceCollectionWithSelector = (collection, selector, withOnyxInstanceState) => _.reduce(collection, (finalCollection, item, key) => {\n // eslint-disable-next-line no-param-reassign\n finalCollection[key] = getSubsetOfData(item, selector, withOnyxInstanceState);\n\n return finalCollection;\n}, {});\n\n/**\n * Get some data from the store\n *\n * @private\n * @param {string} key\n * @returns {Promise<*>}\n */\nfunction get(key) {\n // When we already have the value in cache - resolve right away\n if (cache.hasCacheForKey(key)) {\n return Promise.resolve(cache.getValue(key));\n }\n\n const taskName = `get:${key}`;\n\n // When a value retrieving task for this key is still running hook to it\n if (cache.hasPendingTask(taskName)) {\n return cache.getTaskPromise(taskName);\n }\n\n // Otherwise retrieve the value from storage and capture a promise to aid concurrent usages\n const promise = Storage.getItem(key)\n .then((val) => {\n cache.set(key, val);\n return val;\n })\n .catch(err => Logger.logInfo(`Unable to get item from persistent storage. Key: ${key} Error: ${err}`));\n\n return cache.captureTask(taskName, promise);\n}\n\n/**\n * Returns current key names stored in persisted storage\n * @private\n * @returns {Promise<string[]>}\n */\nfunction getAllKeys() {\n // When we've already read stored keys, resolve right away\n const storedKeys = cache.getAllKeys();\n if (storedKeys.length > 0) {\n return Promise.resolve(storedKeys);\n }\n\n const taskName = 'getAllKeys';\n\n // When a value retrieving task for all keys is still running hook to it\n if (cache.hasPendingTask(taskName)) {\n return cache.getTaskPromise(taskName);\n }\n\n // Otherwise retrieve the keys from storage and capture a promise to aid concurrent usages\n const promise = Storage.getAllKeys()\n .then((keys) => {\n _.each(keys, key => cache.addKey(key));\n return keys;\n });\n\n return cache.captureTask(taskName, promise);\n}\n\n/**\n * Checks to see if the a subscriber's supplied key\n * is associated with a collection of keys.\n *\n * @private\n * @param {String} key\n * @returns {Boolean}\n */\nfunction isCollectionKey(key) {\n return _.contains(_.values(onyxKeys.COLLECTION), key);\n}\n\n/**\n * @param {String} collectionKey\n * @param {String} key\n * @returns {Boolean}\n */\nfunction isCollectionMemberKey(collectionKey, key) {\n return Str.startsWith(key, collectionKey) && key.length > collectionKey.length;\n}\n\n/**\n * Checks to see if a provided key is the exact configured key of our connected subscriber\n * or if the provided key is a collection member key (in case our configured key is a \"collection key\")\n *\n * @private\n * @param {String} configKey\n * @param {String} key\n * @return {Boolean}\n */\nfunction isKeyMatch(configKey, key) {\n return isCollectionKey(configKey)\n ? Str.startsWith(key, configKey)\n : configKey === key;\n}\n\n/**\n * Checks to see if this key has been flagged as\n * safe for removal.\n *\n * @private\n * @param {String} testKey\n * @returns {Boolean}\n */\nfunction isSafeEvictionKey(testKey) {\n return _.some(evictionAllowList, key => isKeyMatch(key, testKey));\n}\n\n/**\n * Tries to get a value from the cache. If the value is not present in cache it will return the default value or undefined.\n * If the requested key is a collection, it will return an object with all the collection members.\n *\n * @param {String} key\n * @param {Object} mapping\n * @returns {Mixed}\n */\nfunction tryGetCachedValue(key, mapping = {}) {\n let val = cache.getValue(key);\n\n if (isCollectionKey(key)) {\n const allKeys = cache.getAllKeys();\n const matchingKeys = _.filter(allKeys, k => k.startsWith(key));\n const values = _.reduce(matchingKeys, (finalObject, matchedKey) => {\n const cachedValue = cache.getValue(matchedKey);\n if (cachedValue) {\n // This is permissible because we're in the process of constructing the final object in a reduce function.\n // eslint-disable-next-line no-param-reassign\n finalObject[matchedKey] = cachedValue;\n }\n return finalObject;\n }, {});\n if (_.isEmpty(values)) {\n return;\n }\n val = values;\n }\n\n if (mapping.selector) {\n const state = mapping.withOnyxInstance ? mapping.withOnyxInstance.state : undefined;\n if (isCollectionKey(key)) {\n return reduceCollectionWithSelector(val, mapping.selector, state);\n }\n return getSubsetOfData(val, mapping.selector, state);\n }\n\n return val;\n}\n\n/**\n * Remove a key from the recently accessed key list.\n *\n * @private\n * @param {String} key\n */\nfunction removeLastAccessedKey(key) {\n recentlyAccessedKeys = _.without(recentlyAccessedKeys, key);\n}\n\n/**\n * Add a key to the list of recently accessed keys. The least\n * recently accessed key should be at the head and the most\n * recently accessed key at the tail.\n *\n * @private\n * @param {String} key\n */\nfunction addLastAccessedKey(key) {\n // Only specific keys belong in this list since we cannot remove an entire collection.\n if (isCollectionKey(key) || !isSafeEvictionKey(key)) {\n return;\n }\n\n removeLastAccessedKey(key);\n recentlyAccessedKeys.push(key);\n}\n\n/**\n * Removes a key previously added to this list\n * which will enable it to be deleted again.\n *\n * @private\n * @param {String} key\n * @param {Number} connectionID\n */\nfunction removeFromEvictionBlockList(key, connectionID) {\n evictionBlocklist[key] = _.without(evictionBlocklist[key] || [], connectionID);\n\n // Remove the key if there are no more subscribers\n if (evictionBlocklist[key].length === 0) {\n delete evictionBlocklist[key];\n }\n}\n\n/**\n * Keys added to this list can never be deleted.\n *\n * @private\n * @param {String} key\n * @param {Number} connectionID\n */\nfunction addToEvictionBlockList(key, connectionID) {\n removeFromEvictionBlockList(key, connectionID);\n\n if (!evictionBlocklist[key]) {\n evictionBlocklist[key] = [];\n }\n\n evictionBlocklist[key].push(connectionID);\n}\n\n/**\n * Take all the keys that are safe to evict and add them to\n * the recently accessed list when initializing the app. This\n * enables keys that have not recently been accessed to be\n * removed.\n *\n * @private\n * @returns {Promise}\n */\nfunction addAllSafeEvictionKeysToRecentlyAccessedList() {\n return getAllKeys()\n .then((keys) => {\n _.each(evictionAllowList, (safeEvictionKey) => {\n _.each(keys, (key) => {\n if (!isKeyMatch(safeEvictionKey, key)) {\n return;\n }\n addLastAccessedKey(key);\n });\n });\n });\n}\n\n/**\n * @private\n * @param {String} collectionKey\n * @returns {Object}\n */\nfunction getCachedCollection(collectionKey) {\n const collectionMemberKeys = _.filter(cache.getAllKeys(), (\n storedKey => isCollectionMemberKey(collectionKey, storedKey)\n ));\n\n return _.reduce(collectionMemberKeys, (prev, curr) => {\n const cachedValue = cache.getValue(curr);\n if (!cachedValue) {\n return prev;\n }\n\n // eslint-disable-next-line no-param-reassign\n prev[curr] = cachedValue;\n return prev;\n }, {});\n}\n\n/**\n * When a collection of keys change, search for any callbacks matching the collection key and trigger those callbacks\n *\n * @private\n * @param {String} collectionKey\n * @param {Object} partialCollection - a partial collection of grouped member keys\n */\nfunction keysChanged(collectionKey, partialCollection) {\n // We are iterating over all subscribers similar to keyChanged(). However, we are looking for subscribers who are subscribing to either a collection key or\n // individual collection key member for the collection that is being updated. It is important to note that the collection parameter cane be a PARTIAL collection\n // and does not represent all of the combined keys and values for a collection key. It is just the \"new\" data that was merged in via mergeCollection().\n const stateMappingKeys = _.keys(callbackToStateMapping);\n for (let i = 0; i < stateMappingKeys.length; i++) {\n const subscriber = callbackToStateMapping[stateMappingKeys[i]];\n if (!subscriber) {\n continue;\n }\n\n // Skip iteration if we do not have a collection key or a collection member key on this subscriber\n if (!Str.startsWith(subscriber.key, collectionKey)) {\n continue;\n }\n\n /**\n * e.g. Onyx.connect({key: ONYXKEYS.COLLECTION.REPORT, callback: ...});\n */\n const isSubscribedToCollectionKey = subscriber.key === collectionKey;\n\n /**\n * e.g. Onyx.connect({key: `${ONYXKEYS.COLLECTION.REPORT}{reportID}`, callback: ...});\n */\n const isSubscribedToCollectionMemberKey = isCollectionMemberKey(collectionKey, subscriber.key);\n\n // We prepare the \"cached collection\" which is the entire collection + the new partial data that\n // was merged in via mergeCollection().\n const cachedCollection = getCachedCollection(collectionKey);\n\n // Regular Onyx.connect() subscriber found.\n if (_.isFunction(subscriber.callback)) {\n // If they are subscribed to the collection key and using waitForCollectionCallback then we'll\n // send the whole cached collection.\n if (isSubscribedToCollectionKey) {\n if (subscriber.waitForCollectionCallback) {\n subscriber.callback(cachedCollection);\n continue;\n }\n\n // If they are not using waitForCollectionCallback then we notify the subscriber with\n // the new merged data but only for any keys in the partial collection.\n const dataKeys = _.keys(partialCollection);\n for (let j = 0; j < dataKeys.length; j++) {\n const dataKey = dataKeys[j];\n subscriber.callback(cachedCollection[dataKey], dataKey);\n }\n continue;\n }\n\n // And if the subscriber is specifically only tracking a particular collection member key then we will\n // notify them with the cached data for that key only.\n if (isSubscribedToCollectionMemberKey) {\n subscriber.callback(cachedCollection[subscriber.key], subscriber.key);\n continue;\n }\n\n continue;\n }\n\n // React component subscriber found.\n if (subscriber.withOnyxInstance) {\n // We are subscribed to a collection key so we must update the data in state with the new\n // collection member key values from the partial update.\n if (isSubscribedToCollectionKey) {\n // If the subscriber has a selector, then the component's state must only be updated with the data\n // returned by the selector.\n if (subscriber.selector) {\n subscriber.withOnyxInstance.setState((prevState) => {\n const previousData = prevState[subscriber.statePropertyName];\n const newData = reduceCollectionWithSelector(cachedCollection, subscriber.selector, subscriber.withOnyxInstance.state);\n\n if (!deepEqual(previousData, newData)) {\n return {\n [subscriber.statePropertyName]: newData,\n };\n }\n return null;\n });\n continue;\n }\n\n subscriber.withOnyxInstance.setState((prevState) => {\n const finalCollection = _.clone(prevState[subscriber.statePropertyName] || {});\n const dataKeys = _.keys(partialCollection);\n for (let j = 0; j < dataKeys.length; j++) {\n const dataKey = dataKeys[j];\n finalCollection[dataKey] = cachedCollection[dataKey];\n }\n\n PerformanceUtils.logSetStateCall(subscriber, prevState[subscriber.statePropertyName], finalCollection, 'keysChanged', collectionKey);\n return {\n [subscriber.statePropertyName]: finalCollection,\n };\n });\n continue;\n }\n\n // If a React component is only interested in a single key then we can set the cached value directly to the state name.\n if (isSubscribedToCollectionMemberKey) {\n // However, we only want to update this subscriber if the partial data contains a change.\n // Otherwise, we would update them with a value they already have and trigger an unnecessary re-render.\n const dataFromCollection = partialCollection[subscriber.key];\n if (_.isUndefined(dataFromCollection)) {\n continue;\n }\n\n // If the subscriber has a selector, then the component's state must only be updated with the data\n // returned by the selector and the state should only change when the subset of data changes from what\n // it was previously.\n if (subscriber.selector) {\n subscriber.withOnyxInstance.setState((prevState) => {\n const prevData = prevState[subscriber.statePropertyName];\n const newData = getSubsetOfData(cachedCollection[subscriber.key], subscriber.selector, subscriber.withOnyxInstance.state);\n if (!deepEqual(prevData, newData)) {\n PerformanceUtils.logSetStateCall(subscriber, prevData, newData, 'keysChanged', collectionKey);\n return {\n [subscriber.statePropertyName]: newData,\n };\n }\n\n return null;\n });\n continue;\n }\n\n subscriber.withOnyxInstance.setState((prevState) => {\n const data = cachedCollection[subscriber.key];\n const previousData = prevState[subscriber.statePropertyName];\n if (data === previousData) {\n return null;\n }\n\n PerformanceUtils.logSetStateCall(subscriber, previousData, data, 'keysChanged', collectionKey);\n return {\n [subscriber.statePropertyName]: data,\n };\n });\n }\n }\n }\n}\n\n/**\n * When a key change happens, search for any callbacks matching the key or collection key and trigger those callbacks\n *\n * @example\n * keyChanged(key, value, subscriber => subscriber.initWithStoredValues === false)\n *\n * @private\n * @param {String} key\n * @param {*} data\n * @param {Function} [canUpdateSubscriber] only subscribers that pass this truth test will be updated\n */\nfunction keyChanged(key, data, canUpdateSubscriber) {\n // Add or remove this key from the recentlyAccessedKeys lists\n if (!_.isNull(data)) {\n addLastAccessedKey(key);\n } else {\n removeLastAccessedKey(key);\n }\n\n // We are iterating over all subscribers to see if they are interested in the key that has just changed. If the subscriber's key is a collection key then we will\n // notify them if the key that changed is a collection member. Or if it is a regular key notify them when there is an exact match. Depending on whether the subscriber\n // was connected via withOnyx we will call setState() directly on the withOnyx instance. If it is a regular connection we will pass the data to the provided callback.\n const stateMappingKeys = _.keys(callbackToStateMapping);\n for (let i = 0; i < stateMappingKeys.length; i++) {\n const subscriber = callbackToStateMapping[stateMappingKeys[i]];\n if (!subscriber || !isKeyMatch(subscriber.key, key) || (_.isFunction(canUpdateSubscriber) && !canUpdateSubscriber(subscriber))) {\n continue;\n }\n\n // Subscriber is a regular call to connect() and provided a callback\n if (_.isFunction(subscriber.callback)) {\n if (isCollectionKey(subscriber.key) && subscriber.waitForCollectionCallback) {\n const cachedCollection = getCachedCollection(subscriber.key);\n cachedCollection[key] = data;\n subscriber.callback(cachedCollection);\n continue;\n }\n\n subscriber.callback(data, key);\n continue;\n }\n\n // Subscriber connected via withOnyx() HOC\n if (subscriber.withOnyxInstance) {\n // Check if we are subscribing to a collection key and overwrite the collection member key value in state\n if (isCollectionKey(subscriber.key)) {\n // If the subscriber has a selector, then the consumer of this data must only be given the data\n // returned by the selector and only when the selected data has changed.\n if (subscriber.selector) {\n subscriber.withOnyxInstance.setState((prevState) => {\n const prevData = prevState[subscriber.statePropertyName];\n const newData = {\n [key]: getSubsetOfData(data, subscriber.selector, subscriber.withOnyxInstance.state),\n };\n const prevDataWithNewData = {\n ...prevData,\n ...newData,\n };\n if (!deepEqual(prevData, prevDataWithNewData)) {\n PerformanceUtils.logSetStateCall(subscriber, prevData, newData, 'keyChanged', key);\n return {\n [subscriber.statePropertyName]: prevDataWithNewData,\n };\n }\n return null;\n });\n continue;\n }\n\n subscriber.withOnyxInstance.setState((prevState) => {\n const collection = prevState[subscriber.statePropertyName] || {};\n const newCollection = {\n ...collection,\n [key]: data,\n };\n PerformanceUtils.logSetStateCall(subscriber, collection, newCollection, 'keyChanged', key);\n return {\n [subscriber.statePropertyName]: newCollection,\n };\n });\n continue;\n }\n\n // If the subscriber has a selector, then the component's state must only be updated with the data\n // returned by the selector and only if the selected data has changed.\n if (subscriber.selector) {\n subscriber.withOnyxInstance.setState((prevState) => {\n const previousValue = getSubsetOfData(prevState[subscriber.statePropertyName], subscriber.selector, subscriber.withOnyxInstance.state);\n const newValue = getSubsetOfData(data, subscriber.selector, subscriber.withOnyxInstance.state);\n if (!deepEqual(previousValue, newValue)) {\n return {\n [subscriber.statePropertyName]: newValue,\n };\n }\n return null;\n });\n continue;\n }\n\n // If we did not match on a collection key then we just set the new data to the state property\n subscriber.withOnyxInstance.setState((prevState) => {\n const previousData = prevState[subscriber.statePropertyName];\n if (previousData === data) {\n return null;\n }\n\n PerformanceUtils.logSetStateCall(subscriber, previousData, data, 'keyChanged', key);\n return {\n [subscriber.statePropertyName]: data,\n };\n });\n continue;\n }\n\n console.error('Warning: Found a matching subscriber to a key that changed, but no callback or withOnyxInstance could be found.');\n }\n}\n\n/**\n * Sends the data obtained from the keys to the connection. It either:\n * - sets state on the withOnyxInstances\n * - triggers the callback function\n *\n * @private\n * @param {Object} mapping\n * @param {Object} [mapping.withOnyxInstance]\n * @param {String} [mapping.statePropertyName]\n * @param {Function} [mapping.callback]\n * @param {String} [mapping.selector]\n * @param {*|null} val\n * @param {String} matchedKey\n */\nfunction sendDataToConnection(mapping, val, matchedKey) {\n // If the mapping no longer exists then we should not send any data.\n // This means our subscriber disconnected or withOnyx wrapped component unmounted.\n if (!callbackToStateMapping[mapping.connectionID]) {\n return;\n }\n\n if (mapping.withOnyxInstance) {\n let newData = val;\n\n // If the mapping has a selector, then the component's state must only be updated with the data\n // returned by the selector.\n if (mapping.selector) {\n if (isCollectionKey(mapping.key)) {\n newData = reduceCollectionWithSelector(val, mapping.selector, mapping.withOnyxInstance.state);\n } else {\n newData = getSubsetOfData(val, mapping.selector, mapping.withOnyxInstance.state);\n }\n }\n\n PerformanceUtils.logSetStateCall(mapping, null, newData, 'sendDataToConnection');\n mapping.withOnyxInstance.setWithOnyxState(mapping.statePropertyName, newData);\n return;\n }\n\n if (_.isFunction(mapping.callback)) {\n mapping.callback(val, matchedKey);\n }\n}\n\n/**\n * We check to see if this key is flagged as safe for eviction and add it to the recentlyAccessedKeys list so that when we\n * run out of storage the least recently accessed key can be removed.\n *\n * @private\n * @param {Object} mapping\n */\nfunction addKeyToRecentlyAccessedIfNeeded(mapping) {\n if (!isSafeEvictionKey(mapping.key)) {\n return;\n }\n\n // Try to free some cache whenever we connect to a safe eviction key\n cache.removeLeastRecentlyUsedKeys();\n\n if (mapping.withOnyxInstance && !isCollectionKey(mapping.key)) {\n // All React components subscribing to a key flagged as a safe eviction key must implement the canEvict property.\n if (_.isUndefined(mapping.canEvict)) {\n throw new Error(\n `Cannot subscribe to safe eviction key '${mapping.key}' without providing a canEvict value.`,\n );\n }\n\n addLastAccessedKey(mapping.key);\n }\n}\n\n/**\n * Gets the data for a given an array of matching keys, combines them into an object, and sends the result back to the subscriber.\n *\n * @private\n * @param {Array} matchingKeys\n * @param {Object} mapping\n */\nfunction getCollectionDataAndSendAsObject(matchingKeys, mapping) {\n Promise.all(_.map(matchingKeys, key => get(key)))\n .then(values => _.reduce(values, (finalObject, value, i) => {\n // eslint-disable-next-line no-param-reassign\n finalObject[matchingKeys[i]] = value;\n return finalObject;\n }, {}))\n .then(val => sendDataToConnection(mapping, val));\n}\n\n/**\n * Subscribes a react component's state directly to a store key\n *\n * @example\n * const connectionID = Onyx.connect({\n * key: ONYXKEYS.SESSION,\n * callback: onSessionChange,\n * });\n *\n * @param {Object} mapping the mapping information to connect Onyx to the components state\n * @param {String} mapping.key ONYXKEY to subscribe to\n * @param {String} [mapping.statePropertyName] the name of the property in the state to connect the data to\n * @param {Object} [mapping.withOnyxInstance] whose setState() method will be called with any changed data\n * This is used by React components to connect to Onyx\n * @param {Function} [mapping.callback] a method that will be called with changed data\n * This is used by any non-React code to connect to Onyx\n * @param {Boolean} [mapping.initWithStoredValues] If set to false, then no data will be prefilled into the\n * component\n * @param {Boolean} [mapping.waitForCollectionCallback] If set to true, it will return the entire collection to the callback as a single object\n * @param {Function} [mapping.selector] THIS PARAM IS ONLY USED WITH withOnyx(). If included, this will be used to subscribe to a subset of an Onyx key's data.\n * The sourceData and withOnyx state are passed to the selector and should return the simplified data. Using this setting on `withOnyx` can have very positive\n * performance benefits because the component will only re-render when the subset of data changes. Otherwise, any change of data on any property would normally\n * cause the component to re-render (and that can be expensive from a performance standpoint).\n * @returns {Number} an ID to use when calling disconnect\n */\nfunction connect(mapping) {\n const connectionID = lastConnectionID++;\n callbackToStateMapping[connectionID] = mapping;\n callbackToStateMapping[connectionID].connectionID = connectionID;\n\n if (mapping.initWithStoredValues === false) {\n return connectionID;\n }\n\n // Commit connection only after init passes\n deferredInitTask.promise\n .then(() => addKeyToRecentlyAccessedIfNeeded(mapping))\n .then(getAllKeys)\n .then((keys) => {\n // We search all the keys in storage to see if any are a \"match\" for the subscriber we are connecting so that we\n // can send data back to the subscriber. Note that multiple keys can match as a subscriber could either be\n // subscribed to a \"collection key\" or a single key.\n const matchingKeys = _.filter(keys, key => isKeyMatch(mapping.key, key));\n\n // If the key being connected to does not exist we initialize the value with null. For subscribers that connected\n // directly via connect() they will simply get a null value sent to them without any information about which key matched\n // since there are none matched. In withOnyx() we wait for all connected keys to return a value before rendering the child\n // component. This null value will be filtered out so that the connected component can utilize defaultProps.\n if (matchingKeys.length === 0) {\n sendDataToConnection(mapping, null);\n return;\n }\n\n // When using a callback subscriber we will either trigger the provided callback for each key we find or combine all values\n // into an object and just make a single call. The latter behavior is enabled by providing a waitForCollectionCallback key\n // combined with a subscription to a collection key.\n if (_.isFunction(mapping.callback)) {\n if (isCollectionKey(mapping.key)) {\n if (mapping.waitForCollectionCallback) {\n getCollectionDataAndSendAsObject(matchingKeys, mapping);\n return;\n }\n\n // We did not opt into using waitForCollectionCallback mode so the callback is called for every matching key.\n for (let i = 0; i < matchingKeys.length; i++) {\n get(matchingKeys[i]).then(val => sendDataToConnection(mapping, val, matchingKeys[i]));\n }\n return;\n }\n\n // If we are not subscribed to a collection key then there's only a single key to send an update for.\n get(mapping.key).then(val => sendDataToConnection(mapping, val, mapping.key));\n return;\n }\n\n // If we have a withOnyxInstance that means a React component has subscribed via the withOnyx() HOC and we need to\n // group collection key member data into an object.\n if (mapping.withOnyxInstance) {\n if (isCollectionKey(mapping.key)) {\n getCollectionDataAndSendAsObject(matchingKeys, mapping);\n return;\n }\n\n // If the subscriber is not using a collection key then we just send a single value back to the subscriber\n get(mapping.key).then(val => sendDataToConnection(mapping, val, mapping.key));\n return;\n }\n\n console.error('Warning: Onyx.connect() was found without a callback or withOnyxInstance');\n });\n\n // The connectionID is returned back to the caller so that it can be used to clean up the connection when it's no longer needed\n // by calling Onyx.disconnect(connectionID).\n return connectionID;\n}\n\n/**\n * Remove the listener for a react component\n * @example\n * Onyx.disconnect(connectionID);\n *\n * @param {Number} connectionID unique id returned by call to Onyx.connect()\n * @param {String} [keyToRemoveFromEvictionBlocklist]\n */\nfunction disconnect(connectionID, keyToRemoveFromEvictionBlocklist) {\n if (!callbackToStateMapping[connectionID]) {\n return;\n }\n\n // Remove this key from the eviction block list as we are no longer\n // subscribing to it and it should be safe to delete again\n if (keyToRemoveFromEvictionBlocklist) {\n removeFromEvictionBlockList(keyToRemoveFromEvictionBlocklist, connectionID);\n }\n\n delete callbackToStateMapping[connectionID];\n}\n\n/**\n * This method mostly exists for historical reasons as this library was initially designed without a memory cache and one was added later.\n * For this reason, Onyx works more similar to what you might expect from a native AsyncStorage with reads, writes, etc all becoming\n * available async. Since we have code in our main applications that might expect things to work this way it's not safe to change this\n * behavior just yet.\n *\n * @example\n * notifySubscribersOnNextTick(key, value, subscriber => subscriber.initWithStoredValues === false)\n *\n * @param {String} key\n * @param {*} value\n * @param {Function} [canUpdateSubscriber] only subscribers that pass this truth test will be updated\n */\n// eslint-disable-next-line rulesdir/no-negated-variables\nfunction notifySubscribersOnNextTick(key, value, canUpdateSubscriber) {\n Promise.resolve().then(() => keyChanged(key, value, canUpdateSubscriber));\n}\n\n/**\n * This method is similar to notifySubscribersOnNextTick but it is built for working specifically with collections\n * so that keysChanged() is triggered for the collection and not keyChanged(). If this was not done, then the\n * subscriber callbacks receive the data in a different format than they normally expect and it breaks code.\n *\n * @param {String} key\n * @param {*} value\n */\n// eslint-disable-next-line rulesdir/no-negated-variables\nfunction notifyCollectionSubscribersOnNextTick(key, value) {\n Promise.resolve().then(() => keysChanged(key, value));\n}\n\n/**\n * Remove a key from Onyx and update the subscribers\n *\n * @private\n * @param {String} key\n * @return {Promise}\n */\nfunction remove(key) {\n cache.drop(key);\n notifySubscribersOnNextTick(key, null);\n return Storage.removeItem(key).then((result) => {\n devTools.registerAction(`REMOVE/${key.toUpperCase()}`, undefined, {[key]: undefined});\n return result;\n });\n}\n\n/**\n * @private\n * @returns {Promise<void>}\n */\nfunction reportStorageQuota() {\n return Storage.getDatabaseSize()\n .then(({bytesUsed, bytesRemaining}) => {\n Logger.logInfo(`Storage Quota Check -- bytesUsed: ${bytesUsed} bytesRemaining: ${bytesRemaining}`);\n })\n .catch((dbSizeError) => {\n Logger.logAlert(`Unable to get database size. Error: ${dbSizeError}`);\n });\n}\n\n/**\n * If we fail to set or merge we must handle this by\n * evicting some data from Onyx and then retrying to do\n * whatever it is we attempted to do.\n *\n * @private\n * @param {Error} error\n * @param {Function} onyxMethod\n * @param {...any} args\n * @return {Promise}\n */\nfunction evictStorageAndRetry(error, onyxMethod, ...args) {\n Logger.logInfo(`Failed to save to storage. Error: ${error}. onyxMethod: ${onyxMethod.name}`);\n\n if (error && Str.startsWith(error.message, 'Failed to execute \\'put\\' on \\'IDBObjectStore\\'')) {\n Logger.logAlert('Attempted to set invalid data set in Onyx. Please ensure all data is serializable.');\n throw error;\n }\n\n // Find the first key that we can remove that has no subscribers in our blocklist\n const keyForRemoval = _.find(recentlyAccessedKeys, key => !evictionBlocklist[key]);\n if (!keyForRemoval) {\n // If we have no acceptable keys to remove then we are possibly trying to save mission critical data. If this is the case,\n // then we should stop retrying as there is not much the user can do to fix this. Instead of getting them stuck in an infinite loop we\n // will allow this write to be skipped.\n Logger.logAlert('Out of storage. But found no acceptable keys to remove.');\n return reportStorageQuota();\n }\n\n // Remove the least recently viewed key that is not currently being accessed and retry.\n Logger.logInfo(`Out of storage. Evicting least recently accessed key (${keyForRemoval}) and retrying.`);\n reportStorageQuota();\n return remove(keyForRemoval)\n .then(() => onyxMethod(...args));\n}\n\n/**\n * Notifys subscribers and writes current value to cache\n *\n * @param {String} key\n * @param {*} value\n * @param {Boolean} hasChanged\n * @param {String} method\n */\nfunction broadcastUpdate(key, value, hasChanged, method) {\n // Logging properties only since values could be sensitive things we don't want to log\n Logger.logInfo(`${method}() called for key: ${key}${_.isObject(value) ? ` properties: ${_.keys(value).join(',')}` : ''}`);\n\n // Update subscribers if the cached value has changed, or when the subscriber specifically requires\n // all updates regardless of value changes (indicated by initWithStoredValues set to false).\n if (hasChanged) {\n cache.set(key, value);\n } else {\n cache.addToAccessedKeys(key);\n }\n\n notifySubscribersOnNextTick(key, value, subscriber => hasChanged || subscriber.initWithStoredValues === false);\n}\n\n/**\n * @param {String} key\n * @returns {Boolean}\n */\nfunction hasPendingMergeForKey(key) {\n return Boolean(mergeQueue[key]);\n}\n\n/**\n * We generally want to remove top-level nullish values from objects written to disk and cache, because it decreases the amount of data stored in memory and on disk.\n * On native, when merging an existing value with new changes, SQLite will use JSON_PATCH, which removes top-level nullish values.\n * To be consistent with the behaviour for merge, we'll also want to remove nullish values for \"set\" operations.\n * On web, IndexedDB will keep the top-level keys along with a null value and this uses up storage and memory.\n * This method will ensure that keys for null values are removed before an object is written to disk and cache so that all platforms are storing the data in the same efficient way.\n * @private\n * @param {*} value\n * @returns {*}\n */\nfunction removeNullObjectValues(value) {\n if (_.isArray(value) || !_.isObject(value)) {\n return value;\n }\n\n return _.omit(value, objectValue => _.isNull(objectValue));\n}\n\n/**\n * Write a value to our store with the given key\n *\n * @param {String} key ONYXKEY to set\n * @param {*} value value to store\n *\n * @returns {Promise}\n */\nfunction set(key, value) {\n if (_.isNull(value)) {\n return remove(key);\n }\n\n if (hasPendingMergeForKey(key)) {\n Logger.logAlert(`Onyx.set() called after Onyx.merge() for key: ${key}. It is recommended to use set() or merge() not both.`);\n }\n\n const valueWithNullRemoved = removeNullObjectValues(value);\n\n const hasChanged = cache.hasValueChanged(key, valueWithNullRemoved);\n\n // This approach prioritizes fast UI changes without waiting for data to be stored in device storage.\n broadcastUpdate(key, value, 'set');\n broadcastUpdate(key, valueWithNullRemoved, hasChanged, 'set');\n\n // If the value has not changed, calling Storage.setItem() would be redundant and a waste of performance, so return early instead.\n if (!hasChanged) {\n return Promise.resolve();\n }\n\n return Storage.setItem(key, valueWithNullRemoved)\n .then((result) => {\n devTools.registerAction(`SET/${key.toUpperCase()}`, valueWithNullRemoved, {[key]: valueWithNullRemoved});\n return result;\n })\n .catch(error => evictStorageAndRetry(error, set, key, valueWithNullRemoved));\n}\n\n/**\n * Storage expects array like: [[\"@MyApp_user\", value_1], [\"@MyApp_key\", value_2]]\n * This method transforms an object like {'@MyApp_user': myUserValue, '@MyApp_key': myKeyValue}\n * to an array of key-value pairs in the above format\n * @private\n * @param {Record} data\n * @return {Array} an array of key - value pairs <[key, value]>\n */\nfunction prepareKeyValuePairsForStorage(data) {\n return _.map(data, (value, key) => [key, value]);\n}\n\n/**\n * Sets multiple keys and values\n *\n * @example Onyx.multiSet({'key1': 'a', 'key2': 'b'});\n *\n * @param {Object} data object keyed by ONYXKEYS and the values to set\n * @returns {Promise}\n */\nfunction multiSet(data) {\n const keyValuePairs = prepareKeyValuePairsForStorage(data);\n\n _.each(data, (val, key) => {\n // Update cache and optimistically inform subscribers on the next tick\n cache.set(key, val);\n notifySubscribersOnNextTick(key, val);\n if (_.isNull(val)) {\n devTools.registerAction(`REMOVE/${key.toUpperCase()}`, val, {[key]: undefined});\n } else {\n devTools.registerAction(`SET/${key.toUpperCase()}`, val, {[key]: val});\n }\n });\n\n return Storage.multiSet(keyValuePairs)\n .catch(error => evictStorageAndRetry(error, multiSet, data));\n}\n\n/**\n * Merges an array of changes with an existing value\n *\n * @private\n * @param {*} existingValue\n * @param {Array<*>} changes Array of changes that should be applied to the existing value\n * @returns {*}\n */\nfunction applyMerge(existingValue, changes) {\n const lastChange = _.last(changes);\n\n if (_.isArray(existingValue) || _.isArray(lastChange)) {\n return lastChange;\n }\n\n if (_.isObject(existingValue) || _.every(changes, _.isObject)) {\n // Object values are merged one after the other\n // lodash adds a small overhead so we don't use it here\n // eslint-disable-next-line prefer-object-spread, rulesdir/prefer-underscore-method\n return _.reduce(changes, (modifiedData, change) => fastMerge(modifiedData, change),\n existingValue || {});\n }\n\n // If we have anything else we can't merge it so we'll\n // simply return the last value that was queued\n return lastChange;\n}\n\n/**\n * Merge a new value into an existing value at a key.\n *\n * The types of values that can be merged are `Object` and `Array`. To set another type of value use `Onyx.set()`.\n * Values of type `Object` get merged with the old value, whilst for `Array`'s we simply replace the current value with the new one.\n *\n * Calls to `Onyx.merge()` are batched so that any calls performed in a single tick will stack in a queue and get\n * applied in the order they were called. Note: `Onyx.set()` calls do not work this way so use caution when mixing\n * `Onyx.merge()` and `Onyx.set()`.\n *\n * @example\n * Onyx.merge(ONYXKEYS.EMPLOYEE_LIST, ['Joe']); // -> ['Joe']\n * Onyx.merge(ONYXKEYS.EMPLOYEE_LIST, ['Jack']); // -> ['Joe', 'Jack']\n * Onyx.merge(ONYXKEYS.POLICY, {id: 1}); // -> {id: 1}\n * Onyx.merge(ONYXKEYS.POLICY, {name: 'My Workspace'}); // -> {id: 1, name: 'My Workspace'}\n *\n * @param {String} key ONYXKEYS key\n * @param {(Object|Array)} changes Object or Array value to merge\n * @returns {Promise}\n */\nfunction merge(key, changes) {\n // Merge attempts are batched together. The delta should be applied after a single call to get() to prevent a race condition.\n // Using the initial value from storage in subsequent merge attempts will lead to an incorrect final merged value.\n if (mergeQueue[key]) {\n mergeQueue[key].push(changes);\n return Promise.resolve();\n }\n mergeQueue[key] = [changes];\n\n return get(key)\n .then((existingValue) => {\n try {\n // We first only merge the changes, so we can provide these to the native implementation (SQLite uses only delta changes in \"JSON_PATCH\" to merge)\n let batchedChanges = applyMerge(undefined, mergeQueue[key]);\n\n // Clean up the write queue so we\n // don't apply these changes again\n delete mergeQueue[key];\n\n // After that we merge the batched changes with the existing value\n const modifiedData = removeNullObjectValues(applyMerge(existingValue, [batchedChanges]));\n\n // On native platforms we use SQLite which utilises JSON_PATCH to merge changes.\n // JSON_PATCH generally removes top-level nullish values from the stored object.\n // When there is no existing value though, SQLite will just insert the changes as a new value and thus the top-level nullish values won't be removed.\n // Therefore we need to remove nullish values from the `batchedChanges` which are sent to the SQLite, if no existing value is present.\n if (!existingValue) {\n batchedChanges = removeNullObjectValues(batchedChanges);\n }\n\n const hasChanged = cache.hasValueChanged(key, modifiedData);\n\n // This approach prioritizes fast UI changes without waiting for data to be stored in device storage.\n broadcastUpdate(key, modifiedData, hasChanged, 'merge');\n\n // If the value has not changed, calling Storage.setItem() would be redundant and a waste of performance, so return early instead.\n if (!hasChanged) {\n return Promise.resolve();\n }\n\n return Storage.mergeItem(key, batchedChanges, modifiedData).then((results) => {\n devTools.registerAction(`MERGE/${key.toUpperCase()}`, modifiedData, {[key]: modifiedData});\n return results;\n });\n } catch (error) {\n Logger.logAlert(`An error occurred while applying merge for key: ${key}, Error: ${error}`);\n }\n\n return Promise.resolve();\n });\n}\n\n/**\n * Merge user provided default key value pairs.\n * @private\n * @param {boolean} enableDevTools\n * @returns {Promise}\n */\nfunction initializeWithDefaultKeyStates(enableDevTools = false) {\n return Storage.multiGet(_.keys(defaultKeyStates))\n .then((pairs) => {\n const asObject = _.object(pairs);\n\n const merged = fastMerge(asObject, defaultKeyStates);\n cache.merge(merged);\n _.each(merged, (val, key) => keyChanged(key, val));\n if (enableDevTools) {\n devTools = new DevTools(merged);\n }\n });\n}\n\n/**\n * Clear out all the data in the store\n *\n * Note that calling Onyx.clear() and then Onyx.set() on a key with a default\n * key state may store an unexpected value in Storage.\n *\n * E.g.\n * Onyx.clear();\n * Onyx.set(ONYXKEYS.DEFAULT_KEY, 'default');\n * Storage.getItem(ONYXKEYS.DEFAULT_KEY)\n * .then((storedValue) => console.log(storedValue));\n * null is logged instead of the expected 'default'\n *\n * Onyx.set() might call Storage.setItem() before Onyx.clear() calls\n * Storage.setItem(). Use Onyx.merge() instead if possible. Onyx.merge() calls\n * Onyx.get(key) before calling Storage.setItem() via Onyx.set().\n * Storage.setItem() from Onyx.clear() will have already finished and the merged\n * value will be saved to storage after the default value.\n *\n * @param {Array} keysToPreserve is a list of ONYXKEYS that should not be cleared with the rest of the data\n * @returns {Promise<void>}\n */\nfunction clear(keysToPreserve = []) {\n return getAllKeys()\n .then((keys) => {\n const keysToBeClearedFromStorage = [];\n const keyValuesToResetAsCollection = {};\n const keyValuesToResetIndividually = {};\n\n // The only keys that should not be cleared are:\n // 1. Anything specifically passed in keysToPreserve (because some keys like language preferences, offline\n // status, or activeClients need to remain in Onyx even when signed out)\n // 2. Any keys with a default state (because they need to remain in Onyx as their default, and setting them\n // to null would cause unknown behavior)\n _.each(keys, (key) => {\n const isKeyToPreserve = _.contains(keysToPreserve, key);\n const isDefaultKey = _.has(defaultKeyStates, key);\n\n // If the key is being removed or reset to default:\n // 1. Update it in the cache\n // 2. Figure out whether it is a collection key or not,\n // since collection key subscribers need to be updated differently\n if (!isKeyToPreserve) {\n const oldValue = cache.getValue(key);\n const newValue = _.get(defaultKeyStates, key, undefined);\n if (newValue !== oldValue) {\n cache.set(key, newValue);\n const collectionKey = key.substring(0, key.indexOf('_') + 1);\n if (collectionKey) {\n if (!keyValuesToResetAsCollection[collectionKey]) {\n keyValuesToResetAsCollection[collectionKey] = {};\n }\n keyValuesToResetAsCollection[collectionKey][key] = newValue;\n } else {\n keyValuesToResetIndividually[key] = newValue;\n }\n }\n }\n\n if (isKeyToPreserve || isDefaultKey) {\n return;\n }\n\n // If it isn't preserved and doesn't have a default, we'll remove it\n keysToBeClearedFromStorage.push(key);\n });\n\n // Notify the subscribers for each key/value group so they can receive the new values\n _.each(keyValuesToResetIndividually, (value, key) => {\n notifySubscribersOnNextTick(key, value);\n });\n _.each(keyValuesToResetAsCollection, (value, key) => {\n notifyCollectionSubscribersOnNextTick(key, value);\n });\n\n const defaultKeyValueState = _.omit(defaultKeyStates, keysToPreserve);\n const defaultKeyValuePairs = _.pairs(defaultKeyValueState);\n\n // Remove only the items that we want cleared from storage, and reset others to default\n _.each(keysToBeClearedFromStorage, key => cache.drop(key));\n return Storage.removeItems(keysToBeClearedFromStorage).then(() => {\n devTools.clearState(keysToBeClearedFromStorage);\n return Storage.multiSet(defaultKeyValuePairs);\n });\n });\n}\n\n/**\n * Merges a collection based on their keys\n *\n * @example\n *\n * Onyx.mergeCollection(ONYXKEYS.COLLECTION.REPORT, {\n * [`${ONYXKEYS.COLLECTION.REPORT}1`]: report1,\n * [`${ONYXKEYS.COLLECTION.REPORT}2`]: report2,\n * });\n *\n * @param {String} collectionKey e.g. `ONYXKEYS.COLLECTION.REPORT`\n * @param {Object} collection Object collection keyed by individual collection member keys and values\n * @returns {Promise}\n */\nfunction mergeCollection(collectionKey, collection) {\n if (!_.isObject(collection) || _.isArray(collection) || _.isEmpty(collection)) {\n Logger.logInfo('mergeCollection() called with invalid or empty value. Skipping this update.');\n return Promise.resolve();\n }\n\n // Confirm all the collection keys belong to the same parent\n let hasCollectionKeyCheckFailed = false;\n _.each(collection, (_data, dataKey) => {\n if (isKeyMatch(collectionKey, dataKey)) {\n return;\n }\n\n if (process.env.NODE_ENV === 'development') {\n throw new Error(`Provided collection doesn't have all its data belonging to the same parent. CollectionKey: ${collectionKey}, DataKey: ${dataKey}`);\n }\n\n hasCollectionKeyCheckFailed = true;\n Logger.logAlert(`Provided collection doesn't have all its data belonging to the same parent. CollectionKey: ${collectionKey}, DataKey: ${dataKey}`);\n });\n\n // Gracefully handle bad mergeCollection updates so it doesn't block the merge queue\n if (hasCollectionKeyCheckFailed) {\n return Promise.resolve();\n }\n\n return getAllKeys()\n .then((persistedKeys) => {\n // Split to keys that exist in storage and keys that don't\n const [existingKeys, newKeys] = _.chain(collection)\n .keys()\n .partition(key => persistedKeys.includes(key))\n .value();\n\n const existingKeyCollection = _.pick(collection, existingKeys);\n const newCollection = _.pick(collection, newKeys);\n const keyValuePairsForExistingCollection = prepareKeyValuePairsForStorage(existingKeyCollection);\n const keyValuePairsForNewCollection = prepareKeyValuePairsForStorage(newCollection);\n\n const promises = [];\n\n // New keys will be added via multiSet while existing keys will be updated using multiMerge\n // This is because setting a key that doesn't exist yet with multiMerge will throw errors\n if (keyValuePairsForExistingCollection.length > 0) {\n promises.push(Storage.multiMerge(keyValuePairsForExistingCollection));\n }\n\n if (keyValuePairsForNewCollection.length > 0) {\n promises.push(Storage.multiSet(keyValuePairsForNewCollection));\n }\n\n // Prefill cache if necessary by calling get() on any existing keys and then merge original data to cache\n // and update all subscribers\n Promise.all(_.map(existingKeys, get)).then(() => {\n cache.merge(collection);\n keysChanged(collectionKey, collection);\n if (_.isNull(collection)) {\n devTools.registerAction(`REMOVE/${collectionKey.toUpperCase()}`, collection, {[collectionKey]: undefined});\n } else {\n devTools.registerAction(`SET/${collectionKey.toUpperCase()}`, collection, {[collectionKey]: collection});\n }\n });\n\n return Promise.all(promises)\n .catch(error => evictStorageAndRetry(error, mergeCollection, collection));\n });\n}\n\n/**\n * Insert API responses and lifecycle data into Onyx\n *\n * @param {Array} data An array of objects with shape {onyxMethod: oneOf('set', 'merge', 'mergeCollection', 'multiSet', 'clear'), key: string, value: *}\n * @returns {Promise} resolves when all operations are complete\n */\nfunction update(data) {\n // First, validate the Onyx object is in the format we expect\n _.each(data, ({onyxMethod, key, value}) => {\n if (!_.contains([METHOD.CLEAR, METHOD.SET, METHOD.MERGE, METHOD.MERGE_COLLECTION, METHOD.MULTI_SET], onyxMethod)) {\n throw new Error(`Invalid onyxMethod ${onyxMethod} in Onyx update.`);\n }\n if (onyxMethod === METHOD.MULTI_SET) {\n // For multiset, we just expect the value to be an object\n if (!_.isObject(value) || _.isArray(value) || _.isFunction(value)) {\n throw new Error('Invalid value provided in Onyx multiSet. Onyx multiSet value must be of type object.');\n }\n } else if (onyxMethod !== METHOD.CLEAR && !_.isString(key)) {\n throw new Error(`Invalid ${typeof key} key provided in Onyx update. Onyx key must be of type string.`);\n }\n });\n\n const promises = [];\n let clearPromise = Promise.resolve();\n\n _.each(data, ({onyxMethod, key, value}) => {\n switch (onyxMethod) {\n case METHOD.SET:\n promises.push(() => set(key, value));\n break;\n case METHOD.MERGE:\n promises.push(() => merge(key, value));\n break;\n case METHOD.MERGE_COLLECTION:\n promises.push(() => mergeCollection(key, value));\n break;\n case METHOD.MULTI_SET:\n promises.push(() => multiSet(value));\n break;\n case METHOD.CLEAR:\n clearPromise = clear();\n break;\n default:\n break;\n }\n });\n\n return clearPromise.then(() => Promise.all(_.map(promises, p => p())));\n}\n\n/**\n * When set these keys will not be persisted to storage\n * @param {string[]} keyList\n */\nfunction setMemoryOnlyKeys(keyList) {\n Storage.setMemoryOnlyKeys(keyList);\n\n // When in memory only mode for certain keys we do not want to ever drop items from the cache as the user will have no way to recover them again via storage.\n cache.setRecentKeysLimit(Infinity);\n}\n\n/**\n * Initialize the store with actions and listening for storage events\n *\n * @param {Object} [options={}] config object\n * @param {Object} [options.keys={}] `ONYXKEYS` constants object\n * @param {Object} [options.initialKeyStates={}] initial data to set when `init()` and `clear()` is called\n * @param {String[]} [options.safeEvictionKeys=[]] This is an array of keys\n * (individual or collection patterns) that when provided to Onyx are flagged\n * as \"safe\" for removal. Any components subscribing to these keys must also\n * implement a canEvict option. See the README for more info.\n * @param {Number} [options.maxCachedKeysCount=55] Sets how many recent keys should we try to keep in cache\n * Setting this to 0 would practically mean no cache\n * We try to free cache when we connect to a safe eviction key\n * @param {Boolean} [options.captureMetrics] Enables Onyx benchmarking and exposes the get/print/reset functions\n * @param {Boolean} [options.shouldSyncMultipleInstances] Auto synchronize storage events between multiple instances\n * of Onyx running in different tabs/windows. Defaults to true for platforms that support local storage (web/desktop)\n * @param {Boolean} [options.debugSetState] Enables debugging setState() calls to connected components.\n * @example\n * Onyx.init({\n * keys: ONYXKEYS,\n * initialKeyStates: {\n * [ONYXKEYS.SESSION]: {loading: false},\n * },\n * });\n */\nfunction init({\n keys = {},\n initialKeyStates = {},\n safeEvictionKeys = [],\n maxCachedKeysCount = 1000,\n captureMetrics = false,\n shouldSyncMultipleInstances = Boolean(global.localStorage),\n debugSetState = false,\n enableDevTools = false,\n} = {}) {\n if (captureMetrics) {\n // The code here is only bundled and applied when the captureMetrics is set\n // eslint-disable-next-line no-use-before-define\n applyDecorators();\n }\n\n if (debugSetState) {\n PerformanceUtils.setShouldDebugSetState(true);\n }\n\n if (maxCachedKeysCount > 0) {\n cache.setRecentKeysLimit(maxCachedKeysCount);\n }\n\n // Let Onyx know about all of our keys\n onyxKeys = keys;\n\n // Set our default key states to use when initializing and clearing Onyx data\n defaultKeyStates = initialKeyStates;\n\n // Let Onyx know about which keys are safe to evict\n evictionAllowList = safeEvictionKeys;\n\n // Initialize all of our keys with data provided then give green light to any pending connections\n Promise.all([\n addAllSafeEvictionKeysToRecentlyAccessedList(),\n initializeWithDefaultKeyStates(enableDevTools),\n ])\n .then(deferredInitTask.resolve);\n\n if (shouldSyncMultipleInstances && _.isFunction(Storage.keepInstancesSync)) {\n Storage.keepInstancesSync((key, value) => {\n cache.set(key, value);\n keyChanged(key, value);\n if (_.isNull(value)) {\n devTools.registerAction(`REMOVE/${key.toUpperCase()}`, value, {[key]: undefined});\n } else {\n devTools.registerAction(`SET/${key.toUpperCase()}`, value, {[key]: value});\n }\n });\n }\n}\n\nconst Onyx = {\n connect,\n disconnect,\n set,\n multiSet,\n merge,\n mergeCollection,\n update,\n clear,\n getAllKeys,\n init,\n registerLogger: Logger.registerLogger,\n addToEvictionBlockList,\n removeFromEvictionBlockList,\n isSafeEvictionKey,\n METHOD,\n setMemoryOnlyKeys,\n tryGetCachedValue,\n hasPendingMergeForKey,\n};\n\n/**\n * Apply calls statistic decorators to benchmark Onyx\n *\n * @private\n */\nfunction applyDecorators() {\n // We're requiring the script dynamically here so that it's only evaluated when decorators are used\n const decorate = require('./metrics');\n\n // Re-assign with decorated functions\n /* eslint-disable no-func-assign */\n get = decorate.decorateWithMetrics(get, 'Onyx:get');\n set = decorate.decorateWithMetrics(set, 'Onyx:set');\n multiSet = decorate.decorateWithMetrics(multiSet, 'Onyx:multiSet');\n clear = decorate.decorateWithMetrics(clear, 'Onyx:clear');\n merge = decorate.decorateWithMetrics(merge, 'Onyx:merge');\n mergeCollection = decorate.decorateWithMetrics(mergeCollection, 'Onyx:mergeCollection');\n getAllKeys = decorate.decorateWithMetrics(getAllKeys, 'Onyx:getAllKeys');\n initializeWithDefaultKeyStates = decorate.decorateWithMetrics(initializeWithDefaultKeyStates, 'Onyx:defaults');\n update = decorate.decorateWithMetrics(update, 'Onyx:update');\n /* eslint-enable */\n\n // Re-expose decorated methods\n /* eslint-disable rulesdir/prefer-actions-set-data */\n Onyx.set = set;\n Onyx.multiSet = multiSet;\n Onyx.clear = clear;\n Onyx.merge = merge;\n Onyx.mergeCollection = mergeCollection;\n Onyx.update = update;\n /* eslint-enable */\n\n // Expose stats methods on Onyx\n Onyx.getMetrics = decorate.getMetrics;\n Onyx.resetMetrics = decorate.resetMetrics;\n Onyx.printMetrics = decorate.printMetrics;\n}\n\nexport default Onyx;\n","/**\n * Create a deferred task that can be resolved when we call `resolve()`\n * The returned promise will complete when we call `resolve`\n * Useful when we want to wait for a tasks that is resolved from an external action\n *\n * @template T\n * @returns {{ resolve: function(*), promise: Promise<T|void> }}\n */\nexport default function createDeferredTask() {\n const deferred = {};\n deferred.promise = new Promise((res) => {\n deferred.resolve = res;\n });\n\n return deferred;\n}\n","/**\n * This is a higher order component that provides the ability to map a state property directly to\n * something in Onyx (a key/value store). That way, as soon as data in Onyx changes, the state will be set and the view\n * will automatically change to reflect the new data.\n */\nimport PropTypes from 'prop-types';\nimport React from 'react';\nimport _ from 'underscore';\nimport Onyx from './Onyx';\nimport * as Str from './Str';\n\n/**\n * Returns the display name of a component\n *\n * @param {object} component\n * @returns {string}\n */\nfunction getDisplayName(component) {\n return component.displayName || component.name || 'Component';\n}\n\nexport default function (mapOnyxToState) {\n // A list of keys that must be present in tempState before we can render the WrappedComponent\n const requiredKeysForInit = _.chain(mapOnyxToState)\n .omit(config => config.initWithStoredValues === false)\n .keys()\n .value();\n return (WrappedComponent) => {\n const displayName = getDisplayName(WrappedComponent);\n class withOnyx extends React.Component {\n constructor(props) {\n super(props);\n\n this.setWithOnyxState = this.setWithOnyxState.bind(this);\n\n // This stores all the Onyx connection IDs to be used when the component unmounts so everything can be\n // disconnected. It is a key value store with the format {[mapping.key]: connectionID}.\n this.activeConnectionIDs = {};\n\n const cachedState = _.reduce(mapOnyxToState, (resultObj, mapping, propertyName) => {\n const key = Str.result(mapping.key, props);\n const value = Onyx.tryGetCachedValue(key, mapping);\n\n /**\n * If we have a pending merge for a key it could mean that data is being set via Onyx.merge() and someone expects a component to have this data immediately.\n *\n * @example\n *\n * Onyx.merge('report_123', value);\n * Navigation.navigate(route); // Where \"route\" expects the \"value\" to be available immediately once rendered.\n *\n * In reality, Onyx.merge() will only update the subscriber after all merges have been batched and the previous value is retrieved via a get() (returns a promise).\n * So, we won't use the cache optimization here as it will lead us to arbitrarily defer various actions in the application code.\n */\n if (value !== undefined && !Onyx.hasPendingMergeForKey(key)) {\n // eslint-disable-next-line no-param-reassign\n resultObj[propertyName] = value;\n }\n\n return resultObj;\n }, {});\n\n // If we have all the data we need, then we can render the component immediately\n cachedState.loading = _.size(cachedState) < requiredKeysForInit.length;\n\n // Object holding the temporary initial state for the component while we load the various Onyx keys\n this.tempState = cachedState;\n\n this.state = cachedState;\n }\n\n componentDidMount() {\n // Subscribe each of the state properties to the proper Onyx key\n _.each(mapOnyxToState, (mapping, propertyName) => {\n this.connectMappingToOnyx(mapping, propertyName);\n });\n this.checkEvictableKeys();\n }\n\n componentDidUpdate(prevProps) {\n // If any of the mappings use data from the props, then when the props change, all the\n // connections need to be reconnected with the new props\n _.each(mapOnyxToState, (mapping, propertyName) => {\n const previousKey = Str.result(mapping.key, prevProps);\n const newKey = Str.result(mapping.key, this.props);\n if (previousKey !== newKey) {\n Onyx.disconnect(this.activeConnectionIDs[previousKey], previousKey);\n delete this.activeConnectionIDs[previousKey];\n this.connectMappingToOnyx(mapping, propertyName);\n }\n });\n this.checkEvictableKeys();\n }\n\n componentWillUnmount() {\n // Disconnect everything from Onyx\n _.each(mapOnyxToState, (mapping) => {\n const key = Str.result(mapping.key, this.props);\n const connectionID = this.activeConnectionIDs[key];\n Onyx.disconnect(connectionID, key);\n });\n }\n\n /**\n * This method is used externally by sendDataToConnection to prevent unnecessary renders while a component\n * still in a loading state. The temporary initial state is saved to the component instance and setState()\n * only called once all the necessary data has been collected.\n *\n * @param {String} statePropertyName\n * @param {*} val\n */\n setWithOnyxState(statePropertyName, val) {\n // We might have loaded the values for the onyx keys/mappings already from the cache.\n // In case we were able to load all the values upfront, the loading state will be false.\n // However, Onyx.js will always call setWithOnyxState, as it doesn't know that this implementation\n // already loaded the values from cache. Thus we have to check whether the value has changed\n // before we set the state to prevent unnecessary renders.\n const prevValue = this.state[statePropertyName];\n if (!this.state.loading && prevValue === val) {\n return;\n }\n\n if (!this.state.loading) {\n this.setState({[statePropertyName]: val});\n return;\n }\n\n this.tempState[statePropertyName] = val;\n\n // All state keys should exist and at least have a value of null\n if (_.some(requiredKeysForInit, key => _.isUndefined(this.tempState[key]))) {\n return;\n }\n\n // Leave untouched previous state to avoid data loss during pre-load updates.\n // This handles case when setState was called before the setWithOnyxState.\n // For example, when an Onyx property was updated by keyChanged before the call of the setWithOnyxState.\n this.setState((prevState) => {\n const remainingTempState = _.omit(this.tempState, _.keys(prevState));\n\n return ({...remainingTempState, loading: false});\n });\n\n delete this.tempState;\n }\n\n /**\n * Makes sure each Onyx key we requested has been set to state with a value of some kind.\n * We are doing this so that the wrapped component will only render when all the data\n * it needs is available to it.\n */\n checkEvictableKeys() {\n // We will add this key to our list of recently accessed keys\n // if the canEvict function returns true. This is necessary criteria\n // we MUST use to specify if a key can be removed or not.\n _.each(mapOnyxToState, (mapping) => {\n if (_.isUndefined(mapping.canEvict)) {\n return;\n }\n\n const canEvict = Str.result(mapping.canEvict, this.props);\n const key = Str.result(mapping.key, this.props);\n\n if (!Onyx.isSafeEvictionKey(key)) {\n throw new Error(`canEvict can't be used on key '${key}'. This key must explicitly be flagged as safe for removal by adding it to Onyx.init({safeEvictionKeys: []}).`);\n }\n\n if (canEvict) {\n Onyx.removeFromEvictionBlockList(key, mapping.connectionID);\n } else {\n Onyx.addToEvictionBlockList(key, mapping.connectionID);\n }\n });\n }\n\n /**\n * Takes a single mapping and binds the state of the component to the store\n *\n * @param {object} mapping\n * @param {string|function} mapping.key key to connect to. can be a string or a\n * function that takes this.props as an argument and returns a string\n * @param {string} statePropertyName the name of the state property that Onyx will add the data to\n * @param {boolean} [mapping.initWithStoredValues] If set to false, then no data will be prefilled into the\n * component\n */\n connectMappingToOnyx(mapping, statePropertyName) {\n const key = Str.result(mapping.key, this.props);\n\n // eslint-disable-next-line rulesdir/prefer-onyx-connect-in-libs\n this.activeConnectionIDs[key] = Onyx.connect({\n ...mapping,\n key,\n statePropertyName,\n withOnyxInstance: this,\n displayName,\n });\n }\n\n render() {\n if (this.state.loading) {\n return null;\n }\n\n // Remove any internal state properties used by withOnyx\n // that should not be passed to a wrapped component\n let stateToPass = _.omit(this.state, 'loading');\n stateToPass = _.omit(stateToPass, value => _.isNull(value));\n\n // Remove any null values so that React replaces them with default props\n const propsToPass = _.omit(this.props, value => _.isNull(value));\n\n // Spreading props and state is necessary in an HOC where the data cannot be predicted\n return (\n <WrappedComponent\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...propsToPass}\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...stateToPass}\n ref={this.props.forwardedRef}\n />\n );\n }\n }\n\n withOnyx.propTypes = {\n forwardedRef: PropTypes.oneOfType([\n PropTypes.func,\n // eslint-disable-next-line react/forbid-prop-types\n PropTypes.shape({current: PropTypes.object}),\n ]),\n };\n withOnyx.defaultProps = {\n forwardedRef: undefined,\n };\n withOnyx.displayName = `withOnyx(${displayName})`;\n return React.forwardRef((props, ref) => {\n const Component = withOnyx;\n // eslint-disable-next-line react/jsx-props-no-spreading\n return <Component {...props} forwardedRef={ref} />;\n });\n };\n}\n","import Onyx from './Onyx';\nimport withOnyx from './withOnyx';\n\nexport default Onyx;\nexport {withOnyx};\n"],"names":["root","factory","exports","module","require","define","amd","self","__WEBPACK_EXTERNAL_MODULE__746__","__WEBPACK_EXTERNAL_MODULE__952__","__WEBPACK_EXTERNAL_MODULE__802__","__WEBPACK_EXTERNAL_MODULE__407__","__WEBPACK_EXTERNAL_MODULE__156__","decorateWithMetrics","func","getMetrics","printMetrics","resetMetrics","freeGlobal","g","global","window","InvalidCharacterError","message","this","prototype","Error","name","error","TABLE","REGEX_SPACE_CHARACTERS","base64","input","String","test","a","b","c","buffer","padding","length","output","position","charCodeAt","charAt","replace","bitStorage","bitCounter","indexOf","fromCharCode","utils","WMap","WeakMap","keys","values","set","key","value","push","get","i","decycle","object","options","replacer","map","noCircularOption","Object","hasOwnProperty","call","withRefs","refs","derez","_value","path","nu","date","Date","$jsan","getTime","regex","RegExp","getRegexFlags","source","stringifyFunction","isNaN","Number","POSITIVE_INFINITY","NEGATIVE_INFINITY","undefined","symbolKey","Symbol","keyFor","toString","slice","Map","Array","from","JSON","stringify","Set","toJSON","keyString","Boolean","foundPath","split","join","circular","apply","nextPath","retrocycle","$","rez","item","restore","cycle","space","_options","arguments","e","decycled","isArray","parse","text","reviver","parsed","needsRetrocycle","obj","paths","pathString","match","matches","exec","getPaths","pathGetter","jsan","flags","ignoreCase","multiline","fn","customToString","str","start","end","type","rest","comma","stack","for","NaN","Infinity","console","warn","errorMessage","ListPrototype","List","ListItem","of","items","iterator","list","append","head","tail","toArray","result","next","prepend","detach","Item","ListItemPrototype","prev","ReactPropTypesSecret","emptyFunction","emptyFunctionWithReset","resetWarningCache","shim","props","propName","componentName","location","propFullName","secret","err","getShim","isRequired","ReactPropTypes","array","bool","number","string","symbol","any","arrayOf","element","elementType","instanceOf","node","objectOf","oneOf","oneOfType","shape","exact","checkPropTypes","PropTypes","__esModule","defaultSocketOptions","secure","hostname","port","autoReconnect","autoReconnectOptions","randomness","connectViaExtension","remote","__REDUX_DEVTOOLS_EXTENSION__","id","instanceId","Math","random","substr","init","state","action","_send","subscribe","listener","listeners","index","splice","unsubscribe","send","payload","socket","emit","connect","_jsan","_socketclusterClient2","_interopRequireDefault","_rnHostDetect2","_constants","default","channel","handleMessages","forEach","socketOptions","create","channelName","log","watch","on","connectToServer","transformAction","config","liftedAction","timestamp","now","getActionType","setTimeout","__fbBatchedBridgeConfig","remoteModuleConfig","passed","some","content","ServerHost","scriptURL","getByRemoteConfig","NativeModules","Constants","SourceCode","originalWarn","__DEV__","PlatformConstants","AndroidConstants","getByRNRequirePolyfill","Emitter","SCChannel","client","PENDING","SUBSCRIBED","UNSUBSCRIBED","setOptions","waitForAuth","batch","data","getState","isSubscribed","includePending","publish","callback","handler","unwatch","watchers","destroy","destroyChannel","mixin","addEventListener","event","_callbacks","once","off","removeListener","removeAllListeners","removeEventListener","cb","callbacks","args","len","hasListeners","objects","$ref","isStrict","AuthTokenExpiredError","expiry","captureStackTrace","callee","AuthTokenInvalidError","AuthTokenNotBeforeError","AuthTokenError","SilentMiddlewareBlockedError","InvalidActionError","InvalidArgumentsError","InvalidOptionsError","InvalidMessageError","SocketProtocolError","code","ServerProtocolError","HTTPServerError","ResourceLimitError","TimeoutError","BadConnectionError","BrokerError","ProcessExitError","UnknownError","socketProtocolErrorStatuses","socketProtocolIgnoreStatuses","unserializableErrorProperties","domain","domainEmitter","domainThrown","dehydrateError","includeStackTrace","dehydratedError","hydrateError","hydratedError","base64Chars","validJSONStartRegex","arrayBufferToBase64","arraybuffer","bytes","Uint8Array","substring","binaryToBase64Replacer","ArrayBuffer","Buffer","rehydratedBuffer","decode","encodedMessage","encode","rawData","SCClientSocket","clients","version","AuthEngine","_internalStorage","isLocalStorageEnabled","_checkLocalStorageEnabled","localStorage","setItem","removeItem","saveToken","token","removeToken","loadToken","authToken","getItem","scErrors","uuid","_clients","getPort","isSecureDefault","isSecure","host","protocol","opts","autoConnect","autoSubscribeOnConnect","connectTimeout","ackTimeout","timestampRequests","timestampParam","authEngine","authTokenName","binaryType","multiplex","pubSubBatchDuration","cloneData","clientMap","clientId","v4","protocolPrefix","queryString","query","queryArray","queryMap","getMultiplexId","Response","sent","_respond","responseData","rid","formatter","SCTransport","querystring","LinkedList","clone","isBrowser","CLOSED","authState","UNAUTHENTICATED","signedAuthToken","pendingReconnect","pendingReconnectTimeout","preparingPendingSubscriptions","channelPrefix","disconnectOnUnload","pingTimeout","pingTimeoutDisabled","active","_clientMap","maxTimeout","pow","verifyDuration","propertyName","_localEvents","connectAttempts","_emitBuffer","channels","_cid","callIdGenerator","reconnectOptions","initialDelay","multiplier","maxDelay","subscriptionRetryOptions","auth","codecEngine","codec","_channelEmitter","_unloadHandler","disconnect","CONNECTING","OPEN","AUTHENTICATED","ignoreStatuses","errorStatuses","_privateEventHandlerMap","undecoratedChannelName","_undecorateChannelName","_triggerChannelUnsubscribe","response","_onSCError","_changeToAuthenticatedState","oldToken","_changeToUnauthenticatedStateAndClearTokens","transport","close","getBytesReceived","deauthenticate","open","clearTimeout","_reconnectTimeoutRef","status","_onSCOpen","_onSCClose","res","_onSCEvent","reconnect","oldState","oldSignedToken","stateChangeData","newState","_extractAuthTokenData","processPendingSubscriptions","decodeBase64","encodedString","atob","encodeBase64","decodedString","btoa","encodedTokenData","tokenData","getAuthToken","getSignedAuthToken","authenticate","authStatus","isAuthenticated","authError","_tryReconnect","timeout","exponent","initialTimeout","round","_flushEmitBuffer","_suspendSubscriptions","_abortAllPendingEventsDueToBadConnection","failureType","nextNode","currentNode","eventObject","cid","cancelPendingResponse","openAbort","closeMessage","emitObject","_handleEventAckTimeout","eventNode","_emit","pubData","_decorateChannelName","_triggerChannelSubscribe","subscriptionOptions","_triggerChannelSubscribeFail","meetsAuthRequirements","_cancelPendingSubscribeCallback","_pendingSubscriptionCid","decoratedChannelName","_trySubscribe","noTimeout","_tryUnsubscribe","currentChannel","subscriptions","subs","pendingChannels","sort","ap","priority","bp","WebSocket","createWebSocket","uri","_pingTimeoutTicker","_callbackMap","_batchSendList","wsSocket","onopen","_onOpen","onclose","_onClose","reason","onmessage","_onMessage","onerror","_connectTimeoutRef","schema","_resetPingTimeout","_handshake","statusCode","_onError","force","badConnectionError","_batchTimeout","_handleEventObject","rehydratedError","readyState","sendObject","bytesReceived","packet","simpleEventObject","Function","serializeObject","formatError","sendObjectBatch","sendObjectSingle","WorkerGlobalScope","MozWebSocket","ws","protocols","_instanceof","nativeMap","nativeSet","nativePromise","_","Promise","parent","depth","includeNonEnumerable","allParents","allChildren","useBuffer","_clone","child","proto","resolve","reject","then","__isArray","__isRegExp","__getRegExpFlags","lastIndex","__isDate","isBuffer","copy","getPrototypeOf","keyChild","valueChild","entryChild","add","attrs","getOwnPropertyDescriptor","getOwnPropertySymbols","symbols","descriptor","enumerable","defineProperty","allPropertyNames","getOwnPropertyNames","__objToStr","o","re","clonePrototype","prop","qs","sep","eq","regexp","maxKeys","kstr","vstr","k","v","x","idx","decodeURIComponent","stringifyPrimitive","isFinite","ks","encodeURIComponent","v1","byteToHex","buf","offset","bth","getRandomValues","crypto","bind","msCrypto","rnds8","rnds","r","_nodeId","_clockseq","rng","bytesToUuid","_lastMSecs","_lastNSecs","clockseq","seedBytes","msecs","nsecs","dt","tl","tmh","n","ii","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","loaded","__webpack_modules__","getter","d","definition","globalThis","toStringTag","nmd","children","logger","logAlert","level","logInfo","isMergeableObject","val","fastMerge","target","destination","targetKeys","sourceKeys","mergeObject","isDefined","constructor","storageKeys","recentKeys","storageMap","pendingPromises","getAllKeys","getValue","addToAccessedKeys","hasCacheForKey","addKey","drop","delete","merge","assign","mergedKeys","hasPendingTask","taskName","getTaskPromise","captureTask","promise","finally","removeLeastRecentlyUsedKeys","size","maxRecentKeysSize","recentlyAccessed","keysToRemove","setRecentKeysLimit","limit","hasValueChanged","deepEqual","startsWith","haystack","needle","parameter","_len","_key","debugSetState","setShouldDebugSetState","debug","logSetStateCall","mapping","previousValue","newValue","caller","keyThatChanged","logParams","difference","changes","comparisonObject","lodashTransform","displayName","customStoreInstance","getCustomStore","createStore","provider","multiGet","keysParam","getMany","multiMerge","pairs","store","all","_ref","promisifyRequest","upsertMany","_ref2","put","mergeItem","_changes","modifiedData","multiSet","setMany","clear","setMemoryOnlyKeys","del","removeItems","delMany","getDatabaseSize","navigator","storage","estimate","bytesUsed","usage","bytesRemaining","quota","catch","SYNC_ONYX","raiseStorageSyncEvent","onyxKey","webStorage","Storage","keepInstancesSync","onStorageKeyChanged","onyxKeys","raiseStorageSyncManyKeysEvent","allKeys","initialState","remotedev","registerAction","stateChanges","clearState","keysToBeRemoved","METHOD","SET","MERGE","MERGE_COLLECTION","MULTI_SET","CLEAR","mergeQueue","lastConnectionID","callbackToStateMapping","recentlyAccessedKeys","evictionAllowList","devTools","evictionBlocklist","defaultKeyStates","deferredInitTask","deferred","createDeferredTask","getSubsetOfData","sourceData","selector","withOnyxInstanceState","reduceCollectionWithSelector","collection","finalCollection","cache","Logger","storedKeys","isCollectionKey","COLLECTION","isCollectionMemberKey","collectionKey","Str","isKeyMatch","configKey","isSafeEvictionKey","testKey","removeLastAccessedKey","addLastAccessedKey","removeFromEvictionBlockList","connectionID","getCachedCollection","collectionMemberKeys","storedKey","curr","cachedValue","keysChanged","partialCollection","stateMappingKeys","subscriber","isSubscribedToCollectionKey","isSubscribedToCollectionMemberKey","cachedCollection","waitForCollectionCallback","dataKeys","j","dataKey","withOnyxInstance","setState","prevState","previousData","statePropertyName","newData","PerformanceUtils","dataFromCollection","prevData","keyChanged","canUpdateSubscriber","prevDataWithNewData","newCollection","sendDataToConnection","matchedKey","setWithOnyxState","getCollectionDataAndSendAsObject","matchingKeys","finalObject","notifySubscribersOnNextTick","remove","toUpperCase","reportStorageQuota","dbSizeError","evictStorageAndRetry","onyxMethod","keyForRemoval","broadcastUpdate","hasChanged","method","initWithStoredValues","hasPendingMergeForKey","removeNullObjectValues","objectValue","valueWithNullRemoved","prepareKeyValuePairsForStorage","keyValuePairs","applyMerge","existingValue","lastChange","change","batchedChanges","results","initializeWithDefaultKeyStates","enableDevTools","asObject","merged","DevTools","keysToPreserve","keysToBeClearedFromStorage","keyValuesToResetAsCollection","keyValuesToResetIndividually","isKeyToPreserve","isDefaultKey","oldValue","notifyCollectionSubscribersOnNextTick","defaultKeyValueState","defaultKeyValuePairs","mergeCollection","hasCollectionKeyCheckFailed","_data","persistedKeys","existingKeys","newKeys","partition","includes","existingKeyCollection","keyValuePairsForExistingCollection","keyValuePairsForNewCollection","promises","update","clearPromise","_ref3","p","Onyx","canEvict","addKeyToRecentlyAccessedIfNeeded","keyToRemoveFromEvictionBlocklist","initialKeyStates","safeEvictionKeys","maxCachedKeysCount","captureMetrics","shouldSyncMultipleInstances","decorate","applyDecorators","safeEvictionKey","registerLogger","addToEvictionBlockList","keyList","tryGetCachedValue","mapOnyxToState","requiredKeysForInit","omit","WrappedComponent","component","withOnyx","React","super","activeConnectionIDs","cachedState","resultObj","loading","tempState","componentDidMount","connectMappingToOnyx","checkEvictableKeys","componentDidUpdate","prevProps","previousKey","componentWillUnmount","prevValue","render","stateToPass","propsToPass","_extends","ref","forwardedRef","propTypes","current","defaultProps","Component"],"sourceRoot":""}
1
+ {"version":3,"file":"web.min.js","mappings":";CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,EAAQG,QAAQ,eAAgBA,QAAQ,cAAeA,QAAQ,cAAeA,QAAQ,oBAAqBA,QAAQ,UAC3G,mBAAXC,QAAyBA,OAAOC,IAC9CD,OAAO,CAAC,cAAe,aAAc,aAAc,mBAAoB,SAAUJ,GACvD,iBAAZC,QACdA,QAAQ,yBAA2BD,EAAQG,QAAQ,eAAgBA,QAAQ,cAAeA,QAAQ,cAAeA,QAAQ,oBAAqBA,QAAQ,UAEtJJ,EAAK,yBAA2BC,EAAQD,EAAK,eAAgBA,EAAiB,WAAGA,EAAK,cAAeA,EAAK,oBAAqBA,EAAY,MAC5I,CATD,CASGO,MAAM,CAACC,EAAkCC,EAAkCC,EAAkCC,EAAkCC,4CCPlJ,SAASC,EAAoBC,GAAQ,OAAOA,CAAM,CAClD,SAASC,IAAc,CACvB,SAAS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KyJ,OAAOxH,GAAS+gB,IAAAA,OAAS/gB,KAGzD,OACI63B,KAAAA,cAACH,EACGqB,GAAA,GACID,EAEAD,EAAW,CACfG,IAAKj7B,KAAKyJ,MAAMyxB,eAG5B,EAcJ,OAXArB,EAASsB,UAAY,CACjBD,aAAc9vB,KAAAA,UAAoB,CAC9BA,KAAAA,KAEAA,KAAAA,MAAgB,CAACgwB,QAAShwB,KAAAA,YAGlCyuB,EAASwB,aAAe,CACpBH,kBAAcj3B,GAElB41B,EAAS9M,YAAe,YAAWA,KAC5B+M,KAAAA,YAAiB,CAACrwB,EAAOwxB,KAC5B,MAAMK,EAAYzB,EAElB,OAAOC,KAAAA,cAACwB,EAASN,GAAA,GAAKvxB,EAAK,CAAEyxB,aAAcD,IAAO,GACpD,CAEV,CC9OA","sources":["webpack://react-native-onyx/web/webpack/universalModuleDefinition","webpack://react-native-onyx/web/./lib/metrics/index.web.js","webpack://react-native-onyx/web/./node_modules/base-64/base64.js","webpack://react-native-onyx/web/./node_modules/jsan/index.js","webpack://react-native-onyx/web/./node_modules/jsan/lib/cycle.js","webpack://react-native-onyx/web/./node_modules/jsan/lib/index.js","webpack://react-native-onyx/web/./node_modules/jsan/lib/path-getter.js","webpack://react-native-onyx/web/./node_modules/jsan/lib/utils.js","webpack://react-native-onyx/web/./node_modules/linked-list/_source/linked-list.js","webpack://react-native-onyx/web/./node_modules/linked-list/index.js","webpack://react-native-onyx/web/./node_modules/prop-types/factoryWithThrowingShims.js","webpack://react-native-onyx/web/./node_modules/prop-types/index.js","webpack://react-native-onyx/web/./node_modules/prop-types/lib/ReactPropTypesSecret.js","webpack://react-native-onyx/web/./node_modules/remotedev/lib/constants.js","webpack://react-native-onyx/web/./node_modules/remotedev/lib/devTools.js","webpack://react-native-onyx/web/./node_modules/remotedev/lib/index.js","webpack://react-native-onyx/web/./node_modules/rn-host-detect/index.js","webpack://react-native-onyx/web/./node_modules/sc-channel/index.js","webpack://react-native-onyx/web/./node_modules/sc-channel/node_modules/component-emitter/index.js","webpack://react-native-onyx/web/./node_modules/sc-errors/decycle.js","webpack://react-native-onyx/web/./node_modules/sc-errors/index.js","webpack://react-native-onyx/web/./node_modules/sc-formatter/index.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/index.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/lib/auth.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/lib/factory.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/lib/response.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/lib/scclientsocket.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/lib/sctransport.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/lib/ws-browser.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/node_modules/clone/clone.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/node_modules/component-emitter/index.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/node_modules/querystring/decode.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/node_modules/querystring/encode.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/node_modules/querystring/index.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/node_modules/uuid/index.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/node_modules/uuid/lib/bytesToUuid.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/node_modules/uuid/lib/rng-browser.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/node_modules/uuid/v1.js","webpack://react-native-onyx/web/./node_modules/socketcluster-client/node_modules/uuid/v4.js","webpack://react-native-onyx/web/external umd \"fast-equals\"","webpack://react-native-onyx/web/external umd \"idb-keyval\"","webpack://react-native-onyx/web/external umd \"lodash/transform\"","webpack://react-native-onyx/web/external umd \"react\"","webpack://react-native-onyx/web/external umd \"underscore\"","webpack://react-native-onyx/web/webpack/bootstrap","webpack://react-native-onyx/web/webpack/runtime/compat get default export","webpack://react-native-onyx/web/webpack/runtime/define property getters","webpack://react-native-onyx/web/webpack/runtime/global","webpack://react-native-onyx/web/webpack/runtime/hasOwnProperty shorthand","webpack://react-native-onyx/web/webpack/runtime/make namespace object","webpack://react-native-onyx/web/webpack/runtime/node module decorator","webpack://react-native-onyx/web/./lib/Logger.js","webpack://react-native-onyx/web/./lib/fastMerge.js","webpack://react-native-onyx/web/./lib/OnyxCache.js","webpack://react-native-onyx/web/./lib/Str.js","webpack://react-native-onyx/web/./lib/metrics/PerformanceUtils.js","webpack://react-native-onyx/web/./lib/storage/providers/IDBKeyVal.js","webpack://react-native-onyx/web/./lib/storage/WebStorage.js","webpack://react-native-onyx/web/./lib/storage/index.web.js","webpack://react-native-onyx/web/./lib/DevTools.js","webpack://react-native-onyx/web/./lib/Onyx.js","webpack://react-native-onyx/web/./lib/createDeferredTask.js","webpack://react-native-onyx/web/./lib/withOnyx.js","webpack://react-native-onyx/web/./lib/index.js"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory(require(\"fast-equals\"), require(\"underscore\"), require(\"idb-keyval\"), require(\"lodash/transform\"), require(\"react\"));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([\"fast-equals\", \"underscore\", \"idb-keyval\", \"lodash/transform\", \"react\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"react-native-onyx/web\"] = factory(require(\"fast-equals\"), require(\"underscore\"), require(\"idb-keyval\"), require(\"lodash/transform\"), require(\"react\"));\n\telse\n\t\troot[\"react-native-onyx/web\"] = factory(root[\"fast-equals\"], root[\"underscore\"], root[\"idb-keyval\"], root[\"lodash/transform\"], root[\"react\"]);\n})(self, (__WEBPACK_EXTERNAL_MODULE__746__, __WEBPACK_EXTERNAL_MODULE__952__, __WEBPACK_EXTERNAL_MODULE__802__, __WEBPACK_EXTERNAL_MODULE__407__, __WEBPACK_EXTERNAL_MODULE__156__) => {\nreturn ","// For web-only implementations of Onyx, this module will just be a no-op\n\nfunction decorateWithMetrics(func) { return func; }\nfunction getMetrics() {}\nfunction printMetrics() {}\nfunction resetMetrics() {}\n\nexport {\n decorateWithMetrics,\n getMetrics,\n resetMetrics,\n printMetrics,\n};\n","/*! http://mths.be/base64 v0.1.0 by @mathias | MIT license */\n;(function(root) {\n\n\t// Detect free variables `exports`.\n\tvar freeExports = typeof exports == 'object' && exports;\n\n\t// Detect free variable `module`.\n\tvar freeModule = typeof module == 'object' && module &&\n\t\tmodule.exports == freeExports && module;\n\n\t// Detect free variable `global`, from Node.js or Browserified code, and use\n\t// it as `root`.\n\tvar freeGlobal = typeof global == 'object' && global;\n\tif (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {\n\t\troot = freeGlobal;\n\t}\n\n\t/*--------------------------------------------------------------------------*/\n\n\tvar InvalidCharacterError = function(message) {\n\t\tthis.message = message;\n\t};\n\tInvalidCharacterError.prototype = new Error;\n\tInvalidCharacterError.prototype.name = 'InvalidCharacterError';\n\n\tvar error = function(message) {\n\t\t// Note: the error messages used throughout this file match those used by\n\t\t// the native `atob`/`btoa` implementation in Chromium.\n\t\tthrow new InvalidCharacterError(message);\n\t};\n\n\tvar TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\t// http://whatwg.org/html/common-microsyntaxes.html#space-character\n\tvar REGEX_SPACE_CHARACTERS = /[\\t\\n\\f\\r ]/g;\n\n\t// `decode` is designed to be fully compatible with `atob` as described in the\n\t// HTML Standard. http://whatwg.org/html/webappapis.html#dom-windowbase64-atob\n\t// The optimized base64-decoding algorithm used is based on @atk’s excellent\n\t// implementation. https://gist.github.com/atk/1020396\n\tvar decode = function(input) {\n\t\tinput = String(input)\n\t\t\t.replace(REGEX_SPACE_CHARACTERS, '');\n\t\tvar length = input.length;\n\t\tif (length % 4 == 0) {\n\t\t\tinput = input.replace(/==?$/, '');\n\t\t\tlength = input.length;\n\t\t}\n\t\tif (\n\t\t\tlength % 4 == 1 ||\n\t\t\t// http://whatwg.org/C#alphanumeric-ascii-characters\n\t\t\t/[^+a-zA-Z0-9/]/.test(input)\n\t\t) {\n\t\t\terror(\n\t\t\t\t'Invalid character: the string to be decoded is not correctly encoded.'\n\t\t\t);\n\t\t}\n\t\tvar bitCounter = 0;\n\t\tvar bitStorage;\n\t\tvar buffer;\n\t\tvar output = '';\n\t\tvar position = -1;\n\t\twhile (++position < length) {\n\t\t\tbuffer = TABLE.indexOf(input.charAt(position));\n\t\t\tbitStorage = bitCounter % 4 ? bitStorage * 64 + buffer : buffer;\n\t\t\t// Unless this is the first of a group of 4 characters…\n\t\t\tif (bitCounter++ % 4) {\n\t\t\t\t// …convert the first 8 bits to a single ASCII character.\n\t\t\t\toutput += String.fromCharCode(\n\t\t\t\t\t0xFF & bitStorage >> (-2 * bitCounter & 6)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn output;\n\t};\n\n\t// `encode` is designed to be fully compatible with `btoa` as described in the\n\t// HTML Standard: http://whatwg.org/html/webappapis.html#dom-windowbase64-btoa\n\tvar encode = function(input) {\n\t\tinput = String(input);\n\t\tif (/[^\\0-\\xFF]/.test(input)) {\n\t\t\t// Note: no need to special-case astral symbols here, as surrogates are\n\t\t\t// matched, and the input is supposed to only contain ASCII anyway.\n\t\t\terror(\n\t\t\t\t'The string to be encoded contains characters outside of the ' +\n\t\t\t\t'Latin1 range.'\n\t\t\t);\n\t\t}\n\t\tvar padding = input.length % 3;\n\t\tvar output = '';\n\t\tvar position = -1;\n\t\tvar a;\n\t\tvar b;\n\t\tvar c;\n\t\tvar d;\n\t\tvar buffer;\n\t\t// Make sure any padding is handled outside of the loop.\n\t\tvar length = input.length - padding;\n\n\t\twhile (++position < length) {\n\t\t\t// Read three bytes, i.e. 24 bits.\n\t\t\ta = input.charCodeAt(position) << 16;\n\t\t\tb = input.charCodeAt(++position) << 8;\n\t\t\tc = input.charCodeAt(++position);\n\t\t\tbuffer = a + b + c;\n\t\t\t// Turn the 24 bits into four chunks of 6 bits each, and append the\n\t\t\t// matching character for each of them to the output.\n\t\t\toutput += (\n\t\t\t\tTABLE.charAt(buffer >> 18 & 0x3F) +\n\t\t\t\tTABLE.charAt(buffer >> 12 & 0x3F) +\n\t\t\t\tTABLE.charAt(buffer >> 6 & 0x3F) +\n\t\t\t\tTABLE.charAt(buffer & 0x3F)\n\t\t\t);\n\t\t}\n\n\t\tif (padding == 2) {\n\t\t\ta = input.charCodeAt(position) << 8;\n\t\t\tb = input.charCodeAt(++position);\n\t\t\tbuffer = a + b;\n\t\t\toutput += (\n\t\t\t\tTABLE.charAt(buffer >> 10) +\n\t\t\t\tTABLE.charAt((buffer >> 4) & 0x3F) +\n\t\t\t\tTABLE.charAt((buffer << 2) & 0x3F) +\n\t\t\t\t'='\n\t\t\t);\n\t\t} else if (padding == 1) {\n\t\t\tbuffer = input.charCodeAt(position);\n\t\t\toutput += (\n\t\t\t\tTABLE.charAt(buffer >> 2) +\n\t\t\t\tTABLE.charAt((buffer << 4) & 0x3F) +\n\t\t\t\t'=='\n\t\t\t);\n\t\t}\n\n\t\treturn output;\n\t};\n\n\tvar base64 = {\n\t\t'encode': encode,\n\t\t'decode': decode,\n\t\t'version': '0.1.0'\n\t};\n\n\t// Some AMD build optimizers, like r.js, check for specific condition patterns\n\t// like the following:\n\tif (\n\t\ttypeof define == 'function' &&\n\t\ttypeof define.amd == 'object' &&\n\t\tdefine.amd\n\t) {\n\t\tdefine(function() {\n\t\t\treturn base64;\n\t\t});\n\t}\telse if (freeExports && !freeExports.nodeType) {\n\t\tif (freeModule) { // in Node.js or RingoJS v0.8.0+\n\t\t\tfreeModule.exports = base64;\n\t\t} else { // in Narwhal or RingoJS v0.7.0-\n\t\t\tfor (var key in base64) {\n\t\t\t\tbase64.hasOwnProperty(key) && (freeExports[key] = base64[key]);\n\t\t\t}\n\t\t}\n\t} else { // in Rhino or a web browser\n\t\troot.base64 = base64;\n\t}\n\n}(this));\n","module.exports = require('./lib');\n","var pathGetter = require('./path-getter');\nvar utils = require('./utils');\n\nvar WMap = typeof WeakMap !== 'undefined'?\n WeakMap:\n function() {\n var keys = [];\n var values = [];\n return {\n set: function(key, value) {\n keys.push(key);\n values.push(value);\n },\n get: function(key) {\n for (var i = 0; i < keys.length; i++) {\n if (keys[i] === key) {\n return values[i];\n }\n }\n }\n }\n };\n\n// Based on https://github.com/douglascrockford/JSON-js/blob/master/cycle.js\n\nexports.decycle = function decycle(object, options, replacer, map) {\n 'use strict';\n\n map = map || new WMap();\n\n var noCircularOption = !Object.prototype.hasOwnProperty.call(options, 'circular');\n var withRefs = options.refs !== false;\n\n return (function derez(_value, path, key) {\n\n // The derez recurses through the object, producing the deep copy.\n\n var i, // The loop counter\n name, // Property name\n nu; // The new object or array\n\n // typeof null === 'object', so go on if this value is really an object but not\n // one of the weird builtin objects.\n\n var value = typeof replacer === 'function' ? replacer(key || '', _value) : _value;\n\n if (options.date && value instanceof Date) {\n return {$jsan: 'd' + value.getTime()};\n }\n if (options.regex && value instanceof RegExp) {\n return {$jsan: 'r' + utils.getRegexFlags(value) + ',' + value.source};\n }\n if (options['function'] && typeof value === 'function') {\n return {$jsan: 'f' + utils.stringifyFunction(value, options['function'])}\n }\n if (options['nan'] && typeof value === 'number' && isNaN(value)) {\n return {$jsan: 'n'}\n }\n if (options['infinity']) {\n if (Number.POSITIVE_INFINITY === value) return {$jsan: 'i'}\n if (Number.NEGATIVE_INFINITY === value) return {$jsan: 'y'}\n }\n if (options['undefined'] && value === undefined) {\n return {$jsan: 'u'}\n }\n if (options['error'] && value instanceof Error) {\n return {$jsan: 'e' + value.message}\n }\n if (options['symbol'] && typeof value === 'symbol') {\n var symbolKey = Symbol.keyFor(value)\n if (symbolKey !== undefined) {\n return {$jsan: 'g' + symbolKey}\n }\n\n // 'Symbol(foo)'.slice(7, -1) === 'foo'\n return {$jsan: 's' + value.toString().slice(7, -1)}\n }\n\n if (options['map'] && typeof Map === 'function' && value instanceof Map && typeof Array.from === 'function') {\n return {$jsan: 'm' + JSON.stringify(decycle(Array.from(value), options, replacer, map))}\n }\n\n if (options['set'] && typeof Set === 'function' && value instanceof Set && typeof Array.from === 'function') {\n return {$jsan: 'l' + JSON.stringify(decycle(Array.from(value), options, replacer, map))}\n }\n\n if (value && typeof value.toJSON === 'function') {\n try {\n value = value.toJSON(key);\n } catch (error) {\n var keyString = (key || '$');\n return \"toJSON failed for '\" + (map.get(value) || keyString) + \"'\";\n }\n }\n\n if (typeof value === 'object' && value !== null &&\n !(value instanceof Boolean) &&\n !(value instanceof Date) &&\n !(value instanceof Number) &&\n !(value instanceof RegExp) &&\n !(value instanceof String) &&\n !(typeof value === 'symbol') &&\n !(value instanceof Error)) {\n\n // If the value is an object or array, look to see if we have already\n // encountered it. If so, return a $ref/path object.\n\n if (typeof value === 'object') {\n var foundPath = map.get(value);\n if (foundPath) {\n if (noCircularOption && withRefs) {\n return {$jsan: foundPath};\n }\n \n // This is only a true circular reference if the parent path is inside of foundPath\n // drop the last component of the current path and check if it starts with foundPath\n var parentPath = path.split('.').slice(0, -1).join('.');\n if (parentPath.indexOf(foundPath) === 0) {\n if (!noCircularOption) {\n return typeof options.circular === 'function'?\n options.circular(value, path, foundPath):\n options.circular;\n }\n return {$jsan: foundPath};\n }\n if (withRefs) return {$jsan: foundPath};\n }\n map.set(value, path);\n }\n\n\n // If it is an array, replicate the array.\n\n if (Object.prototype.toString.apply(value) === '[object Array]') {\n nu = [];\n for (i = 0; i < value.length; i += 1) {\n nu[i] = derez(value[i], path + '[' + i + ']', i);\n }\n } else {\n\n // If it is an object, replicate the object.\n\n nu = {};\n for (name in value) {\n if (Object.prototype.hasOwnProperty.call(value, name)) {\n var nextPath = /^\\w+$/.test(name) ?\n '.' + name :\n '[' + JSON.stringify(name) + ']';\n nu[name] = name === '$jsan' ? [derez(value[name], path + nextPath)] : derez(value[name], path + nextPath, name);\n }\n }\n }\n return nu;\n }\n return value;\n }(object, '$'));\n};\n\n\nexports.retrocycle = function retrocycle($) {\n 'use strict';\n\n\n return (function rez(value) {\n\n // The rez function walks recursively through the object looking for $jsan\n // properties. When it finds one that has a value that is a path, then it\n // replaces the $jsan object with a reference to the value that is found by\n // the path.\n\n var i, item, name, path;\n\n if (value && typeof value === 'object') {\n if (Object.prototype.toString.apply(value) === '[object Array]') {\n for (i = 0; i < value.length; i += 1) {\n item = value[i];\n if (item && typeof item === 'object') {\n if (item.$jsan) {\n value[i] = utils.restore(item.$jsan, $);\n } else {\n rez(item);\n }\n }\n }\n } else {\n for (name in value) {\n // base case passed raw object\n if(typeof value[name] === 'string' && name === '$jsan'){\n return utils.restore(value.$jsan, $);\n break;\n }\n else {\n if (name === '$jsan') {\n value[name] = value[name][0];\n }\n if (typeof value[name] === 'object') {\n item = value[name];\n if (item && typeof item === 'object') {\n if (item.$jsan) {\n value[name] = utils.restore(item.$jsan, $);\n } else {\n rez(item);\n }\n }\n }\n }\n }\n }\n }\n return value;\n }($));\n};\n","var cycle = require('./cycle');\n\nexports.stringify = function stringify(value, replacer, space, _options) {\n\n if (arguments.length < 4) {\n try {\n if (arguments.length === 1) {\n return JSON.stringify(value);\n } else {\n return JSON.stringify.apply(JSON, arguments);\n }\n } catch (e) {}\n }\n\n var options = _options || false;\n if (typeof options === 'boolean') {\n options = {\n 'date': options,\n 'function': options,\n 'regex': options,\n 'undefined': options,\n 'error': options,\n 'symbol': options,\n 'map': options,\n 'set': options,\n 'nan': options,\n 'infinity': options\n }\n }\n\n var decycled = cycle.decycle(value, options, replacer);\n if (arguments.length === 1) {\n return JSON.stringify(decycled);\n } else {\n // decycle already handles when replacer is a function.\n return JSON.stringify(decycled, Array.isArray(replacer) ? replacer : null, space);\n }\n}\n\nexports.parse = function parse(text, reviver) {\n var needsRetrocycle = /\"\\$jsan\"/.test(text);\n var parsed;\n if (arguments.length === 1) {\n parsed = JSON.parse(text);\n } else {\n parsed = JSON.parse(text, reviver);\n }\n if (needsRetrocycle) {\n parsed = cycle.retrocycle(parsed);\n }\n return parsed;\n}\n","module.exports = pathGetter;\n\nfunction pathGetter(obj, path) {\n if (path !== '$') {\n var paths = getPaths(path);\n for (var i = 0; i < paths.length; i++) {\n path = paths[i].toString().replace(/\\\\\"/g, '\"');\n if (typeof obj[path] === 'undefined' && i !== paths.length - 1) continue;\n obj = obj[path];\n }\n }\n return obj;\n}\n\nfunction getPaths(pathString) {\n var regex = /(?:\\.(\\w+))|(?:\\[(\\d+)\\])|(?:\\[\"((?:[^\\\\\"]|\\\\.)*)\"\\])/g;\n var matches = [];\n var match;\n while (match = regex.exec(pathString)) {\n matches.push( match[1] || match[2] || match[3] );\n }\n return matches;\n}\n","var pathGetter = require('./path-getter');\nvar jsan = require('./');\n\nexports.getRegexFlags = function getRegexFlags(regex) {\n var flags = '';\n if (regex.ignoreCase) flags += 'i';\n if (regex.global) flags += 'g';\n if (regex.multiline) flags += 'm';\n return flags;\n};\n\nexports.stringifyFunction = function stringifyFunction(fn, customToString) {\n if (typeof customToString === 'function') {\n return customToString(fn);\n }\n var str = fn.toString();\n var match = str.match(/^[^{]*{|^[^=]*=>/);\n var start = match ? match[0] : '<function> ';\n var end = str[str.length - 1] === '}' ? '}' : '';\n return start.replace(/\\r\\n|\\n/g, ' ').replace(/\\s+/g, ' ') + ' /* ... */ ' + end;\n};\n\nexports.restore = function restore(obj, root) {\n var type = obj[0];\n var rest = obj.slice(1);\n switch(type) {\n case '$':\n return pathGetter(root, obj);\n case 'r':\n var comma = rest.indexOf(',');\n var flags = rest.slice(0, comma);\n var source = rest.slice(comma + 1);\n return RegExp(source, flags);\n case 'd':\n return new Date(+rest);\n case 'f':\n var fn = function() { throw new Error(\"can't run jsan parsed function\") };\n fn.toString = function() { return rest; };\n return fn;\n case 'u':\n return undefined;\n case 'e':\n var error = new Error(rest);\n error.stack = 'Stack is unavailable for jsan parsed errors';\n return error;\n case 's':\n return Symbol(rest);\n case 'g':\n return Symbol.for(rest);\n case 'm':\n return new Map(jsan.parse(rest));\n case 'l':\n return new Set(jsan.parse(rest));\n case 'n':\n return NaN;\n case 'i':\n return Infinity;\n case 'y':\n return -Infinity;\n default:\n console.warn('unknown type', obj);\n return obj;\n }\n}\n","'use strict';\n\n/**\n * Constants.\n */\n\nvar errorMessage;\n\nerrorMessage = 'An argument without append, prepend, ' +\n 'or detach methods was given to `List';\n\n/**\n * Creates a new List: A linked list is a bit like an Array, but\n * knows nothing about how many items are in it, and knows only about its\n * first (`head`) and last (`tail`) items. Each item (e.g. `head`, `tail`,\n * &c.) knows which item comes before or after it (its more like the\n * implementation of the DOM in JavaScript).\n * @global\n * @private\n * @constructor\n * @class Represents an instance of List.\n */\n\nfunction List(/*items...*/) {\n if (arguments.length) {\n return List.from(arguments);\n }\n}\n\nvar ListPrototype;\n\nListPrototype = List.prototype;\n\n/**\n * Creates a new list from the arguments (each a list item) passed in.\n * @name List.of\n * @param {...ListItem} [items] - Zero or more items to attach.\n * @returns {list} - A new instance of List.\n */\n\nList.of = function (/*items...*/) {\n return List.from.call(this, arguments);\n};\n\n/**\n * Creates a new list from the given array-like object (each a list item)\n * passed in.\n * @name List.from\n * @param {ListItem[]} [items] - The items to append.\n * @returns {list} - A new instance of List.\n */\nList.from = function (items) {\n var list = new this(), length, iterator, item;\n\n if (items && (length = items.length)) {\n iterator = -1;\n\n while (++iterator < length) {\n item = items[iterator];\n\n if (item !== null && item !== undefined) {\n list.append(item);\n }\n }\n }\n\n return list;\n};\n\n/**\n * List#head\n * Default to `null`.\n */\nListPrototype.head = null;\n\n/**\n * List#tail\n * Default to `null`.\n */\nListPrototype.tail = null;\n\n/**\n * Returns the list's items as an array. This does *not* detach the items.\n * @name List#toArray\n * @returns {ListItem[]} - An array of (still attached) ListItems.\n */\nListPrototype.toArray = function () {\n var item = this.head,\n result = [];\n\n while (item) {\n result.push(item);\n item = item.next;\n }\n\n return result;\n};\n\n/**\n * Prepends the given item to the list: Item will be the new first item\n * (`head`).\n * @name List#prepend\n * @param {ListItem} item - The item to prepend.\n * @returns {ListItem} - An instance of ListItem (the given item).\n */\nListPrototype.prepend = function (item) {\n if (!item) {\n return false;\n }\n\n if (!item.append || !item.prepend || !item.detach) {\n throw new Error(errorMessage + '#prepend`.');\n }\n\n var self, head;\n\n // Cache self.\n self = this;\n\n // If self has a first item, defer prepend to the first items prepend\n // method, and return the result.\n head = self.head;\n\n if (head) {\n return head.prepend(item);\n }\n\n // ...otherwise, there is no `head` (or `tail`) item yet.\n\n // Detach the prependee.\n item.detach();\n\n // Set the prependees parent list to reference self.\n item.list = self;\n\n // Set self's first item to the prependee, and return the item.\n self.head = item;\n\n return item;\n};\n\n/**\n * Appends the given item to the list: Item will be the new last item (`tail`)\n * if the list had a first item, and its first item (`head`) otherwise.\n * @name List#append\n * @param {ListItem} item - The item to append.\n * @returns {ListItem} - An instance of ListItem (the given item).\n */\n\nListPrototype.append = function (item) {\n if (!item) {\n return false;\n }\n\n if (!item.append || !item.prepend || !item.detach) {\n throw new Error(errorMessage + '#append`.');\n }\n\n var self, head, tail;\n\n // Cache self.\n self = this;\n\n // If self has a last item, defer appending to the last items append\n // method, and return the result.\n tail = self.tail;\n\n if (tail) {\n return tail.append(item);\n }\n\n // If self has a first item, defer appending to the first items append\n // method, and return the result.\n head = self.head;\n\n if (head) {\n return head.append(item);\n }\n\n // ...otherwise, there is no `tail` or `head` item yet.\n\n // Detach the appendee.\n item.detach();\n\n // Set the appendees parent list to reference self.\n item.list = self;\n\n // Set self's first item to the appendee, and return the item.\n self.head = item;\n\n return item;\n};\n\n/**\n * Creates a new ListItem: A linked list item is a bit like DOM node:\n * It knows only about its \"parent\" (`list`), the item before it (`prev`),\n * and the item after it (`next`).\n * @global\n * @private\n * @constructor\n * @class Represents an instance of ListItem.\n */\n\nfunction ListItem() {}\n\nList.Item = ListItem;\n\nvar ListItemPrototype = ListItem.prototype;\n\nListItemPrototype.next = null;\n\nListItemPrototype.prev = null;\n\nListItemPrototype.list = null;\n\n/**\n * Detaches the item operated on from its parent list.\n * @name ListItem#detach\n * @returns {ListItem} - The item operated on.\n */\nListItemPrototype.detach = function () {\n // Cache self, the parent list, and the previous and next items.\n var self = this,\n list = self.list,\n prev = self.prev,\n next = self.next;\n\n // If the item is already detached, return self.\n if (!list) {\n return self;\n }\n\n // If self is the last item in the parent list, link the lists last item\n // to the previous item.\n if (list.tail === self) {\n list.tail = prev;\n }\n\n // If self is the first item in the parent list, link the lists first item\n // to the next item.\n if (list.head === self) {\n list.head = next;\n }\n\n // If both the last and first items in the parent list are the same,\n // remove the link to the last item.\n if (list.tail === list.head) {\n list.tail = null;\n }\n\n // If a previous item exists, link its next item to selfs next item.\n if (prev) {\n prev.next = next;\n }\n\n // If a next item exists, link its previous item to selfs previous item.\n if (next) {\n next.prev = prev;\n }\n\n // Remove links from self to both the next and previous items, and to the\n // parent list.\n self.prev = self.next = self.list = null;\n\n // Return self.\n return self;\n};\n\n/**\n * Prepends the given item *before* the item operated on.\n * @name ListItem#prepend\n * @param {ListItem} item - The item to prepend.\n * @returns {ListItem} - The item operated on, or false when that item is not\n * attached.\n */\nListItemPrototype.prepend = function (item) {\n if (!item || !item.append || !item.prepend || !item.detach) {\n throw new Error(errorMessage + 'Item#prepend`.');\n }\n\n // Cache self, the parent list, and the previous item.\n var self = this,\n list = self.list,\n prev = self.prev;\n\n // If self is detached, return false.\n if (!list) {\n return false;\n }\n\n // Detach the prependee.\n item.detach();\n\n // If self has a previous item...\n if (prev) {\n // ...link the prependees previous item, to selfs previous item.\n item.prev = prev;\n\n // ...link the previous items next item, to self.\n prev.next = item;\n }\n\n // Set the prependees next item to self.\n item.next = self;\n\n // Set the prependees parent list to selfs parent list.\n item.list = list;\n\n // Set the previous item of self to the prependee.\n self.prev = item;\n\n // If self is the first item in the parent list, link the lists first item\n // to the prependee.\n if (self === list.head) {\n list.head = item;\n }\n\n // If the the parent list has no last item, link the lists last item to\n // self.\n if (!list.tail) {\n list.tail = self;\n }\n\n // Return the prependee.\n return item;\n};\n\n/**\n * Appends the given item *after* the item operated on.\n * @name ListItem#append\n * @param {ListItem} item - The item to append.\n * @returns {ListItem} - The item operated on, or false when that item is not\n * attached.\n */\nListItemPrototype.append = function (item) {\n // If item is falsey, return false.\n if (!item || !item.append || !item.prepend || !item.detach) {\n throw new Error(errorMessage + 'Item#append`.');\n }\n\n // Cache self, the parent list, and the next item.\n var self = this,\n list = self.list,\n next = self.next;\n\n // If self is detached, return false.\n if (!list) {\n return false;\n }\n\n // Detach the appendee.\n item.detach();\n\n // If self has a next item...\n if (next) {\n // ...link the appendees next item, to selfs next item.\n item.next = next;\n\n // ...link the next items previous item, to the appendee.\n next.prev = item;\n }\n\n // Set the appendees previous item to self.\n item.prev = self;\n\n // Set the appendees parent list to selfs parent list.\n item.list = list;\n\n // Set the next item of self to the appendee.\n self.next = item;\n\n // If the the parent list has no last item or if self is the parent lists\n // last item, link the lists last item to the appendee.\n if (self === list.tail || !list.tail) {\n list.tail = item;\n }\n\n // Return the appendee.\n return item;\n};\n\n/**\n * Expose `List`.\n */\n\nmodule.exports = List;\n","'use strict';\n\nmodule.exports = require('./_source/linked-list.js');\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nvar ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');\n\nfunction emptyFunction() {}\nfunction emptyFunctionWithReset() {}\nemptyFunctionWithReset.resetWarningCache = emptyFunction;\n\nmodule.exports = function() {\n function shim(props, propName, componentName, location, propFullName, secret) {\n if (secret === ReactPropTypesSecret) {\n // It is still safe when called from React.\n return;\n }\n var err = new Error(\n 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +\n 'Use PropTypes.checkPropTypes() to call them. ' +\n 'Read more at http://fb.me/use-check-prop-types'\n );\n err.name = 'Invariant Violation';\n throw err;\n };\n shim.isRequired = shim;\n function getShim() {\n return shim;\n };\n // Important!\n // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.\n var ReactPropTypes = {\n array: shim,\n bool: shim,\n func: shim,\n number: shim,\n object: shim,\n string: shim,\n symbol: shim,\n\n any: shim,\n arrayOf: getShim,\n element: shim,\n elementType: shim,\n instanceOf: getShim,\n node: shim,\n objectOf: getShim,\n oneOf: getShim,\n oneOfType: getShim,\n shape: getShim,\n exact: getShim,\n\n checkPropTypes: emptyFunctionWithReset,\n resetWarningCache: emptyFunction\n };\n\n ReactPropTypes.PropTypes = ReactPropTypes;\n\n return ReactPropTypes;\n};\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nif (process.env.NODE_ENV !== 'production') {\n var ReactIs = require('react-is');\n\n // By explicitly using `prop-types` you are opting into new development behavior.\n // http://fb.me/prop-types-in-prod\n var throwOnDirectAccess = true;\n module.exports = require('./factoryWithTypeCheckers')(ReactIs.isElement, throwOnDirectAccess);\n} else {\n // By explicitly using `prop-types` you are opting into new production behavior.\n // http://fb.me/prop-types-in-prod\n module.exports = require('./factoryWithThrowingShims')();\n}\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nvar ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';\n\nmodule.exports = ReactPropTypesSecret;\n","'use strict';\n\nexports.__esModule = true;\nvar defaultSocketOptions = exports.defaultSocketOptions = {\n secure: true,\n hostname: 'remotedev.io',\n port: 443,\n autoReconnect: true,\n autoReconnectOptions: {\n randomness: 60000\n }\n};","'use strict';\n\nexports.__esModule = true;\nexports.send = undefined;\nexports.extractState = extractState;\nexports.generateId = generateId;\nexports.start = start;\nexports.connect = connect;\nexports.connectViaExtension = connectViaExtension;\n\nvar _jsan = require('jsan');\n\nvar _socketclusterClient = require('socketcluster-client');\n\nvar _socketclusterClient2 = _interopRequireDefault(_socketclusterClient);\n\nvar _rnHostDetect = require('rn-host-detect');\n\nvar _rnHostDetect2 = _interopRequireDefault(_rnHostDetect);\n\nvar _constants = require('./constants');\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar socket = undefined;\nvar channel = undefined;\nvar listeners = {};\n\nfunction extractState(message) {\n if (!message || !message.state) return undefined;\n if (typeof message.state === 'string') return (0, _jsan.parse)(message.state);\n return message.state;\n}\n\nfunction generateId() {\n return Math.random().toString(36).substr(2);\n}\n\nfunction handleMessages(message) {\n if (!message.payload) message.payload = message.action;\n Object.keys(listeners).forEach(function (id) {\n if (message.instanceId && id !== message.instanceId) return;\n if (typeof listeners[id] === 'function') listeners[id](message);else listeners[id].forEach(function (fn) {\n fn(message);\n });\n });\n}\n\nfunction watch() {\n if (channel) return;\n socket.emit('login', 'master', function (err, channelName) {\n if (err) {\n console.log(err);return;\n }\n channel = socket.subscribe(channelName);\n channel.watch(handleMessages);\n socket.on(channelName, handleMessages);\n });\n}\n\nfunction connectToServer(options) {\n if (socket) return;\n var socketOptions = undefined;\n if (options.port) {\n socketOptions = {\n port: options.port,\n hostname: (0, _rnHostDetect2.default)(options.hostname || 'localhost'),\n secure: !!options.secure\n };\n } else socketOptions = _constants.defaultSocketOptions;\n socket = _socketclusterClient2.default.create(socketOptions);\n watch();\n}\n\nfunction start(options) {\n if (options) {\n if (options.port && !options.hostname) {\n options.hostname = 'localhost';\n }\n }\n connectToServer(options);\n}\n\nfunction transformAction(action, config) {\n if (action.action) return action;\n var liftedAction = { timestamp: Date.now() };\n if (action) {\n if (config.getActionType) liftedAction.action = config.getActionType(action);else {\n if (typeof action === 'string') liftedAction.action = { type: action };else if (!action.type) liftedAction.action = { type: 'update' };else liftedAction.action = action;\n }\n } else {\n liftedAction.action = { type: action };\n }\n return liftedAction;\n}\n\nfunction _send(action, state, options, type, instanceId) {\n start(options);\n setTimeout(function () {\n var message = {\n payload: state ? (0, _jsan.stringify)(state) : '',\n action: type === 'ACTION' ? (0, _jsan.stringify)(transformAction(action, options)) : action,\n type: type || 'ACTION',\n id: socket.id,\n instanceId: instanceId,\n name: options.name\n };\n socket.emit(socket.id ? 'log' : 'log-noid', message);\n }, 0);\n}\n\nexports.send = _send;\nfunction connect() {\n var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];\n\n var id = generateId(options.instanceId);\n start(options);\n return {\n init: function init(state, action) {\n _send(action || {}, state, options, 'INIT', id);\n },\n subscribe: function subscribe(listener) {\n if (!listener) return undefined;\n if (!listeners[id]) listeners[id] = [];\n listeners[id].push(listener);\n\n return function unsubscribe() {\n var index = listeners[id].indexOf(listener);\n listeners[id].splice(index, 1);\n };\n },\n unsubscribe: function unsubscribe() {\n delete listeners[id];\n },\n send: function send(action, payload) {\n if (action) {\n _send(action, payload, options, 'ACTION', id);\n } else {\n _send(undefined, payload, options, 'STATE', id);\n }\n },\n error: function error(payload) {\n socket.emit({ type: 'ERROR', payload: payload, id: socket.id, instanceId: id });\n }\n };\n}\n\nfunction connectViaExtension(options) {\n if (options && options.remote || typeof window === 'undefined' || !window.__REDUX_DEVTOOLS_EXTENSION__) {\n return connect(options);\n }\n return window.__REDUX_DEVTOOLS_EXTENSION__.connect(options);\n}\n\nexports.default = { connect: connect, connectViaExtension: connectViaExtension, send: _send, extractState: extractState, generateId: generateId };","'use strict';\n\nmodule.exports = require('./devTools');","'use strict'\n\n/*\n * It only for Debug Remotely mode for Android\n * When __DEV__ === false, we can't use window.require('NativeModules')\n */\nfunction getByRemoteConfig(hostname) {\n var remoteModuleConfig = typeof window !== 'undefined' &&\n window.__fbBatchedBridgeConfig &&\n window.__fbBatchedBridgeConfig.remoteModuleConfig\n\n if (\n !Array.isArray(remoteModuleConfig) ||\n hostname !== 'localhost' && hostname !== '127.0.0.1'\n ) return { hostname: hostname, passed: false }\n\n var result = hostname\n var passed = false\n remoteModuleConfig.some(function (config) {\n if (!config) return false\n \n var name = config[0]\n var content = config[1]\n if (\n (name === 'AndroidConstants' || name === 'PlatformConstants') &&\n content &&\n content.ServerHost\n ) {\n result = content.ServerHost.split(':')[0]\n passed = true\n return true\n }\n\n if (\n name === 'SourceCode' &&\n content &&\n content.scriptURL\n ) {\n result = content.scriptURL.replace(/https?:\\/\\//, '').split(':')[0]\n passed = true\n return true\n }\n return false\n })\n\n return { hostname: result, passed: passed }\n}\n\nfunction getByRNRequirePolyfill(hostname) {\n var originalWarn = console.warn\n var NativeModules\n var Constants\n var SourceCode\n if (\n typeof window === 'undefined' ||\n !window.__DEV__ ||\n typeof window.require !== 'function' ||\n // RN >= 0.56\n // TODO: Get NativeModules for RN >= 0.56\n window.require.name === 'metroRequire'\n ) {\n return hostname\n }\n console.warn = function() {\n if (\n arguments[0] &&\n typeof arguments[0].indexOf == 'function' &&\n arguments[0].indexOf(\"Requiring module 'NativeModules' by name\") > -1\n )\n return\n return originalWarn.apply(console, arguments)\n }\n try {\n NativeModules = window.require('NativeModules')\n } catch (e) {}\n console.warn = originalWarn\n if (!NativeModules) return hostname\n\n Constants = NativeModules.PlatformConstants || NativeModules.AndroidConstants\n SourceCode = NativeModules.SourceCode\n\n if (Constants && Constants.ServerHost) {\n return Constants.ServerHost.split(':')[0]\n } else if (SourceCode && SourceCode.scriptURL) {\n return SourceCode.scriptURL.replace(/https?:\\/\\//, '').split(':')[0]\n }\n return hostname\n}\n\n/*\n * Get React Native server IP if hostname is `localhost`\n * On Android emulator, the IP of host is `10.0.2.2` (Genymotion: 10.0.3.2)\n */\nmodule.exports = function (hostname) {\n // Check if it in React Native environment\n if (\n typeof __fbBatchedBridgeConfig !== 'object' ||\n hostname !== 'localhost' && hostname !== '127.0.0.1'\n ) {\n return hostname\n }\n var result = getByRemoteConfig(hostname)\n\n // Leave if get hostname by remote config successful\n if (result.passed) {\n return result.hostname\n }\n\n // Otherwise, use RN's require polyfill\n return getByRNRequirePolyfill(hostname)\n}\n","var Emitter = require('component-emitter');\n\nvar SCChannel = function (name, client, options) {\n var self = this;\n\n Emitter.call(this);\n\n this.PENDING = 'pending';\n this.SUBSCRIBED = 'subscribed';\n this.UNSUBSCRIBED = 'unsubscribed';\n\n this.name = name;\n this.state = this.UNSUBSCRIBED;\n this.client = client;\n\n this.options = options || {};\n this.setOptions(this.options);\n};\n\nSCChannel.prototype = Object.create(Emitter.prototype);\n\nSCChannel.prototype.setOptions = function (options) {\n if (!options) {\n options = {};\n }\n this.waitForAuth = options.waitForAuth || false;\n this.batch = options.batch || false;\n\n if (options.data !== undefined) {\n this.data = options.data;\n }\n};\n\nSCChannel.prototype.getState = function () {\n return this.state;\n};\n\nSCChannel.prototype.subscribe = function (options) {\n this.client.subscribe(this.name, options);\n};\n\nSCChannel.prototype.unsubscribe = function () {\n this.client.unsubscribe(this.name);\n};\n\nSCChannel.prototype.isSubscribed = function (includePending) {\n return this.client.isSubscribed(this.name, includePending);\n};\n\nSCChannel.prototype.publish = function (data, callback) {\n this.client.publish(this.name, data, callback);\n};\n\nSCChannel.prototype.watch = function (handler) {\n this.client.watch(this.name, handler);\n};\n\nSCChannel.prototype.unwatch = function (handler) {\n this.client.unwatch(this.name, handler);\n};\n\nSCChannel.prototype.watchers = function () {\n return this.client.watchers(this.name);\n};\n\nSCChannel.prototype.destroy = function () {\n this.client.destroyChannel(this.name);\n};\n\nmodule.exports.SCChannel = SCChannel;\n","\r\n/**\r\n * Expose `Emitter`.\r\n */\r\n\r\nif (typeof module !== 'undefined') {\r\n module.exports = Emitter;\r\n}\r\n\r\n/**\r\n * Initialize a new `Emitter`.\r\n *\r\n * @api public\r\n */\r\n\r\nfunction Emitter(obj) {\r\n if (obj) return mixin(obj);\r\n};\r\n\r\n/**\r\n * Mixin the emitter properties.\r\n *\r\n * @param {Object} obj\r\n * @return {Object}\r\n * @api private\r\n */\r\n\r\nfunction mixin(obj) {\r\n for (var key in Emitter.prototype) {\r\n obj[key] = Emitter.prototype[key];\r\n }\r\n return obj;\r\n}\r\n\r\n/**\r\n * Listen on the given `event` with `fn`.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.on =\r\nEmitter.prototype.addEventListener = function(event, fn){\r\n this._callbacks = this._callbacks || {};\r\n (this._callbacks['$' + event] = this._callbacks['$' + event] || [])\r\n .push(fn);\r\n return this;\r\n};\r\n\r\n/**\r\n * Adds an `event` listener that will be invoked a single\r\n * time then automatically removed.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.once = function(event, fn){\r\n function on() {\r\n this.off(event, on);\r\n fn.apply(this, arguments);\r\n }\r\n\r\n on.fn = fn;\r\n this.on(event, on);\r\n return this;\r\n};\r\n\r\n/**\r\n * Remove the given callback for `event` or all\r\n * registered callbacks.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.off =\r\nEmitter.prototype.removeListener =\r\nEmitter.prototype.removeAllListeners =\r\nEmitter.prototype.removeEventListener = function(event, fn){\r\n this._callbacks = this._callbacks || {};\r\n\r\n // all\r\n if (0 == arguments.length) {\r\n this._callbacks = {};\r\n return this;\r\n }\r\n\r\n // specific event\r\n var callbacks = this._callbacks['$' + event];\r\n if (!callbacks) return this;\r\n\r\n // remove all handlers\r\n if (1 == arguments.length) {\r\n delete this._callbacks['$' + event];\r\n return this;\r\n }\r\n\r\n // remove specific handler\r\n var cb;\r\n for (var i = 0; i < callbacks.length; i++) {\r\n cb = callbacks[i];\r\n if (cb === fn || cb.fn === fn) {\r\n callbacks.splice(i, 1);\r\n break;\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Emit `event` with the given args.\r\n *\r\n * @param {String} event\r\n * @param {Mixed} ...\r\n * @return {Emitter}\r\n */\r\n\r\nEmitter.prototype.emit = function(event){\r\n this._callbacks = this._callbacks || {};\r\n var args = [].slice.call(arguments, 1)\r\n , callbacks = this._callbacks['$' + event];\r\n\r\n if (callbacks) {\r\n callbacks = callbacks.slice(0);\r\n for (var i = 0, len = callbacks.length; i < len; ++i) {\r\n callbacks[i].apply(this, args);\r\n }\r\n }\r\n\r\n return this;\r\n};\r\n\r\n/**\r\n * Return array of callbacks for `event`.\r\n *\r\n * @param {String} event\r\n * @return {Array}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.listeners = function(event){\r\n this._callbacks = this._callbacks || {};\r\n return this._callbacks['$' + event] || [];\r\n};\r\n\r\n/**\r\n * Check if this emitter has `event` handlers.\r\n *\r\n * @param {String} event\r\n * @return {Boolean}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.hasListeners = function(event){\r\n return !! this.listeners(event).length;\r\n};\r\n","// Based on https://github.com/dscape/cycle/blob/master/cycle.js\n\nmodule.exports = function decycle(object) {\n// Make a deep copy of an object or array, assuring that there is at most\n// one instance of each object or array in the resulting structure. The\n// duplicate references (which might be forming cycles) are replaced with\n// an object of the form\n// {$ref: PATH}\n// where the PATH is a JSONPath string that locates the first occurance.\n// So,\n// var a = [];\n// a[0] = a;\n// return JSON.stringify(JSON.decycle(a));\n// produces the string '[{\"$ref\":\"$\"}]'.\n\n// JSONPath is used to locate the unique object. $ indicates the top level of\n// the object or array. [NUMBER] or [STRING] indicates a child member or\n// property.\n\n var objects = [], // Keep a reference to each unique object or array\n paths = []; // Keep the path to each unique object or array\n\n return (function derez(value, path) {\n\n// The derez recurses through the object, producing the deep copy.\n\n var i, // The loop counter\n name, // Property name\n nu; // The new object or array\n\n// typeof null === 'object', so go on if this value is really an object but not\n// one of the weird builtin objects.\n\n if (typeof value === 'object' && value !== null &&\n !(value instanceof Boolean) &&\n !(value instanceof Date) &&\n !(value instanceof Number) &&\n !(value instanceof RegExp) &&\n !(value instanceof String)) {\n\n// If the value is an object or array, look to see if we have already\n// encountered it. If so, return a $ref/path object. This is a hard way,\n// linear search that will get slower as the number of unique objects grows.\n\n for (i = 0; i < objects.length; i += 1) {\n if (objects[i] === value) {\n return {$ref: paths[i]};\n }\n }\n\n// Otherwise, accumulate the unique value and its path.\n\n objects.push(value);\n paths.push(path);\n\n// If it is an array, replicate the array.\n\n if (Object.prototype.toString.apply(value) === '[object Array]') {\n nu = [];\n for (i = 0; i < value.length; i += 1) {\n nu[i] = derez(value[i], path + '[' + i + ']');\n }\n } else {\n\n// If it is an object, replicate the object.\n\n nu = {};\n for (name in value) {\n if (Object.prototype.hasOwnProperty.call(value, name)) {\n nu[name] = derez(value[name],\n path + '[' + JSON.stringify(name) + ']');\n }\n }\n }\n return nu;\n }\n return value;\n }(object, '$'));\n};\n","var decycle = require('./decycle');\n\nvar isStrict = (function () { return !this; })();\n\nfunction AuthTokenExpiredError(message, expiry) {\n this.name = 'AuthTokenExpiredError';\n this.message = message;\n this.expiry = expiry;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nAuthTokenExpiredError.prototype = Object.create(Error.prototype);\n\n\nfunction AuthTokenInvalidError(message) {\n this.name = 'AuthTokenInvalidError';\n this.message = message;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nAuthTokenInvalidError.prototype = Object.create(Error.prototype);\n\n\nfunction AuthTokenNotBeforeError(message, date) {\n this.name = 'AuthTokenNotBeforeError';\n this.message = message;\n this.date = date;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nAuthTokenNotBeforeError.prototype = Object.create(Error.prototype);\n\n\n// For any other auth token error.\nfunction AuthTokenError(message) {\n this.name = 'AuthTokenError';\n this.message = message;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nAuthTokenError.prototype = Object.create(Error.prototype);\n\n\nfunction SilentMiddlewareBlockedError(message, type) {\n this.name = 'SilentMiddlewareBlockedError';\n this.message = message;\n this.type = type;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nSilentMiddlewareBlockedError.prototype = Object.create(Error.prototype);\n\n\nfunction InvalidActionError(message) {\n this.name = 'InvalidActionError';\n this.message = message;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nInvalidActionError.prototype = Object.create(Error.prototype);\n\nfunction InvalidArgumentsError(message) {\n this.name = 'InvalidArgumentsError';\n this.message = message;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nInvalidArgumentsError.prototype = Object.create(Error.prototype);\n\nfunction InvalidOptionsError(message) {\n this.name = 'InvalidOptionsError';\n this.message = message;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nInvalidOptionsError.prototype = Object.create(Error.prototype);\n\n\nfunction InvalidMessageError(message) {\n this.name = 'InvalidMessageError';\n this.message = message;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nInvalidMessageError.prototype = Object.create(Error.prototype);\n\n\nfunction SocketProtocolError(message, code) {\n this.name = 'SocketProtocolError';\n this.message = message;\n this.code = code;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nSocketProtocolError.prototype = Object.create(Error.prototype);\n\n\nfunction ServerProtocolError(message) {\n this.name = 'ServerProtocolError';\n this.message = message;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nServerProtocolError.prototype = Object.create(Error.prototype);\n\nfunction HTTPServerError(message) {\n this.name = 'HTTPServerError';\n this.message = message;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nHTTPServerError.prototype = Object.create(Error.prototype);\n\n\nfunction ResourceLimitError(message) {\n this.name = 'ResourceLimitError';\n this.message = message;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nResourceLimitError.prototype = Object.create(Error.prototype);\n\n\nfunction TimeoutError(message) {\n this.name = 'TimeoutError';\n this.message = message;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nTimeoutError.prototype = Object.create(Error.prototype);\n\n\nfunction BadConnectionError(message, type) {\n this.name = 'BadConnectionError';\n this.message = message;\n this.type = type;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nBadConnectionError.prototype = Object.create(Error.prototype);\n\n\nfunction BrokerError(message) {\n this.name = 'BrokerError';\n this.message = message;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nBrokerError.prototype = Object.create(Error.prototype);\n\n\nfunction ProcessExitError(message, code) {\n this.name = 'ProcessExitError';\n this.message = message;\n this.code = code;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nProcessExitError.prototype = Object.create(Error.prototype);\n\n\nfunction UnknownError(message) {\n this.name = 'UnknownError';\n this.message = message;\n if (Error.captureStackTrace && !isStrict) {\n Error.captureStackTrace(this, arguments.callee);\n } else {\n this.stack = (new Error()).stack;\n }\n}\nUnknownError.prototype = Object.create(Error.prototype);\n\n\n// Expose all error types.\n\nmodule.exports = {\n AuthTokenExpiredError: AuthTokenExpiredError,\n AuthTokenInvalidError: AuthTokenInvalidError,\n AuthTokenNotBeforeError: AuthTokenNotBeforeError,\n AuthTokenError: AuthTokenError,\n SilentMiddlewareBlockedError: SilentMiddlewareBlockedError,\n InvalidActionError: InvalidActionError,\n InvalidArgumentsError: InvalidArgumentsError,\n InvalidOptionsError: InvalidOptionsError,\n InvalidMessageError: InvalidMessageError,\n SocketProtocolError: SocketProtocolError,\n ServerProtocolError: ServerProtocolError,\n HTTPServerError: HTTPServerError,\n ResourceLimitError: ResourceLimitError,\n TimeoutError: TimeoutError,\n BadConnectionError: BadConnectionError,\n BrokerError: BrokerError,\n ProcessExitError: ProcessExitError,\n UnknownError: UnknownError\n};\n\nmodule.exports.socketProtocolErrorStatuses = {\n 1001: 'Socket was disconnected',\n 1002: 'A WebSocket protocol error was encountered',\n 1003: 'Server terminated socket because it received invalid data',\n 1005: 'Socket closed without status code',\n 1006: 'Socket hung up',\n 1007: 'Message format was incorrect',\n 1008: 'Encountered a policy violation',\n 1009: 'Message was too big to process',\n 1010: 'Client ended the connection because the server did not comply with extension requirements',\n 1011: 'Server encountered an unexpected fatal condition',\n 4000: 'Server ping timed out',\n 4001: 'Client pong timed out',\n 4002: 'Server failed to sign auth token',\n 4003: 'Failed to complete handshake',\n 4004: 'Client failed to save auth token',\n 4005: 'Did not receive #handshake from client before timeout',\n 4006: 'Failed to bind socket to message broker',\n 4007: 'Client connection establishment timed out',\n 4008: 'Server rejected handshake from client'\n};\n\nmodule.exports.socketProtocolIgnoreStatuses = {\n 1000: 'Socket closed normally',\n 1001: 'Socket hung up'\n};\n\n// Properties related to error domains cannot be serialized.\nvar unserializableErrorProperties = {\n domain: 1,\n domainEmitter: 1,\n domainThrown: 1\n};\n\n// Convert an error into a JSON-compatible type which can later be hydrated\n// back to its *original* form.\nmodule.exports.dehydrateError = function dehydrateError(error, includeStackTrace) {\n var dehydratedError;\n\n if (error && typeof error === 'object') {\n dehydratedError = {\n message: error.message\n };\n if (includeStackTrace) {\n dehydratedError.stack = error.stack;\n }\n for (var i in error) {\n if (!unserializableErrorProperties[i]) {\n dehydratedError[i] = error[i];\n }\n }\n } else if (typeof error === 'function') {\n dehydratedError = '[function ' + (error.name || 'anonymous') + ']';\n } else {\n dehydratedError = error;\n }\n\n return decycle(dehydratedError);\n};\n\n// Convert a dehydrated error back to its *original* form.\nmodule.exports.hydrateError = function hydrateError(error) {\n var hydratedError = null;\n if (error != null) {\n if (typeof error === 'object') {\n hydratedError = new Error(error.message);\n for (var i in error) {\n if (error.hasOwnProperty(i)) {\n hydratedError[i] = error[i];\n }\n }\n } else {\n hydratedError = error;\n }\n }\n return hydratedError;\n};\n\nmodule.exports.decycle = decycle;\n","const base64Chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\nconst validJSONStartRegex = /^[ \\n\\r\\t]*[{\\[]/;\n\nlet arrayBufferToBase64 = function (arraybuffer) {\n let bytes = new Uint8Array(arraybuffer);\n let len = bytes.length;\n let base64 = '';\n\n for (let i = 0; i < len; i += 3) {\n base64 += base64Chars[bytes[i] >> 2];\n base64 += base64Chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += base64Chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];\n base64 += base64Chars[bytes[i + 2] & 63];\n }\n\n if ((len % 3) === 2) {\n base64 = base64.substring(0, base64.length - 1) + '=';\n } else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + '==';\n }\n\n return base64;\n};\n\nlet binaryToBase64Replacer = function (key, value) {\n if (global.ArrayBuffer && value instanceof global.ArrayBuffer) {\n return {\n base64: true,\n data: arrayBufferToBase64(value)\n };\n } else if (global.Buffer) {\n if (value instanceof global.Buffer){\n return {\n base64: true,\n data: value.toString('base64')\n };\n }\n // Some versions of Node.js convert Buffers to Objects before they are passed to\n // the replacer function - Because of this, we need to rehydrate Buffers\n // before we can convert them to base64 strings.\n if (value && value.type === 'Buffer' && Array.isArray(value.data)) {\n let rehydratedBuffer;\n if (global.Buffer.from) {\n rehydratedBuffer = global.Buffer.from(value.data);\n } else {\n rehydratedBuffer = new global.Buffer(value.data);\n }\n return {\n base64: true,\n data: rehydratedBuffer.toString('base64')\n };\n }\n }\n return value;\n};\n\n// Decode the data which was transmitted over the wire to a JavaScript Object in a format which SC understands.\n// See encode function below for more details.\nmodule.exports.decode = function (encodedMessage) {\n if (encodedMessage == null) {\n return null;\n }\n // Leave ping or pong message as is\n if (encodedMessage === '#1' || encodedMessage === '#2') {\n return encodedMessage;\n }\n let message = encodedMessage.toString();\n\n // Performance optimization to detect invalid JSON packet sooner.\n if (!validJSONStartRegex.test(message)) {\n return message;\n }\n\n try {\n return JSON.parse(message);\n } catch (err) {}\n return message;\n};\n\n// Encode raw data (which is in the SC protocol format) into a format for\n// transfering it over the wire. In this case, we just convert it into a simple JSON string.\n// If you want to create your own custom codec, you can encode the object into any format\n// (e.g. binary ArrayBuffer or string with any kind of compression) so long as your decode\n// function is able to rehydrate that object back into its original JavaScript Object format\n// (which adheres to the SC protocol).\n// See https://github.com/SocketCluster/socketcluster/blob/master/socketcluster-protocol.md\n// for details about the SC protocol.\nmodule.exports.encode = function (rawData) {\n // Leave ping or pong message as is\n if (rawData === '#1' || rawData === '#2') {\n return rawData;\n }\n return JSON.stringify(rawData, binaryToBase64Replacer);\n};\n","var SCClientSocket = require('./lib/scclientsocket');\r\nvar factory = require('./lib/factory');\r\n\r\nmodule.exports.factory = factory;\r\nmodule.exports.SCClientSocket = SCClientSocket;\r\n\r\nmodule.exports.Emitter = require('component-emitter');\r\n\r\nmodule.exports.create = function (options) {\r\n return factory.create(options);\r\n};\r\n\r\nmodule.exports.connect = module.exports.create;\r\n\r\nmodule.exports.destroy = function (socket) {\r\n return factory.destroy(socket);\r\n};\r\n\r\nmodule.exports.clients = factory.clients;\r\n\r\nmodule.exports.version = '13.0.1';\r\n","var AuthEngine = function () {\n this._internalStorage = {};\n this.isLocalStorageEnabled = this._checkLocalStorageEnabled();\n};\n\nAuthEngine.prototype._checkLocalStorageEnabled = function () {\n var err;\n try {\n // Some browsers will throw an error here if localStorage is disabled.\n global.localStorage;\n\n // Safari, in Private Browsing Mode, looks like it supports localStorage but all calls to setItem\n // throw QuotaExceededError. We're going to detect this and avoid hard to debug edge cases.\n global.localStorage.setItem('__scLocalStorageTest', 1);\n global.localStorage.removeItem('__scLocalStorageTest');\n } catch (e) {\n err = e;\n }\n return !err;\n};\n\nAuthEngine.prototype.saveToken = function (name, token, options, callback) {\n if (this.isLocalStorageEnabled && global.localStorage) {\n global.localStorage.setItem(name, token);\n } else {\n this._internalStorage[name] = token;\n }\n callback && callback(null, token);\n};\n\nAuthEngine.prototype.removeToken = function (name, callback) {\n var token;\n\n this.loadToken(name, function (err, authToken) {\n token = authToken;\n });\n\n if (this.isLocalStorageEnabled && global.localStorage) {\n global.localStorage.removeItem(name);\n } else {\n delete this._internalStorage[name];\n }\n\n callback && callback(null, token);\n};\n\nAuthEngine.prototype.loadToken = function (name, callback) {\n var token;\n\n if (this.isLocalStorageEnabled && global.localStorage) {\n token = global.localStorage.getItem(name);\n } else {\n token = this._internalStorage[name] || null;\n }\n callback(null, token);\n};\n\nmodule.exports.AuthEngine = AuthEngine;\n","var SCClientSocket = require('./scclientsocket');\r\nvar scErrors = require('sc-errors');\r\nvar uuid = require('uuid');\r\nvar InvalidArgumentsError = scErrors.InvalidArgumentsError;\r\n\r\nvar _clients = {};\r\n\r\nfunction getMultiplexId(options) {\r\n var protocolPrefix = options.secure ? 'https://' : 'http://';\r\n var queryString = '';\r\n if (options.query) {\r\n if (typeof options.query == 'string') {\r\n queryString = options.query;\r\n } else {\r\n var queryArray = [];\r\n var queryMap = options.query;\r\n for (var key in queryMap) {\r\n if (queryMap.hasOwnProperty(key)) {\r\n queryArray.push(key + '=' + queryMap[key]);\r\n }\r\n }\r\n if (queryArray.length) {\r\n queryString = '?' + queryArray.join('&');\r\n }\r\n }\r\n }\r\n var host;\r\n if (options.host) {\r\n host = options.host;\r\n } else {\r\n host = options.hostname + ':' + options.port;\r\n }\r\n return protocolPrefix + host + options.path + queryString;\r\n}\r\n\r\nfunction isUrlSecure() {\r\n return global.location && location.protocol == 'https:';\r\n}\r\n\r\nfunction getPort(options, isSecureDefault) {\r\n var isSecure = options.secure == null ? isSecureDefault : options.secure;\r\n return options.port || (global.location && location.port ? location.port : isSecure ? 443 : 80);\r\n}\r\n\r\nfunction create(options) {\r\n var self = this;\r\n\r\n options = options || {};\r\n\r\n if (options.host && !options.host.match(/[^:]+:\\d{2,5}/)) {\r\n throw new InvalidArgumentsError('The host option should include both' +\r\n ' the hostname and the port number in the format \"hostname:port\"');\r\n }\r\n\r\n if (options.host && options.hostname) {\r\n throw new InvalidArgumentsError('The host option should already include' +\r\n ' the hostname and the port number in the format \"hostname:port\"' +\r\n ' - Because of this, you should never use host and hostname options together');\r\n }\r\n\r\n if (options.host && options.port) {\r\n throw new InvalidArgumentsError('The host option should already include' +\r\n ' the hostname and the port number in the format \"hostname:port\"' +\r\n ' - Because of this, you should never use host and port options together');\r\n }\r\n\r\n var isSecureDefault = isUrlSecure();\r\n\r\n var opts = {\r\n port: getPort(options, isSecureDefault),\r\n hostname: global.location && location.hostname || 'localhost',\r\n path: '/socketcluster/',\r\n secure: isSecureDefault,\r\n autoConnect: true,\r\n autoReconnect: true,\r\n autoSubscribeOnConnect: true,\r\n connectTimeout: 20000,\r\n ackTimeout: 10000,\r\n timestampRequests: false,\r\n timestampParam: 't',\r\n authEngine: null,\r\n authTokenName: 'socketCluster.authToken',\r\n binaryType: 'arraybuffer',\r\n multiplex: true,\r\n pubSubBatchDuration: null,\r\n cloneData: false\r\n };\r\n for (var i in options) {\r\n if (options.hasOwnProperty(i)) {\r\n opts[i] = options[i];\r\n }\r\n }\r\n opts.clientMap = _clients;\r\n\r\n if (opts.multiplex === false) {\r\n opts.clientId = uuid.v4();\r\n var socket = new SCClientSocket(opts);\r\n _clients[opts.clientId] = socket;\r\n return socket;\r\n }\r\n opts.clientId = getMultiplexId(opts);\r\n\r\n if (_clients[opts.clientId]) {\r\n if (opts.autoConnect) {\r\n _clients[opts.clientId].connect();\r\n }\r\n } else {\r\n _clients[opts.clientId] = new SCClientSocket(opts);\r\n }\r\n return _clients[opts.clientId];\r\n}\r\n\r\nfunction destroy(socket) {\r\n socket.destroy();\r\n}\r\n\r\nmodule.exports = {\r\n create: create,\r\n destroy: destroy,\r\n clients: _clients\r\n};\r\n","var scErrors = require('sc-errors');\nvar InvalidActionError = scErrors.InvalidActionError;\n\nvar Response = function (socket, id) {\n this.socket = socket;\n this.id = id;\n this.sent = false;\n};\n\nResponse.prototype._respond = function (responseData) {\n if (this.sent) {\n throw new InvalidActionError('Response ' + this.id + ' has already been sent');\n } else {\n this.sent = true;\n this.socket.send(this.socket.encode(responseData));\n }\n};\n\nResponse.prototype.end = function (data) {\n if (this.id) {\n var responseData = {\n rid: this.id\n };\n if (data !== undefined) {\n responseData.data = data;\n }\n this._respond(responseData);\n }\n};\n\nResponse.prototype.error = function (error, data) {\n if (this.id) {\n var err = scErrors.dehydrateError(error);\n\n var responseData = {\n rid: this.id,\n error: err\n };\n if (data !== undefined) {\n responseData.data = data;\n }\n\n this._respond(responseData);\n }\n};\n\nResponse.prototype.callback = function (error, data) {\n if (error) {\n this.error(error, data);\n } else {\n this.end(data);\n }\n};\n\nmodule.exports.Response = Response;\n","var Emitter = require('component-emitter');\r\nvar SCChannel = require('sc-channel').SCChannel;\r\nvar Response = require('./response').Response;\r\nvar AuthEngine = require('./auth').AuthEngine;\r\nvar formatter = require('sc-formatter');\r\nvar SCTransport = require('./sctransport').SCTransport;\r\nvar querystring = require('querystring');\r\nvar LinkedList = require('linked-list');\r\nvar base64 = require('base-64');\r\nvar clone = require('clone');\r\n\r\nvar scErrors = require('sc-errors');\r\nvar InvalidArgumentsError = scErrors.InvalidArgumentsError;\r\nvar InvalidMessageError = scErrors.InvalidMessageError;\r\nvar InvalidActionError = scErrors.InvalidActionError;\r\nvar SocketProtocolError = scErrors.SocketProtocolError;\r\nvar TimeoutError = scErrors.TimeoutError;\r\nvar BadConnectionError = scErrors.BadConnectionError;\r\n\r\nvar isBrowser = typeof window != 'undefined';\r\n\r\n\r\nvar SCClientSocket = function (opts) {\r\n var self = this;\r\n\r\n Emitter.call(this);\r\n\r\n this.id = null;\r\n this.state = this.CLOSED;\r\n this.authState = this.UNAUTHENTICATED;\r\n this.signedAuthToken = null;\r\n this.authToken = null;\r\n this.pendingReconnect = false;\r\n this.pendingReconnectTimeout = null;\r\n this.preparingPendingSubscriptions = false;\r\n this.clientId = opts.clientId;\r\n\r\n this.connectTimeout = opts.connectTimeout;\r\n this.ackTimeout = opts.ackTimeout;\r\n this.channelPrefix = opts.channelPrefix || null;\r\n this.disconnectOnUnload = opts.disconnectOnUnload == null ? true : opts.disconnectOnUnload;\r\n this.authTokenName = opts.authTokenName;\r\n\r\n // pingTimeout will be ackTimeout at the start, but it will\r\n // be updated with values provided by the 'connect' event\r\n this.pingTimeout = this.ackTimeout;\r\n this.pingTimeoutDisabled = !!opts.pingTimeoutDisabled;\r\n this.active = true;\r\n\r\n this._clientMap = opts.clientMap || {};\r\n\r\n var maxTimeout = Math.pow(2, 31) - 1;\r\n\r\n var verifyDuration = function (propertyName) {\r\n if (self[propertyName] > maxTimeout) {\r\n throw new InvalidArgumentsError('The ' + propertyName +\r\n ' value provided exceeded the maximum amount allowed');\r\n }\r\n };\r\n\r\n verifyDuration('connectTimeout');\r\n verifyDuration('ackTimeout');\r\n\r\n this._localEvents = {\r\n 'connect': 1,\r\n 'connectAbort': 1,\r\n 'close': 1,\r\n 'disconnect': 1,\r\n 'message': 1,\r\n 'error': 1,\r\n 'raw': 1,\r\n 'kickOut': 1,\r\n 'subscribe': 1,\r\n 'unsubscribe': 1,\r\n 'subscribeStateChange': 1,\r\n 'authStateChange': 1,\r\n 'authenticate': 1,\r\n 'deauthenticate': 1,\r\n 'removeAuthToken': 1,\r\n 'subscribeRequest': 1\r\n };\r\n\r\n this.connectAttempts = 0;\r\n\r\n this._emitBuffer = new LinkedList();\r\n this.channels = {};\r\n\r\n this.options = opts;\r\n\r\n this._cid = 1;\r\n\r\n this.options.callIdGenerator = function () {\r\n return self._cid++;\r\n };\r\n\r\n if (this.options.autoReconnect) {\r\n if (this.options.autoReconnectOptions == null) {\r\n this.options.autoReconnectOptions = {};\r\n }\r\n\r\n // Add properties to the this.options.autoReconnectOptions object.\r\n // We assign the reference to a reconnectOptions variable to avoid repetition.\r\n var reconnectOptions = this.options.autoReconnectOptions;\r\n if (reconnectOptions.initialDelay == null) {\r\n reconnectOptions.initialDelay = 10000;\r\n }\r\n if (reconnectOptions.randomness == null) {\r\n reconnectOptions.randomness = 10000;\r\n }\r\n if (reconnectOptions.multiplier == null) {\r\n reconnectOptions.multiplier = 1.5;\r\n }\r\n if (reconnectOptions.maxDelay == null) {\r\n reconnectOptions.maxDelay = 60000;\r\n }\r\n }\r\n\r\n if (this.options.subscriptionRetryOptions == null) {\r\n this.options.subscriptionRetryOptions = {};\r\n }\r\n\r\n if (this.options.authEngine) {\r\n this.auth = this.options.authEngine;\r\n } else {\r\n this.auth = new AuthEngine();\r\n }\r\n\r\n if (this.options.codecEngine) {\r\n this.codec = this.options.codecEngine;\r\n } else {\r\n // Default codec engine\r\n this.codec = formatter;\r\n }\r\n\r\n this.options.path = this.options.path.replace(/\\/$/, '') + '/';\r\n\r\n this.options.query = opts.query || {};\r\n if (typeof this.options.query == 'string') {\r\n this.options.query = querystring.parse(this.options.query);\r\n }\r\n\r\n this._channelEmitter = new Emitter();\r\n\r\n this._unloadHandler = function () {\r\n self.disconnect();\r\n };\r\n\r\n if (isBrowser && this.disconnectOnUnload && global.addEventListener) {\r\n global.addEventListener('beforeunload', this._unloadHandler, false);\r\n }\r\n this._clientMap[this.clientId] = this;\r\n\r\n if (this.options.autoConnect) {\r\n this.connect();\r\n }\r\n};\r\n\r\nSCClientSocket.prototype = Object.create(Emitter.prototype);\r\n\r\nSCClientSocket.CONNECTING = SCClientSocket.prototype.CONNECTING = SCTransport.prototype.CONNECTING;\r\nSCClientSocket.OPEN = SCClientSocket.prototype.OPEN = SCTransport.prototype.OPEN;\r\nSCClientSocket.CLOSED = SCClientSocket.prototype.CLOSED = SCTransport.prototype.CLOSED;\r\n\r\nSCClientSocket.AUTHENTICATED = SCClientSocket.prototype.AUTHENTICATED = 'authenticated';\r\nSCClientSocket.UNAUTHENTICATED = SCClientSocket.prototype.UNAUTHENTICATED = 'unauthenticated';\r\n\r\nSCClientSocket.PENDING = SCClientSocket.prototype.PENDING = 'pending';\r\n\r\nSCClientSocket.ignoreStatuses = scErrors.socketProtocolIgnoreStatuses;\r\nSCClientSocket.errorStatuses = scErrors.socketProtocolErrorStatuses;\r\n\r\nSCClientSocket.prototype._privateEventHandlerMap = {\r\n '#publish': function (data) {\r\n var undecoratedChannelName = this._undecorateChannelName(data.channel);\r\n var isSubscribed = this.isSubscribed(undecoratedChannelName, true);\r\n\r\n if (isSubscribed) {\r\n this._channelEmitter.emit(undecoratedChannelName, data.data);\r\n }\r\n },\r\n '#kickOut': function (data) {\r\n var undecoratedChannelName = this._undecorateChannelName(data.channel);\r\n var channel = this.channels[undecoratedChannelName];\r\n if (channel) {\r\n Emitter.prototype.emit.call(this, 'kickOut', data.message, undecoratedChannelName);\r\n channel.emit('kickOut', data.message, undecoratedChannelName);\r\n this._triggerChannelUnsubscribe(channel);\r\n }\r\n },\r\n '#setAuthToken': function (data, response) {\r\n var self = this;\r\n\r\n if (data) {\r\n var triggerAuthenticate = function (err) {\r\n if (err) {\r\n // This is a non-fatal error, we don't want to close the connection\r\n // because of this but we do want to notify the server and throw an error\r\n // on the client.\r\n response.error(err);\r\n self._onSCError(err);\r\n } else {\r\n self._changeToAuthenticatedState(data.token);\r\n response.end();\r\n }\r\n };\r\n\r\n this.auth.saveToken(this.authTokenName, data.token, {}, triggerAuthenticate);\r\n } else {\r\n response.error(new InvalidMessageError('No token data provided by #setAuthToken event'));\r\n }\r\n },\r\n '#removeAuthToken': function (data, response) {\r\n var self = this;\r\n\r\n this.auth.removeToken(this.authTokenName, function (err, oldToken) {\r\n if (err) {\r\n // Non-fatal error - Do not close the connection\r\n response.error(err);\r\n self._onSCError(err);\r\n } else {\r\n Emitter.prototype.emit.call(self, 'removeAuthToken', oldToken);\r\n self._changeToUnauthenticatedStateAndClearTokens();\r\n response.end();\r\n }\r\n });\r\n },\r\n '#disconnect': function (data) {\r\n this.transport.close(data.code, data.data);\r\n }\r\n};\r\n\r\nSCClientSocket.prototype.getState = function () {\r\n return this.state;\r\n};\r\n\r\nSCClientSocket.prototype.getBytesReceived = function () {\r\n return this.transport.getBytesReceived();\r\n};\r\n\r\nSCClientSocket.prototype.deauthenticate = function (callback) {\r\n var self = this;\r\n\r\n this.auth.removeToken(this.authTokenName, function (err, oldToken) {\r\n if (err) {\r\n // Non-fatal error - Do not close the connection\r\n self._onSCError(err);\r\n } else {\r\n Emitter.prototype.emit.call(self, 'removeAuthToken', oldToken);\r\n if (self.state != self.CLOSED) {\r\n self.emit('#removeAuthToken');\r\n }\r\n self._changeToUnauthenticatedStateAndClearTokens();\r\n }\r\n callback && callback(err);\r\n });\r\n};\r\n\r\nSCClientSocket.prototype.connect = SCClientSocket.prototype.open = function () {\r\n var self = this;\r\n\r\n if (!this.active) {\r\n var error = new InvalidActionError('Cannot connect a destroyed client');\r\n this._onSCError(error);\r\n return;\r\n }\r\n\r\n if (this.state == this.CLOSED) {\r\n this.pendingReconnect = false;\r\n this.pendingReconnectTimeout = null;\r\n clearTimeout(this._reconnectTimeoutRef);\r\n\r\n this.state = this.CONNECTING;\r\n Emitter.prototype.emit.call(this, 'connecting');\r\n\r\n if (this.transport) {\r\n this.transport.off();\r\n }\r\n\r\n this.transport = new SCTransport(this.auth, this.codec, this.options);\r\n\r\n this.transport.on('open', function (status) {\r\n self.state = self.OPEN;\r\n self._onSCOpen(status);\r\n });\r\n\r\n this.transport.on('error', function (err) {\r\n self._onSCError(err);\r\n });\r\n\r\n this.transport.on('close', function (code, data) {\r\n self.state = self.CLOSED;\r\n self._onSCClose(code, data);\r\n });\r\n\r\n this.transport.on('openAbort', function (code, data) {\r\n self.state = self.CLOSED;\r\n self._onSCClose(code, data, true);\r\n });\r\n\r\n this.transport.on('event', function (event, data, res) {\r\n self._onSCEvent(event, data, res);\r\n });\r\n }\r\n};\r\n\r\nSCClientSocket.prototype.reconnect = function (code, data) {\r\n this.disconnect(code, data);\r\n this.connect();\r\n};\r\n\r\nSCClientSocket.prototype.disconnect = function (code, data) {\r\n code = code || 1000;\r\n\r\n if (typeof code != 'number') {\r\n throw new InvalidArgumentsError('If specified, the code argument must be a number');\r\n }\r\n\r\n if (this.state == this.OPEN || this.state == this.CONNECTING) {\r\n this.transport.close(code, data);\r\n } else {\r\n this.pendingReconnect = false;\r\n this.pendingReconnectTimeout = null;\r\n clearTimeout(this._reconnectTimeoutRef);\r\n }\r\n};\r\n\r\nSCClientSocket.prototype.destroy = function (code, data) {\r\n if (isBrowser && global.removeEventListener) {\r\n global.removeEventListener('beforeunload', this._unloadHandler, false);\r\n }\r\n this.active = false;\r\n this.disconnect(code, data);\r\n delete this._clientMap[this.clientId];\r\n};\r\n\r\nSCClientSocket.prototype._changeToUnauthenticatedStateAndClearTokens = function () {\r\n if (this.authState != this.UNAUTHENTICATED) {\r\n var oldState = this.authState;\r\n var oldSignedToken = this.signedAuthToken;\r\n this.authState = this.UNAUTHENTICATED;\r\n this.signedAuthToken = null;\r\n this.authToken = null;\r\n\r\n var stateChangeData = {\r\n oldState: oldState,\r\n newState: this.authState\r\n };\r\n Emitter.prototype.emit.call(this, 'authStateChange', stateChangeData);\r\n Emitter.prototype.emit.call(this, 'deauthenticate', oldSignedToken);\r\n }\r\n};\r\n\r\nSCClientSocket.prototype._changeToAuthenticatedState = function (signedAuthToken) {\r\n this.signedAuthToken = signedAuthToken;\r\n this.authToken = this._extractAuthTokenData(signedAuthToken);\r\n\r\n if (this.authState != this.AUTHENTICATED) {\r\n var oldState = this.authState;\r\n this.authState = this.AUTHENTICATED;\r\n var stateChangeData = {\r\n oldState: oldState,\r\n newState: this.authState,\r\n signedAuthToken: signedAuthToken,\r\n authToken: this.authToken\r\n };\r\n if (!this.preparingPendingSubscriptions) {\r\n this.processPendingSubscriptions();\r\n }\r\n\r\n Emitter.prototype.emit.call(this, 'authStateChange', stateChangeData);\r\n }\r\n Emitter.prototype.emit.call(this, 'authenticate', signedAuthToken);\r\n};\r\n\r\nSCClientSocket.prototype.decodeBase64 = function (encodedString) {\r\n var decodedString;\r\n if (typeof Buffer == 'undefined') {\r\n if (global.atob) {\r\n decodedString = global.atob(encodedString);\r\n } else {\r\n decodedString = base64.decode(encodedString);\r\n }\r\n } else {\r\n var buffer = new Buffer(encodedString, 'base64');\r\n decodedString = buffer.toString('utf8');\r\n }\r\n return decodedString;\r\n};\r\n\r\nSCClientSocket.prototype.encodeBase64 = function (decodedString) {\r\n var encodedString;\r\n if (typeof Buffer == 'undefined') {\r\n if (global.btoa) {\r\n encodedString = global.btoa(decodedString);\r\n } else {\r\n encodedString = base64.encode(decodedString);\r\n }\r\n } else {\r\n var buffer = new Buffer(decodedString, 'utf8');\r\n encodedString = buffer.toString('base64');\r\n }\r\n return encodedString;\r\n};\r\n\r\nSCClientSocket.prototype._extractAuthTokenData = function (signedAuthToken) {\r\n var tokenParts = (signedAuthToken || '').split('.');\r\n var encodedTokenData = tokenParts[1];\r\n if (encodedTokenData != null) {\r\n var tokenData = encodedTokenData;\r\n try {\r\n tokenData = this.decodeBase64(tokenData);\r\n return JSON.parse(tokenData);\r\n } catch (e) {\r\n return tokenData;\r\n }\r\n }\r\n return null;\r\n};\r\n\r\nSCClientSocket.prototype.getAuthToken = function () {\r\n return this.authToken;\r\n};\r\n\r\nSCClientSocket.prototype.getSignedAuthToken = function () {\r\n return this.signedAuthToken;\r\n};\r\n\r\n// Perform client-initiated authentication by providing an encrypted token string.\r\nSCClientSocket.prototype.authenticate = function (signedAuthToken, callback) {\r\n var self = this;\r\n\r\n this.emit('#authenticate', signedAuthToken, function (err, authStatus) {\r\n if (authStatus && authStatus.isAuthenticated != null) {\r\n // If authStatus is correctly formatted (has an isAuthenticated property),\r\n // then we will rehydrate the authError.\r\n if (authStatus.authError) {\r\n authStatus.authError = scErrors.hydrateError(authStatus.authError);\r\n }\r\n } else {\r\n // Some errors like BadConnectionError and TimeoutError will not pass a valid\r\n // authStatus object to the current function, so we need to create it ourselves.\r\n authStatus = {\r\n isAuthenticated: self.authState,\r\n authError: null\r\n };\r\n }\r\n if (err) {\r\n if (err.name != 'BadConnectionError' && err.name != 'TimeoutError') {\r\n // In case of a bad/closed connection or a timeout, we maintain the last\r\n // known auth state since those errors don't mean that the token is invalid.\r\n\r\n self._changeToUnauthenticatedStateAndClearTokens();\r\n }\r\n callback && callback(err, authStatus);\r\n } else {\r\n self.auth.saveToken(self.authTokenName, signedAuthToken, {}, function (err) {\r\n if (err) {\r\n self._onSCError(err);\r\n }\r\n if (authStatus.isAuthenticated) {\r\n self._changeToAuthenticatedState(signedAuthToken);\r\n } else {\r\n self._changeToUnauthenticatedStateAndClearTokens();\r\n }\r\n callback && callback(err, authStatus);\r\n });\r\n }\r\n });\r\n};\r\n\r\nSCClientSocket.prototype._tryReconnect = function (initialDelay) {\r\n var self = this;\r\n\r\n var exponent = this.connectAttempts++;\r\n var reconnectOptions = this.options.autoReconnectOptions;\r\n var timeout;\r\n\r\n if (initialDelay == null || exponent > 0) {\r\n var initialTimeout = Math.round(reconnectOptions.initialDelay + (reconnectOptions.randomness || 0) * Math.random());\r\n\r\n timeout = Math.round(initialTimeout * Math.pow(reconnectOptions.multiplier, exponent));\r\n } else {\r\n timeout = initialDelay;\r\n }\r\n\r\n if (timeout > reconnectOptions.maxDelay) {\r\n timeout = reconnectOptions.maxDelay;\r\n }\r\n\r\n clearTimeout(this._reconnectTimeoutRef);\r\n\r\n this.pendingReconnect = true;\r\n this.pendingReconnectTimeout = timeout;\r\n this._reconnectTimeoutRef = setTimeout(function () {\r\n self.connect();\r\n }, timeout);\r\n};\r\n\r\nSCClientSocket.prototype._onSCOpen = function (status) {\r\n var self = this;\r\n\r\n this.preparingPendingSubscriptions = true;\r\n\r\n if (status) {\r\n this.id = status.id;\r\n this.pingTimeout = status.pingTimeout;\r\n this.transport.pingTimeout = this.pingTimeout;\r\n if (status.isAuthenticated) {\r\n this._changeToAuthenticatedState(status.authToken);\r\n } else {\r\n this._changeToUnauthenticatedStateAndClearTokens();\r\n }\r\n } else {\r\n // This can happen if auth.loadToken (in sctransport.js) fails with\r\n // an error - This means that the signedAuthToken cannot be loaded by\r\n // the auth engine and therefore, we need to unauthenticate the client.\r\n this._changeToUnauthenticatedStateAndClearTokens();\r\n }\r\n\r\n this.connectAttempts = 0;\r\n\r\n if (this.options.autoSubscribeOnConnect) {\r\n this.processPendingSubscriptions();\r\n }\r\n\r\n // If the user invokes the callback while in autoSubscribeOnConnect mode, it\r\n // won't break anything.\r\n Emitter.prototype.emit.call(this, 'connect', status, function () {\r\n self.processPendingSubscriptions();\r\n });\r\n\r\n if (this.state == this.OPEN) {\r\n this._flushEmitBuffer();\r\n }\r\n};\r\n\r\nSCClientSocket.prototype._onSCError = function (err) {\r\n var self = this;\r\n\r\n // Throw error in different stack frame so that error handling\r\n // cannot interfere with a reconnect action.\r\n setTimeout(function () {\r\n if (self.listeners('error').length < 1) {\r\n throw err;\r\n } else {\r\n Emitter.prototype.emit.call(self, 'error', err);\r\n }\r\n }, 0);\r\n};\r\n\r\nSCClientSocket.prototype._suspendSubscriptions = function () {\r\n var channel, newState;\r\n for (var channelName in this.channels) {\r\n if (this.channels.hasOwnProperty(channelName)) {\r\n channel = this.channels[channelName];\r\n if (channel.state == channel.SUBSCRIBED ||\r\n channel.state == channel.PENDING) {\r\n\r\n newState = channel.PENDING;\r\n } else {\r\n newState = channel.UNSUBSCRIBED;\r\n }\r\n\r\n this._triggerChannelUnsubscribe(channel, newState);\r\n }\r\n }\r\n};\r\n\r\nSCClientSocket.prototype._abortAllPendingEventsDueToBadConnection = function (failureType) {\r\n var currentNode = this._emitBuffer.head;\r\n var nextNode;\r\n\r\n while (currentNode) {\r\n nextNode = currentNode.next;\r\n var eventObject = currentNode.data;\r\n clearTimeout(eventObject.timeout);\r\n delete eventObject.timeout;\r\n currentNode.detach();\r\n currentNode = nextNode;\r\n\r\n var callback = eventObject.callback;\r\n if (callback) {\r\n delete eventObject.callback;\r\n var errorMessage = \"Event '\" + eventObject.event +\r\n \"' was aborted due to a bad connection\";\r\n var error = new BadConnectionError(errorMessage, failureType);\r\n callback.call(eventObject, error, eventObject);\r\n }\r\n // Cleanup any pending response callback in the transport layer too.\r\n if (eventObject.cid) {\r\n this.transport.cancelPendingResponse(eventObject.cid);\r\n }\r\n }\r\n};\r\n\r\nSCClientSocket.prototype._onSCClose = function (code, data, openAbort) {\r\n var self = this;\r\n\r\n this.id = null;\r\n\r\n if (this.transport) {\r\n this.transport.off();\r\n }\r\n this.pendingReconnect = false;\r\n this.pendingReconnectTimeout = null;\r\n clearTimeout(this._reconnectTimeoutRef);\r\n\r\n this._suspendSubscriptions();\r\n this._abortAllPendingEventsDueToBadConnection(openAbort ? 'connectAbort' : 'disconnect');\r\n\r\n // Try to reconnect\r\n // on server ping timeout (4000)\r\n // or on client pong timeout (4001)\r\n // or on close without status (1005)\r\n // or on handshake failure (4003)\r\n // or on handshake rejection (4008)\r\n // or on socket hung up (1006)\r\n if (this.options.autoReconnect) {\r\n if (code == 4000 || code == 4001 || code == 1005) {\r\n // If there is a ping or pong timeout or socket closes without\r\n // status, don't wait before trying to reconnect - These could happen\r\n // if the client wakes up after a period of inactivity and in this case we\r\n // want to re-establish the connection as soon as possible.\r\n this._tryReconnect(0);\r\n\r\n // Codes 4500 and above will be treated as permanent disconnects.\r\n // Socket will not try to auto-reconnect.\r\n } else if (code != 1000 && code < 4500) {\r\n this._tryReconnect();\r\n }\r\n }\r\n\r\n if (openAbort) {\r\n Emitter.prototype.emit.call(self, 'connectAbort', code, data);\r\n } else {\r\n Emitter.prototype.emit.call(self, 'disconnect', code, data);\r\n }\r\n Emitter.prototype.emit.call(self, 'close', code, data);\r\n\r\n if (!SCClientSocket.ignoreStatuses[code]) {\r\n var closeMessage;\r\n if (data) {\r\n closeMessage = 'Socket connection closed with status code ' + code + ' and reason: ' + data;\r\n } else {\r\n closeMessage = 'Socket connection closed with status code ' + code;\r\n }\r\n var err = new SocketProtocolError(SCClientSocket.errorStatuses[code] || closeMessage, code);\r\n this._onSCError(err);\r\n }\r\n};\r\n\r\nSCClientSocket.prototype._onSCEvent = function (event, data, res) {\r\n var handler = this._privateEventHandlerMap[event];\r\n if (handler) {\r\n handler.call(this, data, res);\r\n } else {\r\n Emitter.prototype.emit.call(this, event, data, function () {\r\n res && res.callback.apply(res, arguments);\r\n });\r\n }\r\n};\r\n\r\nSCClientSocket.prototype.decode = function (message) {\r\n return this.transport.decode(message);\r\n};\r\n\r\nSCClientSocket.prototype.encode = function (object) {\r\n return this.transport.encode(object);\r\n};\r\n\r\nSCClientSocket.prototype._flushEmitBuffer = function () {\r\n var currentNode = this._emitBuffer.head;\r\n var nextNode;\r\n\r\n while (currentNode) {\r\n nextNode = currentNode.next;\r\n var eventObject = currentNode.data;\r\n currentNode.detach();\r\n this.transport.emitObject(eventObject);\r\n currentNode = nextNode;\r\n }\r\n};\r\n\r\nSCClientSocket.prototype._handleEventAckTimeout = function (eventObject, eventNode) {\r\n if (eventNode) {\r\n eventNode.detach();\r\n }\r\n delete eventObject.timeout;\r\n\r\n var callback = eventObject.callback;\r\n if (callback) {\r\n delete eventObject.callback;\r\n var error = new TimeoutError(\"Event response for '\" + eventObject.event + \"' timed out\");\r\n callback.call(eventObject, error, eventObject);\r\n }\r\n // Cleanup any pending response callback in the transport layer too.\r\n if (eventObject.cid) {\r\n this.transport.cancelPendingResponse(eventObject.cid);\r\n }\r\n};\r\n\r\nSCClientSocket.prototype._emit = function (event, data, callback) {\r\n var self = this;\r\n\r\n if (this.state == this.CLOSED) {\r\n this.connect();\r\n }\r\n var eventObject = {\r\n event: event,\r\n callback: callback\r\n };\r\n\r\n var eventNode = new LinkedList.Item();\r\n\r\n if (this.options.cloneData) {\r\n eventObject.data = clone(data);\r\n } else {\r\n eventObject.data = data;\r\n }\r\n eventNode.data = eventObject;\r\n\r\n eventObject.timeout = setTimeout(function () {\r\n self._handleEventAckTimeout(eventObject, eventNode);\r\n }, this.ackTimeout);\r\n\r\n this._emitBuffer.append(eventNode);\r\n if (this.state == this.OPEN) {\r\n this._flushEmitBuffer();\r\n }\r\n};\r\n\r\nSCClientSocket.prototype.send = function (data) {\r\n this.transport.send(data);\r\n};\r\n\r\nSCClientSocket.prototype.emit = function (event, data, callback) {\r\n if (this._localEvents[event] == null) {\r\n this._emit(event, data, callback);\r\n } else if (event == 'error') {\r\n Emitter.prototype.emit.call(this, event, data);\r\n } else {\r\n var error = new InvalidActionError('The \"' + event + '\" event is reserved and cannot be emitted on a client socket');\r\n this._onSCError(error);\r\n }\r\n};\r\n\r\nSCClientSocket.prototype.publish = function (channelName, data, callback) {\r\n var pubData = {\r\n channel: this._decorateChannelName(channelName),\r\n data: data\r\n };\r\n this.emit('#publish', pubData, callback);\r\n};\r\n\r\nSCClientSocket.prototype._triggerChannelSubscribe = function (channel, subscriptionOptions) {\r\n var channelName = channel.name;\r\n\r\n if (channel.state != channel.SUBSCRIBED) {\r\n var oldState = channel.state;\r\n channel.state = channel.SUBSCRIBED;\r\n\r\n var stateChangeData = {\r\n channel: channelName,\r\n oldState: oldState,\r\n newState: channel.state,\r\n subscriptionOptions: subscriptionOptions\r\n };\r\n channel.emit('subscribeStateChange', stateChangeData);\r\n channel.emit('subscribe', channelName, subscriptionOptions);\r\n Emitter.prototype.emit.call(this, 'subscribeStateChange', stateChangeData);\r\n Emitter.prototype.emit.call(this, 'subscribe', channelName, subscriptionOptions);\r\n }\r\n};\r\n\r\nSCClientSocket.prototype._triggerChannelSubscribeFail = function (err, channel, subscriptionOptions) {\r\n var channelName = channel.name;\r\n var meetsAuthRequirements = !channel.waitForAuth || this.authState == this.AUTHENTICATED;\r\n\r\n if (channel.state != channel.UNSUBSCRIBED && meetsAuthRequirements) {\r\n channel.state = channel.UNSUBSCRIBED;\r\n\r\n channel.emit('subscribeFail', err, channelName, subscriptionOptions);\r\n Emitter.prototype.emit.call(this, 'subscribeFail', err, channelName, subscriptionOptions);\r\n }\r\n};\r\n\r\n// Cancel any pending subscribe callback\r\nSCClientSocket.prototype._cancelPendingSubscribeCallback = function (channel) {\r\n if (channel._pendingSubscriptionCid != null) {\r\n this.transport.cancelPendingResponse(channel._pendingSubscriptionCid);\r\n delete channel._pendingSubscriptionCid;\r\n }\r\n};\r\n\r\nSCClientSocket.prototype._decorateChannelName = function (channelName) {\r\n if (this.channelPrefix) {\r\n channelName = this.channelPrefix + channelName;\r\n }\r\n return channelName;\r\n};\r\n\r\nSCClientSocket.prototype._undecorateChannelName = function (decoratedChannelName) {\r\n if (this.channelPrefix && decoratedChannelName.indexOf(this.channelPrefix) == 0) {\r\n return decoratedChannelName.replace(this.channelPrefix, '');\r\n }\r\n return decoratedChannelName;\r\n};\r\n\r\nSCClientSocket.prototype._trySubscribe = function (channel) {\r\n var self = this;\r\n\r\n var meetsAuthRequirements = !channel.waitForAuth || this.authState == this.AUTHENTICATED;\r\n\r\n // We can only ever have one pending subscribe action at any given time on a channel\r\n if (this.state == this.OPEN && !this.preparingPendingSubscriptions &&\r\n channel._pendingSubscriptionCid == null && meetsAuthRequirements) {\r\n\r\n var options = {\r\n noTimeout: true\r\n };\r\n\r\n var subscriptionOptions = {\r\n channel: this._decorateChannelName(channel.name)\r\n };\r\n if (channel.waitForAuth) {\r\n options.waitForAuth = true;\r\n subscriptionOptions.waitForAuth = options.waitForAuth;\r\n }\r\n if (channel.data) {\r\n subscriptionOptions.data = channel.data;\r\n }\r\n if (channel.batch) {\r\n options.batch = true;\r\n subscriptionOptions.batch = true;\r\n }\r\n\r\n channel._pendingSubscriptionCid = this.transport.emit(\r\n '#subscribe', subscriptionOptions, options,\r\n function (err) {\r\n delete channel._pendingSubscriptionCid;\r\n if (err) {\r\n self._triggerChannelSubscribeFail(err, channel, subscriptionOptions);\r\n } else {\r\n self._triggerChannelSubscribe(channel, subscriptionOptions);\r\n }\r\n }\r\n );\r\n Emitter.prototype.emit.call(this, 'subscribeRequest', channel.name, subscriptionOptions);\r\n }\r\n};\r\n\r\nSCClientSocket.prototype.subscribe = function (channelName, options) {\r\n var channel = this.channels[channelName];\r\n\r\n if (!channel) {\r\n channel = new SCChannel(channelName, this, options);\r\n this.channels[channelName] = channel;\r\n } else if (options) {\r\n channel.setOptions(options);\r\n }\r\n\r\n if (channel.state == channel.UNSUBSCRIBED) {\r\n channel.state = channel.PENDING;\r\n this._trySubscribe(channel);\r\n }\r\n\r\n return channel;\r\n};\r\n\r\nSCClientSocket.prototype._triggerChannelUnsubscribe = function (channel, newState) {\r\n var channelName = channel.name;\r\n var oldState = channel.state;\r\n\r\n if (newState) {\r\n channel.state = newState;\r\n } else {\r\n channel.state = channel.UNSUBSCRIBED;\r\n }\r\n this._cancelPendingSubscribeCallback(channel);\r\n\r\n if (oldState == channel.SUBSCRIBED) {\r\n var stateChangeData = {\r\n channel: channelName,\r\n oldState: oldState,\r\n newState: channel.state\r\n };\r\n channel.emit('subscribeStateChange', stateChangeData);\r\n channel.emit('unsubscribe', channelName);\r\n Emitter.prototype.emit.call(this, 'subscribeStateChange', stateChangeData);\r\n Emitter.prototype.emit.call(this, 'unsubscribe', channelName);\r\n }\r\n};\r\n\r\nSCClientSocket.prototype._tryUnsubscribe = function (channel) {\r\n var self = this;\r\n\r\n if (this.state == this.OPEN) {\r\n var options = {\r\n noTimeout: true\r\n };\r\n if (channel.batch) {\r\n options.batch = true;\r\n }\r\n // If there is a pending subscribe action, cancel the callback\r\n this._cancelPendingSubscribeCallback(channel);\r\n\r\n // This operation cannot fail because the TCP protocol guarantees delivery\r\n // so long as the connection remains open. If the connection closes,\r\n // the server will automatically unsubscribe the client and thus complete\r\n // the operation on the server side.\r\n var decoratedChannelName = this._decorateChannelName(channel.name);\r\n this.transport.emit('#unsubscribe', decoratedChannelName, options);\r\n }\r\n};\r\n\r\nSCClientSocket.prototype.unsubscribe = function (channelName) {\r\n var channel = this.channels[channelName];\r\n\r\n if (channel) {\r\n if (channel.state != channel.UNSUBSCRIBED) {\r\n\r\n this._triggerChannelUnsubscribe(channel);\r\n this._tryUnsubscribe(channel);\r\n }\r\n }\r\n};\r\n\r\nSCClientSocket.prototype.channel = function (channelName, options) {\r\n var currentChannel = this.channels[channelName];\r\n\r\n if (!currentChannel) {\r\n currentChannel = new SCChannel(channelName, this, options);\r\n this.channels[channelName] = currentChannel;\r\n }\r\n return currentChannel;\r\n};\r\n\r\nSCClientSocket.prototype.destroyChannel = function (channelName) {\r\n var channel = this.channels[channelName];\r\n\r\n if (channel) {\r\n channel.unwatch();\r\n channel.unsubscribe();\r\n delete this.channels[channelName];\r\n }\r\n};\r\n\r\nSCClientSocket.prototype.subscriptions = function (includePending) {\r\n var subs = [];\r\n var channel, includeChannel;\r\n for (var channelName in this.channels) {\r\n if (this.channels.hasOwnProperty(channelName)) {\r\n channel = this.channels[channelName];\r\n\r\n if (includePending) {\r\n includeChannel = channel && (channel.state == channel.SUBSCRIBED ||\r\n channel.state == channel.PENDING);\r\n } else {\r\n includeChannel = channel && channel.state == channel.SUBSCRIBED;\r\n }\r\n\r\n if (includeChannel) {\r\n subs.push(channelName);\r\n }\r\n }\r\n }\r\n return subs;\r\n};\r\n\r\nSCClientSocket.prototype.isSubscribed = function (channelName, includePending) {\r\n var channel = this.channels[channelName];\r\n if (includePending) {\r\n return !!channel && (channel.state == channel.SUBSCRIBED ||\r\n channel.state == channel.PENDING);\r\n }\r\n return !!channel && channel.state == channel.SUBSCRIBED;\r\n};\r\n\r\nSCClientSocket.prototype.processPendingSubscriptions = function () {\r\n var self = this;\r\n\r\n this.preparingPendingSubscriptions = false;\r\n\r\n var pendingChannels = [];\r\n\r\n for (var i in this.channels) {\r\n if (this.channels.hasOwnProperty(i)) {\r\n var channel = this.channels[i];\r\n if (channel.state == channel.PENDING) {\r\n pendingChannels.push(channel);\r\n }\r\n }\r\n }\r\n\r\n pendingChannels.sort(function (a, b) {\r\n var ap = a.priority || 0;\r\n var bp = b.priority || 0;\r\n if (ap > bp) {\r\n return -1;\r\n }\r\n if (ap < bp) {\r\n return 1;\r\n }\r\n return 0;\r\n });\r\n\r\n pendingChannels.forEach(function (channel) {\r\n self._trySubscribe(channel);\r\n });\r\n};\r\n\r\nSCClientSocket.prototype.watch = function (channelName, handler) {\r\n if (typeof handler != 'function') {\r\n throw new InvalidArgumentsError('No handler function was provided');\r\n }\r\n this._channelEmitter.on(channelName, handler);\r\n};\r\n\r\nSCClientSocket.prototype.unwatch = function (channelName, handler) {\r\n if (handler) {\r\n this._channelEmitter.removeListener(channelName, handler);\r\n } else {\r\n this._channelEmitter.removeAllListeners(channelName);\r\n }\r\n};\r\n\r\nSCClientSocket.prototype.watchers = function (channelName) {\r\n return this._channelEmitter.listeners(channelName);\r\n};\r\n\r\nmodule.exports = SCClientSocket;\r\n","var Emitter = require('component-emitter');\r\nvar Response = require('./response').Response;\r\nvar querystring = require('querystring');\r\nvar WebSocket;\r\nvar createWebSocket;\r\n\r\nif (global.WebSocket) {\r\n WebSocket = global.WebSocket;\r\n createWebSocket = function (uri, options) {\r\n return new WebSocket(uri);\r\n };\r\n} else {\r\n WebSocket = require('ws');\r\n createWebSocket = function (uri, options) {\r\n return new WebSocket(uri, null, options);\r\n };\r\n}\r\n\r\nvar scErrors = require('sc-errors');\r\nvar TimeoutError = scErrors.TimeoutError;\r\nvar BadConnectionError = scErrors.BadConnectionError;\r\n\r\n\r\nvar SCTransport = function (authEngine, codecEngine, options) {\r\n var self = this;\r\n\r\n this.state = this.CLOSED;\r\n this.auth = authEngine;\r\n this.codec = codecEngine;\r\n this.options = options;\r\n this.connectTimeout = options.connectTimeout;\r\n this.pingTimeout = options.ackTimeout;\r\n this.pingTimeoutDisabled = !!options.pingTimeoutDisabled;\r\n this.callIdGenerator = options.callIdGenerator;\r\n this.authTokenName = options.authTokenName;\r\n\r\n this._pingTimeoutTicker = null;\r\n this._callbackMap = {};\r\n this._batchSendList = [];\r\n\r\n // Open the connection.\r\n\r\n this.state = this.CONNECTING;\r\n var uri = this.uri();\r\n\r\n var wsSocket = createWebSocket(uri, this.options);\r\n wsSocket.binaryType = this.options.binaryType;\r\n\r\n this.socket = wsSocket;\r\n\r\n wsSocket.onopen = function () {\r\n self._onOpen();\r\n };\r\n\r\n wsSocket.onclose = function (event) {\r\n var code;\r\n if (event.code == null) {\r\n // This is to handle an edge case in React Native whereby\r\n // event.code is undefined when the mobile device is locked.\r\n // TODO: This is not perfect since this condition could also apply to\r\n // an abnormal close (no close control frame) which would be a 1006.\r\n code = 1005;\r\n } else {\r\n code = event.code;\r\n }\r\n self._onClose(code, event.reason);\r\n };\r\n\r\n wsSocket.onmessage = function (message, flags) {\r\n self._onMessage(message.data);\r\n };\r\n\r\n wsSocket.onerror = function (error) {\r\n // The onclose event will be called automatically after the onerror event\r\n // if the socket is connected - Otherwise, if it's in the middle of\r\n // connecting, we want to close it manually with a 1006 - This is necessary\r\n // to prevent inconsistent behavior when running the client in Node.js\r\n // vs in a browser.\r\n\r\n if (self.state === self.CONNECTING) {\r\n self._onClose(1006);\r\n }\r\n };\r\n\r\n this._connectTimeoutRef = setTimeout(function () {\r\n self._onClose(4007);\r\n self.socket.close(4007);\r\n }, this.connectTimeout);\r\n};\r\n\r\nSCTransport.prototype = Object.create(Emitter.prototype);\r\n\r\nSCTransport.CONNECTING = SCTransport.prototype.CONNECTING = 'connecting';\r\nSCTransport.OPEN = SCTransport.prototype.OPEN = 'open';\r\nSCTransport.CLOSED = SCTransport.prototype.CLOSED = 'closed';\r\n\r\nSCTransport.prototype.uri = function () {\r\n var query = this.options.query || {};\r\n var schema = this.options.secure ? 'wss' : 'ws';\r\n\r\n if (this.options.timestampRequests) {\r\n query[this.options.timestampParam] = (new Date()).getTime();\r\n }\r\n\r\n query = querystring.encode(query);\r\n\r\n if (query.length) {\r\n query = '?' + query;\r\n }\r\n\r\n var host;\r\n if (this.options.host) {\r\n host = this.options.host;\r\n } else {\r\n var port = '';\r\n\r\n if (this.options.port && ((schema == 'wss' && this.options.port != 443)\r\n || (schema == 'ws' && this.options.port != 80))) {\r\n port = ':' + this.options.port;\r\n }\r\n host = this.options.hostname + port;\r\n }\r\n\r\n return schema + '://' + host + this.options.path + query;\r\n};\r\n\r\nSCTransport.prototype._onOpen = function () {\r\n var self = this;\r\n\r\n clearTimeout(this._connectTimeoutRef);\r\n this._resetPingTimeout();\r\n\r\n this._handshake(function (err, status) {\r\n if (err) {\r\n var statusCode;\r\n if (status && status.code) {\r\n statusCode = status.code;\r\n } else {\r\n statusCode = 4003;\r\n }\r\n self._onError(err);\r\n self._onClose(statusCode, err.toString());\r\n self.socket.close(statusCode);\r\n } else {\r\n self.state = self.OPEN;\r\n Emitter.prototype.emit.call(self, 'open', status);\r\n self._resetPingTimeout();\r\n }\r\n });\r\n};\r\n\r\nSCTransport.prototype._handshake = function (callback) {\r\n var self = this;\r\n this.auth.loadToken(this.authTokenName, function (err, token) {\r\n if (err) {\r\n callback(err);\r\n } else {\r\n // Don't wait for this.state to be 'open'.\r\n // The underlying WebSocket (this.socket) is already open.\r\n var options = {\r\n force: true\r\n };\r\n self.emit('#handshake', {\r\n authToken: token\r\n }, options, function (err, status) {\r\n if (status) {\r\n // Add the token which was used as part of authentication attempt\r\n // to the status object.\r\n status.authToken = token;\r\n if (status.authError) {\r\n status.authError = scErrors.hydrateError(status.authError);\r\n }\r\n }\r\n callback(err, status);\r\n });\r\n }\r\n });\r\n};\r\n\r\nSCTransport.prototype._abortAllPendingEventsDueToBadConnection = function (failureType) {\r\n for (var i in this._callbackMap) {\r\n if (this._callbackMap.hasOwnProperty(i)) {\r\n var eventObject = this._callbackMap[i];\r\n delete this._callbackMap[i];\r\n\r\n clearTimeout(eventObject.timeout);\r\n delete eventObject.timeout;\r\n\r\n var errorMessage = \"Event '\" + eventObject.event +\r\n \"' was aborted due to a bad connection\";\r\n var badConnectionError = new BadConnectionError(errorMessage, failureType);\r\n\r\n var callback = eventObject.callback;\r\n delete eventObject.callback;\r\n callback.call(eventObject, badConnectionError, eventObject);\r\n }\r\n }\r\n};\r\n\r\nSCTransport.prototype._onClose = function (code, data) {\r\n delete this.socket.onopen;\r\n delete this.socket.onclose;\r\n delete this.socket.onmessage;\r\n delete this.socket.onerror;\r\n\r\n clearTimeout(this._connectTimeoutRef);\r\n clearTimeout(this._pingTimeoutTicker);\r\n clearTimeout(this._batchTimeout);\r\n\r\n if (this.state == this.OPEN) {\r\n this.state = this.CLOSED;\r\n Emitter.prototype.emit.call(this, 'close', code, data);\r\n this._abortAllPendingEventsDueToBadConnection('disconnect');\r\n\r\n } else if (this.state == this.CONNECTING) {\r\n this.state = this.CLOSED;\r\n Emitter.prototype.emit.call(this, 'openAbort', code, data);\r\n this._abortAllPendingEventsDueToBadConnection('connectAbort');\r\n }\r\n};\r\n\r\nSCTransport.prototype._handleEventObject = function (obj, message) {\r\n if (obj && obj.event != null) {\r\n var response = new Response(this, obj.cid);\r\n Emitter.prototype.emit.call(this, 'event', obj.event, obj.data, response);\r\n } else if (obj && obj.rid != null) {\r\n var eventObject = this._callbackMap[obj.rid];\r\n if (eventObject) {\r\n clearTimeout(eventObject.timeout);\r\n delete eventObject.timeout;\r\n delete this._callbackMap[obj.rid];\r\n\r\n if (eventObject.callback) {\r\n var rehydratedError = scErrors.hydrateError(obj.error);\r\n eventObject.callback(rehydratedError, obj.data);\r\n }\r\n }\r\n } else {\r\n Emitter.prototype.emit.call(this, 'event', 'raw', message);\r\n }\r\n};\r\n\r\nSCTransport.prototype._onMessage = function (message) {\r\n Emitter.prototype.emit.call(this, 'event', 'message', message);\r\n\r\n var obj = this.decode(message);\r\n\r\n // If ping\r\n if (obj == '#1') {\r\n this._resetPingTimeout();\r\n if (this.socket.readyState == this.socket.OPEN) {\r\n this.sendObject('#2');\r\n }\r\n } else {\r\n if (Array.isArray(obj)) {\r\n var len = obj.length;\r\n for (var i = 0; i < len; i++) {\r\n this._handleEventObject(obj[i], message);\r\n }\r\n } else {\r\n this._handleEventObject(obj, message);\r\n }\r\n }\r\n};\r\n\r\nSCTransport.prototype._onError = function (err) {\r\n Emitter.prototype.emit.call(this, 'error', err);\r\n};\r\n\r\nSCTransport.prototype._resetPingTimeout = function () {\r\n if (this.pingTimeoutDisabled) {\r\n return;\r\n }\r\n var self = this;\r\n\r\n var now = (new Date()).getTime();\r\n clearTimeout(this._pingTimeoutTicker);\r\n\r\n this._pingTimeoutTicker = setTimeout(function () {\r\n self._onClose(4000);\r\n self.socket.close(4000);\r\n }, this.pingTimeout);\r\n};\r\n\r\nSCTransport.prototype.getBytesReceived = function () {\r\n return this.socket.bytesReceived;\r\n};\r\n\r\nSCTransport.prototype.close = function (code, data) {\r\n code = code || 1000;\r\n\r\n if (this.state == this.OPEN) {\r\n var packet = {\r\n code: code,\r\n data: data\r\n };\r\n this.emit('#disconnect', packet);\r\n\r\n this._onClose(code, data);\r\n this.socket.close(code);\r\n\r\n } else if (this.state == this.CONNECTING) {\r\n this._onClose(code, data);\r\n this.socket.close(code);\r\n }\r\n};\r\n\r\nSCTransport.prototype.emitObject = function (eventObject, options) {\r\n var simpleEventObject = {\r\n event: eventObject.event,\r\n data: eventObject.data\r\n };\r\n\r\n if (eventObject.callback) {\r\n simpleEventObject.cid = eventObject.cid = this.callIdGenerator();\r\n this._callbackMap[eventObject.cid] = eventObject;\r\n }\r\n\r\n this.sendObject(simpleEventObject, options);\r\n\r\n return eventObject.cid || null;\r\n};\r\n\r\nSCTransport.prototype._handleEventAckTimeout = function (eventObject) {\r\n if (eventObject.cid) {\r\n delete this._callbackMap[eventObject.cid];\r\n }\r\n delete eventObject.timeout;\r\n\r\n var callback = eventObject.callback;\r\n if (callback) {\r\n delete eventObject.callback;\r\n var error = new TimeoutError(\"Event response for '\" + eventObject.event + \"' timed out\");\r\n callback.call(eventObject, error, eventObject);\r\n }\r\n};\r\n\r\n// The last two optional arguments (a and b) can be options and/or callback\r\nSCTransport.prototype.emit = function (event, data, a, b) {\r\n var self = this;\r\n\r\n var callback, options;\r\n\r\n if (b) {\r\n options = a;\r\n callback = b;\r\n } else {\r\n if (a instanceof Function) {\r\n options = {};\r\n callback = a;\r\n } else {\r\n options = a;\r\n }\r\n }\r\n\r\n var eventObject = {\r\n event: event,\r\n data: data,\r\n callback: callback\r\n };\r\n\r\n if (callback && !options.noTimeout) {\r\n eventObject.timeout = setTimeout(function () {\r\n self._handleEventAckTimeout(eventObject);\r\n }, this.options.ackTimeout);\r\n }\r\n\r\n var cid = null;\r\n if (this.state == this.OPEN || options.force) {\r\n cid = this.emitObject(eventObject, options);\r\n }\r\n return cid;\r\n};\r\n\r\nSCTransport.prototype.cancelPendingResponse = function (cid) {\r\n delete this._callbackMap[cid];\r\n};\r\n\r\nSCTransport.prototype.decode = function (message) {\r\n return this.codec.decode(message);\r\n};\r\n\r\nSCTransport.prototype.encode = function (object) {\r\n return this.codec.encode(object);\r\n};\r\n\r\nSCTransport.prototype.send = function (data) {\r\n if (this.socket.readyState != this.socket.OPEN) {\r\n this._onClose(1005);\r\n } else {\r\n this.socket.send(data);\r\n }\r\n};\r\n\r\nSCTransport.prototype.serializeObject = function (object) {\r\n var str, formatError;\r\n try {\r\n str = this.encode(object);\r\n } catch (err) {\r\n formatError = err;\r\n this._onError(formatError);\r\n }\r\n if (!formatError) {\r\n return str;\r\n }\r\n return null;\r\n};\r\n\r\nSCTransport.prototype.sendObjectBatch = function (object) {\r\n var self = this;\r\n\r\n this._batchSendList.push(object);\r\n if (this._batchTimeout) {\r\n return;\r\n }\r\n\r\n this._batchTimeout = setTimeout(function () {\r\n delete self._batchTimeout;\r\n if (self._batchSendList.length) {\r\n var str = self.serializeObject(self._batchSendList);\r\n if (str != null) {\r\n self.send(str);\r\n }\r\n self._batchSendList = [];\r\n }\r\n }, this.options.pubSubBatchDuration || 0);\r\n};\r\n\r\nSCTransport.prototype.sendObjectSingle = function (object) {\r\n var str = this.serializeObject(object);\r\n if (str != null) {\r\n this.send(str);\r\n }\r\n};\r\n\r\nSCTransport.prototype.sendObject = function (object, options) {\r\n if (options && options.batch) {\r\n this.sendObjectBatch(object);\r\n } else {\r\n this.sendObjectSingle(object);\r\n }\r\n};\r\n\r\nmodule.exports.SCTransport = SCTransport;\r\n","var global;\nif (typeof WorkerGlobalScope !== 'undefined') {\n global = self;\n} else {\n global = typeof window != 'undefined' && window || (function() { return this; })();\n}\n\nvar WebSocket = global.WebSocket || global.MozWebSocket;\n\n/**\n * WebSocket constructor.\n *\n * The third `opts` options object gets ignored in web browsers, since it's\n * non-standard, and throws a TypeError if passed to the constructor.\n * See: https://github.com/einaros/ws/issues/227\n *\n * @param {String} uri\n * @param {Array} protocols (optional)\n * @param {Object} opts (optional)\n * @api public\n */\n\nfunction ws(uri, protocols, opts) {\n var instance;\n if (protocols) {\n instance = new WebSocket(uri, protocols);\n } else {\n instance = new WebSocket(uri);\n }\n return instance;\n}\n\nif (WebSocket) ws.prototype = WebSocket.prototype;\n\nmodule.exports = WebSocket ? ws : null;\n","var clone = (function() {\n'use strict';\n\nfunction _instanceof(obj, type) {\n return type != null && obj instanceof type;\n}\n\nvar nativeMap;\ntry {\n nativeMap = Map;\n} catch(_) {\n // maybe a reference error because no `Map`. Give it a dummy value that no\n // value will ever be an instanceof.\n nativeMap = function() {};\n}\n\nvar nativeSet;\ntry {\n nativeSet = Set;\n} catch(_) {\n nativeSet = function() {};\n}\n\nvar nativePromise;\ntry {\n nativePromise = Promise;\n} catch(_) {\n nativePromise = function() {};\n}\n\n/**\n * Clones (copies) an Object using deep copying.\n *\n * This function supports circular references by default, but if you are certain\n * there are no circular references in your object, you can save some CPU time\n * by calling clone(obj, false).\n *\n * Caution: if `circular` is false and `parent` contains circular references,\n * your program may enter an infinite loop and crash.\n *\n * @param `parent` - the object to be cloned\n * @param `circular` - set to true if the object to be cloned may contain\n * circular references. (optional - true by default)\n * @param `depth` - set to a number if the object is only to be cloned to\n * a particular depth. (optional - defaults to Infinity)\n * @param `prototype` - sets the prototype to be used when cloning an object.\n * (optional - defaults to parent prototype).\n * @param `includeNonEnumerable` - set to true if the non-enumerable properties\n * should be cloned as well. Non-enumerable properties on the prototype\n * chain will be ignored. (optional - false by default)\n*/\nfunction clone(parent, circular, depth, prototype, includeNonEnumerable) {\n if (typeof circular === 'object') {\n depth = circular.depth;\n prototype = circular.prototype;\n includeNonEnumerable = circular.includeNonEnumerable;\n circular = circular.circular;\n }\n // maintain two arrays for circular references, where corresponding parents\n // and children have the same index\n var allParents = [];\n var allChildren = [];\n\n var useBuffer = typeof Buffer != 'undefined';\n\n if (typeof circular == 'undefined')\n circular = true;\n\n if (typeof depth == 'undefined')\n depth = Infinity;\n\n // recurse this function so we don't reset allParents and allChildren\n function _clone(parent, depth) {\n // cloning null always returns null\n if (parent === null)\n return null;\n\n if (depth === 0)\n return parent;\n\n var child;\n var proto;\n if (typeof parent != 'object') {\n return parent;\n }\n\n if (_instanceof(parent, nativeMap)) {\n child = new nativeMap();\n } else if (_instanceof(parent, nativeSet)) {\n child = new nativeSet();\n } else if (_instanceof(parent, nativePromise)) {\n child = new nativePromise(function (resolve, reject) {\n parent.then(function(value) {\n resolve(_clone(value, depth - 1));\n }, function(err) {\n reject(_clone(err, depth - 1));\n });\n });\n } else if (clone.__isArray(parent)) {\n child = [];\n } else if (clone.__isRegExp(parent)) {\n child = new RegExp(parent.source, __getRegExpFlags(parent));\n if (parent.lastIndex) child.lastIndex = parent.lastIndex;\n } else if (clone.__isDate(parent)) {\n child = new Date(parent.getTime());\n } else if (useBuffer && Buffer.isBuffer(parent)) {\n child = new Buffer(parent.length);\n parent.copy(child);\n return child;\n } else if (_instanceof(parent, Error)) {\n child = Object.create(parent);\n } else {\n if (typeof prototype == 'undefined') {\n proto = Object.getPrototypeOf(parent);\n child = Object.create(proto);\n }\n else {\n child = Object.create(prototype);\n proto = prototype;\n }\n }\n\n if (circular) {\n var index = allParents.indexOf(parent);\n\n if (index != -1) {\n return allChildren[index];\n }\n allParents.push(parent);\n allChildren.push(child);\n }\n\n if (_instanceof(parent, nativeMap)) {\n parent.forEach(function(value, key) {\n var keyChild = _clone(key, depth - 1);\n var valueChild = _clone(value, depth - 1);\n child.set(keyChild, valueChild);\n });\n }\n if (_instanceof(parent, nativeSet)) {\n parent.forEach(function(value) {\n var entryChild = _clone(value, depth - 1);\n child.add(entryChild);\n });\n }\n\n for (var i in parent) {\n var attrs;\n if (proto) {\n attrs = Object.getOwnPropertyDescriptor(proto, i);\n }\n\n if (attrs && attrs.set == null) {\n continue;\n }\n child[i] = _clone(parent[i], depth - 1);\n }\n\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(parent);\n for (var i = 0; i < symbols.length; i++) {\n // Don't need to worry about cloning a symbol because it is a primitive,\n // like a number or string.\n var symbol = symbols[i];\n var descriptor = Object.getOwnPropertyDescriptor(parent, symbol);\n if (descriptor && !descriptor.enumerable && !includeNonEnumerable) {\n continue;\n }\n child[symbol] = _clone(parent[symbol], depth - 1);\n if (!descriptor.enumerable) {\n Object.defineProperty(child, symbol, {\n enumerable: false\n });\n }\n }\n }\n\n if (includeNonEnumerable) {\n var allPropertyNames = Object.getOwnPropertyNames(parent);\n for (var i = 0; i < allPropertyNames.length; i++) {\n var propertyName = allPropertyNames[i];\n var descriptor = Object.getOwnPropertyDescriptor(parent, propertyName);\n if (descriptor && descriptor.enumerable) {\n continue;\n }\n child[propertyName] = _clone(parent[propertyName], depth - 1);\n Object.defineProperty(child, propertyName, {\n enumerable: false\n });\n }\n }\n\n return child;\n }\n\n return _clone(parent, depth);\n}\n\n/**\n * Simple flat clone using prototype, accepts only objects, usefull for property\n * override on FLAT configuration object (no nested props).\n *\n * USE WITH CAUTION! This may not behave as you wish if you do not know how this\n * works.\n */\nclone.clonePrototype = function clonePrototype(parent) {\n if (parent === null)\n return null;\n\n var c = function () {};\n c.prototype = parent;\n return new c();\n};\n\n// private utility functions\n\nfunction __objToStr(o) {\n return Object.prototype.toString.call(o);\n}\nclone.__objToStr = __objToStr;\n\nfunction __isDate(o) {\n return typeof o === 'object' && __objToStr(o) === '[object Date]';\n}\nclone.__isDate = __isDate;\n\nfunction __isArray(o) {\n return typeof o === 'object' && __objToStr(o) === '[object Array]';\n}\nclone.__isArray = __isArray;\n\nfunction __isRegExp(o) {\n return typeof o === 'object' && __objToStr(o) === '[object RegExp]';\n}\nclone.__isRegExp = __isRegExp;\n\nfunction __getRegExpFlags(re) {\n var flags = '';\n if (re.global) flags += 'g';\n if (re.ignoreCase) flags += 'i';\n if (re.multiline) flags += 'm';\n return flags;\n}\nclone.__getRegExpFlags = __getRegExpFlags;\n\nreturn clone;\n})();\n\nif (typeof module === 'object' && module.exports) {\n module.exports = clone;\n}\n","\r\n/**\r\n * Expose `Emitter`.\r\n */\r\n\r\nif (typeof module !== 'undefined') {\r\n module.exports = Emitter;\r\n}\r\n\r\n/**\r\n * Initialize a new `Emitter`.\r\n *\r\n * @api public\r\n */\r\n\r\nfunction Emitter(obj) {\r\n if (obj) return mixin(obj);\r\n};\r\n\r\n/**\r\n * Mixin the emitter properties.\r\n *\r\n * @param {Object} obj\r\n * @return {Object}\r\n * @api private\r\n */\r\n\r\nfunction mixin(obj) {\r\n for (var key in Emitter.prototype) {\r\n obj[key] = Emitter.prototype[key];\r\n }\r\n return obj;\r\n}\r\n\r\n/**\r\n * Listen on the given `event` with `fn`.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.on =\r\nEmitter.prototype.addEventListener = function(event, fn){\r\n this._callbacks = this._callbacks || {};\r\n (this._callbacks['$' + event] = this._callbacks['$' + event] || [])\r\n .push(fn);\r\n return this;\r\n};\r\n\r\n/**\r\n * Adds an `event` listener that will be invoked a single\r\n * time then automatically removed.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.once = function(event, fn){\r\n function on() {\r\n this.off(event, on);\r\n fn.apply(this, arguments);\r\n }\r\n\r\n on.fn = fn;\r\n this.on(event, on);\r\n return this;\r\n};\r\n\r\n/**\r\n * Remove the given callback for `event` or all\r\n * registered callbacks.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.off =\r\nEmitter.prototype.removeListener =\r\nEmitter.prototype.removeAllListeners =\r\nEmitter.prototype.removeEventListener = function(event, fn){\r\n this._callbacks = this._callbacks || {};\r\n\r\n // all\r\n if (0 == arguments.length) {\r\n this._callbacks = {};\r\n return this;\r\n }\r\n\r\n // specific event\r\n var callbacks = this._callbacks['$' + event];\r\n if (!callbacks) return this;\r\n\r\n // remove all handlers\r\n if (1 == arguments.length) {\r\n delete this._callbacks['$' + event];\r\n return this;\r\n }\r\n\r\n // remove specific handler\r\n var cb;\r\n for (var i = 0; i < callbacks.length; i++) {\r\n cb = callbacks[i];\r\n if (cb === fn || cb.fn === fn) {\r\n callbacks.splice(i, 1);\r\n break;\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Emit `event` with the given args.\r\n *\r\n * @param {String} event\r\n * @param {Mixed} ...\r\n * @return {Emitter}\r\n */\r\n\r\nEmitter.prototype.emit = function(event){\r\n this._callbacks = this._callbacks || {};\r\n var args = [].slice.call(arguments, 1)\r\n , callbacks = this._callbacks['$' + event];\r\n\r\n if (callbacks) {\r\n callbacks = callbacks.slice(0);\r\n for (var i = 0, len = callbacks.length; i < len; ++i) {\r\n callbacks[i].apply(this, args);\r\n }\r\n }\r\n\r\n return this;\r\n};\r\n\r\n/**\r\n * Return array of callbacks for `event`.\r\n *\r\n * @param {String} event\r\n * @return {Array}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.listeners = function(event){\r\n this._callbacks = this._callbacks || {};\r\n return this._callbacks['$' + event] || [];\r\n};\r\n\r\n/**\r\n * Check if this emitter has `event` handlers.\r\n *\r\n * @param {String} event\r\n * @return {Boolean}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.hasListeners = function(event){\r\n return !! this.listeners(event).length;\r\n};\r\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n// If obj.hasOwnProperty has been overridden, then calling\n// obj.hasOwnProperty(prop) will break.\n// See: https://github.com/joyent/node/issues/1707\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nmodule.exports = function(qs, sep, eq, options) {\n sep = sep || '&';\n eq = eq || '=';\n var obj = {};\n\n if (typeof qs !== 'string' || qs.length === 0) {\n return obj;\n }\n\n var regexp = /\\+/g;\n qs = qs.split(sep);\n\n var maxKeys = 1000;\n if (options && typeof options.maxKeys === 'number') {\n maxKeys = options.maxKeys;\n }\n\n var len = qs.length;\n // maxKeys <= 0 means that we should not limit keys count\n if (maxKeys > 0 && len > maxKeys) {\n len = maxKeys;\n }\n\n for (var i = 0; i < len; ++i) {\n var x = qs[i].replace(regexp, '%20'),\n idx = x.indexOf(eq),\n kstr, vstr, k, v;\n\n if (idx >= 0) {\n kstr = x.substr(0, idx);\n vstr = x.substr(idx + 1);\n } else {\n kstr = x;\n vstr = '';\n }\n\n k = decodeURIComponent(kstr);\n v = decodeURIComponent(vstr);\n\n if (!hasOwnProperty(obj, k)) {\n obj[k] = v;\n } else if (Array.isArray(obj[k])) {\n obj[k].push(v);\n } else {\n obj[k] = [obj[k], v];\n }\n }\n\n return obj;\n};\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar stringifyPrimitive = function(v) {\n switch (typeof v) {\n case 'string':\n return v;\n\n case 'boolean':\n return v ? 'true' : 'false';\n\n case 'number':\n return isFinite(v) ? v : '';\n\n default:\n return '';\n }\n};\n\nmodule.exports = function(obj, sep, eq, name) {\n sep = sep || '&';\n eq = eq || '=';\n if (obj === null) {\n obj = undefined;\n }\n\n if (typeof obj === 'object') {\n return Object.keys(obj).map(function(k) {\n var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;\n if (Array.isArray(obj[k])) {\n return obj[k].map(function(v) {\n return ks + encodeURIComponent(stringifyPrimitive(v));\n }).join(sep);\n } else {\n return ks + encodeURIComponent(stringifyPrimitive(obj[k]));\n }\n }).join(sep);\n\n }\n\n if (!name) return '';\n return encodeURIComponent(stringifyPrimitive(name)) + eq +\n encodeURIComponent(stringifyPrimitive(obj));\n};\n","'use strict';\n\nexports.decode = exports.parse = require('./decode');\nexports.encode = exports.stringify = require('./encode');\n","var v1 = require('./v1');\nvar v4 = require('./v4');\n\nvar uuid = v4;\nuuid.v1 = v1;\nuuid.v4 = v4;\n\nmodule.exports = uuid;\n","/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\nvar byteToHex = [];\nfor (var i = 0; i < 256; ++i) {\n byteToHex[i] = (i + 0x100).toString(16).substr(1);\n}\n\nfunction bytesToUuid(buf, offset) {\n var i = offset || 0;\n var bth = byteToHex;\n return bth[buf[i++]] + bth[buf[i++]] +\n bth[buf[i++]] + bth[buf[i++]] + '-' +\n bth[buf[i++]] + bth[buf[i++]] + '-' +\n bth[buf[i++]] + bth[buf[i++]] + '-' +\n bth[buf[i++]] + bth[buf[i++]] + '-' +\n bth[buf[i++]] + bth[buf[i++]] +\n bth[buf[i++]] + bth[buf[i++]] +\n bth[buf[i++]] + bth[buf[i++]];\n}\n\nmodule.exports = bytesToUuid;\n","// Unique ID creation requires a high quality random # generator. In the\n// browser this is a little complicated due to unknown quality of Math.random()\n// and inconsistent support for the `crypto` API. We do the best we can via\n// feature-detection\n\n// getRandomValues needs to be invoked in a context where \"this\" is a Crypto implementation.\nvar getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues.bind(crypto)) ||\n (typeof(msCrypto) != 'undefined' && msCrypto.getRandomValues.bind(msCrypto));\nif (getRandomValues) {\n // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto\n var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef\n\n module.exports = function whatwgRNG() {\n getRandomValues(rnds8);\n return rnds8;\n };\n} else {\n // Math.random()-based (RNG)\n //\n // If all else fails, use Math.random(). It's fast, but is of unspecified\n // quality.\n var rnds = new Array(16);\n\n module.exports = function mathRNG() {\n for (var i = 0, r; i < 16; i++) {\n if ((i & 0x03) === 0) r = Math.random() * 0x100000000;\n rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;\n }\n\n return rnds;\n };\n}\n","var rng = require('./lib/rng');\nvar bytesToUuid = require('./lib/bytesToUuid');\n\n// **`v1()` - Generate time-based UUID**\n//\n// Inspired by https://github.com/LiosK/UUID.js\n// and http://docs.python.org/library/uuid.html\n\nvar _nodeId;\nvar _clockseq;\n\n// Previous uuid creation time\nvar _lastMSecs = 0;\nvar _lastNSecs = 0;\n\n// See https://github.com/broofa/node-uuid for API details\nfunction v1(options, buf, offset) {\n var i = buf && offset || 0;\n var b = buf || [];\n\n options = options || {};\n var node = options.node || _nodeId;\n var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;\n\n // node and clockseq need to be initialized to random values if they're not\n // specified. We do this lazily to minimize issues related to insufficient\n // system entropy. See #189\n if (node == null || clockseq == null) {\n var seedBytes = rng();\n if (node == null) {\n // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n node = _nodeId = [\n seedBytes[0] | 0x01,\n seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]\n ];\n }\n if (clockseq == null) {\n // Per 4.2.2, randomize (14 bit) clockseq\n clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;\n }\n }\n\n // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();\n\n // Per 4.2.1.2, use count of uuid's generated during the current clock\n // cycle to simulate higher resolution clock\n var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;\n\n // Time since last uuid creation (in msecs)\n var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;\n\n // Per 4.2.1.2, Bump clockseq on clock regression\n if (dt < 0 && options.clockseq === undefined) {\n clockseq = clockseq + 1 & 0x3fff;\n }\n\n // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n // time interval\n if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {\n nsecs = 0;\n }\n\n // Per 4.2.1.2 Throw error if too many uuids are requested\n if (nsecs >= 10000) {\n throw new Error('uuid.v1(): Can\\'t create more than 10M uuids/sec');\n }\n\n _lastMSecs = msecs;\n _lastNSecs = nsecs;\n _clockseq = clockseq;\n\n // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n msecs += 12219292800000;\n\n // `time_low`\n var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n b[i++] = tl >>> 24 & 0xff;\n b[i++] = tl >>> 16 & 0xff;\n b[i++] = tl >>> 8 & 0xff;\n b[i++] = tl & 0xff;\n\n // `time_mid`\n var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;\n b[i++] = tmh >>> 8 & 0xff;\n b[i++] = tmh & 0xff;\n\n // `time_high_and_version`\n b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n b[i++] = tmh >>> 16 & 0xff;\n\n // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n b[i++] = clockseq >>> 8 | 0x80;\n\n // `clock_seq_low`\n b[i++] = clockseq & 0xff;\n\n // `node`\n for (var n = 0; n < 6; ++n) {\n b[i + n] = node[n];\n }\n\n return buf ? buf : bytesToUuid(b);\n}\n\nmodule.exports = v1;\n","var rng = require('./lib/rng');\nvar bytesToUuid = require('./lib/bytesToUuid');\n\nfunction v4(options, buf, offset) {\n var i = buf && offset || 0;\n\n if (typeof(options) == 'string') {\n buf = options === 'binary' ? new Array(16) : null;\n options = null;\n }\n options = options || {};\n\n var rnds = options.random || (options.rng || rng)();\n\n // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n rnds[6] = (rnds[6] & 0x0f) | 0x40;\n rnds[8] = (rnds[8] & 0x3f) | 0x80;\n\n // Copy bytes to buffer, if provided\n if (buf) {\n for (var ii = 0; ii < 16; ++ii) {\n buf[i + ii] = rnds[ii];\n }\n }\n\n return buf || bytesToUuid(rnds);\n}\n\nmodule.exports = v4;\n","module.exports = __WEBPACK_EXTERNAL_MODULE__746__;","module.exports = __WEBPACK_EXTERNAL_MODULE__802__;","module.exports = __WEBPACK_EXTERNAL_MODULE__407__;","module.exports = __WEBPACK_EXTERNAL_MODULE__156__;","module.exports = __WEBPACK_EXTERNAL_MODULE__952__;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","// Logging callback\nlet logger = () => {};\n\n/**\n * Register the logging callback\n *\n * @param {Function} callback\n */\nfunction registerLogger(callback) {\n logger = callback;\n}\n\n/**\n * Send an alert message to the logger\n *\n * @param {String} message\n */\nfunction logAlert(message) {\n logger({message: `[Onyx] ${message}`, level: 'alert'});\n}\n\n/**\n * Send an info message to the logger\n *\n * @param {String} message\n */\nfunction logInfo(message) {\n logger({message: `[Onyx] ${message}`, level: 'info'});\n}\n\nexport {\n registerLogger,\n logInfo,\n logAlert,\n};\n","// Mostly copied from https://medium.com/@lubaka.a/how-to-remove-lodash-performance-improvement-b306669ad0e1\n\n/**\n * @param {mixed} val\n * @returns {boolean}\n*/\nfunction isMergeableObject(val) {\n const nonNullObject = val != null ? typeof val === 'object' : false;\n return (nonNullObject\n && Object.prototype.toString.call(val) !== '[object RegExp]'\n && Object.prototype.toString.call(val) !== '[object Date]');\n}\n\n/**\n * @param {Object} target\n * @param {Object} source\n * @returns {Object}\n*/\nfunction mergeObject(target, source) {\n const destination = {};\n if (isMergeableObject(target)) {\n // lodash adds a small overhead so we don't use it here\n // eslint-disable-next-line rulesdir/prefer-underscore-method\n const targetKeys = Object.keys(target);\n for (let i = 0; i < targetKeys.length; ++i) {\n const key = targetKeys[i];\n destination[key] = target[key];\n }\n }\n\n // lodash adds a small overhead so we don't use it here\n // eslint-disable-next-line rulesdir/prefer-underscore-method\n const sourceKeys = Object.keys(source);\n for (let i = 0; i < sourceKeys.length; ++i) {\n const key = sourceKeys[i];\n if (source[key] === undefined) {\n // eslint-disable-next-line no-continue\n continue;\n }\n if (!isMergeableObject(source[key]) || !target[key]) {\n destination[key] = source[key];\n } else {\n // eslint-disable-next-line no-use-before-define\n destination[key] = fastMerge(target[key], source[key]);\n }\n }\n\n return destination;\n}\n\n/**\n * @param {Object|Array} target\n * @param {Object|Array} source\n * @returns {Object|Array}\n*/\nfunction fastMerge(target, source) {\n // lodash adds a small overhead so we don't use it here\n // eslint-disable-next-line rulesdir/prefer-underscore-method\n const array = Array.isArray(source);\n if (array) {\n return source;\n }\n return mergeObject(target, source);\n}\n\nexport default fastMerge;\n","import _ from 'underscore';\nimport {deepEqual} from 'fast-equals';\nimport fastMerge from './fastMerge';\n\nconst isDefined = _.negate(_.isUndefined);\n\n/**\n * In memory cache providing data by reference\n * Encapsulates Onyx cache related functionality\n */\nclass OnyxCache {\n constructor() {\n /**\n * @private\n * Cache of all the storage keys available in persistent storage\n * @type {Set<string>}\n */\n this.storageKeys = new Set();\n\n /**\n * @private\n * Unique list of keys maintained in access order (most recent at the end)\n * @type {Set<string>}\n */\n this.recentKeys = new Set();\n\n /**\n * @private\n * A map of cached values\n * @type {Record<string, *>}\n */\n this.storageMap = {};\n\n /**\n * @private\n * Captured pending tasks for already running storage methods\n * @type {Record<string, Promise>}\n */\n this.pendingPromises = {};\n\n // bind all public methods to prevent problems with `this`\n _.bindAll(\n this,\n 'getAllKeys', 'getValue', 'hasCacheForKey', 'addKey', 'set', 'drop', 'merge',\n 'hasPendingTask', 'getTaskPromise', 'captureTask', 'removeLeastRecentlyUsedKeys',\n 'setRecentKeysLimit',\n );\n }\n\n /**\n * Get all the storage keys\n * @returns {string[]}\n */\n getAllKeys() {\n return Array.from(this.storageKeys);\n }\n\n /**\n * Get a cached value from storage\n * @param {string} key\n * @returns {*}\n */\n getValue(key) {\n this.addToAccessedKeys(key);\n return this.storageMap[key];\n }\n\n /**\n * Check whether cache has data for the given key\n * @param {string} key\n * @returns {boolean}\n */\n hasCacheForKey(key) {\n return isDefined(this.storageMap[key]);\n }\n\n /**\n * Saves a key in the storage keys list\n * Serves to keep the result of `getAllKeys` up to date\n * @param {string} key\n */\n addKey(key) {\n this.storageKeys.add(key);\n }\n\n /**\n * Set's a key value in cache\n * Adds the key to the storage keys list as well\n * @param {string} key\n * @param {*} value\n * @returns {*} value - returns the cache value\n */\n set(key, value) {\n this.addKey(key);\n this.addToAccessedKeys(key);\n this.storageMap[key] = value;\n\n return value;\n }\n\n /**\n * Forget the cached value for the given key\n * @param {string} key\n */\n drop(key) {\n delete this.storageMap[key];\n this.storageKeys.delete(key);\n this.recentKeys.delete(key);\n }\n\n /**\n * Deep merge data to cache, any non existing keys will be created\n * @param {Record<string, *>} data - a map of (cache) key - values\n */\n merge(data) {\n if (!_.isObject(data) || _.isArray(data)) {\n throw new Error('data passed to cache.merge() must be an Object of onyx key/value pairs');\n }\n\n // lodash adds a small overhead so we don't use it here\n // eslint-disable-next-line prefer-object-spread, rulesdir/prefer-underscore-method\n this.storageMap = Object.assign({}, fastMerge(this.storageMap, data));\n\n const storageKeys = this.getAllKeys();\n const mergedKeys = _.keys(data);\n this.storageKeys = new Set([...storageKeys, ...mergedKeys]);\n _.each(mergedKeys, key => this.addToAccessedKeys(key));\n }\n\n /**\n * Check whether the given task is already running\n * @param {string} taskName - unique name given for the task\n * @returns {*}\n */\n hasPendingTask(taskName) {\n return isDefined(this.pendingPromises[taskName]);\n }\n\n /**\n * Use this method to prevent concurrent calls for the same thing\n * Instead of calling the same task again use the existing promise\n * provided from this function\n * @template T\n * @param {string} taskName - unique name given for the task\n * @returns {Promise<T>}\n */\n getTaskPromise(taskName) {\n return this.pendingPromises[taskName];\n }\n\n /**\n * Capture a promise for a given task so other caller can\n * hook up to the promise if it's still pending\n * @template T\n * @param {string} taskName - unique name for the task\n * @param {Promise<T>} promise\n * @returns {Promise<T>}\n */\n captureTask(taskName, promise) {\n this.pendingPromises[taskName] = promise.finally(() => {\n delete this.pendingPromises[taskName];\n });\n\n return this.pendingPromises[taskName];\n }\n\n /**\n * @private\n * Adds a key to the top of the recently accessed keys\n * @param {string} key\n */\n addToAccessedKeys(key) {\n // Removing and re-adding a key ensures it's at the end of the list\n this.recentKeys.delete(key);\n this.recentKeys.add(key);\n }\n\n /**\n * Remove keys that don't fall into the range of recently used keys\n */\n removeLeastRecentlyUsedKeys() {\n if (this.recentKeys.size <= this.maxRecentKeysSize) {\n return;\n }\n\n // Get the last N keys by doing a negative slice\n const recentlyAccessed = [...this.recentKeys].slice(-this.maxRecentKeysSize);\n const storageKeys = _.keys(this.storageMap);\n const keysToRemove = _.difference(storageKeys, recentlyAccessed);\n\n _.each(keysToRemove, this.drop);\n }\n\n /**\n * Set the recent keys list size\n * @param {number} limit\n */\n setRecentKeysLimit(limit) {\n this.maxRecentKeysSize = limit;\n }\n\n /**\n * @param {String} key\n * @param {*} value\n * @returns {Boolean}\n */\n hasValueChanged(key, value) {\n return !deepEqual(this.storageMap[key], value);\n }\n}\n\nconst instance = new OnyxCache();\n\nexport default instance;\n","import _ from 'underscore';\n\n/**\n * Returns true if the haystack begins with the needle\n *\n * @param {String} haystack The full string to be searched\n * @param {String} needle The case-sensitive string to search for\n * @return {Boolean} Returns true if the haystack starts with the needle.\n */\nfunction startsWith(haystack, needle) {\n return _.isString(haystack)\n && _.isString(needle)\n && haystack.startsWith(needle);\n}\n\n/**\n * Checks if parameter is a string or function.\n * If it is a string, then we will just return it.\n * If it is a function, then we will call it with\n * any additional arguments and return the result.\n *\n * @param {String|Function} parameter\n * @returns {*}\n */\nfunction result(parameter, ...args) {\n return _.isFunction(parameter) ? parameter(...args) : parameter;\n}\n\nexport {startsWith, result};\n","import lodashTransform from 'lodash/transform';\nimport _ from 'underscore';\n\nlet debugSetState = false;\n\n/**\n * @param {Boolean} debug\n */\nfunction setShouldDebugSetState(debug) {\n debugSetState = debug;\n}\n\n/**\n * Deep diff between two objects. Useful for figuring out what changed about an object from one render to the next so\n * that state and props updates can be optimized.\n *\n * @param {Object} object\n * @param {Object} base\n * @return {Object}\n */\nfunction diffObject(object, base) {\n function changes(obj, comparisonObject) {\n return lodashTransform(obj, (result, value, key) => {\n if (_.isEqual(value, comparisonObject[key])) {\n return;\n }\n\n // eslint-disable-next-line no-param-reassign\n result[key] = (_.isObject(value) && _.isObject(comparisonObject[key]))\n ? changes(value, comparisonObject[key])\n : value;\n });\n }\n return changes(object, base);\n}\n\n/**\n * Provide insights into why a setState() call occurred by diffing the before and after values.\n *\n * @param {Object} mapping\n * @param {*} previousValue\n * @param {*} newValue\n * @param {String} caller\n * @param {String} [keyThatChanged]\n */\nfunction logSetStateCall(mapping, previousValue, newValue, caller, keyThatChanged) {\n if (!debugSetState) {\n return;\n }\n\n const logParams = {};\n if (keyThatChanged) {\n logParams.keyThatChanged = keyThatChanged;\n }\n if (_.isObject(newValue) && _.isObject(previousValue)) {\n logParams.difference = diffObject(previousValue, newValue);\n } else {\n logParams.previousValue = previousValue;\n logParams.newValue = newValue;\n }\n\n console.debug(`[Onyx-Debug] ${mapping.displayName} setState() called. Subscribed to key '${mapping.key}' (${caller})`, logParams);\n}\n\nexport {\n logSetStateCall,\n setShouldDebugSetState,\n};\n","import {\n set,\n keys,\n getMany,\n setMany,\n get,\n clear,\n del,\n delMany,\n createStore,\n promisifyRequest,\n} from 'idb-keyval';\nimport _ from 'underscore';\nimport fastMerge from '../../fastMerge';\n\n// We don't want to initialize the store while the JS bundle loads as idb-keyval will try to use global.indexedDB\n// which might not be available in certain environments that load the bundle (e.g. electron main process).\nlet customStoreInstance;\nconst getCustomStore = () => {\n if (!customStoreInstance) {\n customStoreInstance = createStore('OnyxDB', 'keyvaluepairs');\n }\n return customStoreInstance;\n};\n\nconst provider = {\n /**\n * Sets the value for a given key. The only requirement is that the value should be serializable to JSON string\n * @param {String} key\n * @param {*} value\n * @return {Promise<void>}\n */\n setItem: (key, value) => set(key, value, getCustomStore()),\n\n /**\n * Get multiple key-value pairs for the give array of keys in a batch.\n * This is optimized to use only one database transaction.\n * @param {String[]} keysParam\n * @return {Promise<Array<[key, value]>>}\n */\n multiGet: keysParam => getMany(keysParam, getCustomStore())\n .then(values => _.map(values, (value, index) => [keysParam[index], value])),\n\n /**\n * Multiple merging of existing and new values in a batch\n * @param {Array<[key, value]>} pairs\n * @return {Promise<void>}\n */\n multiMerge: pairs => getCustomStore()('readwrite', (store) => {\n // Note: we are using the manual store transaction here, to fit the read and update\n // of the items in one transaction to achieve best performance.\n\n const getValues = Promise.all(_.map(pairs, ([key]) => promisifyRequest(store.get(key))));\n\n return getValues.then((values) => {\n const upsertMany = _.map(pairs, ([key, value], index) => {\n const prev = values[index];\n const newValue = _.isObject(prev) ? fastMerge(prev, value) : value;\n return promisifyRequest(store.put(newValue, key));\n });\n return Promise.all(upsertMany);\n });\n }),\n\n /**\n * Merging an existing value with a new one\n * @param {String} key\n * @param {any} _changes - not used, as we rely on the pre-merged data from the `modifiedData`\n * @param {any} modifiedData - the pre-merged data from `Onyx.applyMerge`\n * @return {Promise<void>}\n */\n mergeItem(key, _changes, modifiedData) {\n return provider.multiMerge([[key, modifiedData]]);\n },\n\n /**\n * Stores multiple key-value pairs in a batch\n * @param {Array<[key, value]>} pairs\n * @return {Promise<void>}\n */\n multiSet: pairs => setMany(pairs, getCustomStore()),\n\n /**\n * Clear everything from storage and also stops the SyncQueue from adding anything more to storage\n * @returns {Promise<void>}\n */\n clear: () => clear(getCustomStore()),\n\n // This is a noop for now in order to keep clients from crashing see https://github.com/Expensify/Expensify/issues/312438\n setMemoryOnlyKeys: () => {},\n\n /**\n * Returns all keys available in storage\n * @returns {Promise<String[]>}\n */\n getAllKeys: () => keys(getCustomStore()),\n\n /**\n * Get the value of a given key or return `null` if it's not available in storage\n * @param {String} key\n * @return {Promise<*>}\n */\n getItem: key => get(key, getCustomStore()),\n\n /**\n * Remove given key and it's value from storage\n * @param {String} key\n * @returns {Promise<void>}\n */\n removeItem: key => del(key, getCustomStore()),\n\n /**\n * Remove given keys and their values from storage\n *\n * @param {Array} keysParam\n * @returns {Promise}\n */\n removeItems: keysParam => delMany(keysParam, getCustomStore()),\n\n /**\n * Gets the total bytes of the database file\n * @returns {Promise<number>}\n */\n getDatabaseSize() {\n if (!window.navigator || !window.navigator.storage) {\n throw new Error('StorageManager browser API unavailable');\n }\n\n return window.navigator.storage.estimate()\n .then(value => ({\n bytesUsed: value.usage,\n bytesRemaining: value.quota - value.usage,\n }))\n .catch((error) => {\n throw new Error(`Unable to estimate web storage quota. Original error: ${error}`);\n });\n },\n};\n\nexport default provider;\n","/**\n * This file is here to wrap IDBKeyVal with a layer that provides data-changed events like the ones that exist\n * when using LocalStorage APIs in the browser. These events are great because multiple tabs can listen for when\n * data changes and then stay up-to-date with everything happening in Onyx.\n */\nimport _ from 'underscore';\nimport Storage from './providers/IDBKeyVal';\n\nconst SYNC_ONYX = 'SYNC_ONYX';\n\n/**\n * Raise an event thorough `localStorage` to let other tabs know a value changed\n * @param {String} onyxKey\n */\nfunction raiseStorageSyncEvent(onyxKey) {\n global.localStorage.setItem(SYNC_ONYX, onyxKey);\n global.localStorage.removeItem(SYNC_ONYX, onyxKey);\n}\n\nfunction raiseStorageSyncManyKeysEvent(onyxKeys) {\n _.each(onyxKeys, (onyxKey) => {\n raiseStorageSyncEvent(onyxKey);\n });\n}\n\nconst webStorage = {\n ...Storage,\n\n /**\n * @param {Function} onStorageKeyChanged Storage synchronization mechanism keeping all opened tabs in sync\n */\n keepInstancesSync(onStorageKeyChanged) {\n // Override set, remove and clear to raise storage events that we intercept in other tabs\n this.setItem = (key, value) => Storage.setItem(key, value)\n .then(() => raiseStorageSyncEvent(key));\n\n this.removeItem = key => Storage.removeItem(key)\n .then(() => raiseStorageSyncEvent(key));\n\n this.removeItems = keys => Storage.removeItems(keys)\n .then(() => raiseStorageSyncManyKeysEvent(keys));\n\n // If we just call Storage.clear other tabs will have no idea which keys were available previously\n // so that they can call keysChanged for them. That's why we iterate over every key and raise a storage sync\n // event for each one\n this.clear = () => {\n let allKeys;\n\n // They keys must be retreived before storage is cleared or else the list of keys would be empty\n return Storage.getAllKeys()\n .then((keys) => {\n allKeys = keys;\n })\n .then(() => Storage.clear())\n .then(() => {\n // Now that storage is cleared, the storage sync event can happen which is a more atomic action\n // for other browser tabs\n _.each(allKeys, raiseStorageSyncEvent);\n });\n };\n\n // This listener will only be triggered by events coming from other tabs\n global.addEventListener('storage', (event) => {\n // Ignore events that don't originate from the SYNC_ONYX logic\n if (event.key !== SYNC_ONYX || !event.newValue) {\n return;\n }\n\n const onyxKey = event.newValue;\n Storage.getItem(onyxKey)\n .then(value => onStorageKeyChanged(onyxKey, value));\n });\n },\n};\n\nexport default webStorage;\n","import WebStorage from './WebStorage';\n\nexport default WebStorage;\n","import _ from 'underscore';\n\nconst {connectViaExtension} = process.env.NODE_ENV === 'production' ? require('remotedev') : {\n connectViaExtension: () => ({\n init: () => {},\n send: () => {},\n }),\n};\n\nclass DevTools {\n /**\n * @callback onStateChange\n * @param {object} state\n */\n /**\n * Creates an instance of DevTools, with an internal state that mirrors the storage.\n *\n * @param {object} initialState - initial state of the storage\n * @param {onStateChange} onStateChange - callback which is triggered when we timetravel to a different registered action\n */\n constructor(initialState = {}) {\n this.state = initialState;\n this.remotedev = connectViaExtension();\n this.remotedev.init(this.state);\n }\n\n /**\n * Registers an action that updated the current state of the storage\n *\n * @param {string} type - name of the action\n * @param {any} payload - data written to the storage\n * @param {object} stateChanges - partial state that got updated after the changes\n */\n registerAction(type, payload = undefined, stateChanges = {}) {\n const newState = {\n ...this.state,\n ...stateChanges,\n };\n\n this.remotedev.send({type, payload}, newState);\n this.state = newState;\n }\n\n /**\n * This clears the internal state of the DevTools, preserving the keys not included in `keyToBeRemoved`\n *\n * @param {string[]} keysToBeRemoved\n */\n clearState(keysToBeRemoved = []) {\n const pairs = _.map(keysToBeRemoved, key => [key, undefined]);\n this.registerAction('CLEAR', undefined, _.object(pairs));\n }\n}\n\nexport default DevTools;\n","/* eslint-disable no-continue */\nimport {deepEqual} from 'fast-equals';\nimport _ from 'underscore';\nimport * as Logger from './Logger';\nimport cache from './OnyxCache';\nimport * as Str from './Str';\nimport createDeferredTask from './createDeferredTask';\nimport fastMerge from './fastMerge';\nimport * as PerformanceUtils from './metrics/PerformanceUtils';\nimport Storage from './storage';\nimport DevTools from './DevTools';\n\n// Method constants\nconst METHOD = {\n SET: 'set',\n MERGE: 'merge',\n MERGE_COLLECTION: 'mergecollection',\n MULTI_SET: 'multiset',\n CLEAR: 'clear',\n};\n\n// Key/value store of Onyx key and arrays of values to merge\nconst mergeQueue = {};\n\n// Keeps track of the last connectionID that was used so we can keep incrementing it\nlet lastConnectionID = 0;\n\n// Holds a mapping of all the react components that want their state subscribed to a store key\nconst callbackToStateMapping = {};\n\n// Keeps a copy of the values of the onyx collection keys as a map for faster lookups\nlet onyxCollectionKeyMap = new Map();\n\n// Holds a list of keys that have been directly subscribed to or recently modified from least to most recent\nlet recentlyAccessedKeys = [];\n\n// Holds a list of keys that are safe to remove when we reach max storage. If a key does not match with\n// whatever appears in this list it will NEVER be a candidate for eviction.\nlet evictionAllowList = [];\n\nlet devTools = {\n registerAction: () => {},\n clearState: () => {},\n};\n\n// Holds a map of keys and connectionID arrays whose keys will never be automatically evicted as\n// long as we have at least one subscriber that returns false for the canEvict property.\nconst evictionBlocklist = {};\n\n// Optional user-provided key value states set when Onyx initializes or clears\nlet defaultKeyStates = {};\n\n// Connections can be made before `Onyx.init`. They would wait for this task before resolving\nconst deferredInitTask = createDeferredTask();\n\n/**\n * Uses a selector function to return a simplified version of sourceData\n * @param {Mixed} sourceData\n * @param {Function} selector Function that takes sourceData and returns a simplified version of it\n * @param {Object} [withOnyxInstanceState]\n * @returns {Mixed}\n */\nconst getSubsetOfData = (sourceData, selector, withOnyxInstanceState) => selector(sourceData, withOnyxInstanceState);\n\n/**\n * Takes a collection of items (eg. {testKey_1:{a:'a'}, testKey_2:{b:'b'}})\n * and runs it through a reducer function to return a subset of the data according to a selector.\n * The resulting collection will only contain items that are returned by the selector.\n * @param {Object} collection\n * @param {String|Function} selector (see method docs for getSubsetOfData() for full details)\n * @param {Object} [withOnyxInstanceState]\n * @returns {Object}\n */\nconst reduceCollectionWithSelector = (collection, selector, withOnyxInstanceState) => _.reduce(collection, (finalCollection, item, key) => {\n // eslint-disable-next-line no-param-reassign\n finalCollection[key] = getSubsetOfData(item, selector, withOnyxInstanceState);\n\n return finalCollection;\n}, {});\n\n/**\n * Get some data from the store\n *\n * @private\n * @param {string} key\n * @returns {Promise<*>}\n */\nfunction get(key) {\n // When we already have the value in cache - resolve right away\n if (cache.hasCacheForKey(key)) {\n return Promise.resolve(cache.getValue(key));\n }\n\n const taskName = `get:${key}`;\n\n // When a value retrieving task for this key is still running hook to it\n if (cache.hasPendingTask(taskName)) {\n return cache.getTaskPromise(taskName);\n }\n\n // Otherwise retrieve the value from storage and capture a promise to aid concurrent usages\n const promise = Storage.getItem(key)\n .then((val) => {\n cache.set(key, val);\n return val;\n })\n .catch(err => Logger.logInfo(`Unable to get item from persistent storage. Key: ${key} Error: ${err}`));\n\n return cache.captureTask(taskName, promise);\n}\n\n/**\n * Returns current key names stored in persisted storage\n * @private\n * @returns {Promise<string[]>}\n */\nfunction getAllKeys() {\n // When we've already read stored keys, resolve right away\n const storedKeys = cache.getAllKeys();\n if (storedKeys.length > 0) {\n return Promise.resolve(storedKeys);\n }\n\n const taskName = 'getAllKeys';\n\n // When a value retrieving task for all keys is still running hook to it\n if (cache.hasPendingTask(taskName)) {\n return cache.getTaskPromise(taskName);\n }\n\n // Otherwise retrieve the keys from storage and capture a promise to aid concurrent usages\n const promise = Storage.getAllKeys()\n .then((keys) => {\n _.each(keys, key => cache.addKey(key));\n return keys;\n });\n\n return cache.captureTask(taskName, promise);\n}\n\n/**\n * Checks to see if the a subscriber's supplied key\n * is associated with a collection of keys.\n *\n * @private\n * @param {String} key\n * @returns {Boolean}\n */\nfunction isCollectionKey(key) {\n return onyxCollectionKeyMap.has(key);\n}\n\n/**\n * @param {String} collectionKey\n * @param {String} key\n * @returns {Boolean}\n */\nfunction isCollectionMemberKey(collectionKey, key) {\n return Str.startsWith(key, collectionKey) && key.length > collectionKey.length;\n}\n\n/**\n * Checks to see if a provided key is the exact configured key of our connected subscriber\n * or if the provided key is a collection member key (in case our configured key is a \"collection key\")\n *\n * @private\n * @param {String} configKey\n * @param {String} key\n * @return {Boolean}\n */\nfunction isKeyMatch(configKey, key) {\n return isCollectionKey(configKey)\n ? Str.startsWith(key, configKey)\n : configKey === key;\n}\n\n/**\n * Checks to see if this key has been flagged as\n * safe for removal.\n *\n * @private\n * @param {String} testKey\n * @returns {Boolean}\n */\nfunction isSafeEvictionKey(testKey) {\n return _.some(evictionAllowList, key => isKeyMatch(key, testKey));\n}\n\n/**\n * Tries to get a value from the cache. If the value is not present in cache it will return the default value or undefined.\n * If the requested key is a collection, it will return an object with all the collection members.\n *\n * @param {String} key\n * @param {Object} mapping\n * @returns {Mixed}\n */\nfunction tryGetCachedValue(key, mapping = {}) {\n let val = cache.getValue(key);\n\n if (isCollectionKey(key)) {\n const allKeys = cache.getAllKeys();\n const matchingKeys = _.filter(allKeys, k => k.startsWith(key));\n const values = _.reduce(matchingKeys, (finalObject, matchedKey) => {\n const cachedValue = cache.getValue(matchedKey);\n if (cachedValue) {\n // This is permissible because we're in the process of constructing the final object in a reduce function.\n // eslint-disable-next-line no-param-reassign\n finalObject[matchedKey] = cachedValue;\n }\n return finalObject;\n }, {});\n if (_.isEmpty(values)) {\n return;\n }\n val = values;\n }\n\n if (mapping.selector) {\n const state = mapping.withOnyxInstance ? mapping.withOnyxInstance.state : undefined;\n if (isCollectionKey(key)) {\n return reduceCollectionWithSelector(val, mapping.selector, state);\n }\n return getSubsetOfData(val, mapping.selector, state);\n }\n\n return val;\n}\n\n/**\n * Remove a key from the recently accessed key list.\n *\n * @private\n * @param {String} key\n */\nfunction removeLastAccessedKey(key) {\n recentlyAccessedKeys = _.without(recentlyAccessedKeys, key);\n}\n\n/**\n * Add a key to the list of recently accessed keys. The least\n * recently accessed key should be at the head and the most\n * recently accessed key at the tail.\n *\n * @private\n * @param {String} key\n */\nfunction addLastAccessedKey(key) {\n // Only specific keys belong in this list since we cannot remove an entire collection.\n if (isCollectionKey(key) || !isSafeEvictionKey(key)) {\n return;\n }\n\n removeLastAccessedKey(key);\n recentlyAccessedKeys.push(key);\n}\n\n/**\n * Removes a key previously added to this list\n * which will enable it to be deleted again.\n *\n * @private\n * @param {String} key\n * @param {Number} connectionID\n */\nfunction removeFromEvictionBlockList(key, connectionID) {\n evictionBlocklist[key] = _.without(evictionBlocklist[key] || [], connectionID);\n\n // Remove the key if there are no more subscribers\n if (evictionBlocklist[key].length === 0) {\n delete evictionBlocklist[key];\n }\n}\n\n/**\n * Keys added to this list can never be deleted.\n *\n * @private\n * @param {String} key\n * @param {Number} connectionID\n */\nfunction addToEvictionBlockList(key, connectionID) {\n removeFromEvictionBlockList(key, connectionID);\n\n if (!evictionBlocklist[key]) {\n evictionBlocklist[key] = [];\n }\n\n evictionBlocklist[key].push(connectionID);\n}\n\n/**\n * Take all the keys that are safe to evict and add them to\n * the recently accessed list when initializing the app. This\n * enables keys that have not recently been accessed to be\n * removed.\n *\n * @private\n * @returns {Promise}\n */\nfunction addAllSafeEvictionKeysToRecentlyAccessedList() {\n return getAllKeys()\n .then((keys) => {\n _.each(evictionAllowList, (safeEvictionKey) => {\n _.each(keys, (key) => {\n if (!isKeyMatch(safeEvictionKey, key)) {\n return;\n }\n addLastAccessedKey(key);\n });\n });\n });\n}\n\n/**\n * @private\n * @param {String} collectionKey\n * @returns {Object}\n */\nfunction getCachedCollection(collectionKey) {\n const collectionMemberKeys = _.filter(cache.getAllKeys(), (\n storedKey => isCollectionMemberKey(collectionKey, storedKey)\n ));\n\n return _.reduce(collectionMemberKeys, (prev, curr) => {\n const cachedValue = cache.getValue(curr);\n if (!cachedValue) {\n return prev;\n }\n\n // eslint-disable-next-line no-param-reassign\n prev[curr] = cachedValue;\n return prev;\n }, {});\n}\n\n/**\n * When a collection of keys change, search for any callbacks matching the collection key and trigger those callbacks\n *\n * @private\n * @param {String} collectionKey\n * @param {Object} partialCollection - a partial collection of grouped member keys\n */\nfunction keysChanged(collectionKey, partialCollection) {\n // We are iterating over all subscribers similar to keyChanged(). However, we are looking for subscribers who are subscribing to either a collection key or\n // individual collection key member for the collection that is being updated. It is important to note that the collection parameter cane be a PARTIAL collection\n // and does not represent all of the combined keys and values for a collection key. It is just the \"new\" data that was merged in via mergeCollection().\n const stateMappingKeys = _.keys(callbackToStateMapping);\n for (let i = 0; i < stateMappingKeys.length; i++) {\n const subscriber = callbackToStateMapping[stateMappingKeys[i]];\n if (!subscriber) {\n continue;\n }\n\n // Skip iteration if we do not have a collection key or a collection member key on this subscriber\n if (!Str.startsWith(subscriber.key, collectionKey)) {\n continue;\n }\n\n /**\n * e.g. Onyx.connect({key: ONYXKEYS.COLLECTION.REPORT, callback: ...});\n */\n const isSubscribedToCollectionKey = subscriber.key === collectionKey;\n\n /**\n * e.g. Onyx.connect({key: `${ONYXKEYS.COLLECTION.REPORT}{reportID}`, callback: ...});\n */\n const isSubscribedToCollectionMemberKey = isCollectionMemberKey(collectionKey, subscriber.key);\n\n // We prepare the \"cached collection\" which is the entire collection + the new partial data that\n // was merged in via mergeCollection().\n const cachedCollection = getCachedCollection(collectionKey);\n\n // Regular Onyx.connect() subscriber found.\n if (_.isFunction(subscriber.callback)) {\n // If they are subscribed to the collection key and using waitForCollectionCallback then we'll\n // send the whole cached collection.\n if (isSubscribedToCollectionKey) {\n if (subscriber.waitForCollectionCallback) {\n subscriber.callback(cachedCollection);\n continue;\n }\n\n // If they are not using waitForCollectionCallback then we notify the subscriber with\n // the new merged data but only for any keys in the partial collection.\n const dataKeys = _.keys(partialCollection);\n for (let j = 0; j < dataKeys.length; j++) {\n const dataKey = dataKeys[j];\n subscriber.callback(cachedCollection[dataKey], dataKey);\n }\n continue;\n }\n\n // And if the subscriber is specifically only tracking a particular collection member key then we will\n // notify them with the cached data for that key only.\n if (isSubscribedToCollectionMemberKey) {\n subscriber.callback(cachedCollection[subscriber.key], subscriber.key);\n continue;\n }\n\n continue;\n }\n\n // React component subscriber found.\n if (subscriber.withOnyxInstance) {\n // We are subscribed to a collection key so we must update the data in state with the new\n // collection member key values from the partial update.\n if (isSubscribedToCollectionKey) {\n // If the subscriber has a selector, then the component's state must only be updated with the data\n // returned by the selector.\n if (subscriber.selector) {\n subscriber.withOnyxInstance.setState((prevState) => {\n const previousData = prevState[subscriber.statePropertyName];\n const newData = reduceCollectionWithSelector(cachedCollection, subscriber.selector, subscriber.withOnyxInstance.state);\n\n if (!deepEqual(previousData, newData)) {\n return {\n [subscriber.statePropertyName]: newData,\n };\n }\n return null;\n });\n continue;\n }\n\n subscriber.withOnyxInstance.setState((prevState) => {\n const finalCollection = _.clone(prevState[subscriber.statePropertyName] || {});\n const dataKeys = _.keys(partialCollection);\n for (let j = 0; j < dataKeys.length; j++) {\n const dataKey = dataKeys[j];\n finalCollection[dataKey] = cachedCollection[dataKey];\n }\n\n PerformanceUtils.logSetStateCall(subscriber, prevState[subscriber.statePropertyName], finalCollection, 'keysChanged', collectionKey);\n return {\n [subscriber.statePropertyName]: finalCollection,\n };\n });\n continue;\n }\n\n // If a React component is only interested in a single key then we can set the cached value directly to the state name.\n if (isSubscribedToCollectionMemberKey) {\n // However, we only want to update this subscriber if the partial data contains a change.\n // Otherwise, we would update them with a value they already have and trigger an unnecessary re-render.\n const dataFromCollection = partialCollection[subscriber.key];\n if (_.isUndefined(dataFromCollection)) {\n continue;\n }\n\n // If the subscriber has a selector, then the component's state must only be updated with the data\n // returned by the selector and the state should only change when the subset of data changes from what\n // it was previously.\n if (subscriber.selector) {\n subscriber.withOnyxInstance.setState((prevState) => {\n const prevData = prevState[subscriber.statePropertyName];\n const newData = getSubsetOfData(cachedCollection[subscriber.key], subscriber.selector, subscriber.withOnyxInstance.state);\n if (!deepEqual(prevData, newData)) {\n PerformanceUtils.logSetStateCall(subscriber, prevData, newData, 'keysChanged', collectionKey);\n return {\n [subscriber.statePropertyName]: newData,\n };\n }\n\n return null;\n });\n continue;\n }\n\n subscriber.withOnyxInstance.setState((prevState) => {\n const data = cachedCollection[subscriber.key];\n const previousData = prevState[subscriber.statePropertyName];\n if (data === previousData) {\n return null;\n }\n\n PerformanceUtils.logSetStateCall(subscriber, previousData, data, 'keysChanged', collectionKey);\n return {\n [subscriber.statePropertyName]: data,\n };\n });\n }\n }\n }\n}\n\n/**\n * When a key change happens, search for any callbacks matching the key or collection key and trigger those callbacks\n *\n * @example\n * keyChanged(key, value, subscriber => subscriber.initWithStoredValues === false)\n *\n * @private\n * @param {String} key\n * @param {*} data\n * @param {Function} [canUpdateSubscriber] only subscribers that pass this truth test will be updated\n */\nfunction keyChanged(key, data, canUpdateSubscriber) {\n // Add or remove this key from the recentlyAccessedKeys lists\n if (!_.isNull(data)) {\n addLastAccessedKey(key);\n } else {\n removeLastAccessedKey(key);\n }\n\n // We are iterating over all subscribers to see if they are interested in the key that has just changed. If the subscriber's key is a collection key then we will\n // notify them if the key that changed is a collection member. Or if it is a regular key notify them when there is an exact match. Depending on whether the subscriber\n // was connected via withOnyx we will call setState() directly on the withOnyx instance. If it is a regular connection we will pass the data to the provided callback.\n const stateMappingKeys = _.keys(callbackToStateMapping);\n for (let i = 0; i < stateMappingKeys.length; i++) {\n const subscriber = callbackToStateMapping[stateMappingKeys[i]];\n if (!subscriber || !isKeyMatch(subscriber.key, key) || (_.isFunction(canUpdateSubscriber) && !canUpdateSubscriber(subscriber))) {\n continue;\n }\n\n // Subscriber is a regular call to connect() and provided a callback\n if (_.isFunction(subscriber.callback)) {\n if (isCollectionKey(subscriber.key) && subscriber.waitForCollectionCallback) {\n const cachedCollection = getCachedCollection(subscriber.key);\n cachedCollection[key] = data;\n subscriber.callback(cachedCollection);\n continue;\n }\n\n subscriber.callback(data, key);\n continue;\n }\n\n // Subscriber connected via withOnyx() HOC\n if (subscriber.withOnyxInstance) {\n // Check if we are subscribing to a collection key and overwrite the collection member key value in state\n if (isCollectionKey(subscriber.key)) {\n // If the subscriber has a selector, then the consumer of this data must only be given the data\n // returned by the selector and only when the selected data has changed.\n if (subscriber.selector) {\n subscriber.withOnyxInstance.setState((prevState) => {\n const prevData = prevState[subscriber.statePropertyName];\n const newData = {\n [key]: getSubsetOfData(data, subscriber.selector, subscriber.withOnyxInstance.state),\n };\n const prevDataWithNewData = {\n ...prevData,\n ...newData,\n };\n if (!deepEqual(prevData, prevDataWithNewData)) {\n PerformanceUtils.logSetStateCall(subscriber, prevData, newData, 'keyChanged', key);\n return {\n [subscriber.statePropertyName]: prevDataWithNewData,\n };\n }\n return null;\n });\n continue;\n }\n\n subscriber.withOnyxInstance.setState((prevState) => {\n const collection = prevState[subscriber.statePropertyName] || {};\n const newCollection = {\n ...collection,\n [key]: data,\n };\n PerformanceUtils.logSetStateCall(subscriber, collection, newCollection, 'keyChanged', key);\n return {\n [subscriber.statePropertyName]: newCollection,\n };\n });\n continue;\n }\n\n // If the subscriber has a selector, then the component's state must only be updated with the data\n // returned by the selector and only if the selected data has changed.\n if (subscriber.selector) {\n subscriber.withOnyxInstance.setState((prevState) => {\n const previousValue = getSubsetOfData(prevState[subscriber.statePropertyName], subscriber.selector, subscriber.withOnyxInstance.state);\n const newValue = getSubsetOfData(data, subscriber.selector, subscriber.withOnyxInstance.state);\n if (!deepEqual(previousValue, newValue)) {\n return {\n [subscriber.statePropertyName]: newValue,\n };\n }\n return null;\n });\n continue;\n }\n\n // If we did not match on a collection key then we just set the new data to the state property\n subscriber.withOnyxInstance.setState((prevState) => {\n const previousData = prevState[subscriber.statePropertyName];\n if (previousData === data) {\n return null;\n }\n\n PerformanceUtils.logSetStateCall(subscriber, previousData, data, 'keyChanged', key);\n return {\n [subscriber.statePropertyName]: data,\n };\n });\n continue;\n }\n\n console.error('Warning: Found a matching subscriber to a key that changed, but no callback or withOnyxInstance could be found.');\n }\n}\n\n/**\n * Sends the data obtained from the keys to the connection. It either:\n * - sets state on the withOnyxInstances\n * - triggers the callback function\n *\n * @private\n * @param {Object} mapping\n * @param {Object} [mapping.withOnyxInstance]\n * @param {String} [mapping.statePropertyName]\n * @param {Function} [mapping.callback]\n * @param {String} [mapping.selector]\n * @param {*|null} val\n * @param {String} matchedKey\n */\nfunction sendDataToConnection(mapping, val, matchedKey) {\n // If the mapping no longer exists then we should not send any data.\n // This means our subscriber disconnected or withOnyx wrapped component unmounted.\n if (!callbackToStateMapping[mapping.connectionID]) {\n return;\n }\n\n if (mapping.withOnyxInstance) {\n let newData = val;\n\n // If the mapping has a selector, then the component's state must only be updated with the data\n // returned by the selector.\n if (mapping.selector) {\n if (isCollectionKey(mapping.key)) {\n newData = reduceCollectionWithSelector(val, mapping.selector, mapping.withOnyxInstance.state);\n } else {\n newData = getSubsetOfData(val, mapping.selector, mapping.withOnyxInstance.state);\n }\n }\n\n PerformanceUtils.logSetStateCall(mapping, null, newData, 'sendDataToConnection');\n mapping.withOnyxInstance.setWithOnyxState(mapping.statePropertyName, newData);\n return;\n }\n\n if (_.isFunction(mapping.callback)) {\n mapping.callback(val, matchedKey);\n }\n}\n\n/**\n * We check to see if this key is flagged as safe for eviction and add it to the recentlyAccessedKeys list so that when we\n * run out of storage the least recently accessed key can be removed.\n *\n * @private\n * @param {Object} mapping\n */\nfunction addKeyToRecentlyAccessedIfNeeded(mapping) {\n if (!isSafeEvictionKey(mapping.key)) {\n return;\n }\n\n // Try to free some cache whenever we connect to a safe eviction key\n cache.removeLeastRecentlyUsedKeys();\n\n if (mapping.withOnyxInstance && !isCollectionKey(mapping.key)) {\n // All React components subscribing to a key flagged as a safe eviction key must implement the canEvict property.\n if (_.isUndefined(mapping.canEvict)) {\n throw new Error(\n `Cannot subscribe to safe eviction key '${mapping.key}' without providing a canEvict value.`,\n );\n }\n\n addLastAccessedKey(mapping.key);\n }\n}\n\n/**\n * Gets the data for a given an array of matching keys, combines them into an object, and sends the result back to the subscriber.\n *\n * @private\n * @param {Array} matchingKeys\n * @param {Object} mapping\n */\nfunction getCollectionDataAndSendAsObject(matchingKeys, mapping) {\n Promise.all(_.map(matchingKeys, key => get(key)))\n .then(values => _.reduce(values, (finalObject, value, i) => {\n // eslint-disable-next-line no-param-reassign\n finalObject[matchingKeys[i]] = value;\n return finalObject;\n }, {}))\n .then(val => sendDataToConnection(mapping, val));\n}\n\n/**\n * Subscribes a react component's state directly to a store key\n *\n * @example\n * const connectionID = Onyx.connect({\n * key: ONYXKEYS.SESSION,\n * callback: onSessionChange,\n * });\n *\n * @param {Object} mapping the mapping information to connect Onyx to the components state\n * @param {String} mapping.key ONYXKEY to subscribe to\n * @param {String} [mapping.statePropertyName] the name of the property in the state to connect the data to\n * @param {Object} [mapping.withOnyxInstance] whose setState() method will be called with any changed data\n * This is used by React components to connect to Onyx\n * @param {Function} [mapping.callback] a method that will be called with changed data\n * This is used by any non-React code to connect to Onyx\n * @param {Boolean} [mapping.initWithStoredValues] If set to false, then no data will be prefilled into the\n * component\n * @param {Boolean} [mapping.waitForCollectionCallback] If set to true, it will return the entire collection to the callback as a single object\n * @param {Function} [mapping.selector] THIS PARAM IS ONLY USED WITH withOnyx(). If included, this will be used to subscribe to a subset of an Onyx key's data.\n * The sourceData and withOnyx state are passed to the selector and should return the simplified data. Using this setting on `withOnyx` can have very positive\n * performance benefits because the component will only re-render when the subset of data changes. Otherwise, any change of data on any property would normally\n * cause the component to re-render (and that can be expensive from a performance standpoint).\n * @returns {Number} an ID to use when calling disconnect\n */\nfunction connect(mapping) {\n const connectionID = lastConnectionID++;\n callbackToStateMapping[connectionID] = mapping;\n callbackToStateMapping[connectionID].connectionID = connectionID;\n\n if (mapping.initWithStoredValues === false) {\n return connectionID;\n }\n\n // Commit connection only after init passes\n deferredInitTask.promise\n .then(() => addKeyToRecentlyAccessedIfNeeded(mapping))\n .then(getAllKeys)\n .then((keys) => {\n // We search all the keys in storage to see if any are a \"match\" for the subscriber we are connecting so that we\n // can send data back to the subscriber. Note that multiple keys can match as a subscriber could either be\n // subscribed to a \"collection key\" or a single key.\n const matchingKeys = _.filter(keys, key => isKeyMatch(mapping.key, key));\n\n // If the key being connected to does not exist we initialize the value with null. For subscribers that connected\n // directly via connect() they will simply get a null value sent to them without any information about which key matched\n // since there are none matched. In withOnyx() we wait for all connected keys to return a value before rendering the child\n // component. This null value will be filtered out so that the connected component can utilize defaultProps.\n if (matchingKeys.length === 0) {\n sendDataToConnection(mapping, null);\n return;\n }\n\n // When using a callback subscriber we will either trigger the provided callback for each key we find or combine all values\n // into an object and just make a single call. The latter behavior is enabled by providing a waitForCollectionCallback key\n // combined with a subscription to a collection key.\n if (_.isFunction(mapping.callback)) {\n if (isCollectionKey(mapping.key)) {\n if (mapping.waitForCollectionCallback) {\n getCollectionDataAndSendAsObject(matchingKeys, mapping);\n return;\n }\n\n // We did not opt into using waitForCollectionCallback mode so the callback is called for every matching key.\n for (let i = 0; i < matchingKeys.length; i++) {\n get(matchingKeys[i]).then(val => sendDataToConnection(mapping, val, matchingKeys[i]));\n }\n return;\n }\n\n // If we are not subscribed to a collection key then there's only a single key to send an update for.\n get(mapping.key).then(val => sendDataToConnection(mapping, val, mapping.key));\n return;\n }\n\n // If we have a withOnyxInstance that means a React component has subscribed via the withOnyx() HOC and we need to\n // group collection key member data into an object.\n if (mapping.withOnyxInstance) {\n if (isCollectionKey(mapping.key)) {\n getCollectionDataAndSendAsObject(matchingKeys, mapping);\n return;\n }\n\n // If the subscriber is not using a collection key then we just send a single value back to the subscriber\n get(mapping.key).then(val => sendDataToConnection(mapping, val, mapping.key));\n return;\n }\n\n console.error('Warning: Onyx.connect() was found without a callback or withOnyxInstance');\n });\n\n // The connectionID is returned back to the caller so that it can be used to clean up the connection when it's no longer needed\n // by calling Onyx.disconnect(connectionID).\n return connectionID;\n}\n\n/**\n * Remove the listener for a react component\n * @example\n * Onyx.disconnect(connectionID);\n *\n * @param {Number} connectionID unique id returned by call to Onyx.connect()\n * @param {String} [keyToRemoveFromEvictionBlocklist]\n */\nfunction disconnect(connectionID, keyToRemoveFromEvictionBlocklist) {\n if (!callbackToStateMapping[connectionID]) {\n return;\n }\n\n // Remove this key from the eviction block list as we are no longer\n // subscribing to it and it should be safe to delete again\n if (keyToRemoveFromEvictionBlocklist) {\n removeFromEvictionBlockList(keyToRemoveFromEvictionBlocklist, connectionID);\n }\n\n delete callbackToStateMapping[connectionID];\n}\n\n/**\n * This method mostly exists for historical reasons as this library was initially designed without a memory cache and one was added later.\n * For this reason, Onyx works more similar to what you might expect from a native AsyncStorage with reads, writes, etc all becoming\n * available async. Since we have code in our main applications that might expect things to work this way it's not safe to change this\n * behavior just yet.\n *\n * @example\n * notifySubscribersOnNextTick(key, value, subscriber => subscriber.initWithStoredValues === false)\n *\n * @param {String} key\n * @param {*} value\n * @param {Function} [canUpdateSubscriber] only subscribers that pass this truth test will be updated\n */\n// eslint-disable-next-line rulesdir/no-negated-variables\nfunction notifySubscribersOnNextTick(key, value, canUpdateSubscriber) {\n Promise.resolve().then(() => keyChanged(key, value, canUpdateSubscriber));\n}\n\n/**\n * This method is similar to notifySubscribersOnNextTick but it is built for working specifically with collections\n * so that keysChanged() is triggered for the collection and not keyChanged(). If this was not done, then the\n * subscriber callbacks receive the data in a different format than they normally expect and it breaks code.\n *\n * @param {String} key\n * @param {*} value\n */\n// eslint-disable-next-line rulesdir/no-negated-variables\nfunction notifyCollectionSubscribersOnNextTick(key, value) {\n Promise.resolve().then(() => keysChanged(key, value));\n}\n\n/**\n * Remove a key from Onyx and update the subscribers\n *\n * @private\n * @param {String} key\n * @return {Promise}\n */\nfunction remove(key) {\n cache.drop(key);\n notifySubscribersOnNextTick(key, null);\n return Storage.removeItem(key).then((result) => {\n devTools.registerAction(`REMOVE/${key.toUpperCase()}`, undefined, {[key]: undefined});\n return result;\n });\n}\n\n/**\n * @private\n * @returns {Promise<void>}\n */\nfunction reportStorageQuota() {\n return Storage.getDatabaseSize()\n .then(({bytesUsed, bytesRemaining}) => {\n Logger.logInfo(`Storage Quota Check -- bytesUsed: ${bytesUsed} bytesRemaining: ${bytesRemaining}`);\n })\n .catch((dbSizeError) => {\n Logger.logAlert(`Unable to get database size. Error: ${dbSizeError}`);\n });\n}\n\n/**\n * If we fail to set or merge we must handle this by\n * evicting some data from Onyx and then retrying to do\n * whatever it is we attempted to do.\n *\n * @private\n * @param {Error} error\n * @param {Function} onyxMethod\n * @param {...any} args\n * @return {Promise}\n */\nfunction evictStorageAndRetry(error, onyxMethod, ...args) {\n Logger.logInfo(`Failed to save to storage. Error: ${error}. onyxMethod: ${onyxMethod.name}`);\n\n if (error && Str.startsWith(error.message, 'Failed to execute \\'put\\' on \\'IDBObjectStore\\'')) {\n Logger.logAlert('Attempted to set invalid data set in Onyx. Please ensure all data is serializable.');\n throw error;\n }\n\n // Find the first key that we can remove that has no subscribers in our blocklist\n const keyForRemoval = _.find(recentlyAccessedKeys, key => !evictionBlocklist[key]);\n if (!keyForRemoval) {\n // If we have no acceptable keys to remove then we are possibly trying to save mission critical data. If this is the case,\n // then we should stop retrying as there is not much the user can do to fix this. Instead of getting them stuck in an infinite loop we\n // will allow this write to be skipped.\n Logger.logAlert('Out of storage. But found no acceptable keys to remove.');\n return reportStorageQuota();\n }\n\n // Remove the least recently viewed key that is not currently being accessed and retry.\n Logger.logInfo(`Out of storage. Evicting least recently accessed key (${keyForRemoval}) and retrying.`);\n reportStorageQuota();\n return remove(keyForRemoval)\n .then(() => onyxMethod(...args));\n}\n\n/**\n * Notifys subscribers and writes current value to cache\n *\n * @param {String} key\n * @param {*} value\n * @param {Boolean} hasChanged\n * @param {String} method\n */\nfunction broadcastUpdate(key, value, hasChanged, method) {\n // Logging properties only since values could be sensitive things we don't want to log\n Logger.logInfo(`${method}() called for key: ${key}${_.isObject(value) ? ` properties: ${_.keys(value).join(',')}` : ''}`);\n\n // Update subscribers if the cached value has changed, or when the subscriber specifically requires\n // all updates regardless of value changes (indicated by initWithStoredValues set to false).\n if (hasChanged) {\n cache.set(key, value);\n } else {\n cache.addToAccessedKeys(key);\n }\n\n notifySubscribersOnNextTick(key, value, subscriber => hasChanged || subscriber.initWithStoredValues === false);\n}\n\n/**\n * @param {String} key\n * @returns {Boolean}\n */\nfunction hasPendingMergeForKey(key) {\n return Boolean(mergeQueue[key]);\n}\n\n/**\n * We generally want to remove top-level nullish values from objects written to disk and cache, because it decreases the amount of data stored in memory and on disk.\n * On native, when merging an existing value with new changes, SQLite will use JSON_PATCH, which removes top-level nullish values.\n * To be consistent with the behaviour for merge, we'll also want to remove nullish values for \"set\" operations.\n * On web, IndexedDB will keep the top-level keys along with a null value and this uses up storage and memory.\n * This method will ensure that keys for null values are removed before an object is written to disk and cache so that all platforms are storing the data in the same efficient way.\n * @private\n * @param {*} value\n * @returns {*}\n */\nfunction removeNullObjectValues(value) {\n if (_.isArray(value) || !_.isObject(value)) {\n return value;\n }\n\n return _.omit(value, objectValue => _.isNull(objectValue));\n}\n\n/**\n * Write a value to our store with the given key\n *\n * @param {String} key ONYXKEY to set\n * @param {*} value value to store\n *\n * @returns {Promise}\n */\nfunction set(key, value) {\n if (_.isNull(value)) {\n return remove(key);\n }\n\n if (hasPendingMergeForKey(key)) {\n Logger.logAlert(`Onyx.set() called after Onyx.merge() for key: ${key}. It is recommended to use set() or merge() not both.`);\n }\n\n const valueWithNullRemoved = removeNullObjectValues(value);\n\n const hasChanged = cache.hasValueChanged(key, valueWithNullRemoved);\n\n // This approach prioritizes fast UI changes without waiting for data to be stored in device storage.\n broadcastUpdate(key, value, 'set');\n broadcastUpdate(key, valueWithNullRemoved, hasChanged, 'set');\n\n // If the value has not changed, calling Storage.setItem() would be redundant and a waste of performance, so return early instead.\n if (!hasChanged) {\n return Promise.resolve();\n }\n\n return Storage.setItem(key, valueWithNullRemoved)\n .then((result) => {\n devTools.registerAction(`SET/${key.toUpperCase()}`, valueWithNullRemoved, {[key]: valueWithNullRemoved});\n return result;\n })\n .catch(error => evictStorageAndRetry(error, set, key, valueWithNullRemoved));\n}\n\n/**\n * Storage expects array like: [[\"@MyApp_user\", value_1], [\"@MyApp_key\", value_2]]\n * This method transforms an object like {'@MyApp_user': myUserValue, '@MyApp_key': myKeyValue}\n * to an array of key-value pairs in the above format\n * @private\n * @param {Record} data\n * @return {Array} an array of key - value pairs <[key, value]>\n */\nfunction prepareKeyValuePairsForStorage(data) {\n return _.map(data, (value, key) => [key, value]);\n}\n\n/**\n * Sets multiple keys and values\n *\n * @example Onyx.multiSet({'key1': 'a', 'key2': 'b'});\n *\n * @param {Object} data object keyed by ONYXKEYS and the values to set\n * @returns {Promise}\n */\nfunction multiSet(data) {\n const keyValuePairs = prepareKeyValuePairsForStorage(data);\n\n _.each(data, (val, key) => {\n // Update cache and optimistically inform subscribers on the next tick\n cache.set(key, val);\n notifySubscribersOnNextTick(key, val);\n if (_.isNull(val)) {\n devTools.registerAction(`REMOVE/${key.toUpperCase()}`, val, {[key]: undefined});\n } else {\n devTools.registerAction(`SET/${key.toUpperCase()}`, val, {[key]: val});\n }\n });\n\n return Storage.multiSet(keyValuePairs)\n .catch(error => evictStorageAndRetry(error, multiSet, data));\n}\n\n/**\n * Merges an array of changes with an existing value\n *\n * @private\n * @param {*} existingValue\n * @param {Array<*>} changes Array of changes that should be applied to the existing value\n * @returns {*}\n */\nfunction applyMerge(existingValue, changes) {\n const lastChange = _.last(changes);\n\n if (_.isArray(existingValue) || _.isArray(lastChange)) {\n return lastChange;\n }\n\n if (_.isObject(existingValue) || _.every(changes, _.isObject)) {\n // Object values are merged one after the other\n // lodash adds a small overhead so we don't use it here\n // eslint-disable-next-line prefer-object-spread, rulesdir/prefer-underscore-method\n return _.reduce(changes, (modifiedData, change) => fastMerge(modifiedData, change),\n existingValue || {});\n }\n\n // If we have anything else we can't merge it so we'll\n // simply return the last value that was queued\n return lastChange;\n}\n\n/**\n * Merge a new value into an existing value at a key.\n *\n * The types of values that can be merged are `Object` and `Array`. To set another type of value use `Onyx.set()`.\n * Values of type `Object` get merged with the old value, whilst for `Array`'s we simply replace the current value with the new one.\n *\n * Calls to `Onyx.merge()` are batched so that any calls performed in a single tick will stack in a queue and get\n * applied in the order they were called. Note: `Onyx.set()` calls do not work this way so use caution when mixing\n * `Onyx.merge()` and `Onyx.set()`.\n *\n * @example\n * Onyx.merge(ONYXKEYS.EMPLOYEE_LIST, ['Joe']); // -> ['Joe']\n * Onyx.merge(ONYXKEYS.EMPLOYEE_LIST, ['Jack']); // -> ['Joe', 'Jack']\n * Onyx.merge(ONYXKEYS.POLICY, {id: 1}); // -> {id: 1}\n * Onyx.merge(ONYXKEYS.POLICY, {name: 'My Workspace'}); // -> {id: 1, name: 'My Workspace'}\n *\n * @param {String} key ONYXKEYS key\n * @param {(Object|Array)} changes Object or Array value to merge\n * @returns {Promise}\n */\nfunction merge(key, changes) {\n // Merge attempts are batched together. The delta should be applied after a single call to get() to prevent a race condition.\n // Using the initial value from storage in subsequent merge attempts will lead to an incorrect final merged value.\n if (mergeQueue[key]) {\n mergeQueue[key].push(changes);\n return Promise.resolve();\n }\n mergeQueue[key] = [changes];\n\n return get(key)\n .then((existingValue) => {\n try {\n // We first only merge the changes, so we can provide these to the native implementation (SQLite uses only delta changes in \"JSON_PATCH\" to merge)\n let batchedChanges = applyMerge(undefined, mergeQueue[key]);\n\n // Clean up the write queue so we\n // don't apply these changes again\n delete mergeQueue[key];\n\n // After that we merge the batched changes with the existing value\n const modifiedData = removeNullObjectValues(applyMerge(existingValue, [batchedChanges]));\n\n // On native platforms we use SQLite which utilises JSON_PATCH to merge changes.\n // JSON_PATCH generally removes top-level nullish values from the stored object.\n // When there is no existing value though, SQLite will just insert the changes as a new value and thus the top-level nullish values won't be removed.\n // Therefore we need to remove nullish values from the `batchedChanges` which are sent to the SQLite, if no existing value is present.\n if (!existingValue) {\n batchedChanges = removeNullObjectValues(batchedChanges);\n }\n\n const hasChanged = cache.hasValueChanged(key, modifiedData);\n\n // This approach prioritizes fast UI changes without waiting for data to be stored in device storage.\n broadcastUpdate(key, modifiedData, hasChanged, 'merge');\n\n // If the value has not changed, calling Storage.setItem() would be redundant and a waste of performance, so return early instead.\n if (!hasChanged) {\n return Promise.resolve();\n }\n\n return Storage.mergeItem(key, batchedChanges, modifiedData).then((results) => {\n devTools.registerAction(`MERGE/${key.toUpperCase()}`, modifiedData, {[key]: modifiedData});\n return results;\n });\n } catch (error) {\n Logger.logAlert(`An error occurred while applying merge for key: ${key}, Error: ${error}`);\n }\n\n return Promise.resolve();\n });\n}\n\n/**\n * Merge user provided default key value pairs.\n * @private\n * @param {boolean} enableDevTools\n * @returns {Promise}\n */\nfunction initializeWithDefaultKeyStates(enableDevTools = false) {\n return Storage.multiGet(_.keys(defaultKeyStates))\n .then((pairs) => {\n const asObject = _.object(pairs);\n\n const merged = fastMerge(asObject, defaultKeyStates);\n cache.merge(merged);\n _.each(merged, (val, key) => keyChanged(key, val));\n if (enableDevTools) {\n devTools = new DevTools(merged);\n }\n });\n}\n\n/**\n * Clear out all the data in the store\n *\n * Note that calling Onyx.clear() and then Onyx.set() on a key with a default\n * key state may store an unexpected value in Storage.\n *\n * E.g.\n * Onyx.clear();\n * Onyx.set(ONYXKEYS.DEFAULT_KEY, 'default');\n * Storage.getItem(ONYXKEYS.DEFAULT_KEY)\n * .then((storedValue) => console.log(storedValue));\n * null is logged instead of the expected 'default'\n *\n * Onyx.set() might call Storage.setItem() before Onyx.clear() calls\n * Storage.setItem(). Use Onyx.merge() instead if possible. Onyx.merge() calls\n * Onyx.get(key) before calling Storage.setItem() via Onyx.set().\n * Storage.setItem() from Onyx.clear() will have already finished and the merged\n * value will be saved to storage after the default value.\n *\n * @param {Array} keysToPreserve is a list of ONYXKEYS that should not be cleared with the rest of the data\n * @returns {Promise<void>}\n */\nfunction clear(keysToPreserve = []) {\n return getAllKeys()\n .then((keys) => {\n const keysToBeClearedFromStorage = [];\n const keyValuesToResetAsCollection = {};\n const keyValuesToResetIndividually = {};\n\n // The only keys that should not be cleared are:\n // 1. Anything specifically passed in keysToPreserve (because some keys like language preferences, offline\n // status, or activeClients need to remain in Onyx even when signed out)\n // 2. Any keys with a default state (because they need to remain in Onyx as their default, and setting them\n // to null would cause unknown behavior)\n _.each(keys, (key) => {\n const isKeyToPreserve = _.contains(keysToPreserve, key);\n const isDefaultKey = _.has(defaultKeyStates, key);\n\n // If the key is being removed or reset to default:\n // 1. Update it in the cache\n // 2. Figure out whether it is a collection key or not,\n // since collection key subscribers need to be updated differently\n if (!isKeyToPreserve) {\n const oldValue = cache.getValue(key);\n const newValue = _.get(defaultKeyStates, key, undefined);\n if (newValue !== oldValue) {\n cache.set(key, newValue);\n const collectionKey = key.substring(0, key.indexOf('_') + 1);\n if (collectionKey) {\n if (!keyValuesToResetAsCollection[collectionKey]) {\n keyValuesToResetAsCollection[collectionKey] = {};\n }\n keyValuesToResetAsCollection[collectionKey][key] = newValue;\n } else {\n keyValuesToResetIndividually[key] = newValue;\n }\n }\n }\n\n if (isKeyToPreserve || isDefaultKey) {\n return;\n }\n\n // If it isn't preserved and doesn't have a default, we'll remove it\n keysToBeClearedFromStorage.push(key);\n });\n\n // Notify the subscribers for each key/value group so they can receive the new values\n _.each(keyValuesToResetIndividually, (value, key) => {\n notifySubscribersOnNextTick(key, value);\n });\n _.each(keyValuesToResetAsCollection, (value, key) => {\n notifyCollectionSubscribersOnNextTick(key, value);\n });\n\n const defaultKeyValueState = _.omit(defaultKeyStates, keysToPreserve);\n const defaultKeyValuePairs = _.pairs(defaultKeyValueState);\n\n // Remove only the items that we want cleared from storage, and reset others to default\n _.each(keysToBeClearedFromStorage, key => cache.drop(key));\n return Storage.removeItems(keysToBeClearedFromStorage).then(() => {\n devTools.clearState(keysToBeClearedFromStorage);\n return Storage.multiSet(defaultKeyValuePairs);\n });\n });\n}\n\n/**\n * Merges a collection based on their keys\n *\n * @example\n *\n * Onyx.mergeCollection(ONYXKEYS.COLLECTION.REPORT, {\n * [`${ONYXKEYS.COLLECTION.REPORT}1`]: report1,\n * [`${ONYXKEYS.COLLECTION.REPORT}2`]: report2,\n * });\n *\n * @param {String} collectionKey e.g. `ONYXKEYS.COLLECTION.REPORT`\n * @param {Object} collection Object collection keyed by individual collection member keys and values\n * @returns {Promise}\n */\nfunction mergeCollection(collectionKey, collection) {\n if (!_.isObject(collection) || _.isArray(collection) || _.isEmpty(collection)) {\n Logger.logInfo('mergeCollection() called with invalid or empty value. Skipping this update.');\n return Promise.resolve();\n }\n\n // Confirm all the collection keys belong to the same parent\n let hasCollectionKeyCheckFailed = false;\n _.each(collection, (_data, dataKey) => {\n if (isKeyMatch(collectionKey, dataKey)) {\n return;\n }\n\n if (process.env.NODE_ENV === 'development') {\n throw new Error(`Provided collection doesn't have all its data belonging to the same parent. CollectionKey: ${collectionKey}, DataKey: ${dataKey}`);\n }\n\n hasCollectionKeyCheckFailed = true;\n Logger.logAlert(`Provided collection doesn't have all its data belonging to the same parent. CollectionKey: ${collectionKey}, DataKey: ${dataKey}`);\n });\n\n // Gracefully handle bad mergeCollection updates so it doesn't block the merge queue\n if (hasCollectionKeyCheckFailed) {\n return Promise.resolve();\n }\n\n return getAllKeys()\n .then((persistedKeys) => {\n // Split to keys that exist in storage and keys that don't\n const [existingKeys, newKeys] = _.chain(collection)\n .keys()\n .partition(key => persistedKeys.includes(key))\n .value();\n\n const existingKeyCollection = _.pick(collection, existingKeys);\n const newCollection = _.pick(collection, newKeys);\n const keyValuePairsForExistingCollection = prepareKeyValuePairsForStorage(existingKeyCollection);\n const keyValuePairsForNewCollection = prepareKeyValuePairsForStorage(newCollection);\n\n const promises = [];\n\n // New keys will be added via multiSet while existing keys will be updated using multiMerge\n // This is because setting a key that doesn't exist yet with multiMerge will throw errors\n if (keyValuePairsForExistingCollection.length > 0) {\n promises.push(Storage.multiMerge(keyValuePairsForExistingCollection));\n }\n\n if (keyValuePairsForNewCollection.length > 0) {\n promises.push(Storage.multiSet(keyValuePairsForNewCollection));\n }\n\n // Prefill cache if necessary by calling get() on any existing keys and then merge original data to cache\n // and update all subscribers\n Promise.all(_.map(existingKeys, get)).then(() => {\n cache.merge(collection);\n keysChanged(collectionKey, collection);\n if (_.isNull(collection)) {\n devTools.registerAction(`REMOVE/${collectionKey.toUpperCase()}`, collection, {[collectionKey]: undefined});\n } else {\n devTools.registerAction(`SET/${collectionKey.toUpperCase()}`, collection, {[collectionKey]: collection});\n }\n });\n\n return Promise.all(promises)\n .catch(error => evictStorageAndRetry(error, mergeCollection, collection));\n });\n}\n\n/**\n * Insert API responses and lifecycle data into Onyx\n *\n * @param {Array} data An array of objects with shape {onyxMethod: oneOf('set', 'merge', 'mergeCollection', 'multiSet', 'clear'), key: string, value: *}\n * @returns {Promise} resolves when all operations are complete\n */\nfunction update(data) {\n // First, validate the Onyx object is in the format we expect\n _.each(data, ({onyxMethod, key, value}) => {\n if (!_.contains([METHOD.CLEAR, METHOD.SET, METHOD.MERGE, METHOD.MERGE_COLLECTION, METHOD.MULTI_SET], onyxMethod)) {\n throw new Error(`Invalid onyxMethod ${onyxMethod} in Onyx update.`);\n }\n if (onyxMethod === METHOD.MULTI_SET) {\n // For multiset, we just expect the value to be an object\n if (!_.isObject(value) || _.isArray(value) || _.isFunction(value)) {\n throw new Error('Invalid value provided in Onyx multiSet. Onyx multiSet value must be of type object.');\n }\n } else if (onyxMethod !== METHOD.CLEAR && !_.isString(key)) {\n throw new Error(`Invalid ${typeof key} key provided in Onyx update. Onyx key must be of type string.`);\n }\n });\n\n const promises = [];\n let clearPromise = Promise.resolve();\n\n _.each(data, ({onyxMethod, key, value}) => {\n switch (onyxMethod) {\n case METHOD.SET:\n promises.push(() => set(key, value));\n break;\n case METHOD.MERGE:\n promises.push(() => merge(key, value));\n break;\n case METHOD.MERGE_COLLECTION:\n promises.push(() => mergeCollection(key, value));\n break;\n case METHOD.MULTI_SET:\n promises.push(() => multiSet(value));\n break;\n case METHOD.CLEAR:\n clearPromise = clear();\n break;\n default:\n break;\n }\n });\n\n return clearPromise.then(() => Promise.all(_.map(promises, p => p())));\n}\n\n/**\n * When set these keys will not be persisted to storage\n * @param {string[]} keyList\n */\nfunction setMemoryOnlyKeys(keyList) {\n Storage.setMemoryOnlyKeys(keyList);\n\n // When in memory only mode for certain keys we do not want to ever drop items from the cache as the user will have no way to recover them again via storage.\n cache.setRecentKeysLimit(Infinity);\n}\n\n/**\n * Initialize the store with actions and listening for storage events\n *\n * @param {Object} [options={}] config object\n * @param {Object} [options.keys={}] `ONYXKEYS` constants object\n * @param {Object} [options.initialKeyStates={}] initial data to set when `init()` and `clear()` is called\n * @param {String[]} [options.safeEvictionKeys=[]] This is an array of keys\n * (individual or collection patterns) that when provided to Onyx are flagged\n * as \"safe\" for removal. Any components subscribing to these keys must also\n * implement a canEvict option. See the README for more info.\n * @param {Number} [options.maxCachedKeysCount=55] Sets how many recent keys should we try to keep in cache\n * Setting this to 0 would practically mean no cache\n * We try to free cache when we connect to a safe eviction key\n * @param {Boolean} [options.captureMetrics] Enables Onyx benchmarking and exposes the get/print/reset functions\n * @param {Boolean} [options.shouldSyncMultipleInstances] Auto synchronize storage events between multiple instances\n * of Onyx running in different tabs/windows. Defaults to true for platforms that support local storage (web/desktop)\n * @param {Boolean} [options.debugSetState] Enables debugging setState() calls to connected components.\n * @example\n * Onyx.init({\n * keys: ONYXKEYS,\n * initialKeyStates: {\n * [ONYXKEYS.SESSION]: {loading: false},\n * },\n * });\n */\nfunction init({\n keys = {},\n initialKeyStates = {},\n safeEvictionKeys = [],\n maxCachedKeysCount = 1000,\n captureMetrics = false,\n shouldSyncMultipleInstances = Boolean(global.localStorage),\n debugSetState = false,\n enableDevTools = false,\n} = {}) {\n if (captureMetrics) {\n // The code here is only bundled and applied when the captureMetrics is set\n // eslint-disable-next-line no-use-before-define\n applyDecorators();\n }\n\n if (debugSetState) {\n PerformanceUtils.setShouldDebugSetState(true);\n }\n\n if (maxCachedKeysCount > 0) {\n cache.setRecentKeysLimit(maxCachedKeysCount);\n }\n\n // We need the value of the collection keys later for checking if a\n // key is a collection. We store it in a map for faster lookup.\n const collectionValues = _.values(keys.COLLECTION);\n onyxCollectionKeyMap = _.reduce(collectionValues, (acc, val) => {\n acc.set(val, true);\n return acc;\n }, new Map());\n\n // Set our default key states to use when initializing and clearing Onyx data\n defaultKeyStates = initialKeyStates;\n\n // Let Onyx know about which keys are safe to evict\n evictionAllowList = safeEvictionKeys;\n\n // Initialize all of our keys with data provided then give green light to any pending connections\n Promise.all([\n addAllSafeEvictionKeysToRecentlyAccessedList(),\n initializeWithDefaultKeyStates(enableDevTools),\n ])\n .then(deferredInitTask.resolve);\n\n if (shouldSyncMultipleInstances && _.isFunction(Storage.keepInstancesSync)) {\n Storage.keepInstancesSync((key, value) => {\n cache.set(key, value);\n keyChanged(key, value);\n if (_.isNull(value)) {\n devTools.registerAction(`REMOVE/${key.toUpperCase()}`, value, {[key]: undefined});\n } else {\n devTools.registerAction(`SET/${key.toUpperCase()}`, value, {[key]: value});\n }\n });\n }\n}\n\nconst Onyx = {\n connect,\n disconnect,\n set,\n multiSet,\n merge,\n mergeCollection,\n update,\n clear,\n getAllKeys,\n init,\n registerLogger: Logger.registerLogger,\n addToEvictionBlockList,\n removeFromEvictionBlockList,\n isSafeEvictionKey,\n METHOD,\n setMemoryOnlyKeys,\n tryGetCachedValue,\n hasPendingMergeForKey,\n};\n\n/**\n * Apply calls statistic decorators to benchmark Onyx\n *\n * @private\n */\nfunction applyDecorators() {\n // We're requiring the script dynamically here so that it's only evaluated when decorators are used\n const decorate = require('./metrics');\n\n // Re-assign with decorated functions\n /* eslint-disable no-func-assign */\n get = decorate.decorateWithMetrics(get, 'Onyx:get');\n set = decorate.decorateWithMetrics(set, 'Onyx:set');\n multiSet = decorate.decorateWithMetrics(multiSet, 'Onyx:multiSet');\n clear = decorate.decorateWithMetrics(clear, 'Onyx:clear');\n merge = decorate.decorateWithMetrics(merge, 'Onyx:merge');\n mergeCollection = decorate.decorateWithMetrics(mergeCollection, 'Onyx:mergeCollection');\n getAllKeys = decorate.decorateWithMetrics(getAllKeys, 'Onyx:getAllKeys');\n initializeWithDefaultKeyStates = decorate.decorateWithMetrics(initializeWithDefaultKeyStates, 'Onyx:defaults');\n update = decorate.decorateWithMetrics(update, 'Onyx:update');\n /* eslint-enable */\n\n // Re-expose decorated methods\n /* eslint-disable rulesdir/prefer-actions-set-data */\n Onyx.set = set;\n Onyx.multiSet = multiSet;\n Onyx.clear = clear;\n Onyx.merge = merge;\n Onyx.mergeCollection = mergeCollection;\n Onyx.update = update;\n /* eslint-enable */\n\n // Expose stats methods on Onyx\n Onyx.getMetrics = decorate.getMetrics;\n Onyx.resetMetrics = decorate.resetMetrics;\n Onyx.printMetrics = decorate.printMetrics;\n}\n\nexport default Onyx;\n","/**\n * Create a deferred task that can be resolved when we call `resolve()`\n * The returned promise will complete when we call `resolve`\n * Useful when we want to wait for a tasks that is resolved from an external action\n *\n * @template T\n * @returns {{ resolve: function(*), promise: Promise<T|void> }}\n */\nexport default function createDeferredTask() {\n const deferred = {};\n deferred.promise = new Promise((res) => {\n deferred.resolve = res;\n });\n\n return deferred;\n}\n","/**\n * This is a higher order component that provides the ability to map a state property directly to\n * something in Onyx (a key/value store). That way, as soon as data in Onyx changes, the state will be set and the view\n * will automatically change to reflect the new data.\n */\nimport PropTypes from 'prop-types';\nimport React from 'react';\nimport _ from 'underscore';\nimport Onyx from './Onyx';\nimport * as Str from './Str';\n\n/**\n * Returns the display name of a component\n *\n * @param {object} component\n * @returns {string}\n */\nfunction getDisplayName(component) {\n return component.displayName || component.name || 'Component';\n}\n\nexport default function (mapOnyxToState) {\n // A list of keys that must be present in tempState before we can render the WrappedComponent\n const requiredKeysForInit = _.chain(mapOnyxToState)\n .omit(config => config.initWithStoredValues === false)\n .keys()\n .value();\n return (WrappedComponent) => {\n const displayName = getDisplayName(WrappedComponent);\n class withOnyx extends React.Component {\n constructor(props) {\n super(props);\n\n this.setWithOnyxState = this.setWithOnyxState.bind(this);\n\n // This stores all the Onyx connection IDs to be used when the component unmounts so everything can be\n // disconnected. It is a key value store with the format {[mapping.key]: connectionID}.\n this.activeConnectionIDs = {};\n\n const cachedState = _.reduce(mapOnyxToState, (resultObj, mapping, propertyName) => {\n const key = Str.result(mapping.key, props);\n const value = Onyx.tryGetCachedValue(key, mapping);\n\n /**\n * If we have a pending merge for a key it could mean that data is being set via Onyx.merge() and someone expects a component to have this data immediately.\n *\n * @example\n *\n * Onyx.merge('report_123', value);\n * Navigation.navigate(route); // Where \"route\" expects the \"value\" to be available immediately once rendered.\n *\n * In reality, Onyx.merge() will only update the subscriber after all merges have been batched and the previous value is retrieved via a get() (returns a promise).\n * So, we won't use the cache optimization here as it will lead us to arbitrarily defer various actions in the application code.\n */\n if (value !== undefined && !Onyx.hasPendingMergeForKey(key)) {\n // eslint-disable-next-line no-param-reassign\n resultObj[propertyName] = value;\n }\n\n return resultObj;\n }, {});\n\n // If we have all the data we need, then we can render the component immediately\n cachedState.loading = _.size(cachedState) < requiredKeysForInit.length;\n\n // Object holding the temporary initial state for the component while we load the various Onyx keys\n this.tempState = cachedState;\n\n this.state = cachedState;\n }\n\n componentDidMount() {\n // Subscribe each of the state properties to the proper Onyx key\n _.each(mapOnyxToState, (mapping, propertyName) => {\n this.connectMappingToOnyx(mapping, propertyName);\n });\n this.checkEvictableKeys();\n }\n\n componentDidUpdate(prevProps) {\n // If any of the mappings use data from the props, then when the props change, all the\n // connections need to be reconnected with the new props\n _.each(mapOnyxToState, (mapping, propertyName) => {\n const previousKey = Str.result(mapping.key, prevProps);\n const newKey = Str.result(mapping.key, this.props);\n if (previousKey !== newKey) {\n Onyx.disconnect(this.activeConnectionIDs[previousKey], previousKey);\n delete this.activeConnectionIDs[previousKey];\n this.connectMappingToOnyx(mapping, propertyName);\n }\n });\n this.checkEvictableKeys();\n }\n\n componentWillUnmount() {\n // Disconnect everything from Onyx\n _.each(mapOnyxToState, (mapping) => {\n const key = Str.result(mapping.key, this.props);\n const connectionID = this.activeConnectionIDs[key];\n Onyx.disconnect(connectionID, key);\n });\n }\n\n /**\n * This method is used externally by sendDataToConnection to prevent unnecessary renders while a component\n * still in a loading state. The temporary initial state is saved to the component instance and setState()\n * only called once all the necessary data has been collected.\n *\n * @param {String} statePropertyName\n * @param {*} val\n */\n setWithOnyxState(statePropertyName, val) {\n // We might have loaded the values for the onyx keys/mappings already from the cache.\n // In case we were able to load all the values upfront, the loading state will be false.\n // However, Onyx.js will always call setWithOnyxState, as it doesn't know that this implementation\n // already loaded the values from cache. Thus we have to check whether the value has changed\n // before we set the state to prevent unnecessary renders.\n const prevValue = this.state[statePropertyName];\n if (!this.state.loading && prevValue === val) {\n return;\n }\n\n if (!this.state.loading) {\n this.setState({[statePropertyName]: val});\n return;\n }\n\n this.tempState[statePropertyName] = val;\n\n // All state keys should exist and at least have a value of null\n if (_.some(requiredKeysForInit, key => _.isUndefined(this.tempState[key]))) {\n return;\n }\n\n // Leave untouched previous state to avoid data loss during pre-load updates.\n // This handles case when setState was called before the setWithOnyxState.\n // For example, when an Onyx property was updated by keyChanged before the call of the setWithOnyxState.\n this.setState((prevState) => {\n const remainingTempState = _.omit(this.tempState, _.keys(prevState));\n\n return ({...remainingTempState, loading: false});\n });\n\n delete this.tempState;\n }\n\n /**\n * Makes sure each Onyx key we requested has been set to state with a value of some kind.\n * We are doing this so that the wrapped component will only render when all the data\n * it needs is available to it.\n */\n checkEvictableKeys() {\n // We will add this key to our list of recently accessed keys\n // if the canEvict function returns true. This is necessary criteria\n // we MUST use to specify if a key can be removed or not.\n _.each(mapOnyxToState, (mapping) => {\n if (_.isUndefined(mapping.canEvict)) {\n return;\n }\n\n const canEvict = Str.result(mapping.canEvict, this.props);\n const key = Str.result(mapping.key, this.props);\n\n if (!Onyx.isSafeEvictionKey(key)) {\n throw new Error(`canEvict can't be used on key '${key}'. This key must explicitly be flagged as safe for removal by adding it to Onyx.init({safeEvictionKeys: []}).`);\n }\n\n if (canEvict) {\n Onyx.removeFromEvictionBlockList(key, mapping.connectionID);\n } else {\n Onyx.addToEvictionBlockList(key, mapping.connectionID);\n }\n });\n }\n\n /**\n * Takes a single mapping and binds the state of the component to the store\n *\n * @param {object} mapping\n * @param {string|function} mapping.key key to connect to. can be a string or a\n * function that takes this.props as an argument and returns a string\n * @param {string} statePropertyName the name of the state property that Onyx will add the data to\n * @param {boolean} [mapping.initWithStoredValues] If set to false, then no data will be prefilled into the\n * component\n */\n connectMappingToOnyx(mapping, statePropertyName) {\n const key = Str.result(mapping.key, this.props);\n\n // eslint-disable-next-line rulesdir/prefer-onyx-connect-in-libs\n this.activeConnectionIDs[key] = Onyx.connect({\n ...mapping,\n key,\n statePropertyName,\n withOnyxInstance: this,\n displayName,\n });\n }\n\n render() {\n if (this.state.loading) {\n return null;\n }\n\n // Remove any internal state properties used by withOnyx\n // that should not be passed to a wrapped component\n let stateToPass = _.omit(this.state, 'loading');\n stateToPass = _.omit(stateToPass, value => _.isNull(value));\n\n // Remove any null values so that React replaces them with default props\n const propsToPass = _.omit(this.props, value => _.isNull(value));\n\n // Spreading props and state is necessary in an HOC where the data cannot be predicted\n return (\n <WrappedComponent\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...propsToPass}\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...stateToPass}\n ref={this.props.forwardedRef}\n />\n );\n }\n }\n\n withOnyx.propTypes = {\n forwardedRef: PropTypes.oneOfType([\n PropTypes.func,\n // eslint-disable-next-line react/forbid-prop-types\n PropTypes.shape({current: PropTypes.object}),\n ]),\n };\n withOnyx.defaultProps = {\n forwardedRef: undefined,\n };\n withOnyx.displayName = `withOnyx(${displayName})`;\n return React.forwardRef((props, ref) => {\n const Component = withOnyx;\n // eslint-disable-next-line react/jsx-props-no-spreading\n return <Component {...props} forwardedRef={ref} />;\n });\n };\n}\n","import Onyx from './Onyx';\nimport withOnyx from './withOnyx';\n\nexport default Onyx;\nexport {withOnyx};\n"],"names":["root","factory","exports","module","require","define","amd","self","__WEBPACK_EXTERNAL_MODULE__746__","__WEBPACK_EXTERNAL_MODULE__952__","__WEBPACK_EXTERNAL_MODULE__802__","__WEBPACK_EXTERNAL_MODULE__407__","__WEBPACK_EXTERNAL_MODULE__156__","decorateWithMetrics","func","getMetrics","printMetrics","resetMetrics","freeGlobal","g","global","window","InvalidCharacterError","message","this","prototype","Error","name","error","TABLE","REGEX_SPACE_CHARACTERS","base64","input","String","test","a","b","c","buffer","padding","length","output","position","charCodeAt","charAt","replace","bitStorage","bitCounter","indexOf","fromCharCode","utils","WMap","WeakMap","keys","values","set","key","value","push","get","i","decycle","object","options","replacer","map","noCircularOption","Object","hasOwnProperty","call","withRefs","refs","derez","_value","path","nu","date","Date","$jsan","getTime","regex","RegExp","getRegexFlags","source","stringifyFunction","isNaN","Number","POSITIVE_INFINITY","NEGATIVE_INFINITY","undefined","symbolKey","Symbol","keyFor","toString","slice","Map","Array","from","JSON","stringify","Set","toJSON","keyString","Boolean","foundPath","split","join","circular","apply","nextPath","retrocycle","$","rez","item","restore","cycle","space","_options","arguments","e","decycled","isArray","parse","text","reviver","parsed","needsRetrocycle","obj","paths","pathString","match","matches","exec","getPaths","pathGetter","jsan","flags","ignoreCase","multiline","fn","customToString","str","start","end","type","rest","comma","stack","for","NaN","Infinity","console","warn","errorMessage","ListPrototype","List","ListItem","of","items","iterator","list","append","head","tail","toArray","result","next","prepend","detach","Item","ListItemPrototype","prev","ReactPropTypesSecret","emptyFunction","emptyFunctionWithReset","resetWarningCache","shim","props","propName","componentName","location","propFullName","secret","err","getShim","isRequired","ReactPropTypes","array","bool","number","string","symbol","any","arrayOf","element","elementType","instanceOf","node","objectOf","oneOf","oneOfType","shape","exact","checkPropTypes","PropTypes","__esModule","defaultSocketOptions","secure","hostname","port","autoReconnect","autoReconnectOptions","randomness","send","extractState","generateId","connect","connectViaExtension","_jsan","_socketclusterClient2","_interopRequireDefault","_rnHostDetect2","_constants","default","socket","channel","listeners","state","Math","random","substr","handleMessages","payload","action","forEach","id","instanceId","socketOptions","create","emit","channelName","log","subscribe","watch","on","connectToServer","transformAction","config","liftedAction","timestamp","now","getActionType","_send","setTimeout","init","listener","index","splice","unsubscribe","remote","__REDUX_DEVTOOLS_EXTENSION__","__fbBatchedBridgeConfig","remoteModuleConfig","passed","some","content","ServerHost","scriptURL","getByRemoteConfig","NativeModules","Constants","SourceCode","originalWarn","__DEV__","PlatformConstants","AndroidConstants","getByRNRequirePolyfill","Emitter","SCChannel","client","PENDING","SUBSCRIBED","UNSUBSCRIBED","setOptions","waitForAuth","batch","data","getState","isSubscribed","includePending","publish","callback","handler","unwatch","watchers","destroy","destroyChannel","mixin","addEventListener","event","_callbacks","once","off","removeListener","removeAllListeners","removeEventListener","cb","callbacks","args","len","hasListeners","objects","$ref","isStrict","AuthTokenExpiredError","expiry","captureStackTrace","callee","AuthTokenInvalidError","AuthTokenNotBeforeError","AuthTokenError","SilentMiddlewareBlockedError","InvalidActionError","InvalidArgumentsError","InvalidOptionsError","InvalidMessageError","SocketProtocolError","code","ServerProtocolError","HTTPServerError","ResourceLimitError","TimeoutError","BadConnectionError","BrokerError","ProcessExitError","UnknownError","socketProtocolErrorStatuses","socketProtocolIgnoreStatuses","unserializableErrorProperties","domain","domainEmitter","domainThrown","dehydrateError","includeStackTrace","dehydratedError","hydrateError","hydratedError","base64Chars","validJSONStartRegex","arrayBufferToBase64","arraybuffer","bytes","Uint8Array","substring","binaryToBase64Replacer","ArrayBuffer","Buffer","rehydratedBuffer","decode","encodedMessage","encode","rawData","SCClientSocket","clients","version","AuthEngine","_internalStorage","isLocalStorageEnabled","_checkLocalStorageEnabled","localStorage","setItem","removeItem","saveToken","token","removeToken","loadToken","authToken","getItem","scErrors","uuid","_clients","getPort","isSecureDefault","isSecure","host","protocol","opts","autoConnect","autoSubscribeOnConnect","connectTimeout","ackTimeout","timestampRequests","timestampParam","authEngine","authTokenName","binaryType","multiplex","pubSubBatchDuration","cloneData","clientMap","clientId","v4","protocolPrefix","queryString","query","queryArray","queryMap","getMultiplexId","Response","sent","_respond","responseData","rid","formatter","SCTransport","querystring","LinkedList","clone","isBrowser","CLOSED","authState","UNAUTHENTICATED","signedAuthToken","pendingReconnect","pendingReconnectTimeout","preparingPendingSubscriptions","channelPrefix","disconnectOnUnload","pingTimeout","pingTimeoutDisabled","active","_clientMap","maxTimeout","pow","verifyDuration","propertyName","_localEvents","connectAttempts","_emitBuffer","channels","_cid","callIdGenerator","reconnectOptions","initialDelay","multiplier","maxDelay","subscriptionRetryOptions","auth","codecEngine","codec","_channelEmitter","_unloadHandler","disconnect","CONNECTING","OPEN","AUTHENTICATED","ignoreStatuses","errorStatuses","_privateEventHandlerMap","undecoratedChannelName","_undecorateChannelName","_triggerChannelUnsubscribe","response","_onSCError","_changeToAuthenticatedState","oldToken","_changeToUnauthenticatedStateAndClearTokens","transport","close","getBytesReceived","deauthenticate","open","clearTimeout","_reconnectTimeoutRef","status","_onSCOpen","_onSCClose","res","_onSCEvent","reconnect","oldState","oldSignedToken","stateChangeData","newState","_extractAuthTokenData","processPendingSubscriptions","decodeBase64","encodedString","atob","encodeBase64","decodedString","btoa","encodedTokenData","tokenData","getAuthToken","getSignedAuthToken","authenticate","authStatus","isAuthenticated","authError","_tryReconnect","timeout","exponent","initialTimeout","round","_flushEmitBuffer","_suspendSubscriptions","_abortAllPendingEventsDueToBadConnection","failureType","nextNode","currentNode","eventObject","cid","cancelPendingResponse","openAbort","closeMessage","emitObject","_handleEventAckTimeout","eventNode","_emit","pubData","_decorateChannelName","_triggerChannelSubscribe","subscriptionOptions","_triggerChannelSubscribeFail","meetsAuthRequirements","_cancelPendingSubscribeCallback","_pendingSubscriptionCid","decoratedChannelName","_trySubscribe","noTimeout","_tryUnsubscribe","currentChannel","subscriptions","subs","pendingChannels","sort","ap","priority","bp","WebSocket","createWebSocket","uri","_pingTimeoutTicker","_callbackMap","_batchSendList","wsSocket","onopen","_onOpen","onclose","_onClose","reason","onmessage","_onMessage","onerror","_connectTimeoutRef","schema","_resetPingTimeout","_handshake","statusCode","_onError","force","badConnectionError","_batchTimeout","_handleEventObject","rehydratedError","readyState","sendObject","bytesReceived","packet","simpleEventObject","Function","serializeObject","formatError","sendObjectBatch","sendObjectSingle","WorkerGlobalScope","MozWebSocket","ws","protocols","_instanceof","nativeMap","nativeSet","nativePromise","_","Promise","parent","depth","includeNonEnumerable","allParents","allChildren","useBuffer","_clone","child","proto","resolve","reject","then","__isArray","__isRegExp","__getRegExpFlags","lastIndex","__isDate","isBuffer","copy","getPrototypeOf","keyChild","valueChild","entryChild","add","attrs","getOwnPropertyDescriptor","getOwnPropertySymbols","symbols","descriptor","enumerable","defineProperty","allPropertyNames","getOwnPropertyNames","__objToStr","o","re","clonePrototype","prop","qs","sep","eq","regexp","maxKeys","kstr","vstr","k","v","x","idx","decodeURIComponent","stringifyPrimitive","isFinite","ks","encodeURIComponent","v1","byteToHex","buf","offset","bth","getRandomValues","crypto","bind","msCrypto","rnds8","rnds","r","_nodeId","_clockseq","rng","bytesToUuid","_lastMSecs","_lastNSecs","clockseq","seedBytes","msecs","nsecs","dt","tl","tmh","n","ii","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","loaded","__webpack_modules__","getter","d","definition","globalThis","toStringTag","nmd","children","logger","logAlert","level","logInfo","isMergeableObject","val","fastMerge","target","destination","targetKeys","sourceKeys","mergeObject","isDefined","constructor","storageKeys","recentKeys","storageMap","pendingPromises","getAllKeys","getValue","addToAccessedKeys","hasCacheForKey","addKey","drop","delete","merge","assign","mergedKeys","hasPendingTask","taskName","getTaskPromise","captureTask","promise","finally","removeLeastRecentlyUsedKeys","size","maxRecentKeysSize","recentlyAccessed","keysToRemove","setRecentKeysLimit","limit","hasValueChanged","deepEqual","startsWith","haystack","needle","parameter","_len","_key","debugSetState","setShouldDebugSetState","debug","logSetStateCall","mapping","previousValue","newValue","caller","keyThatChanged","logParams","difference","changes","comparisonObject","lodashTransform","displayName","customStoreInstance","getCustomStore","createStore","provider","multiGet","keysParam","getMany","multiMerge","pairs","store","all","_ref","promisifyRequest","upsertMany","_ref2","put","mergeItem","_changes","modifiedData","multiSet","setMany","clear","setMemoryOnlyKeys","del","removeItems","delMany","getDatabaseSize","navigator","storage","estimate","bytesUsed","usage","bytesRemaining","quota","catch","SYNC_ONYX","raiseStorageSyncEvent","onyxKey","Storage","keepInstancesSync","onStorageKeyChanged","raiseStorageSyncManyKeysEvent","onyxKeys","allKeys","initialState","remotedev","registerAction","stateChanges","clearState","keysToBeRemoved","METHOD","SET","MERGE","MERGE_COLLECTION","MULTI_SET","CLEAR","mergeQueue","lastConnectionID","callbackToStateMapping","onyxCollectionKeyMap","recentlyAccessedKeys","evictionAllowList","devTools","evictionBlocklist","defaultKeyStates","deferredInitTask","deferred","createDeferredTask","getSubsetOfData","sourceData","selector","withOnyxInstanceState","reduceCollectionWithSelector","collection","finalCollection","cache","Logger","storedKeys","isCollectionKey","has","isCollectionMemberKey","collectionKey","Str","isKeyMatch","configKey","isSafeEvictionKey","testKey","removeLastAccessedKey","addLastAccessedKey","removeFromEvictionBlockList","connectionID","getCachedCollection","collectionMemberKeys","storedKey","curr","cachedValue","keysChanged","partialCollection","stateMappingKeys","subscriber","isSubscribedToCollectionKey","isSubscribedToCollectionMemberKey","cachedCollection","waitForCollectionCallback","dataKeys","j","dataKey","withOnyxInstance","setState","prevState","previousData","statePropertyName","newData","PerformanceUtils","dataFromCollection","prevData","keyChanged","canUpdateSubscriber","prevDataWithNewData","newCollection","sendDataToConnection","matchedKey","setWithOnyxState","getCollectionDataAndSendAsObject","matchingKeys","finalObject","notifySubscribersOnNextTick","remove","toUpperCase","reportStorageQuota","dbSizeError","evictStorageAndRetry","onyxMethod","keyForRemoval","broadcastUpdate","hasChanged","method","initWithStoredValues","hasPendingMergeForKey","removeNullObjectValues","objectValue","valueWithNullRemoved","prepareKeyValuePairsForStorage","keyValuePairs","applyMerge","existingValue","lastChange","change","batchedChanges","results","initializeWithDefaultKeyStates","enableDevTools","asObject","merged","DevTools","keysToPreserve","keysToBeClearedFromStorage","keyValuesToResetAsCollection","keyValuesToResetIndividually","isKeyToPreserve","isDefaultKey","oldValue","notifyCollectionSubscribersOnNextTick","defaultKeyValueState","defaultKeyValuePairs","mergeCollection","hasCollectionKeyCheckFailed","_data","persistedKeys","existingKeys","newKeys","partition","includes","existingKeyCollection","keyValuePairsForExistingCollection","keyValuePairsForNewCollection","promises","update","clearPromise","_ref3","p","Onyx","canEvict","addKeyToRecentlyAccessedIfNeeded","keyToRemoveFromEvictionBlocklist","initialKeyStates","safeEvictionKeys","maxCachedKeysCount","captureMetrics","shouldSyncMultipleInstances","decorate","applyDecorators","collectionValues","COLLECTION","acc","safeEvictionKey","registerLogger","addToEvictionBlockList","keyList","tryGetCachedValue","mapOnyxToState","requiredKeysForInit","omit","WrappedComponent","component","withOnyx","React","super","activeConnectionIDs","cachedState","resultObj","loading","tempState","componentDidMount","connectMappingToOnyx","checkEvictableKeys","componentDidUpdate","prevProps","previousKey","componentWillUnmount","prevValue","render","stateToPass","propsToPass","_extends","ref","forwardedRef","propTypes","current","defaultProps","Component"],"sourceRoot":""}