{"version":3,"sources":["webpack://Pusher/webpack/universalModuleDefinition","webpack://Pusher/webpack/bootstrap","webpack://Pusher/./node_modules/@stablelib/base64/base64.ts","webpack://Pusher/./node_modules/@stablelib/utf8/utf8.ts","webpack://Pusher/./src/core/pusher.js","webpack://Pusher/./src/core/base64.ts","webpack://Pusher/./src/core/utils/timers/abstract_timer.ts","webpack://Pusher/./src/core/utils/timers/index.ts","webpack://Pusher/./src/core/util.ts","webpack://Pusher/./src/core/utils/collections.ts","webpack://Pusher/./src/core/defaults.ts","webpack://Pusher/./src/core/transports/url_schemes.ts","webpack://Pusher/./src/core/events/callback_registry.ts","webpack://Pusher/./src/core/events/dispatcher.ts","webpack://Pusher/./src/core/logger.ts","webpack://Pusher/./src/core/transports/transport_connection.ts","webpack://Pusher/./src/core/transports/transport.ts","webpack://Pusher/./src/runtimes/isomorphic/transports/transports.ts","webpack://Pusher/./src/core/transports/assistant_to_the_transport_manager.ts","webpack://Pusher/./src/core/connection/protocol/protocol.ts","webpack://Pusher/./src/core/connection/connection.ts","webpack://Pusher/./src/core/connection/handshake/index.ts","webpack://Pusher/./src/core/timeline/timeline_sender.ts","webpack://Pusher/./src/core/errors.ts","webpack://Pusher/./src/core/utils/url_store.ts","webpack://Pusher/./src/core/channels/channel.ts","webpack://Pusher/./src/core/channels/private_channel.ts","webpack://Pusher/./src/core/channels/members.ts","webpack://Pusher/./src/core/channels/presence_channel.ts","webpack://Pusher/./src/core/channels/encrypted_channel.ts","webpack://Pusher/./src/core/connection/connection_manager.ts","webpack://Pusher/./src/core/channels/channels.ts","webpack://Pusher/./src/core/utils/factory.ts","webpack://Pusher/./src/core/transports/transport_manager.ts","webpack://Pusher/./src/core/strategies/sequential_strategy.ts","webpack://Pusher/./src/core/strategies/best_connected_ever_strategy.ts","webpack://Pusher/./src/core/strategies/cached_strategy.ts","webpack://Pusher/./src/core/strategies/delayed_strategy.ts","webpack://Pusher/./src/core/strategies/if_strategy.ts","webpack://Pusher/./src/core/strategies/first_connected_strategy.ts","webpack://Pusher/./src/runtimes/isomorphic/default_strategy.ts","webpack://Pusher/./src/core/http/state.ts","webpack://Pusher/./src/core/http/http_request.ts","webpack://Pusher/./src/core/http/http_socket.ts","webpack://Pusher/./src/core/timeline/level.ts","webpack://Pusher/./src/core/http/http_streaming_socket.ts","webpack://Pusher/./src/core/http/http_polling_socket.ts","webpack://Pusher/./src/runtimes/isomorphic/http/http_xhr_request.ts","webpack://Pusher/./src/runtimes/isomorphic/runtime.ts","webpack://Pusher/./src/runtimes/isomorphic/transports/transport_connection_initializer.ts","webpack://Pusher/./src/runtimes/isomorphic/http/http.ts","webpack://Pusher/./src/runtimes/worker/net_info.ts","webpack://Pusher/./src/runtimes/worker/auth/fetch_auth.ts","webpack://Pusher/./src/runtimes/worker/runtime.ts","webpack://Pusher/./src/runtimes/worker/timeline/fetch_timeline.ts","webpack://Pusher/./src/core/timeline/timeline.ts","webpack://Pusher/./src/core/strategies/transport_strategy.ts","webpack://Pusher/./src/core/strategies/strategy_builder.ts","webpack://Pusher/./src/core/auth/options.ts","webpack://Pusher/./src/core/auth/user_authenticator.ts","webpack://Pusher/./src/core/auth/channel_authorizer.ts","webpack://Pusher/./src/core/config.ts","webpack://Pusher/./src/core/auth/deprecated_channel_authorizer.ts","webpack://Pusher/./src/core/watchlist.ts","webpack://Pusher/./src/core/utils/flat_promise.ts","webpack://Pusher/./src/core/user.ts","webpack://Pusher/./src/core/pusher.ts","webpack://Pusher/./src/core/options.ts"],"names":["root","factory","exports","module","define","amd","this","installedModules","__webpack_require__","moduleId","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","_paddingCharacter","encodedLength","length","encode","data","out","_encodeByte","left","maxDecodedLength","decodedLength","_getPaddingLength","decode","Uint8Array","paddingLength","op","haveBad","v0","v1","v2","v3","_decodeChar","charCodeAt","Error","b","result","String","fromCharCode","Coder","stdCoder","URLSafeCoder","urlSafeCoder","INVALID_UTF8","arr","pos","chars","min","n1","n2","n3","push","join","default","b64chars","b64tab","charAt","cb_utob","cc","utob","u","replace","cb_encode","ccc","padlen","ord","btoa","set","clear","delay","callback","timer","isRunning","ensureAborted","clearTimeout","clearInterval","setTimeout","setInterval","now","Date","valueOf","defer","OneOffTimer","method","boundArguments","Array","slice","arguments","apply","concat","extend","target","sources","extensions","constructor","stringify","safeJSONStringify","arrayIndexOf","array","item","nativeIndexOf","indexOf","objectApply","f","keys","_","context","map","filter","test","filterObject","Boolean","any","encodeParamsObject","encodeURIComponent","toString","buildQueryString","params","undefined","source","JSON","e","objects","paths","derez","path","nu","$ref","VERSION","PROTOCOL","wsPort","wssPort","wsPath","httpHost","httpPort","httpsPort","httpPath","stats_host","authEndpoint","authTransport","activityTimeout","pongTimeout","unavailableTimeout","userAuthentication","endpoint","transport","channelAuthorization","cdn_http","cdn_https","dependency_suffix","getGenericURL","baseScheme","useTLS","hostTLS","hostNonTLS","getGenericPath","queryString","ws","getInitial","http","_callbacks","prefix","add","prefixedEventName","fn","remove","names","removeCallback","removeAllCallbacks","binding","failThrough","callbacks","global_callbacks","eventName","bind_global","unbind","unbind_global","unbind_all","emit","metadata","args","globalLog","message","console","log","debug","warn","globalLogWarn","error","globalLogError","defaultLoggingFunction","logToConsole","hooks","priority","options","initialize","transportConnectionInitializer","state","timeline","id","generateUniqueID","handlesActivityChecks","supportsPing","connect","socket","url","urls","getSocket","onError","changeState","bindListeners","close","send","ping","onOpen","beforeOpen","getPath","onopen","type","buildTimelineMessage","onClose","closeEvent","code","reason","wasClean","unbindListeners","onMessage","onActivity","onerror","onclose","onmessage","onactivity","info","cid","isSupported","environment","createConnection","WSTransport","isInitialized","getWebSocketAPI","createWebSocket","httpConfiguration","streamingConfiguration","HTTPFactory","createStreamingSocket","pollingConfiguration","createPollingSocket","xhrConfiguration","isXHRSupported","xhr_streaming","xhr_polling","manager","minPingDelay","maxPingDelay","pingDelay","connection","openTimestamp","onClosed","reportDeath","lifespan","Math","max","isAlive","Protocol","decodeMessage","messageEvent","messageData","parse","pusherEventData","pusherEvent","event","channel","user_id","encodeMessage","processHandshake","activity_timeout","action","socket_id","getCloseAction","getCloseError","send_event","listeners","activity","closed","handleCloseEvent","listener","finish","isEmpty","TimelineTransport","getAgent","msg","setPrototypeOf","status","urlStore","baseUrl","authenticationEndpoint","authorizationEndpoint","javascriptQuickStart","triggeringClientEvents","encryptedChannelSupport","fullUrl","urlObj","urlPrefix","pusher","subscribed","subscriptionPending","subscriptionCancelled","authorize","socketId","auth","trigger","suffix","disconnect","handleEvent","handleSubscriptionSucceededEvent","handleSubscriptionCountEvent","unsubscribe","subscription_count","subscriptionCount","subscribe","assign","HTTPAuthError","channel_data","cancelSubscription","reinstateSubscription","config","channelAuthorizer","channelName","reset","members","each","member","setMyID","myID","onSubscription","subscriptionData","presence","hash","count","me","addMember","memberData","user_info","removeMember","authData","channelData","user","signinDonePromise","user_data","handleInternalEvent","addedMember","removedMember","nacl","sharedSecret","handleEncryptedEvent","ciphertext","nonce","cipherText","secretbox","overheadLength","nonceLength","bytes","open","getDataToEmit","raw","usingTLS","errorCallbacks","buildErrorCallbacks","connectionCallbacks","buildConnectionCallbacks","handshakeCallbacks","buildHandshakeCallbacks","Network","getNetwork","netinfo","retryIn","sendActivityCheck","updateStrategy","runner","strategy","updateState","startConnecting","setUnavailableTimer","disconnectInternally","isUsingTLS","handshake","handshakeError","abortConnecting","abort","clearRetryTimer","clearUnavailableTimer","abandonConnection","getStrategy","round","retryTimer","unavailableTimer","stopActivityCheck","activityTimer","pong_timed_out","resetActivityCheck","shouldRetry","connected","Infinity","setConnection","withErrorEmitted","tls_only","refused","backoff","retry","newState","previousState","newStateDescription","previous","current","channels","createEncryptedChannel","errMsg","createPrivateChannel","createPresenceChannel","createChannel","all","values","find","createChannels","createConnectionManager","createTimelineSender","createHandshake","createAssistantToTheTransportManager","livesLeft","lives","getAssistant","strategies","loop","failFast","timeout","timeoutLimit","minPriority","tryNextStrategy","tryStrategy","forceMinPriority","callbackBuilder","runners","rs","abortRunner","allRunnersFailed","aborted","transports","ttl","storage","getLocalStorage","serializedCache","getTransportCacheKey","flushTransportCache","fetchTransportCache","timestamp","cached","latency","startTimestamp","pop","cb","storeTransportCache","number","trueBranch","falseBranch","testSupportsStrategy","State","baseOptions","defineTransport","definedTransports","defineTransportStrategy","wsStrategy","ws_options","wsHost","wss_options","http_options","timeouts","ws_manager","streaming_manager","ws_transport","wss_transport","xhr_streaming_transport","xhr_polling_transport","ws_loop","wss_loop","streaming_loop","polling_loop","http_loop","start","payload","position","xhr","getRequest","unloader","addUnloadListener","setRequestHeader","removeUnloadListener","abortRequest","onChunk","chunk","advanceBuffer","isBufferTooLong","buffer","unreadData","endOfLinePosition","autoIncrement","getUniqueURL","separator","randomNumber","randomInt","TimelineLevel","session","randomString","location","parts","exec","base","getLocation","readyState","CONNECTING","openStream","sendRaw","sendHeartbeat","OPEN","createSocketRequest","reconnect","closeStream","CLOSED","onEvent","onHeartbeat","hostname","urlParts","stream","getReceiveURL","onFinished","getXHRAPI","onreadystatechange","onprogress","responseText","getDefaultStrategy","Transports","createSocket","createXHR","createRequest","setup","PusherClass","ready","getClientFeatures","getProtocol","isOnline","query","authOptions","authRequestType","headers","Headers","headerName","headersProvider","dynamicHeaders","body","request","Request","credentials","fetch","then","response","text","parsedData","err","sender","host","json","getAuthorizers","ajax","WebSocket","XMLHttpRequest","floor","window","crypto","getRandomValues","Uint32Array","events","sent","uniqueID","level","limit","shift","ERROR","INFO","DEBUG","sendfn","bundle","lib","version","cluster","features","failAttempt","onInitialized","serializedTransport","AuthRequestType","transportClass","enabledTransports","disabledTransports","ignoreNullOrigin","deferred","paramsProvider","dynamicParams","composeChannelQuery","UserAuthentication","ChannelAuthorization","getHttpHost","opts","getWebsocketHost","shouldUseTLS","forceTLS","getEnableStatsConfig","enableStats","disableStats","buildUserAuthenticator","buildChannelAuthorizer","customHandler","channelAuthorizerGenerator","deprecatedAuthorizerOptions","ChannelAuthorizerProxy","authorizer","buildChannelAuth","bindWatchlistInternalEvent","forEach","watchlistEvent","resolve","reject","promise","Promise","res","rej","signin_requested","serverToUserChannel","_signinDoneResolve","_onAuthorize","_cleanup","_signin","_newSigninPromiseIfNeeded","watchlist","_onSigninSuccess","signin","userAuthenticator","_subscribeChannels","done","setDone","app_key","checkAppKey","validateOptions","statsHost","timelineParams","global_emitter","sessionID","Pusher","timelineSender","subscribeAll","internal","instances","isReady","allChannels","timelineSenderTimer","PeriodicTimer","event_name","channel_name","Runtime","ScriptReceivers","DependenciesReceivers","auth_callbacks"],"mappings":";;;;;;;CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,GACe,iBAAZC,QACdA,QAAgB,OAAID,IAEpBD,EAAa,OAAIC,IARnB,CASGK,MAAM,WACT,O,YCTE,IAAIC,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUP,QAGnC,IAAIC,EAASI,EAAiBE,GAAY,CACzCC,EAAGD,EACHE,GAAG,EACHT,QAAS,IAUV,OANAU,EAAQH,GAAUI,KAAKV,EAAOD,QAASC,EAAQA,EAAOD,QAASM,GAG/DL,EAAOQ,GAAI,EAGJR,EAAOD,QA0Df,OArDAM,EAAoBM,EAAIF,EAGxBJ,EAAoBO,EAAIR,EAGxBC,EAAoBQ,EAAI,SAASd,EAASe,EAAMC,GAC3CV,EAAoBW,EAAEjB,EAASe,IAClCG,OAAOC,eAAenB,EAASe,EAAM,CAAEK,YAAY,EAAMC,IAAKL,KAKhEV,EAAoBgB,EAAI,SAAStB,GACX,oBAAXuB,QAA0BA,OAAOC,aAC1CN,OAAOC,eAAenB,EAASuB,OAAOC,YAAa,CAAEC,MAAO,WAE7DP,OAAOC,eAAenB,EAAS,aAAc,CAAEyB,OAA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OvS,KAAKuR,WAAWyB,WAAW+X,EAAYvoB,EAAM+P,IAGtD,YAAAoV,aAAA,WACE,OAAO3nB,KAAK6V,OAAO7K,QAGrB,YAAA0e,OAAA,WACE1pB,KAAKkX,KAAKwS,UAxNL,EAAAgB,UAAsB,GACtB,EAAAC,SAAmB,EACnB,EAAApd,cAAwB,EAGxB,EAAA0d,QAA2B,GAC3B,EAAAC,gBAA6B,GAASA,gBACtC,EAAAC,sBAAmC,GAASA,sBAC5C,EAAAC,eAA4B,GAASA,eAkN9C,EA5NA,GAAqB,gBAoOrB,GAAQ7H,MAAM","file":"pusher.worker.min.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"Pusher\"] = factory();\n\telse\n\t\troot[\"Pusher\"] = factory();\n})(this, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 2);\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package base64 implements Base64 encoding and decoding.\n */\n\n// Invalid character used in decoding to indicate\n// that the character to decode is out of range of\n// alphabet and cannot be decoded.\nconst INVALID_BYTE = 256;\n\n/**\n * Implements standard Base64 encoding.\n *\n * Operates in constant time.\n */\nexport class Coder {\n // TODO(dchest): methods to encode chunk-by-chunk.\n\n constructor(private _paddingCharacter = \"=\") { }\n\n encodedLength(length: number): number {\n if (!this._paddingCharacter) {\n return (length * 8 + 5) / 6 | 0;\n }\n return (length + 2) / 3 * 4 | 0;\n }\n\n encode(data: Uint8Array): string {\n let out = \"\";\n\n let i = 0;\n for (; i < data.length - 2; i += 3) {\n let c = (data[i] << 16) | (data[i + 1] << 8) | (data[i + 2]);\n out += this._encodeByte((c >>> 3 * 6) & 63);\n out += this._encodeByte((c >>> 2 * 6) & 63);\n out += this._encodeByte((c >>> 1 * 6) & 63);\n out += this._encodeByte((c >>> 0 * 6) & 63);\n }\n\n const left = data.length - i;\n if (left > 0) {\n let c = (data[i] << 16) | (left === 2 ? data[i + 1] << 8 : 0);\n out += this._encodeByte((c >>> 3 * 6) & 63);\n out += this._encodeByte((c >>> 2 * 6) & 63);\n if (left === 2) {\n out += this._encodeByte((c >>> 1 * 6) & 63);\n } else {\n out += this._paddingCharacter || \"\";\n }\n out += this._paddingCharacter || \"\";\n }\n\n return out;\n }\n\n maxDecodedLength(length: number): number {\n if (!this._paddingCharacter) {\n return (length * 6 + 7) / 8 | 0;\n }\n return length / 4 * 3 | 0;\n }\n\n decodedLength(s: string): number {\n return this.maxDecodedLength(s.length - this._getPaddingLength(s));\n }\n\n decode(s: string): Uint8Array {\n if (s.length === 0) {\n return new Uint8Array(0);\n }\n const paddingLength = this._getPaddingLength(s);\n const length = s.length - paddingLength;\n const out = new Uint8Array(this.maxDecodedLength(length));\n let op = 0;\n let i = 0;\n let haveBad = 0;\n let v0 = 0, v1 = 0, v2 = 0, v3 = 0;\n for (; i < length - 4; i += 4) {\n v0 = this._decodeChar(s.charCodeAt(i + 0));\n v1 = this._decodeChar(s.charCodeAt(i + 1));\n v2 = this._decodeChar(s.charCodeAt(i + 2));\n v3 = this._decodeChar(s.charCodeAt(i + 3));\n out[op++] = (v0 << 2) | (v1 >>> 4);\n out[op++] = (v1 << 4) | (v2 >>> 2);\n out[op++] = (v2 << 6) | v3;\n haveBad |= v0 & INVALID_BYTE;\n haveBad |= v1 & INVALID_BYTE;\n haveBad |= v2 & INVALID_BYTE;\n haveBad |= v3 & INVALID_BYTE;\n }\n if (i < length - 1) {\n v0 = this._decodeChar(s.charCodeAt(i));\n v1 = this._decodeChar(s.charCodeAt(i + 1));\n out[op++] = (v0 << 2) | (v1 >>> 4);\n haveBad |= v0 & INVALID_BYTE;\n haveBad |= v1 & INVALID_BYTE;\n }\n if (i < length - 2) {\n v2 = this._decodeChar(s.charCodeAt(i + 2));\n out[op++] = (v1 << 4) | (v2 >>> 2);\n haveBad |= v2 & INVALID_BYTE;\n }\n if (i < length - 3) {\n v3 = this._decodeChar(s.charCodeAt(i + 3));\n out[op++] = (v2 << 6) | v3;\n haveBad |= v3 & INVALID_BYTE;\n }\n if (haveBad !== 0) {\n throw new Error(\"Base64Coder: incorrect characters for decoding\");\n }\n return out;\n }\n\n // Standard encoding have the following encoded/decoded ranges,\n // which we need to convert between.\n //\n // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 + /\n // Index: 0 - 25 26 - 51 52 - 61 62 63\n // ASCII: 65 - 90 97 - 122 48 - 57 43 47\n //\n\n // Encode 6 bits in b into a new character.\n protected _encodeByte(b: number): string {\n // Encoding uses constant time operations as follows:\n //\n // 1. Define comparison of A with B using (A - B) >>> 8:\n // if A > B, then result is positive integer\n // if A <= B, then result is 0\n //\n // 2. Define selection of C or 0 using bitwise AND: X & C:\n // if X == 0, then result is 0\n // if X != 0, then result is C\n //\n // 3. Start with the smallest comparison (b >= 0), which is always\n // true, so set the result to the starting ASCII value (65).\n //\n // 4. Continue comparing b to higher ASCII values, and selecting\n // zero if comparison isn't true, otherwise selecting a value\n // to add to result, which:\n //\n // a) undoes the previous addition\n // b) provides new value to add\n //\n let result = b;\n // b >= 0\n result += 65;\n // b > 25\n result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);\n // b > 51\n result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);\n // b > 61\n result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 43);\n // b > 62\n result += ((62 - b) >>> 8) & ((62 - 43) - 63 + 47);\n\n return String.fromCharCode(result);\n }\n\n // Decode a character code into a byte.\n // Must return 256 if character is out of alphabet range.\n protected _decodeChar(c: number): number {\n // Decoding works similar to encoding: using the same comparison\n // function, but now it works on ranges: result is always incremented\n // by value, but this value becomes zero if the range is not\n // satisfied.\n //\n // Decoding starts with invalid value, 256, which is then\n // subtracted when the range is satisfied. If none of the ranges\n // apply, the function returns 256, which is then checked by\n // the caller to throw error.\n let result = INVALID_BYTE; // start with invalid character\n\n // c == 43 (c > 42 and c < 44)\n result += (((42 - c) & (c - 44)) >>> 8) & (-INVALID_BYTE + c - 43 + 62);\n // c == 47 (c > 46 and c < 48)\n result += (((46 - c) & (c - 48)) >>> 8) & (-INVALID_BYTE + c - 47 + 63);\n // c > 47 and c < 58\n result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);\n // c > 64 and c < 91\n result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);\n // c > 96 and c < 123\n result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);\n\n return result;\n }\n\n private _getPaddingLength(s: string): number {\n let paddingLength = 0;\n if (this._paddingCharacter) {\n for (let i = s.length - 1; i >= 0; i--) {\n if (s[i] !== this._paddingCharacter) {\n break;\n }\n paddingLength++;\n }\n if (s.length < 4 || paddingLength > 2) {\n throw new Error(\"Base64Coder: incorrect padding\");\n }\n }\n return paddingLength;\n }\n\n}\n\nconst stdCoder = new Coder();\n\nexport function encode(data: Uint8Array): string {\n return stdCoder.encode(data);\n}\n\nexport function decode(s: string): Uint8Array {\n return stdCoder.decode(s);\n}\n\n/**\n * Implements URL-safe Base64 encoding.\n * (Same as Base64, but '+' is replaced with '-', and '/' with '_').\n *\n * Operates in constant time.\n */\nexport class URLSafeCoder extends Coder {\n // URL-safe encoding have the following encoded/decoded ranges:\n //\n // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 - _\n // Index: 0 - 25 26 - 51 52 - 61 62 63\n // ASCII: 65 - 90 97 - 122 48 - 57 45 95\n //\n\n protected _encodeByte(b: number): string {\n let result = b;\n // b >= 0\n result += 65;\n // b > 25\n result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);\n // b > 51\n result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);\n // b > 61\n result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 45);\n // b > 62\n result += ((62 - b) >>> 8) & ((62 - 45) - 63 + 95);\n\n return String.fromCharCode(result);\n }\n\n protected _decodeChar(c: number): number {\n let result = INVALID_BYTE;\n\n // c == 45 (c > 44 and c < 46)\n result += (((44 - c) & (c - 46)) >>> 8) & (-INVALID_BYTE + c - 45 + 62);\n // c == 95 (c > 94 and c < 96)\n result += (((94 - c) & (c - 96)) >>> 8) & (-INVALID_BYTE + c - 95 + 63);\n // c > 47 and c < 58\n result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);\n // c > 64 and c < 91\n result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);\n // c > 96 and c < 123\n result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);\n\n return result;\n }\n}\n\nconst urlSafeCoder = new URLSafeCoder();\n\nexport function encodeURLSafe(data: Uint8Array): string {\n return urlSafeCoder.encode(data);\n}\n\nexport function decodeURLSafe(s: string): Uint8Array {\n return urlSafeCoder.decode(s);\n}\n\n\nexport const encodedLength = (length: number) =>\n stdCoder.encodedLength(length);\n\nexport const maxDecodedLength = (length: number) =>\n stdCoder.maxDecodedLength(length);\n\nexport const decodedLength = (s: string) =>\n stdCoder.decodedLength(s);\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package utf8 implements UTF-8 encoding and decoding.\n */\n\nconst INVALID_UTF16 = \"utf8: invalid string\";\nconst INVALID_UTF8 = \"utf8: invalid source encoding\";\n\n/**\n * Encodes the given string into UTF-8 byte array.\n * Throws if the source string has invalid UTF-16 encoding.\n */\nexport function encode(s: string): Uint8Array {\n // Calculate result length and allocate output array.\n // encodedLength() also validates string and throws errors,\n // so we don't need repeat validation here.\n const arr = new Uint8Array(encodedLength(s));\n\n let pos = 0;\n for (let i = 0; i < s.length; i++) {\n let c = s.charCodeAt(i);\n if (c < 0x80) {\n arr[pos++] = c;\n } else if (c < 0x800) {\n arr[pos++] = 0xc0 | c >> 6;\n arr[pos++] = 0x80 | c & 0x3f;\n } else if (c < 0xd800) {\n arr[pos++] = 0xe0 | c >> 12;\n arr[pos++] = 0x80 | (c >> 6) & 0x3f;\n arr[pos++] = 0x80 | c & 0x3f;\n } else {\n i++; // get one more character\n c = (c & 0x3ff) << 10;\n c |= s.charCodeAt(i) & 0x3ff;\n c += 0x10000;\n\n arr[pos++] = 0xf0 | c >> 18;\n arr[pos++] = 0x80 | (c >> 12) & 0x3f;\n arr[pos++] = 0x80 | (c >> 6) & 0x3f;\n arr[pos++] = 0x80 | c & 0x3f;\n }\n }\n return arr;\n}\n\n/**\n * Returns the number of bytes required to encode the given string into UTF-8.\n * Throws if the source string has invalid UTF-16 encoding.\n */\nexport function encodedLength(s: string): number {\n let result = 0;\n for (let i = 0; i < s.length; i++) {\n const c = s.charCodeAt(i);\n if (c < 0x80) {\n result += 1;\n } else if (c < 0x800) {\n result += 2;\n } else if (c < 0xd800) {\n result += 3;\n } else if (c <= 0xdfff) {\n if (i >= s.length - 1) {\n throw new Error(INVALID_UTF16);\n }\n i++; // \"eat\" next character\n result += 4;\n } else {\n throw new Error(INVALID_UTF16);\n }\n }\n return result;\n}\n\n/**\n * Decodes the given byte array from UTF-8 into a string.\n * Throws if encoding is invalid.\n */\nexport function decode(arr: Uint8Array): string {\n const chars: string[] = [];\n for (let i = 0; i < arr.length; i++) {\n let b = arr[i];\n\n if (b & 0x80) {\n let min;\n if (b < 0xe0) {\n // Need 1 more byte.\n if (i >= arr.length) {\n throw new Error(INVALID_UTF8);\n }\n const n1 = arr[++i];\n if ((n1 & 0xc0) !== 0x80) {\n throw new Error(INVALID_UTF8);\n }\n b = (b & 0x1f) << 6 | (n1 & 0x3f);\n min = 0x80;\n } else if (b < 0xf0) {\n // Need 2 more bytes.\n if (i >= arr.length - 1) {\n throw new Error(INVALID_UTF8);\n }\n const n1 = arr[++i];\n const n2 = arr[++i];\n if ((n1 & 0xc0) !== 0x80 || (n2 & 0xc0) !== 0x80) {\n throw new Error(INVALID_UTF8);\n }\n b = (b & 0x0f) << 12 | (n1 & 0x3f) << 6 | (n2 & 0x3f);\n min = 0x800;\n } else if (b < 0xf8) {\n // Need 3 more bytes.\n if (i >= arr.length - 2) {\n throw new Error(INVALID_UTF8);\n }\n const n1 = arr[++i];\n const n2 = arr[++i];\n const n3 = arr[++i];\n if ((n1 & 0xc0) !== 0x80 || (n2 & 0xc0) !== 0x80 || (n3 & 0xc0) !== 0x80) {\n throw new Error(INVALID_UTF8);\n }\n b = (b & 0x0f) << 18 | (n1 & 0x3f) << 12 | (n2 & 0x3f) << 6 | (n3 & 0x3f);\n min = 0x10000;\n } else {\n throw new Error(INVALID_UTF8);\n }\n\n if (b < min || (b >= 0xd800 && b <= 0xdfff)) {\n throw new Error(INVALID_UTF8);\n }\n\n if (b >= 0x10000) {\n // Surrogate pair.\n if (b > 0x10ffff) {\n throw new Error(INVALID_UTF8);\n }\n b -= 0x10000;\n chars.push(String.fromCharCode(0xd800 | (b >> 10)));\n b = 0xdc00 | (b & 0x3ff);\n }\n }\n\n chars.push(String.fromCharCode(b));\n }\n return chars.join(\"\");\n}\n","// required so we don't have to do require('pusher').default etc.\nmodule.exports = require('./pusher').default;\n","export default function encode(s: any): string {\n return btoa(utob(s));\n}\n\nvar fromCharCode = String.fromCharCode;\n\nvar b64chars =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\nvar b64tab = {};\n\nfor (var i = 0, l = b64chars.length; i < l; i++) {\n b64tab[b64chars.charAt(i)] = i;\n}\n\nvar cb_utob = function(c) {\n var cc = c.charCodeAt(0);\n return cc < 0x80\n ? c\n : cc < 0x800\n ? fromCharCode(0xc0 | (cc >>> 6)) + fromCharCode(0x80 | (cc & 0x3f))\n : fromCharCode(0xe0 | ((cc >>> 12) & 0x0f)) +\n fromCharCode(0x80 | ((cc >>> 6) & 0x3f)) +\n fromCharCode(0x80 | (cc & 0x3f));\n};\n\nvar utob = function(u) {\n return u.replace(/[^\\x00-\\x7F]/g, cb_utob);\n};\n\nvar cb_encode = function(ccc) {\n var padlen = [0, 2, 1][ccc.length % 3];\n var ord =\n (ccc.charCodeAt(0) << 16) |\n ((ccc.length > 1 ? ccc.charCodeAt(1) : 0) << 8) |\n (ccc.length > 2 ? ccc.charCodeAt(2) : 0);\n var chars = [\n b64chars.charAt(ord >>> 18),\n b64chars.charAt((ord >>> 12) & 63),\n padlen >= 2 ? '=' : b64chars.charAt((ord >>> 6) & 63),\n padlen >= 1 ? '=' : b64chars.charAt(ord & 63)\n ];\n return chars.join('');\n};\n\nvar btoa =\n global.btoa ||\n function(b) {\n return b.replace(/[\\s\\S]{1,3}/g, cb_encode);\n };\n","import TimedCallback from './timed_callback';\nimport { Delay, Scheduler, Canceller } from './scheduling';\n\nabstract class Timer {\n protected clear: Canceller;\n protected timer: number | void;\n\n constructor(\n set: Scheduler,\n clear: Canceller,\n delay: Delay,\n callback: TimedCallback\n ) {\n this.clear = clear;\n this.timer = set(() => {\n if (this.timer) {\n this.timer = callback(this.timer);\n }\n }, delay);\n }\n\n /** Returns whether the timer is still running.\n *\n * @return {Boolean}\n */\n isRunning(): boolean {\n return this.timer !== null;\n }\n\n /** Aborts a timer when it's running. */\n ensureAborted() {\n if (this.timer) {\n this.clear(this.timer);\n this.timer = null;\n }\n }\n}\n\nexport default Timer;\n","import Timer from './abstract_timer';\nimport TimedCallback from './timed_callback';\nimport { Delay } from './scheduling';\n\n// We need to bind clear functions this way to avoid exceptions on IE8\nfunction clearTimeout(timer) {\n global.clearTimeout(timer);\n}\nfunction clearInterval(timer) {\n global.clearInterval(timer);\n}\n\n/** Cross-browser compatible one-off timer abstraction.\n *\n * @param {Number} delay\n * @param {Function} callback\n */\nexport class OneOffTimer extends Timer {\n constructor(delay: Delay, callback: TimedCallback) {\n super(setTimeout, clearTimeout, delay, function(timer) {\n callback();\n return null;\n });\n }\n}\n\n/** Cross-browser compatible periodic timer abstraction.\n *\n * @param {Number} delay\n * @param {Function} callback\n */\nexport class PeriodicTimer extends Timer {\n constructor(delay: Delay, callback: TimedCallback) {\n super(setInterval, clearInterval, delay, function(timer) {\n callback();\n return timer;\n });\n }\n}\n","import * as Collections from './utils/collections';\nimport TimedCallback from './utils/timers/timed_callback';\nimport { OneOffTimer, PeriodicTimer } from './utils/timers';\n\nvar Util = {\n now(): number {\n if (Date.now) {\n return Date.now();\n } else {\n return new Date().valueOf();\n }\n },\n\n defer(callback: TimedCallback): OneOffTimer {\n return new OneOffTimer(0, callback);\n },\n\n /** Builds a function that will proxy a method call to its first argument.\n *\n * Allows partial application of arguments, so additional arguments are\n * prepended to the argument list.\n *\n * @param {String} name method name\n * @return {Function} proxy function\n */\n method(name: string, ...args: any[]): Function {\n var boundArguments = Array.prototype.slice.call(arguments, 1);\n return function(object) {\n return object[name].apply(object, boundArguments.concat(arguments));\n };\n }\n};\n\nexport default Util;\n","import base64encode from '../base64';\nimport Util from '../util';\n\n/** Merges multiple objects into the target argument.\n *\n * For properties that are plain Objects, performs a deep-merge. For the\n * rest it just copies the value of the property.\n *\n * To extend prototypes use it as following:\n * Pusher.Util.extend(Target.prototype, Base.prototype)\n *\n * You can also use it to merge objects without altering them:\n * Pusher.Util.extend({}, object1, object2)\n *\n * @param {Object} target\n * @return {Object} the target argument\n */\nexport function extend(target: any, ...sources: any[]): T {\n for (var i = 0; i < sources.length; i++) {\n var extensions = sources[i];\n for (var property in extensions) {\n if (\n extensions[property] &&\n extensions[property].constructor &&\n extensions[property].constructor === Object\n ) {\n target[property] = extend(target[property] || {}, extensions[property]);\n } else {\n target[property] = extensions[property];\n }\n }\n }\n return target;\n}\n\nexport function stringify(): string {\n var m = ['Pusher'];\n for (var i = 0; i < arguments.length; i++) {\n if (typeof arguments[i] === 'string') {\n m.push(arguments[i]);\n } else {\n m.push(safeJSONStringify(arguments[i]));\n }\n }\n return m.join(' : ');\n}\n\nexport function arrayIndexOf(array: any[], item: any): number {\n // MSIE doesn't have array.indexOf\n var nativeIndexOf = Array.prototype.indexOf;\n if (array === null) {\n return -1;\n }\n if (nativeIndexOf && array.indexOf === nativeIndexOf) {\n return array.indexOf(item);\n }\n for (var i = 0, l = array.length; i < l; i++) {\n if (array[i] === item) {\n return i;\n }\n }\n return -1;\n}\n\n/** Applies a function f to all properties of an object.\n *\n * Function f gets 3 arguments passed:\n * - element from the object\n * - key of the element\n * - reference to the object\n *\n * @param {Object} object\n * @param {Function} f\n */\nexport function objectApply(object: any, f: Function) {\n for (var key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n f(object[key], key, object);\n }\n }\n}\n\n/** Return a list of objects own proerty keys\n *\n * @param {Object} object\n * @returns {Array}\n */\nexport function keys(object: any): string[] {\n var keys = [];\n objectApply(object, function(_, key) {\n keys.push(key);\n });\n return keys;\n}\n\n/** Return a list of object's own property values\n *\n * @param {Object} object\n * @returns {Array}\n */\nexport function values(object: any): any[] {\n var values = [];\n objectApply(object, function(value) {\n values.push(value);\n });\n return values;\n}\n\n/** Applies a function f to all elements of an array.\n *\n * Function f gets 3 arguments passed:\n * - element from the array\n * - index of the element\n * - reference to the array\n *\n * @param {Array} array\n * @param {Function} f\n */\nexport function apply(array: any[], f: Function, context?: any) {\n for (var i = 0; i < array.length; i++) {\n f.call(context || global, array[i], i, array);\n }\n}\n\n/** Maps all elements of the array and returns the result.\n *\n * Function f gets 4 arguments passed:\n * - element from the array\n * - index of the element\n * - reference to the source array\n * - reference to the destination array\n *\n * @param {Array} array\n * @param {Function} f\n */\nexport function map(array: any[], f: Function): any[] {\n var result = [];\n for (var i = 0; i < array.length; i++) {\n result.push(f(array[i], i, array, result));\n }\n return result;\n}\n\n/** Maps all elements of the object and returns the result.\n *\n * Function f gets 4 arguments passed:\n * - element from the object\n * - key of the element\n * - reference to the source object\n * - reference to the destination object\n *\n * @param {Object} object\n * @param {Function} f\n */\nexport function mapObject(object: any, f: Function): any {\n var result = {};\n objectApply(object, function(value, key) {\n result[key] = f(value);\n });\n return result;\n}\n\n/** Filters elements of the array using a test function.\n *\n * Function test gets 4 arguments passed:\n * - element from the array\n * - index of the element\n * - reference to the source array\n * - reference to the destination array\n *\n * @param {Array} array\n * @param {Function} f\n */\nexport function filter(array: any[], test: Function): any[] {\n test =\n test ||\n function(value) {\n return !!value;\n };\n\n var result = [];\n for (var i = 0; i < array.length; i++) {\n if (test(array[i], i, array, result)) {\n result.push(array[i]);\n }\n }\n return result;\n}\n\n/** Filters properties of the object using a test function.\n *\n * Function test gets 4 arguments passed:\n * - element from the object\n * - key of the element\n * - reference to the source object\n * - reference to the destination object\n *\n * @param {Object} object\n * @param {Function} f\n */\nexport function filterObject(object: Object, test: Function) {\n var result = {};\n objectApply(object, function(value, key) {\n if ((test && test(value, key, object, result)) || Boolean(value)) {\n result[key] = value;\n }\n });\n return result;\n}\n\n/** Flattens an object into a two-dimensional array.\n *\n * @param {Object} object\n * @return {Array} resulting array of [key, value] pairs\n */\nexport function flatten(object: Object): any[] {\n var result = [];\n objectApply(object, function(value, key) {\n result.push([key, value]);\n });\n return result;\n}\n\n/** Checks whether any element of the array passes the test.\n *\n * Function test gets 3 arguments passed:\n * - element from the array\n * - index of the element\n * - reference to the source array\n *\n * @param {Array} array\n * @param {Function} f\n */\nexport function any(array: any[], test: Function): boolean {\n for (var i = 0; i < array.length; i++) {\n if (test(array[i], i, array)) {\n return true;\n }\n }\n return false;\n}\n\n/** Checks whether all elements of the array pass the test.\n *\n * Function test gets 3 arguments passed:\n * - element from the array\n * - index of the element\n * - reference to the source array\n *\n * @param {Array} array\n * @param {Function} f\n */\nexport function all(array: any[], test: Function): boolean {\n for (var i = 0; i < array.length; i++) {\n if (!test(array[i], i, array)) {\n return false;\n }\n }\n return true;\n}\n\nexport function encodeParamsObject(data): string {\n return mapObject(data, function(value) {\n if (typeof value === 'object') {\n value = safeJSONStringify(value);\n }\n return encodeURIComponent(base64encode(value.toString()));\n });\n}\n\nexport function buildQueryString(data: any): string {\n var params = filterObject(data, function(value) {\n return value !== undefined;\n });\n\n var query = map(\n flatten(encodeParamsObject(params)),\n Util.method('join', '=')\n ).join('&');\n\n return query;\n}\n\n/**\n * See https://github.com/douglascrockford/JSON-js/blob/master/cycle.js\n *\n * Remove circular references from an object. Required for JSON.stringify in\n * React Native, which tends to blow up a lot.\n *\n * @param {any} object\n * @return {any} Decycled object\n */\nexport function decycleObject(object: any): any {\n var objects = [],\n paths = [];\n\n return (function derez(value, path) {\n var i, name, nu;\n\n switch (typeof value) {\n case 'object':\n if (!value) {\n return null;\n }\n for (i = 0; i < objects.length; i += 1) {\n if (objects[i] === value) {\n return { $ref: paths[i] };\n }\n }\n\n objects.push(value);\n paths.push(path);\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 nu = {};\n for (name in value) {\n if (Object.prototype.hasOwnProperty.call(value, name)) {\n nu[name] = derez(\n value[name],\n path + '[' + JSON.stringify(name) + ']'\n );\n }\n }\n }\n return nu;\n case 'number':\n case 'string':\n case 'boolean':\n return value;\n }\n })(object, '$');\n}\n\n/**\n * Provides a cross-browser and cross-platform way to safely stringify objects\n * into JSON. This is particularly necessary for ReactNative, where circular JSON\n * structures throw an exception.\n *\n * @param {any} source The object to stringify\n * @return {string} The serialized output.\n */\nexport function safeJSONStringify(source: any): string {\n try {\n return JSON.stringify(source);\n } catch (e) {\n return JSON.stringify(decycleObject(source));\n }\n}\n","import {\n ChannelAuthorizationOptions,\n UserAuthenticationOptions\n} from './auth/options';\nimport { AuthTransport } from './config';\n\nexport interface DefaultConfig {\n VERSION: string;\n PROTOCOL: number;\n wsPort: number;\n wssPort: number;\n wsPath: string;\n httpHost: string;\n httpPort: number;\n httpsPort: number;\n httpPath: string;\n stats_host: string;\n authEndpoint: string;\n authTransport: AuthTransport;\n activityTimeout: number;\n pongTimeout: number;\n unavailableTimeout: number;\n userAuthentication: UserAuthenticationOptions;\n channelAuthorization: ChannelAuthorizationOptions;\n\n cdn_http?: string;\n cdn_https?: string;\n dependency_suffix?: string;\n}\n\nvar Defaults: DefaultConfig = {\n VERSION: VERSION,\n PROTOCOL: 7,\n\n wsPort: 80,\n wssPort: 443,\n wsPath: '',\n // DEPRECATED: SockJS fallback parameters\n httpHost: 'sockjs.pusher.com',\n httpPort: 80,\n httpsPort: 443,\n httpPath: '/pusher',\n // DEPRECATED: Stats\n stats_host: 'stats.pusher.com',\n // DEPRECATED: Other settings\n authEndpoint: '/pusher/auth',\n authTransport: 'ajax',\n activityTimeout: 120000,\n pongTimeout: 30000,\n unavailableTimeout: 10000,\n userAuthentication: {\n endpoint: '/pusher/user-auth',\n transport: 'ajax'\n },\n channelAuthorization: {\n endpoint: '/pusher/auth',\n transport: 'ajax'\n },\n\n // CDN configuration\n cdn_http: CDN_HTTP,\n cdn_https: CDN_HTTPS,\n dependency_suffix: DEPENDENCY_SUFFIX\n};\n\nexport default Defaults;\n","import Defaults from '../defaults';\nimport { default as URLScheme, URLSchemeParams } from './url_scheme';\n\nfunction getGenericURL(\n baseScheme: string,\n params: URLSchemeParams,\n path: string\n): string {\n var scheme = baseScheme + (params.useTLS ? 's' : '');\n var host = params.useTLS ? params.hostTLS : params.hostNonTLS;\n return scheme + '://' + host + path;\n}\n\nfunction getGenericPath(key: string, queryString?: string): string {\n var path = '/app/' + key;\n var query =\n '?protocol=' +\n Defaults.PROTOCOL +\n '&client=js' +\n '&version=' +\n Defaults.VERSION +\n (queryString ? '&' + queryString : '');\n return path + query;\n}\n\nexport var ws: URLScheme = {\n getInitial: function(key: string, params: URLSchemeParams): string {\n var path = (params.httpPath || '') + getGenericPath(key, 'flash=false');\n return getGenericURL('ws', params, path);\n }\n};\n\nexport var http: URLScheme = {\n getInitial: function(key: string, params: URLSchemeParams): string {\n var path = (params.httpPath || '/pusher') + getGenericPath(key);\n return getGenericURL('http', params, path);\n }\n};\n\nexport var sockjs: URLScheme = {\n getInitial: function(key: string, params: URLSchemeParams): string {\n return getGenericURL('http', params, params.httpPath || '/pusher');\n },\n getPath: function(key: string, params: URLSchemeParams): string {\n return getGenericPath(key);\n }\n};\n","import Callback from './callback';\nimport * as Collections from '../utils/collections';\nimport CallbackTable from './callback_table';\n\nexport default class CallbackRegistry {\n _callbacks: CallbackTable;\n\n constructor() {\n this._callbacks = {};\n }\n\n get(name: string): Callback[] {\n return this._callbacks[prefix(name)];\n }\n\n add(name: string, callback: Function, context: any) {\n var prefixedEventName = prefix(name);\n this._callbacks[prefixedEventName] =\n this._callbacks[prefixedEventName] || [];\n this._callbacks[prefixedEventName].push({\n fn: callback,\n context: context\n });\n }\n\n remove(name?: string, callback?: Function, context?: any) {\n if (!name && !callback && !context) {\n this._callbacks = {};\n return;\n }\n\n var names = name ? [prefix(name)] : Collections.keys(this._callbacks);\n\n if (callback || context) {\n this.removeCallback(names, callback, context);\n } else {\n this.removeAllCallbacks(names);\n }\n }\n\n private removeCallback(names: string[], callback: Function, context: any) {\n Collections.apply(\n names,\n function(name) {\n this._callbacks[name] = Collections.filter(\n this._callbacks[name] || [],\n function(binding) {\n return (\n (callback && callback !== binding.fn) ||\n (context && context !== binding.context)\n );\n }\n );\n if (this._callbacks[name].length === 0) {\n delete this._callbacks[name];\n }\n },\n this\n );\n }\n\n private removeAllCallbacks(names: string[]) {\n Collections.apply(\n names,\n function(name) {\n delete this._callbacks[name];\n },\n this\n );\n }\n}\n\nfunction prefix(name: string): string {\n return '_' + name;\n}\n","import * as Collections from '../utils/collections';\nimport Callback from './callback';\nimport Metadata from '../channels/metadata';\nimport CallbackRegistry from './callback_registry';\n\n/** Manages callback bindings and event emitting.\n *\n * @param Function failThrough called when no listeners are bound to an event\n */\nexport default class Dispatcher {\n callbacks: CallbackRegistry;\n global_callbacks: Function[];\n failThrough: Function;\n\n constructor(failThrough?: Function) {\n this.callbacks = new CallbackRegistry();\n this.global_callbacks = [];\n this.failThrough = failThrough;\n }\n\n bind(eventName: string, callback: Function, context?: any) {\n this.callbacks.add(eventName, callback, context);\n return this;\n }\n\n bind_global(callback: Function) {\n this.global_callbacks.push(callback);\n return this;\n }\n\n unbind(eventName?: string, callback?: Function, context?: any) {\n this.callbacks.remove(eventName, callback, context);\n return this;\n }\n\n unbind_global(callback?: Function) {\n if (!callback) {\n this.global_callbacks = [];\n return this;\n }\n\n this.global_callbacks = Collections.filter(\n this.global_callbacks || [],\n c => c !== callback\n );\n\n return this;\n }\n\n unbind_all() {\n this.unbind();\n this.unbind_global();\n return this;\n }\n\n emit(eventName: string, data?: any, metadata?: Metadata): Dispatcher {\n for (var i = 0; i < this.global_callbacks.length; i++) {\n this.global_callbacks[i](eventName, data);\n }\n\n var callbacks = this.callbacks.get(eventName);\n var args = [];\n\n if (metadata) {\n // if there's a metadata argument, we need to call the callback with both\n // data and metadata regardless of whether data is undefined\n args.push(data, metadata);\n } else if (data) {\n // metadata is undefined, so we only need to call the callback with data\n // if data exists\n args.push(data);\n }\n\n if (callbacks && callbacks.length > 0) {\n for (var i = 0; i < callbacks.length; i++) {\n callbacks[i].fn.apply(callbacks[i].context || global, args);\n }\n } else if (this.failThrough) {\n this.failThrough(eventName, data);\n }\n\n return this;\n }\n}\n","import { stringify } from './utils/collections';\nimport Pusher from './pusher';\n\nclass Logger {\n debug(...args: any[]) {\n this.log(this.globalLog, args);\n }\n\n warn(...args: any[]) {\n this.log(this.globalLogWarn, args);\n }\n\n error(...args: any[]) {\n this.log(this.globalLogError, args);\n }\n\n private globalLog = (message: string) => {\n if (global.console && global.console.log) {\n global.console.log(message);\n }\n };\n\n private globalLogWarn(message: string) {\n if (global.console && global.console.warn) {\n global.console.warn(message);\n } else {\n this.globalLog(message);\n }\n }\n\n private globalLogError(message: string) {\n if (global.console && global.console.error) {\n global.console.error(message);\n } else {\n this.globalLogWarn(message);\n }\n }\n\n private log(\n defaultLoggingFunction: (message: string) => void,\n ...args: any[]\n ) {\n var message = stringify.apply(this, arguments);\n if (Pusher.log) {\n Pusher.log(message);\n } else if (Pusher.logToConsole) {\n const log = defaultLoggingFunction.bind(this);\n log(message);\n }\n }\n}\n\nexport default new Logger();\n","import Util from '../util';\nimport * as Collections from '../utils/collections';\nimport { default as EventsDispatcher } from '../events/dispatcher';\nimport Logger from '../logger';\nimport TransportHooks from './transport_hooks';\nimport Socket from '../socket';\nimport Runtime from 'runtime';\nimport Timeline from '../timeline/timeline';\nimport TransportConnectionOptions from './transport_connection_options';\n\n/** Provides universal API for transport connections.\n *\n * Transport connection is a low-level object that wraps a connection method\n * and exposes a simple evented interface for the connection state and\n * messaging. It does not implement Pusher-specific WebSocket protocol.\n *\n * Additionally, it fetches resources needed for transport to work and exposes\n * an interface for querying transport features.\n *\n * States:\n * - new - initial state after constructing the object\n * - initializing - during initialization phase, usually fetching resources\n * - intialized - ready to establish a connection\n * - connection - when connection is being established\n * - open - when connection ready to be used\n * - closed - after connection was closed be either side\n *\n * Emits:\n * - error - after the connection raised an error\n *\n * Options:\n * - useTLS - whether connection should be over TLS\n * - hostTLS - host to connect to when connection is over TLS\n * - hostNonTLS - host to connect to when connection is over TLS\n *\n * @param {String} key application key\n * @param {Object} options\n */\nexport default class TransportConnection extends EventsDispatcher {\n hooks: TransportHooks;\n name: string;\n priority: number;\n key: string;\n options: TransportConnectionOptions;\n state: string;\n timeline: Timeline;\n activityTimeout: number;\n id: number;\n socket: Socket;\n beforeOpen: Function;\n initialize: Function;\n\n constructor(\n hooks: TransportHooks,\n name: string,\n priority: number,\n key: string,\n options: TransportConnectionOptions\n ) {\n super();\n this.initialize = Runtime.transportConnectionInitializer;\n this.hooks = hooks;\n this.name = name;\n this.priority = priority;\n this.key = key;\n this.options = options;\n\n this.state = 'new';\n this.timeline = options.timeline;\n this.activityTimeout = options.activityTimeout;\n this.id = this.timeline.generateUniqueID();\n }\n\n /** Checks whether the transport handles activity checks by itself.\n *\n * @return {Boolean}\n */\n handlesActivityChecks(): boolean {\n return Boolean(this.hooks.handlesActivityChecks);\n }\n\n /** Checks whether the transport supports the ping/pong API.\n *\n * @return {Boolean}\n */\n supportsPing(): boolean {\n return Boolean(this.hooks.supportsPing);\n }\n\n /** Tries to establish a connection.\n *\n * @returns {Boolean} false if transport is in invalid state\n */\n connect(): boolean {\n if (this.socket || this.state !== 'initialized') {\n return false;\n }\n\n var url = this.hooks.urls.getInitial(this.key, this.options);\n try {\n this.socket = this.hooks.getSocket(url, this.options);\n } catch (e) {\n Util.defer(() => {\n this.onError(e);\n this.changeState('closed');\n });\n return false;\n }\n\n this.bindListeners();\n\n Logger.debug('Connecting', { transport: this.name, url });\n this.changeState('connecting');\n return true;\n }\n\n /** Closes the connection.\n *\n * @return {Boolean} true if there was a connection to close\n */\n close(): boolean {\n if (this.socket) {\n this.socket.close();\n return true;\n } else {\n return false;\n }\n }\n\n /** Sends data over the open connection.\n *\n * @param {String} data\n * @return {Boolean} true only when in the \"open\" state\n */\n send(data: any): boolean {\n if (this.state === 'open') {\n // Workaround for MobileSafari bug (see https://gist.github.com/2052006)\n Util.defer(() => {\n if (this.socket) {\n this.socket.send(data);\n }\n });\n return true;\n } else {\n return false;\n }\n }\n\n /** Sends a ping if the connection is open and transport supports it. */\n ping() {\n if (this.state === 'open' && this.supportsPing()) {\n this.socket.ping();\n }\n }\n\n private onOpen() {\n if (this.hooks.beforeOpen) {\n this.hooks.beforeOpen(\n this.socket,\n this.hooks.urls.getPath(this.key, this.options)\n );\n }\n this.changeState('open');\n this.socket.onopen = undefined;\n }\n\n private onError(error) {\n this.emit('error', { type: 'WebSocketError', error: error });\n this.timeline.error(this.buildTimelineMessage({ error: error.toString() }));\n }\n\n private onClose(closeEvent?: any) {\n if (closeEvent) {\n this.changeState('closed', {\n code: closeEvent.code,\n reason: closeEvent.reason,\n wasClean: closeEvent.wasClean\n });\n } else {\n this.changeState('closed');\n }\n this.unbindListeners();\n this.socket = undefined;\n }\n\n private onMessage(message) {\n this.emit('message', message);\n }\n\n private onActivity() {\n this.emit('activity');\n }\n\n private bindListeners() {\n this.socket.onopen = () => {\n this.onOpen();\n };\n this.socket.onerror = error => {\n this.onError(error);\n };\n this.socket.onclose = closeEvent => {\n this.onClose(closeEvent);\n };\n this.socket.onmessage = message => {\n this.onMessage(message);\n };\n\n if (this.supportsPing()) {\n this.socket.onactivity = () => {\n this.onActivity();\n };\n }\n }\n\n private unbindListeners() {\n if (this.socket) {\n this.socket.onopen = undefined;\n this.socket.onerror = undefined;\n this.socket.onclose = undefined;\n this.socket.onmessage = undefined;\n if (this.supportsPing()) {\n this.socket.onactivity = undefined;\n }\n }\n }\n\n private changeState(state: string, params?: any) {\n this.state = state;\n this.timeline.info(\n this.buildTimelineMessage({\n state: state,\n params: params\n })\n );\n this.emit(state, params);\n }\n\n buildTimelineMessage(message): any {\n return Collections.extend({ cid: this.id }, message);\n }\n}\n","import Factory from '../utils/factory';\nimport TransportHooks from './transport_hooks';\nimport TransportConnection from './transport_connection';\nimport TransportConnectionOptions from './transport_connection_options';\n\n/** Provides interface for transport connection instantiation.\n *\n * Takes transport-specific hooks as the only argument, which allow checking\n * for transport support and creating its connections.\n *\n * Supported hooks: * - file - the name of the file to be fetched during initialization\n * - urls - URL scheme to be used by transport\n * - handlesActivityCheck - true when the transport handles activity checks\n * - supportsPing - true when the transport has a ping/activity API\n * - isSupported - tells whether the transport is supported in the environment\n * - getSocket - creates a WebSocket-compatible transport socket\n *\n * See transports.js for specific implementations.\n *\n * @param {Object} hooks object containing all needed transport hooks\n */\nexport default class Transport {\n hooks: TransportHooks;\n\n constructor(hooks: TransportHooks) {\n this.hooks = hooks;\n }\n\n /** Returns whether the transport is supported in the environment.\n *\n * @param {Object} envronment te environment details (encryption, settings)\n * @returns {Boolean} true when the transport is supported\n */\n isSupported(environment: any): boolean {\n return this.hooks.isSupported(environment);\n }\n\n /** Creates a transport connection.\n *\n * @param {String} name\n * @param {Number} priority\n * @param {String} key the application key\n * @param {Object} options\n * @returns {TransportConnection}\n */\n createConnection(\n name: string,\n priority: number,\n key: string,\n options: any\n ): TransportConnection {\n return new TransportConnection(this.hooks, name, priority, key, options);\n }\n}\n","import * as URLSchemes from 'core/transports/url_schemes';\nimport URLScheme from 'core/transports/url_scheme';\nimport Transport from 'core/transports/transport';\nimport Util from 'core/util';\nimport * as Collections from 'core/utils/collections';\nimport TransportHooks from 'core/transports/transport_hooks';\nimport TransportsTable from 'core/transports/transports_table';\nimport Runtime from 'runtime';\n\n/** WebSocket transport.\n *\n * Uses native WebSocket implementation, including MozWebSocket supported by\n * earlier Firefox versions.\n */\nvar WSTransport = new Transport({\n urls: URLSchemes.ws,\n handlesActivityChecks: false,\n supportsPing: false,\n\n isInitialized: function() {\n return Boolean(Runtime.getWebSocketAPI());\n },\n isSupported: function(): boolean {\n return Boolean(Runtime.getWebSocketAPI());\n },\n getSocket: function(url) {\n return Runtime.createWebSocket(url);\n }\n});\n\nvar httpConfiguration = {\n urls: URLSchemes.http,\n handlesActivityChecks: false,\n supportsPing: true,\n isInitialized: function() {\n return true;\n }\n};\n\nexport var streamingConfiguration = Collections.extend(\n {\n getSocket: function(url) {\n return Runtime.HTTPFactory.createStreamingSocket(url);\n }\n },\n httpConfiguration\n);\nexport var pollingConfiguration = Collections.extend(\n {\n getSocket: function(url) {\n return Runtime.HTTPFactory.createPollingSocket(url);\n }\n },\n httpConfiguration\n);\n\nvar xhrConfiguration = {\n isSupported: function(): boolean {\n return Runtime.isXHRSupported();\n }\n};\n\n/** HTTP streaming transport using CORS-enabled XMLHttpRequest. */\nvar XHRStreamingTransport = new Transport(\n (\n Collections.extend({}, streamingConfiguration, xhrConfiguration)\n )\n);\n\n/** HTTP long-polling transport using CORS-enabled XMLHttpRequest. */\nvar XHRPollingTransport = new Transport(\n Collections.extend({}, pollingConfiguration, xhrConfiguration)\n);\n\nvar Transports: TransportsTable = {\n ws: WSTransport,\n xhr_streaming: XHRStreamingTransport,\n xhr_polling: XHRPollingTransport\n};\n\nexport default Transports;\n","import Util from '../util';\nimport * as Collections from '../utils/collections';\nimport TransportManager from './transport_manager';\nimport TransportConnection from './transport_connection';\nimport Transport from './transport';\nimport PingDelayOptions from './ping_delay_options';\n\n/** Creates transport connections monitored by a transport manager.\n *\n * When a transport is closed, it might mean the environment does not support\n * it. It's possible that messages get stuck in an intermediate buffer or\n * proxies terminate inactive connections. To combat these problems,\n * assistants monitor the connection lifetime, report unclean exits and\n * adjust ping timeouts to keep the connection active. The decision to disable\n * a transport is the manager's responsibility.\n *\n * @param {TransportManager} manager\n * @param {TransportConnection} transport\n * @param {Object} options\n */\nexport default class AssistantToTheTransportManager {\n manager: TransportManager;\n transport: Transport;\n minPingDelay: number;\n maxPingDelay: number;\n pingDelay: number;\n\n constructor(\n manager: TransportManager,\n transport: Transport,\n options: PingDelayOptions\n ) {\n this.manager = manager;\n this.transport = transport;\n this.minPingDelay = options.minPingDelay;\n this.maxPingDelay = options.maxPingDelay;\n this.pingDelay = undefined;\n }\n\n /** Creates a transport connection.\n *\n * This function has the same API as Transport#createConnection.\n *\n * @param {String} name\n * @param {Number} priority\n * @param {String} key the application key\n * @param {Object} options\n * @returns {TransportConnection}\n */\n createConnection(\n name: string,\n priority: number,\n key: string,\n options: Object\n ): TransportConnection {\n options = Collections.extend({}, options, {\n activityTimeout: this.pingDelay\n });\n var connection = this.transport.createConnection(\n name,\n priority,\n key,\n options\n );\n\n var openTimestamp = null;\n\n var onOpen = function() {\n connection.unbind('open', onOpen);\n connection.bind('closed', onClosed);\n openTimestamp = Util.now();\n };\n var onClosed = closeEvent => {\n connection.unbind('closed', onClosed);\n\n if (closeEvent.code === 1002 || closeEvent.code === 1003) {\n // we don't want to use transports not obeying the protocol\n this.manager.reportDeath();\n } else if (!closeEvent.wasClean && openTimestamp) {\n // report deaths only for short-living transport\n var lifespan = Util.now() - openTimestamp;\n if (lifespan < 2 * this.maxPingDelay) {\n this.manager.reportDeath();\n this.pingDelay = Math.max(lifespan / 2, this.minPingDelay);\n }\n }\n };\n\n connection.bind('open', onOpen);\n return connection;\n }\n\n /** Returns whether the transport is supported in the environment.\n *\n * This function has the same API as Transport#isSupported. Might return false\n * when the manager decides to kill the transport.\n *\n * @param {Object} environment the environment details (encryption, settings)\n * @returns {Boolean} true when the transport is supported\n */\n isSupported(environment: string): boolean {\n return this.manager.isAlive() && this.transport.isSupported(environment);\n }\n}\n","import Action from './action';\nimport { PusherEvent } from './message-types';\n/**\n * Provides functions for handling Pusher protocol-specific messages.\n */\n\nconst Protocol = {\n /**\n * Decodes a message in a Pusher format.\n *\n * The MessageEvent we receive from the transport should contain a pusher event\n * (https://pusher.com/docs/pusher_protocol#events) serialized as JSON in the\n * data field\n *\n * The pusher event may contain a data field too, and it may also be\n * serialised as JSON\n *\n * Throws errors when messages are not parse'able.\n *\n * @param {MessageEvent} messageEvent\n * @return {PusherEvent}\n */\n decodeMessage: function(messageEvent: MessageEvent): PusherEvent {\n try {\n var messageData = JSON.parse(messageEvent.data);\n var pusherEventData = messageData.data;\n if (typeof pusherEventData === 'string') {\n try {\n pusherEventData = JSON.parse(messageData.data);\n } catch (e) {}\n }\n var pusherEvent: PusherEvent = {\n event: messageData.event,\n channel: messageData.channel,\n data: pusherEventData\n };\n if (messageData.user_id) {\n pusherEvent.user_id = messageData.user_id;\n }\n return pusherEvent;\n } catch (e) {\n throw { type: 'MessageParseError', error: e, data: messageEvent.data };\n }\n },\n\n /**\n * Encodes a message to be sent.\n *\n * @param {PusherEvent} event\n * @return {String}\n */\n encodeMessage: function(event: PusherEvent): string {\n return JSON.stringify(event);\n },\n\n /**\n * Processes a handshake message and returns appropriate actions.\n *\n * Returns an object with an 'action' and other action-specific properties.\n *\n * There are three outcomes when calling this function. First is a successful\n * connection attempt, when pusher:connection_established is received, which\n * results in a 'connected' action with an 'id' property. When passed a\n * pusher:error event, it returns a result with action appropriate to the\n * close code and an error. Otherwise, it raises an exception.\n *\n * @param {String} message\n * @result Object\n */\n processHandshake: function(messageEvent: MessageEvent): Action {\n var message = Protocol.decodeMessage(messageEvent);\n\n if (message.event === 'pusher:connection_established') {\n if (!message.data.activity_timeout) {\n throw 'No activity timeout specified in handshake';\n }\n return {\n action: 'connected',\n id: message.data.socket_id,\n activityTimeout: message.data.activity_timeout * 1000\n };\n } else if (message.event === 'pusher:error') {\n // From protocol 6 close codes are sent only once, so this only\n // happens when connection does not support close codes\n return {\n action: this.getCloseAction(message.data),\n error: this.getCloseError(message.data)\n };\n } else {\n throw 'Invalid handshake';\n }\n },\n\n /**\n * Dispatches the close event and returns an appropriate action name.\n *\n * See:\n * 1. https://developer.mozilla.org/en-US/docs/WebSockets/WebSockets_reference/CloseEvent\n * 2. http://pusher.com/docs/pusher_protocol\n *\n * @param {CloseEvent} closeEvent\n * @return {String} close action name\n */\n getCloseAction: function(closeEvent): string {\n if (closeEvent.code < 4000) {\n // ignore 1000 CLOSE_NORMAL, 1001 CLOSE_GOING_AWAY,\n // 1005 CLOSE_NO_STATUS, 1006 CLOSE_ABNORMAL\n // ignore 1007...3999\n // handle 1002 CLOSE_PROTOCOL_ERROR, 1003 CLOSE_UNSUPPORTED,\n // 1004 CLOSE_TOO_LARGE\n if (closeEvent.code >= 1002 && closeEvent.code <= 1004) {\n return 'backoff';\n } else {\n return null;\n }\n } else if (closeEvent.code === 4000) {\n return 'tls_only';\n } else if (closeEvent.code < 4100) {\n return 'refused';\n } else if (closeEvent.code < 4200) {\n return 'backoff';\n } else if (closeEvent.code < 4300) {\n return 'retry';\n } else {\n // unknown error\n return 'refused';\n }\n },\n\n /**\n * Returns an error or null basing on the close event.\n *\n * Null is returned when connection was closed cleanly. Otherwise, an object\n * with error details is returned.\n *\n * @param {CloseEvent} closeEvent\n * @return {Object} error object\n */\n getCloseError: function(closeEvent): any {\n if (closeEvent.code !== 1000 && closeEvent.code !== 1001) {\n return {\n type: 'PusherError',\n data: {\n code: closeEvent.code,\n message: closeEvent.reason || closeEvent.message\n }\n };\n } else {\n return null;\n }\n }\n};\n\nexport default Protocol;\n","import * as Collections from '../utils/collections';\nimport { default as EventsDispatcher } from '../events/dispatcher';\nimport Protocol from './protocol/protocol';\nimport { PusherEvent } from './protocol/message-types';\nimport Logger from '../logger';\nimport TransportConnection from '../transports/transport_connection';\nimport Socket from '../socket';\n/**\n * Provides Pusher protocol interface for transports.\n *\n * Emits following events:\n * - message - on received messages\n * - ping - on ping requests\n * - pong - on pong responses\n * - error - when the transport emits an error\n * - closed - after closing the transport\n *\n * It also emits more events when connection closes with a code.\n * See Protocol.getCloseAction to get more details.\n *\n * @param {Number} id\n * @param {AbstractTransport} transport\n */\nexport default class Connection extends EventsDispatcher implements Socket {\n id: string;\n transport: TransportConnection;\n activityTimeout: number;\n\n constructor(id: string, transport: TransportConnection) {\n super();\n this.id = id;\n this.transport = transport;\n this.activityTimeout = transport.activityTimeout;\n this.bindListeners();\n }\n\n /** Returns whether used transport handles activity checks by itself\n *\n * @returns {Boolean} true if activity checks are handled by the transport\n */\n handlesActivityChecks() {\n return this.transport.handlesActivityChecks();\n }\n\n /** Sends raw data.\n *\n * @param {String} data\n */\n send(data: any): boolean {\n return this.transport.send(data);\n }\n\n /** Sends an event.\n *\n * @param {String} name\n * @param {String} data\n * @param {String} [channel]\n * @returns {Boolean} whether message was sent or not\n */\n send_event(name: string, data: any, channel?: string): boolean {\n var event: PusherEvent = { event: name, data: data };\n if (channel) {\n event.channel = channel;\n }\n Logger.debug('Event sent', event);\n return this.send(Protocol.encodeMessage(event));\n }\n\n /** Sends a ping message to the server.\n *\n * Basing on the underlying transport, it might send either transport's\n * protocol-specific ping or pusher:ping event.\n */\n ping() {\n if (this.transport.supportsPing()) {\n this.transport.ping();\n } else {\n this.send_event('pusher:ping', {});\n }\n }\n\n /** Closes the connection. */\n close() {\n this.transport.close();\n }\n\n private bindListeners() {\n var listeners = {\n message: (messageEvent: MessageEvent) => {\n var pusherEvent;\n try {\n pusherEvent = Protocol.decodeMessage(messageEvent);\n } catch (e) {\n this.emit('error', {\n type: 'MessageParseError',\n error: e,\n data: messageEvent.data\n });\n }\n\n if (pusherEvent !== undefined) {\n Logger.debug('Event recd', pusherEvent);\n\n switch (pusherEvent.event) {\n case 'pusher:error':\n this.emit('error', {\n type: 'PusherError',\n data: pusherEvent.data\n });\n break;\n case 'pusher:ping':\n this.emit('ping');\n break;\n case 'pusher:pong':\n this.emit('pong');\n break;\n }\n this.emit('message', pusherEvent);\n }\n },\n activity: () => {\n this.emit('activity');\n },\n error: error => {\n this.emit('error', error);\n },\n closed: closeEvent => {\n unbindListeners();\n\n if (closeEvent && closeEvent.code) {\n this.handleCloseEvent(closeEvent);\n }\n\n this.transport = null;\n this.emit('closed');\n }\n };\n\n var unbindListeners = () => {\n Collections.objectApply(listeners, (listener, event) => {\n this.transport.unbind(event, listener);\n });\n };\n\n Collections.objectApply(listeners, (listener, event) => {\n this.transport.bind(event, listener);\n });\n }\n\n private handleCloseEvent(closeEvent: any) {\n var action = Protocol.getCloseAction(closeEvent);\n var error = Protocol.getCloseError(closeEvent);\n if (error) {\n this.emit('error', error);\n }\n if (action) {\n this.emit(action, { action: action, error: error });\n }\n }\n}\n","import Util from '../../util';\nimport * as Collections from '../../utils/collections';\nimport Protocol from '../protocol/protocol';\nimport Connection from '../connection';\nimport TransportConnection from '../../transports/transport_connection';\nimport HandshakePayload from './handshake_payload';\n\n/**\n * Handles Pusher protocol handshakes for transports.\n *\n * Calls back with a result object after handshake is completed. Results\n * always have two fields:\n * - action - string describing action to be taken after the handshake\n * - transport - the transport object passed to the constructor\n *\n * Different actions can set different additional properties on the result.\n * In the case of 'connected' action, there will be a 'connection' property\n * containing a Connection object for the transport. Other actions should\n * carry an 'error' property.\n *\n * @param {AbstractTransport} transport\n * @param {Function} callback\n */\nexport default class Handshake {\n transport: TransportConnection;\n callback: (HandshakePayload) => void;\n onMessage: Function;\n onClosed: Function;\n\n constructor(\n transport: TransportConnection,\n callback: (HandshakePayload) => void\n ) {\n this.transport = transport;\n this.callback = callback;\n this.bindListeners();\n }\n\n close() {\n this.unbindListeners();\n this.transport.close();\n }\n\n private bindListeners() {\n this.onMessage = m => {\n this.unbindListeners();\n\n var result;\n try {\n result = Protocol.processHandshake(m);\n } catch (e) {\n this.finish('error', { error: e });\n this.transport.close();\n return;\n }\n\n if (result.action === 'connected') {\n this.finish('connected', {\n connection: new Connection(result.id, this.transport),\n activityTimeout: result.activityTimeout\n });\n } else {\n this.finish(result.action, { error: result.error });\n this.transport.close();\n }\n };\n\n this.onClosed = closeEvent => {\n this.unbindListeners();\n\n var action = Protocol.getCloseAction(closeEvent) || 'backoff';\n var error = Protocol.getCloseError(closeEvent);\n this.finish(action, { error: error });\n };\n\n this.transport.bind('message', this.onMessage);\n this.transport.bind('closed', this.onClosed);\n }\n\n private unbindListeners() {\n this.transport.unbind('message', this.onMessage);\n this.transport.unbind('closed', this.onClosed);\n }\n\n private finish(action: string, params: any) {\n this.callback(\n Collections.extend({ transport: this.transport, action: action }, params)\n );\n }\n}\n","import * as Collections from '../utils/collections';\nimport Util from '../util';\nimport base64encode from '../base64';\nimport Timeline from './timeline';\nimport Runtime from 'runtime';\n\nexport interface TimelineSenderOptions {\n host?: string;\n port?: number;\n path?: string;\n}\n\nexport default class TimelineSender {\n timeline: Timeline;\n options: TimelineSenderOptions;\n host: string;\n\n constructor(timeline: Timeline, options: TimelineSenderOptions) {\n this.timeline = timeline;\n this.options = options || {};\n }\n\n send(useTLS: boolean, callback?: Function) {\n if (this.timeline.isEmpty()) {\n return;\n }\n\n this.timeline.send(\n Runtime.TimelineTransport.getAgent(this, useTLS),\n callback\n );\n }\n}\n","/** Error classes used throughout the library. */\n// https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\nexport class BadEventName extends Error {\n constructor(msg?: string) {\n super(msg);\n\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class BadChannelName extends Error {\n constructor(msg?: string) {\n super(msg);\n\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class RequestTimedOut extends Error {\n constructor(msg?: string) {\n super(msg);\n\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\nexport class TransportPriorityTooLow extends Error {\n constructor(msg?: string) {\n super(msg);\n\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\nexport class TransportClosed extends Error {\n constructor(msg?: string) {\n super(msg);\n\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\nexport class UnsupportedFeature extends Error {\n constructor(msg?: string) {\n super(msg);\n\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\nexport class UnsupportedTransport extends Error {\n constructor(msg?: string) {\n super(msg);\n\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\nexport class UnsupportedStrategy extends Error {\n constructor(msg?: string) {\n super(msg);\n\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\nexport class HTTPAuthError extends Error {\n status: number;\n constructor(status: number, msg?: string) {\n super(msg);\n this.status = status;\n\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","/**\n * A place to store help URLs for error messages etc\n */\n\nconst urlStore = {\n baseUrl: 'https://pusher.com',\n urls: {\n authenticationEndpoint: {\n path: '/docs/channels/server_api/authenticating_users'\n },\n authorizationEndpoint: {\n path: '/docs/channels/server_api/authorizing-users/'\n },\n javascriptQuickStart: {\n path: '/docs/javascript_quick_start'\n },\n triggeringClientEvents: {\n path: '/docs/client_api_guide/client_events#trigger-events'\n },\n encryptedChannelSupport: {\n fullUrl:\n 'https://github.com/pusher/pusher-js/tree/cc491015371a4bde5743d1c87a0fbac0feb53195#encrypted-channel-support'\n }\n }\n};\n\n/** Builds a consistent string with links to pusher documentation\n *\n * @param {string} key - relevant key in the url_store.urls object\n * @return {string} suffix string to append to log message\n */\nconst buildLogSuffix = function(key: string): string {\n const urlPrefix = 'See:';\n const urlObj = urlStore.urls[key];\n if (!urlObj) return '';\n\n let url;\n if (urlObj.fullUrl) {\n url = urlObj.fullUrl;\n } else if (urlObj.path) {\n url = urlStore.baseUrl + urlObj.path;\n }\n\n if (!url) return '';\n return `${urlPrefix} ${url}`;\n};\n\nexport default { buildLogSuffix };\n","import { default as EventsDispatcher } from '../events/dispatcher';\nimport * as Errors from '../errors';\nimport Logger from '../logger';\nimport Pusher from '../pusher';\nimport { PusherEvent } from '../connection/protocol/message-types';\nimport Metadata from './metadata';\nimport UrlStore from '../utils/url_store';\nimport {\n ChannelAuthorizationData,\n ChannelAuthorizationCallback\n} from '../auth/options';\nimport { HTTPAuthError } from '../errors';\n\n/** Provides base public channel interface with an event emitter.\n *\n * Emits:\n * - pusher:subscription_succeeded - after subscribing successfully\n * - other non-internal events\n *\n * @param {String} name\n * @param {Pusher} pusher\n */\nexport default class Channel extends EventsDispatcher {\n name: string;\n pusher: Pusher;\n subscribed: boolean;\n subscriptionPending: boolean;\n subscriptionCancelled: boolean;\n subscriptionCount: null;\n\n constructor(name: string, pusher: Pusher) {\n super(function(event, data) {\n Logger.debug('No callbacks on ' + name + ' for ' + event);\n });\n\n this.name = name;\n this.pusher = pusher;\n this.subscribed = false;\n this.subscriptionPending = false;\n this.subscriptionCancelled = false;\n }\n\n /** Skips authorization, since public channels don't require it.\n *\n * @param {Function} callback\n */\n authorize(socketId: string, callback: ChannelAuthorizationCallback) {\n return callback(null, { auth: '' });\n }\n\n /** Triggers an event */\n trigger(event: string, data: any) {\n if (event.indexOf('client-') !== 0) {\n throw new Errors.BadEventName(\n \"Event '\" + event + \"' does not start with 'client-'\"\n );\n }\n if (!this.subscribed) {\n var suffix = UrlStore.buildLogSuffix('triggeringClientEvents');\n Logger.warn(\n `Client event triggered before channel 'subscription_succeeded' event . ${suffix}`\n );\n }\n return this.pusher.send_event(event, data, this.name);\n }\n\n /** Signals disconnection to the channel. For internal use only. */\n disconnect() {\n this.subscribed = false;\n this.subscriptionPending = false;\n }\n\n /** Handles a PusherEvent. For internal use only.\n *\n * @param {PusherEvent} event\n */\n handleEvent(event: PusherEvent) {\n var eventName = event.event;\n var data = event.data;\n if (eventName === 'pusher_internal:subscription_succeeded') {\n this.handleSubscriptionSucceededEvent(event);\n } else if (eventName === 'pusher_internal:subscription_count') {\n this.handleSubscriptionCountEvent(event);\n } else if (eventName.indexOf('pusher_internal:') !== 0) {\n var metadata: Metadata = {};\n this.emit(eventName, data, metadata);\n }\n }\n\n handleSubscriptionSucceededEvent(event: PusherEvent) {\n this.subscriptionPending = false;\n this.subscribed = true;\n if (this.subscriptionCancelled) {\n this.pusher.unsubscribe(this.name);\n } else {\n this.emit('pusher:subscription_succeeded', event.data);\n }\n }\n\n handleSubscriptionCountEvent(event: PusherEvent) {\n if (event.data.subscription_count) {\n this.subscriptionCount = event.data.subscription_count;\n }\n\n this.emit('pusher:subscription_count', event.data);\n }\n\n /** Sends a subscription request. For internal use only. */\n subscribe() {\n if (this.subscribed) {\n return;\n }\n this.subscriptionPending = true;\n this.subscriptionCancelled = false;\n this.authorize(\n this.pusher.connection.socket_id,\n (error: Error | null, data: ChannelAuthorizationData) => {\n if (error) {\n this.subscriptionPending = false;\n // Why not bind to 'pusher:subscription_error' a level up, and log there?\n // Binding to this event would cause the warning about no callbacks being\n // bound (see constructor) to be suppressed, that's not what we want.\n Logger.error(error.toString());\n this.emit(\n 'pusher:subscription_error',\n Object.assign(\n {},\n {\n type: 'AuthError',\n error: error.message\n },\n error instanceof HTTPAuthError ? { status: error.status } : {}\n )\n );\n } else {\n this.pusher.send_event('pusher:subscribe', {\n auth: data.auth,\n channel_data: data.channel_data,\n channel: this.name\n });\n }\n }\n );\n }\n\n /** Sends an unsubscription request. For internal use only. */\n unsubscribe() {\n this.subscribed = false;\n this.pusher.send_event('pusher:unsubscribe', {\n channel: this.name\n });\n }\n\n /** Cancels an in progress subscription. For internal use only. */\n cancelSubscription() {\n this.subscriptionCancelled = true;\n }\n\n /** Reinstates an in progress subscripiton. For internal use only. */\n reinstateSubscription() {\n this.subscriptionCancelled = false;\n }\n}\n","import Factory from '../utils/factory';\nimport Channel from './channel';\nimport { ChannelAuthorizationCallback } from '../auth/options';\n\n/** Extends public channels to provide private channel interface.\n *\n * @param {String} name\n * @param {Pusher} pusher\n */\nexport default class PrivateChannel extends Channel {\n /** Authorizes the connection to use the channel.\n *\n * @param {String} socketId\n * @param {Function} callback\n */\n authorize(socketId: string, callback: ChannelAuthorizationCallback) {\n return this.pusher.config.channelAuthorizer(\n {\n channelName: this.name,\n socketId: socketId\n },\n callback\n );\n }\n}\n","import * as Collections from '../utils/collections';\n\n/** Represents a collection of members of a presence channel. */\nexport default class Members {\n members: any;\n count: number;\n myID: any;\n me: any;\n\n constructor() {\n this.reset();\n }\n\n /** Returns member's info for given id.\n *\n * Resulting object containts two fields - id and info.\n *\n * @param {Number} id\n * @return {Object} member's info or null\n */\n get(id: string): any {\n if (Object.prototype.hasOwnProperty.call(this.members, id)) {\n return {\n id: id,\n info: this.members[id]\n };\n } else {\n return null;\n }\n }\n\n /** Calls back for each member in unspecified order.\n *\n * @param {Function} callback\n */\n each(callback: Function) {\n Collections.objectApply(this.members, (member, id) => {\n callback(this.get(id));\n });\n }\n\n /** Updates the id for connected member. For internal use only. */\n setMyID(id: string) {\n this.myID = id;\n }\n\n /** Handles subscription data. For internal use only. */\n onSubscription(subscriptionData: any) {\n this.members = subscriptionData.presence.hash;\n this.count = subscriptionData.presence.count;\n this.me = this.get(this.myID);\n }\n\n /** Adds a new member to the collection. For internal use only. */\n addMember(memberData: any) {\n if (this.get(memberData.user_id) === null) {\n this.count++;\n }\n this.members[memberData.user_id] = memberData.user_info;\n return this.get(memberData.user_id);\n }\n\n /** Adds a member from the collection. For internal use only. */\n removeMember(memberData: any) {\n var member = this.get(memberData.user_id);\n if (member) {\n delete this.members[memberData.user_id];\n this.count--;\n }\n return member;\n }\n\n /** Resets the collection to the initial state. For internal use only. */\n reset() {\n this.members = {};\n this.count = 0;\n this.myID = null;\n this.me = null;\n }\n}\n","import PrivateChannel from './private_channel';\nimport Logger from '../logger';\nimport Members from './members';\nimport Pusher from '../pusher';\nimport UrlStore from 'core/utils/url_store';\nimport { PusherEvent } from '../connection/protocol/message-types';\nimport Metadata from './metadata';\nimport { ChannelAuthorizationData } from '../auth/options';\n\nexport default class PresenceChannel extends PrivateChannel {\n members: Members;\n\n /** Adds presence channel functionality to private channels.\n *\n * @param {String} name\n * @param {Pusher} pusher\n */\n constructor(name: string, pusher: Pusher) {\n super(name, pusher);\n this.members = new Members();\n }\n\n /** Authorizes the connection as a member of the channel.\n *\n * @param {String} socketId\n * @param {Function} callback\n */\n authorize(socketId: string, callback: Function) {\n super.authorize(socketId, async (error, authData) => {\n if (!error) {\n authData = authData as ChannelAuthorizationData;\n if (authData.channel_data != null) {\n var channelData = JSON.parse(authData.channel_data);\n this.members.setMyID(channelData.user_id);\n } else {\n await this.pusher.user.signinDonePromise;\n if (this.pusher.user.user_data != null) {\n // If the user is signed in, get the id of the authenticated user\n // and allow the presence authorization to continue.\n this.members.setMyID(this.pusher.user.user_data.id);\n } else {\n let suffix = UrlStore.buildLogSuffix('authorizationEndpoint');\n Logger.error(\n `Invalid auth response for channel '${this.name}', ` +\n `expected 'channel_data' field. ${suffix}, ` +\n `or the user should be signed in.`\n );\n callback('Invalid auth response');\n return;\n }\n }\n }\n callback(error, authData);\n });\n }\n\n /** Handles presence and subscription events. For internal use only.\n *\n * @param {PusherEvent} event\n */\n handleEvent(event: PusherEvent) {\n var eventName = event.event;\n if (eventName.indexOf('pusher_internal:') === 0) {\n this.handleInternalEvent(event);\n } else {\n var data = event.data;\n var metadata: Metadata = {};\n if (event.user_id) {\n metadata.user_id = event.user_id;\n }\n this.emit(eventName, data, metadata);\n }\n }\n handleInternalEvent(event: PusherEvent) {\n var eventName = event.event;\n var data = event.data;\n switch (eventName) {\n case 'pusher_internal:subscription_succeeded':\n this.handleSubscriptionSucceededEvent(event);\n break;\n case 'pusher_internal:subscription_count':\n this.handleSubscriptionCountEvent(event);\n break;\n case 'pusher_internal:member_added':\n var addedMember = this.members.addMember(data);\n this.emit('pusher:member_added', addedMember);\n break;\n case 'pusher_internal:member_removed':\n var removedMember = this.members.removeMember(data);\n if (removedMember) {\n this.emit('pusher:member_removed', removedMember);\n }\n break;\n }\n }\n\n handleSubscriptionSucceededEvent(event: PusherEvent) {\n this.subscriptionPending = false;\n this.subscribed = true;\n if (this.subscriptionCancelled) {\n this.pusher.unsubscribe(this.name);\n } else {\n this.members.onSubscription(event.data);\n this.emit('pusher:subscription_succeeded', this.members);\n }\n }\n\n /** Resets the channel state, including members map. For internal use only. */\n disconnect() {\n this.members.reset();\n super.disconnect();\n }\n}\n","import PrivateChannel from './private_channel';\nimport * as Errors from '../errors';\nimport Logger from '../logger';\nimport Pusher from '../pusher';\nimport { decode as encodeUTF8 } from '@stablelib/utf8';\nimport { decode as decodeBase64 } from '@stablelib/base64';\nimport Dispatcher from '../events/dispatcher';\nimport { PusherEvent } from '../connection/protocol/message-types';\nimport {\n ChannelAuthorizationData,\n ChannelAuthorizationCallback\n} from '../auth/options';\nimport * as nacl from 'tweetnacl';\n\n/** Extends private channels to provide encrypted channel interface.\n *\n * @param {String} name\n * @param {Pusher} pusher\n */\nexport default class EncryptedChannel extends PrivateChannel {\n key: Uint8Array = null;\n nacl: nacl;\n\n constructor(name: string, pusher: Pusher, nacl: nacl) {\n super(name, pusher);\n this.nacl = nacl;\n }\n\n /** Authorizes the connection to use the channel.\n *\n * @param {String} socketId\n * @param {Function} callback\n */\n authorize(socketId: string, callback: ChannelAuthorizationCallback) {\n super.authorize(\n socketId,\n (error: Error | null, authData: ChannelAuthorizationData) => {\n if (error) {\n callback(error, authData);\n return;\n }\n let sharedSecret = authData['shared_secret'];\n if (!sharedSecret) {\n callback(\n new Error(\n `No shared_secret key in auth payload for encrypted channel: ${this.name}`\n ),\n null\n );\n return;\n }\n this.key = decodeBase64(sharedSecret);\n delete authData['shared_secret'];\n callback(null, authData);\n }\n );\n }\n\n trigger(event: string, data: any): boolean {\n throw new Errors.UnsupportedFeature(\n 'Client events are not currently supported for encrypted channels'\n );\n }\n\n /** Handles an event. For internal use only.\n *\n * @param {PusherEvent} event\n */\n handleEvent(event: PusherEvent) {\n var eventName = event.event;\n var data = event.data;\n if (\n eventName.indexOf('pusher_internal:') === 0 ||\n eventName.indexOf('pusher:') === 0\n ) {\n super.handleEvent(event);\n return;\n }\n this.handleEncryptedEvent(eventName, data);\n }\n\n private handleEncryptedEvent(event: string, data: any): void {\n if (!this.key) {\n Logger.debug(\n 'Received encrypted event before key has been retrieved from the authEndpoint'\n );\n return;\n }\n if (!data.ciphertext || !data.nonce) {\n Logger.error(\n 'Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: ' +\n data\n );\n return;\n }\n let cipherText = decodeBase64(data.ciphertext);\n if (cipherText.length < this.nacl.secretbox.overheadLength) {\n Logger.error(\n `Expected encrypted event ciphertext length to be ${this.nacl.secretbox.overheadLength}, got: ${cipherText.length}`\n );\n return;\n }\n let nonce = decodeBase64(data.nonce);\n if (nonce.length < this.nacl.secretbox.nonceLength) {\n Logger.error(\n `Expected encrypted event nonce length to be ${this.nacl.secretbox.nonceLength}, got: ${nonce.length}`\n );\n return;\n }\n\n let bytes = this.nacl.secretbox.open(cipherText, nonce, this.key);\n if (bytes === null) {\n Logger.debug(\n 'Failed to decrypt an event, probably because it was encrypted with a different key. Fetching a new key from the authEndpoint...'\n );\n // Try a single time to retrieve a new auth key and decrypt the event with it\n // If this fails, a new key will be requested when a new message is received\n this.authorize(this.pusher.connection.socket_id, (error, authData) => {\n if (error) {\n Logger.error(\n `Failed to make a request to the authEndpoint: ${authData}. Unable to fetch new key, so dropping encrypted event`\n );\n return;\n }\n bytes = this.nacl.secretbox.open(cipherText, nonce, this.key);\n if (bytes === null) {\n Logger.error(\n `Failed to decrypt event with new key. Dropping encrypted event`\n );\n return;\n }\n this.emit(event, this.getDataToEmit(bytes));\n return;\n });\n return;\n }\n this.emit(event, this.getDataToEmit(bytes));\n }\n\n // Try and parse the decrypted bytes as JSON. If we can't parse it, just\n // return the utf-8 string\n getDataToEmit(bytes: Uint8Array): string {\n let raw = encodeUTF8(bytes);\n try {\n return JSON.parse(raw);\n } catch {\n return raw;\n }\n }\n}\n","import { default as EventsDispatcher } from '../events/dispatcher';\nimport { OneOffTimer as Timer } from '../utils/timers';\nimport { Config } from '../config';\nimport Logger from '../logger';\nimport HandshakePayload from './handshake/handshake_payload';\nimport Connection from './connection';\nimport Strategy from '../strategies/strategy';\nimport StrategyRunner from '../strategies/strategy_runner';\nimport * as Collections from '../utils/collections';\nimport Timeline from '../timeline/timeline';\nimport ConnectionManagerOptions from './connection_manager_options';\nimport Runtime from 'runtime';\n\nimport {\n ErrorCallbacks,\n HandshakeCallbacks,\n ConnectionCallbacks\n} from './callbacks';\nimport Action from './protocol/action';\n\n/** Manages connection to Pusher.\n *\n * Uses a strategy (currently only default), timers and network availability\n * info to establish a connection and export its state. In case of failures,\n * manages reconnection attempts.\n *\n * Exports state changes as following events:\n * - \"state_change\", { previous: p, current: state }\n * - state\n *\n * States:\n * - initialized - initial state, never transitioned to\n * - connecting - connection is being established\n * - connected - connection has been fully established\n * - disconnected - on requested disconnection\n * - unavailable - after connection timeout or when there's no network\n * - failed - when the connection strategy is not supported\n *\n * Options:\n * - unavailableTimeout - time to transition to unavailable state\n * - activityTimeout - time after which ping message should be sent\n * - pongTimeout - time for Pusher to respond with pong before reconnecting\n *\n * @param {String} key application key\n * @param {Object} options\n */\nexport default class ConnectionManager extends EventsDispatcher {\n key: string;\n options: ConnectionManagerOptions;\n state: string;\n connection: Connection;\n usingTLS: boolean;\n timeline: Timeline;\n socket_id: string;\n unavailableTimer: Timer;\n activityTimer: Timer;\n retryTimer: Timer;\n activityTimeout: number;\n strategy: Strategy;\n runner: StrategyRunner;\n errorCallbacks: ErrorCallbacks;\n handshakeCallbacks: HandshakeCallbacks;\n connectionCallbacks: ConnectionCallbacks;\n\n constructor(key: string, options: ConnectionManagerOptions) {\n super();\n this.state = 'initialized';\n this.connection = null;\n\n this.key = key;\n this.options = options;\n this.timeline = this.options.timeline;\n this.usingTLS = this.options.useTLS;\n\n this.errorCallbacks = this.buildErrorCallbacks();\n this.connectionCallbacks = this.buildConnectionCallbacks(\n this.errorCallbacks\n );\n this.handshakeCallbacks = this.buildHandshakeCallbacks(this.errorCallbacks);\n\n var Network = Runtime.getNetwork();\n\n Network.bind('online', () => {\n this.timeline.info({ netinfo: 'online' });\n if (this.state === 'connecting' || this.state === 'unavailable') {\n this.retryIn(0);\n }\n });\n Network.bind('offline', () => {\n this.timeline.info({ netinfo: 'offline' });\n if (this.connection) {\n this.sendActivityCheck();\n }\n });\n\n this.updateStrategy();\n }\n\n /** Establishes a connection to Pusher.\n *\n * Does nothing when connection is already established. See top-level doc\n * to find events emitted on connection attempts.\n */\n connect() {\n if (this.connection || this.runner) {\n return;\n }\n if (!this.strategy.isSupported()) {\n this.updateState('failed');\n return;\n }\n this.updateState('connecting');\n this.startConnecting();\n this.setUnavailableTimer();\n }\n\n /** Sends raw data.\n *\n * @param {String} data\n */\n send(data) {\n if (this.connection) {\n return this.connection.send(data);\n } else {\n return false;\n }\n }\n\n /** Sends an event.\n *\n * @param {String} name\n * @param {String} data\n * @param {String} [channel]\n * @returns {Boolean} whether message was sent or not\n */\n send_event(name: string, data: any, channel?: string) {\n if (this.connection) {\n return this.connection.send_event(name, data, channel);\n } else {\n return false;\n }\n }\n\n /** Closes the connection. */\n disconnect() {\n this.disconnectInternally();\n this.updateState('disconnected');\n }\n\n isUsingTLS() {\n return this.usingTLS;\n }\n\n private startConnecting() {\n var callback = (error, handshake) => {\n if (error) {\n this.runner = this.strategy.connect(0, callback);\n } else {\n if (handshake.action === 'error') {\n this.emit('error', {\n type: 'HandshakeError',\n error: handshake.error\n });\n this.timeline.error({ handshakeError: handshake.error });\n } else {\n this.abortConnecting(); // we don't support switching connections yet\n this.handshakeCallbacks[handshake.action](handshake);\n }\n }\n };\n this.runner = this.strategy.connect(0, callback);\n }\n\n private abortConnecting() {\n if (this.runner) {\n this.runner.abort();\n this.runner = null;\n }\n }\n\n private disconnectInternally() {\n this.abortConnecting();\n this.clearRetryTimer();\n this.clearUnavailableTimer();\n if (this.connection) {\n var connection = this.abandonConnection();\n connection.close();\n }\n }\n\n private updateStrategy() {\n this.strategy = this.options.getStrategy({\n key: this.key,\n timeline: this.timeline,\n useTLS: this.usingTLS\n });\n }\n\n private retryIn(delay) {\n this.timeline.info({ action: 'retry', delay: delay });\n if (delay > 0) {\n this.emit('connecting_in', Math.round(delay / 1000));\n }\n this.retryTimer = new Timer(delay || 0, () => {\n this.disconnectInternally();\n this.connect();\n });\n }\n\n private clearRetryTimer() {\n if (this.retryTimer) {\n this.retryTimer.ensureAborted();\n this.retryTimer = null;\n }\n }\n\n private setUnavailableTimer() {\n this.unavailableTimer = new Timer(this.options.unavailableTimeout, () => {\n this.updateState('unavailable');\n });\n }\n\n private clearUnavailableTimer() {\n if (this.unavailableTimer) {\n this.unavailableTimer.ensureAborted();\n }\n }\n\n private sendActivityCheck() {\n this.stopActivityCheck();\n this.connection.ping();\n // wait for pong response\n this.activityTimer = new Timer(this.options.pongTimeout, () => {\n this.timeline.error({ pong_timed_out: this.options.pongTimeout });\n this.retryIn(0);\n });\n }\n\n private resetActivityCheck() {\n this.stopActivityCheck();\n // send ping after inactivity\n if (this.connection && !this.connection.handlesActivityChecks()) {\n this.activityTimer = new Timer(this.activityTimeout, () => {\n this.sendActivityCheck();\n });\n }\n }\n\n private stopActivityCheck() {\n if (this.activityTimer) {\n this.activityTimer.ensureAborted();\n }\n }\n\n private buildConnectionCallbacks(\n errorCallbacks: ErrorCallbacks\n ): ConnectionCallbacks {\n return Collections.extend({}, errorCallbacks, {\n message: message => {\n // includes pong messages from server\n this.resetActivityCheck();\n this.emit('message', message);\n },\n ping: () => {\n this.send_event('pusher:pong', {});\n },\n activity: () => {\n this.resetActivityCheck();\n },\n error: error => {\n // just emit error to user - socket will already be closed by browser\n this.emit('error', error);\n },\n closed: () => {\n this.abandonConnection();\n if (this.shouldRetry()) {\n this.retryIn(1000);\n }\n }\n });\n }\n\n private buildHandshakeCallbacks(\n errorCallbacks: ErrorCallbacks\n ): HandshakeCallbacks {\n return Collections.extend({}, errorCallbacks, {\n connected: (handshake: HandshakePayload) => {\n this.activityTimeout = Math.min(\n this.options.activityTimeout,\n handshake.activityTimeout,\n handshake.connection.activityTimeout || Infinity\n );\n this.clearUnavailableTimer();\n this.setConnection(handshake.connection);\n this.socket_id = this.connection.id;\n this.updateState('connected', { socket_id: this.socket_id });\n }\n });\n }\n\n private buildErrorCallbacks(): ErrorCallbacks {\n let withErrorEmitted = callback => {\n return (result: Action | HandshakePayload) => {\n if (result.error) {\n this.emit('error', { type: 'WebSocketError', error: result.error });\n }\n callback(result);\n };\n };\n\n return {\n tls_only: withErrorEmitted(() => {\n this.usingTLS = true;\n this.updateStrategy();\n this.retryIn(0);\n }),\n refused: withErrorEmitted(() => {\n this.disconnect();\n }),\n backoff: withErrorEmitted(() => {\n this.retryIn(1000);\n }),\n retry: withErrorEmitted(() => {\n this.retryIn(0);\n })\n };\n }\n\n private setConnection(connection) {\n this.connection = connection;\n for (var event in this.connectionCallbacks) {\n this.connection.bind(event, this.connectionCallbacks[event]);\n }\n this.resetActivityCheck();\n }\n\n private abandonConnection() {\n if (!this.connection) {\n return;\n }\n this.stopActivityCheck();\n for (var event in this.connectionCallbacks) {\n this.connection.unbind(event, this.connectionCallbacks[event]);\n }\n var connection = this.connection;\n this.connection = null;\n return connection;\n }\n\n private updateState(newState: string, data?: any) {\n var previousState = this.state;\n this.state = newState;\n if (previousState !== newState) {\n var newStateDescription = newState;\n if (newStateDescription === 'connected') {\n newStateDescription += ' with new socket ID ' + data.socket_id;\n }\n Logger.debug(\n 'State changed',\n previousState + ' -> ' + newStateDescription\n );\n this.timeline.info({ state: newState, params: data });\n this.emit('state_change', { previous: previousState, current: newState });\n this.emit(newState, data);\n }\n }\n\n private shouldRetry(): boolean {\n return this.state === 'connecting' || this.state === 'connected';\n }\n}\n","import Channel from './channel';\nimport * as Collections from '../utils/collections';\nimport ChannelTable from './channel_table';\nimport Factory from '../utils/factory';\nimport Pusher from '../pusher';\nimport Logger from '../logger';\nimport * as Errors from '../errors';\nimport urlStore from '../utils/url_store';\n\n/** Handles a channel map. */\nexport default class Channels {\n channels: ChannelTable;\n\n constructor() {\n this.channels = {};\n }\n\n /** Creates or retrieves an existing channel by its name.\n *\n * @param {String} name\n * @param {Pusher} pusher\n * @return {Channel}\n */\n add(name: string, pusher: Pusher) {\n if (!this.channels[name]) {\n this.channels[name] = createChannel(name, pusher);\n }\n return this.channels[name];\n }\n\n /** Returns a list of all channels\n *\n * @return {Array}\n */\n all(): Channel[] {\n return Collections.values(this.channels);\n }\n\n /** Finds a channel by its name.\n *\n * @param {String} name\n * @return {Channel} channel or null if it doesn't exist\n */\n find(name: string) {\n return this.channels[name];\n }\n\n /** Removes a channel from the map.\n *\n * @param {String} name\n */\n remove(name: string) {\n var channel = this.channels[name];\n delete this.channels[name];\n return channel;\n }\n\n /** Proxies disconnection signal to all channels. */\n disconnect() {\n Collections.objectApply(this.channels, function(channel) {\n channel.disconnect();\n });\n }\n}\n\nfunction createChannel(name: string, pusher: Pusher): Channel {\n if (name.indexOf('private-encrypted-') === 0) {\n if (pusher.config.nacl) {\n return Factory.createEncryptedChannel(name, pusher, pusher.config.nacl);\n }\n let errMsg =\n 'Tried to subscribe to a private-encrypted- channel but no nacl implementation available';\n let suffix = urlStore.buildLogSuffix('encryptedChannelSupport');\n throw new Errors.UnsupportedFeature(`${errMsg}. ${suffix}`);\n } else if (name.indexOf('private-') === 0) {\n return Factory.createPrivateChannel(name, pusher);\n } else if (name.indexOf('presence-') === 0) {\n return Factory.createPresenceChannel(name, pusher);\n } else if (name.indexOf('#') === 0) {\n throw new Errors.BadChannelName(\n 'Cannot create a channel with name \"' + name + '\".'\n );\n } else {\n return Factory.createChannel(name, pusher);\n }\n}\n","import AssistantToTheTransportManager from '../transports/assistant_to_the_transport_manager';\nimport PingDelayOptions from '../transports/ping_delay_options';\nimport Transport from '../transports/transport';\nimport TransportManager from '../transports/transport_manager';\nimport Handshake from '../connection/handshake';\nimport TransportConnection from '../transports/transport_connection';\nimport SocketHooks from '../http/socket_hooks';\nimport HTTPSocket from '../http/http_socket';\n\nimport Timeline from '../timeline/timeline';\nimport {\n default as TimelineSender,\n TimelineSenderOptions\n} from '../timeline/timeline_sender';\nimport PresenceChannel from '../channels/presence_channel';\nimport PrivateChannel from '../channels/private_channel';\nimport EncryptedChannel from '../channels/encrypted_channel';\nimport Channel from '../channels/channel';\nimport ConnectionManager from '../connection/connection_manager';\nimport ConnectionManagerOptions from '../connection/connection_manager_options';\nimport Ajax from '../http/ajax';\nimport Channels from '../channels/channels';\nimport Pusher from '../pusher';\nimport { Config } from '../config';\nimport * as nacl from 'tweetnacl';\n\nvar Factory = {\n createChannels(): Channels {\n return new Channels();\n },\n\n createConnectionManager(\n key: string,\n options: ConnectionManagerOptions\n ): ConnectionManager {\n return new ConnectionManager(key, options);\n },\n\n createChannel(name: string, pusher: Pusher): Channel {\n return new Channel(name, pusher);\n },\n\n createPrivateChannel(name: string, pusher: Pusher): PrivateChannel {\n return new PrivateChannel(name, pusher);\n },\n\n createPresenceChannel(name: string, pusher: Pusher): PresenceChannel {\n return new PresenceChannel(name, pusher);\n },\n\n createEncryptedChannel(\n name: string,\n pusher: Pusher,\n nacl: nacl\n ): EncryptedChannel {\n return new EncryptedChannel(name, pusher, nacl);\n },\n\n createTimelineSender(timeline: Timeline, options: TimelineSenderOptions) {\n return new TimelineSender(timeline, options);\n },\n\n createHandshake(\n transport: TransportConnection,\n callback: (HandshakePayload) => void\n ): Handshake {\n return new Handshake(transport, callback);\n },\n\n createAssistantToTheTransportManager(\n manager: TransportManager,\n transport: Transport,\n options: PingDelayOptions\n ): AssistantToTheTransportManager {\n return new AssistantToTheTransportManager(manager, transport, options);\n }\n};\n\nexport default Factory;\n","import AssistantToTheTransportManager from './assistant_to_the_transport_manager';\nimport Transport from './transport';\nimport PingDelayOptions from './ping_delay_options';\nimport Factory from '../utils/factory';\n\nexport interface TransportManagerOptions extends PingDelayOptions {\n lives?: number;\n}\n\n/** Keeps track of the number of lives left for a transport.\n *\n * In the beginning of a session, transports may be assigned a number of\n * lives. When an AssistantToTheTransportManager instance reports a transport\n * connection closed uncleanly, the transport loses a life. When the number\n * of lives drops to zero, the transport gets disabled by its manager.\n *\n * @param {Object} options\n */\nexport default class TransportManager {\n options: TransportManagerOptions;\n livesLeft: number;\n\n constructor(options: TransportManagerOptions) {\n this.options = options || {};\n this.livesLeft = this.options.lives || Infinity;\n }\n\n /** Creates a assistant for the transport.\n *\n * @param {Transport} transport\n * @returns {AssistantToTheTransportManager}\n */\n getAssistant(transport: Transport): AssistantToTheTransportManager {\n return Factory.createAssistantToTheTransportManager(this, transport, {\n minPingDelay: this.options.minPingDelay,\n maxPingDelay: this.options.maxPingDelay\n });\n }\n\n /** Returns whether the transport has any lives left.\n *\n * @returns {Boolean}\n */\n isAlive(): boolean {\n return this.livesLeft > 0;\n }\n\n /** Takes one life from the transport. */\n reportDeath() {\n this.livesLeft -= 1;\n }\n}\n","import * as Collections from '../utils/collections';\nimport Util from '../util';\nimport { OneOffTimer as Timer } from '../utils/timers';\nimport Strategy from './strategy';\nimport StrategyOptions from './strategy_options';\n\n/** Loops through strategies with optional timeouts.\n *\n * Options:\n * - loop - whether it should loop through the substrategy list\n * - timeout - initial timeout for a single substrategy\n * - timeoutLimit - maximum timeout\n *\n * @param {Strategy[]} strategies\n * @param {Object} options\n */\nexport default class SequentialStrategy implements Strategy {\n strategies: Strategy[];\n loop: boolean;\n failFast: boolean;\n timeout: number;\n timeoutLimit: number;\n\n constructor(strategies: Strategy[], options: StrategyOptions) {\n this.strategies = strategies;\n this.loop = Boolean(options.loop);\n this.failFast = Boolean(options.failFast);\n this.timeout = options.timeout;\n this.timeoutLimit = options.timeoutLimit;\n }\n\n isSupported(): boolean {\n return Collections.any(this.strategies, Util.method('isSupported'));\n }\n\n connect(minPriority: number, callback: Function) {\n var strategies = this.strategies;\n var current = 0;\n var timeout = this.timeout;\n var runner = null;\n\n var tryNextStrategy = (error, handshake) => {\n if (handshake) {\n callback(null, handshake);\n } else {\n current = current + 1;\n if (this.loop) {\n current = current % strategies.length;\n }\n\n if (current < strategies.length) {\n if (timeout) {\n timeout = timeout * 2;\n if (this.timeoutLimit) {\n timeout = Math.min(timeout, this.timeoutLimit);\n }\n }\n runner = this.tryStrategy(\n strategies[current],\n minPriority,\n { timeout, failFast: this.failFast },\n tryNextStrategy\n );\n } else {\n callback(true);\n }\n }\n };\n\n runner = this.tryStrategy(\n strategies[current],\n minPriority,\n { timeout: timeout, failFast: this.failFast },\n tryNextStrategy\n );\n\n return {\n abort: function() {\n runner.abort();\n },\n forceMinPriority: function(p) {\n minPriority = p;\n if (runner) {\n runner.forceMinPriority(p);\n }\n }\n };\n }\n\n private tryStrategy(\n strategy: Strategy,\n minPriority: number,\n options: StrategyOptions,\n callback: Function\n ) {\n var timer = null;\n var runner = null;\n\n if (options.timeout > 0) {\n timer = new Timer(options.timeout, function() {\n runner.abort();\n callback(true);\n });\n }\n\n runner = strategy.connect(minPriority, function(error, handshake) {\n if (error && timer && timer.isRunning() && !options.failFast) {\n // advance to the next strategy after the timeout\n return;\n }\n if (timer) {\n timer.ensureAborted();\n }\n callback(error, handshake);\n });\n\n return {\n abort: function() {\n if (timer) {\n timer.ensureAborted();\n }\n runner.abort();\n },\n forceMinPriority: function(p) {\n runner.forceMinPriority(p);\n }\n };\n }\n}\n","import * as Collections from '../utils/collections';\nimport Util from '../util';\nimport Strategy from './strategy';\n\n/** Launches all substrategies and emits prioritized connected transports.\n *\n * @param {Array} strategies\n */\nexport default class BestConnectedEverStrategy implements Strategy {\n strategies: Strategy[];\n\n constructor(strategies: Strategy[]) {\n this.strategies = strategies;\n }\n\n isSupported(): boolean {\n return Collections.any(this.strategies, Util.method('isSupported'));\n }\n\n connect(minPriority: number, callback: Function) {\n return connect(this.strategies, minPriority, function(i, runners) {\n return function(error, handshake) {\n runners[i].error = error;\n if (error) {\n if (allRunnersFailed(runners)) {\n callback(true);\n }\n return;\n }\n Collections.apply(runners, function(runner) {\n runner.forceMinPriority(handshake.transport.priority);\n });\n callback(null, handshake);\n };\n });\n }\n}\n\n/** Connects to all strategies in parallel.\n *\n * Callback builder should be a function that takes two arguments: index\n * and a list of runners. It should return another function that will be\n * passed to the substrategy with given index. Runners can be aborted using\n * abortRunner(s) functions from this class.\n *\n * @param {Array} strategies\n * @param {Function} callbackBuilder\n * @return {Object} strategy runner\n */\nfunction connect(\n strategies: Strategy[],\n minPriority: number,\n callbackBuilder: Function\n) {\n var runners = Collections.map(strategies, function(strategy, i, _, rs) {\n return strategy.connect(minPriority, callbackBuilder(i, rs));\n });\n return {\n abort: function() {\n Collections.apply(runners, abortRunner);\n },\n forceMinPriority: function(p) {\n Collections.apply(runners, function(runner) {\n runner.forceMinPriority(p);\n });\n }\n };\n}\n\nfunction allRunnersFailed(runners): boolean {\n return Collections.all(runners, function(runner) {\n return Boolean(runner.error);\n });\n}\n\nfunction abortRunner(runner) {\n if (!runner.error && !runner.aborted) {\n runner.abort();\n runner.aborted = true;\n }\n}\n","import Util from '../util';\nimport Runtime from 'runtime';\nimport Strategy from './strategy';\nimport SequentialStrategy from './sequential_strategy';\nimport StrategyOptions from './strategy_options';\nimport TransportStrategy from './transport_strategy';\nimport Timeline from '../timeline/timeline';\nimport * as Collections from '../utils/collections';\n\nexport interface TransportStrategyDictionary {\n [key: string]: TransportStrategy;\n}\n\n/** Caches last successful transport and uses it for following attempts.\n *\n * @param {Strategy} strategy\n * @param {Object} transports\n * @param {Object} options\n */\nexport default class CachedStrategy implements Strategy {\n strategy: Strategy;\n transports: TransportStrategyDictionary;\n ttl: number;\n usingTLS: boolean;\n timeline: Timeline;\n\n constructor(\n strategy: Strategy,\n transports: TransportStrategyDictionary,\n options: StrategyOptions\n ) {\n this.strategy = strategy;\n this.transports = transports;\n this.ttl = options.ttl || 1800 * 1000;\n this.usingTLS = options.useTLS;\n this.timeline = options.timeline;\n }\n\n isSupported(): boolean {\n return this.strategy.isSupported();\n }\n\n connect(minPriority: number, callback: Function) {\n var usingTLS = this.usingTLS;\n var info = fetchTransportCache(usingTLS);\n\n var strategies = [this.strategy];\n if (info && info.timestamp + this.ttl >= Util.now()) {\n var transport = this.transports[info.transport];\n if (transport) {\n this.timeline.info({\n cached: true,\n transport: info.transport,\n latency: info.latency\n });\n strategies.push(\n new SequentialStrategy([transport], {\n timeout: info.latency * 2 + 1000,\n failFast: true\n })\n );\n }\n }\n\n var startTimestamp = Util.now();\n var runner = strategies\n .pop()\n .connect(minPriority, function cb(error, handshake) {\n if (error) {\n flushTransportCache(usingTLS);\n if (strategies.length > 0) {\n startTimestamp = Util.now();\n runner = strategies.pop().connect(minPriority, cb);\n } else {\n callback(error);\n }\n } else {\n storeTransportCache(\n usingTLS,\n handshake.transport.name,\n Util.now() - startTimestamp\n );\n callback(null, handshake);\n }\n });\n\n return {\n abort: function() {\n runner.abort();\n },\n forceMinPriority: function(p) {\n minPriority = p;\n if (runner) {\n runner.forceMinPriority(p);\n }\n }\n };\n }\n}\n\nfunction getTransportCacheKey(usingTLS: boolean): string {\n return 'pusherTransport' + (usingTLS ? 'TLS' : 'NonTLS');\n}\n\nfunction fetchTransportCache(usingTLS: boolean): any {\n var storage = Runtime.getLocalStorage();\n if (storage) {\n try {\n var serializedCache = storage[getTransportCacheKey(usingTLS)];\n if (serializedCache) {\n return JSON.parse(serializedCache);\n }\n } catch (e) {\n flushTransportCache(usingTLS);\n }\n }\n return null;\n}\n\nfunction storeTransportCache(\n usingTLS: boolean,\n transport: TransportStrategy,\n latency: number\n) {\n var storage = Runtime.getLocalStorage();\n if (storage) {\n try {\n storage[getTransportCacheKey(usingTLS)] = Collections.safeJSONStringify({\n timestamp: Util.now(),\n transport: transport,\n latency: latency\n });\n } catch (e) {\n // catch over quota exceptions raised by localStorage\n }\n }\n}\n\nfunction flushTransportCache(usingTLS: boolean) {\n var storage = Runtime.getLocalStorage();\n if (storage) {\n try {\n delete storage[getTransportCacheKey(usingTLS)];\n } catch (e) {\n // catch exceptions raised by localStorage\n }\n }\n}\n","import { OneOffTimer as Timer } from '../utils/timers';\nimport Strategy from './strategy';\nimport StrategyOptions from './strategy_options';\n\n/** Runs substrategy after specified delay.\n *\n * Options:\n * - delay - time in miliseconds to delay the substrategy attempt\n *\n * @param {Strategy} strategy\n * @param {Object} options\n */\nexport default class DelayedStrategy implements Strategy {\n strategy: Strategy;\n options: { delay: number };\n\n constructor(strategy: Strategy, { delay: number }) {\n this.strategy = strategy;\n this.options = { delay: number };\n }\n\n isSupported(): boolean {\n return this.strategy.isSupported();\n }\n\n connect(minPriority: number, callback: Function) {\n var strategy = this.strategy;\n var runner;\n var timer = new Timer(this.options.delay, function() {\n runner = strategy.connect(minPriority, callback);\n });\n\n return {\n abort: function() {\n timer.ensureAborted();\n if (runner) {\n runner.abort();\n }\n },\n forceMinPriority: function(p) {\n minPriority = p;\n if (runner) {\n runner.forceMinPriority(p);\n }\n }\n };\n }\n}\n","import Strategy from './strategy';\nimport StrategyRunner from './strategy_runner';\n\n/** Proxies method calls to one of substrategies basing on the test function.\n *\n * @param {Function} test\n * @param {Strategy} trueBranch strategy used when test returns true\n * @param {Strategy} falseBranch strategy used when test returns false\n */\nexport default class IfStrategy implements Strategy {\n test: () => boolean;\n trueBranch: Strategy;\n falseBranch: Strategy;\n\n constructor(\n test: () => boolean,\n trueBranch: Strategy,\n falseBranch: Strategy\n ) {\n this.test = test;\n this.trueBranch = trueBranch;\n this.falseBranch = falseBranch;\n }\n\n isSupported(): boolean {\n var branch = this.test() ? this.trueBranch : this.falseBranch;\n return branch.isSupported();\n }\n\n connect(minPriority: number, callback: Function): StrategyRunner {\n var branch = this.test() ? this.trueBranch : this.falseBranch;\n return branch.connect(minPriority, callback);\n }\n}\n","import Strategy from './strategy';\nimport StrategyRunner from './strategy_runner';\n\n/** Launches the substrategy and terminates on the first open connection.\n *\n * @param {Strategy} strategy\n */\nexport default class FirstConnectedStrategy implements Strategy {\n strategy: Strategy;\n\n constructor(strategy: Strategy) {\n this.strategy = strategy;\n }\n\n isSupported(): boolean {\n return this.strategy.isSupported();\n }\n\n connect(minPriority: number, callback: Function): StrategyRunner {\n var runner = this.strategy.connect(minPriority, function(error, handshake) {\n if (handshake) {\n runner.abort();\n }\n callback(error, handshake);\n });\n return runner;\n }\n}\n","import * as Collections from 'core/utils/collections';\nimport TransportManager from 'core/transports/transport_manager';\nimport Strategy from 'core/strategies/strategy';\nimport SequentialStrategy from 'core/strategies/sequential_strategy';\nimport BestConnectedEverStrategy from 'core/strategies/best_connected_ever_strategy';\nimport CachedStrategy, {\n TransportStrategyDictionary\n} from 'core/strategies/cached_strategy';\nimport DelayedStrategy from 'core/strategies/delayed_strategy';\nimport IfStrategy from 'core/strategies/if_strategy';\nimport FirstConnectedStrategy from 'core/strategies/first_connected_strategy';\nimport { Config } from 'core/config';\nimport StrategyOptions from 'core/strategies/strategy_options';\n\nfunction testSupportsStrategy(strategy: Strategy) {\n return function() {\n return strategy.isSupported();\n };\n}\n\nvar getDefaultStrategy = function(\n config: Config,\n baseOptions: StrategyOptions,\n defineTransport: Function\n): Strategy {\n var definedTransports = {};\n\n function defineTransportStrategy(\n name: string,\n type: string,\n priority: number,\n options: StrategyOptions,\n manager?: TransportManager\n ) {\n var transport = defineTransport(\n config,\n name,\n type,\n priority,\n options,\n manager\n );\n\n definedTransports[name] = transport;\n\n return transport;\n }\n\n var ws_options: StrategyOptions = Object.assign({}, baseOptions, {\n hostNonTLS: config.wsHost + ':' + config.wsPort,\n hostTLS: config.wsHost + ':' + config.wssPort,\n httpPath: config.wsPath\n });\n var wss_options: StrategyOptions = Collections.extend({}, ws_options, {\n useTLS: true\n });\n var http_options: StrategyOptions = Object.assign({}, baseOptions, {\n hostNonTLS: config.httpHost + ':' + config.httpPort,\n hostTLS: config.httpHost + ':' + config.httpsPort,\n httpPath: config.httpPath\n });\n var timeouts = {\n loop: true,\n timeout: 15000,\n timeoutLimit: 60000\n };\n\n var ws_manager = new TransportManager({\n lives: 2,\n minPingDelay: 10000,\n maxPingDelay: config.activityTimeout\n });\n var streaming_manager = new TransportManager({\n lives: 2,\n minPingDelay: 10000,\n maxPingDelay: config.activityTimeout\n });\n\n var ws_transport = defineTransportStrategy(\n 'ws',\n 'ws',\n 3,\n ws_options,\n ws_manager\n );\n var wss_transport = defineTransportStrategy(\n 'wss',\n 'ws',\n 3,\n wss_options,\n ws_manager\n );\n var xhr_streaming_transport = defineTransportStrategy(\n 'xhr_streaming',\n 'xhr_streaming',\n 1,\n http_options,\n streaming_manager\n );\n var xhr_polling_transport = defineTransportStrategy(\n 'xhr_polling',\n 'xhr_polling',\n 1,\n http_options\n );\n\n var ws_loop = new SequentialStrategy([ws_transport], timeouts);\n var wss_loop = new SequentialStrategy([wss_transport], timeouts);\n var streaming_loop = new SequentialStrategy(\n [xhr_streaming_transport],\n timeouts\n );\n var polling_loop = new SequentialStrategy([xhr_polling_transport], timeouts);\n\n var http_loop = new SequentialStrategy(\n [\n new IfStrategy(\n testSupportsStrategy(streaming_loop),\n new BestConnectedEverStrategy([\n streaming_loop,\n new DelayedStrategy(polling_loop, { delay: 4000 })\n ]),\n polling_loop\n )\n ],\n timeouts\n );\n\n var wsStrategy;\n if (baseOptions.useTLS) {\n wsStrategy = new BestConnectedEverStrategy([\n ws_loop,\n new DelayedStrategy(http_loop, { delay: 2000 })\n ]);\n } else {\n wsStrategy = new BestConnectedEverStrategy([\n ws_loop,\n new DelayedStrategy(wss_loop, { delay: 2000 }),\n new DelayedStrategy(http_loop, { delay: 5000 })\n ]);\n }\n\n return new CachedStrategy(\n new FirstConnectedStrategy(\n new IfStrategy(testSupportsStrategy(ws_transport), wsStrategy, http_loop)\n ),\n definedTransports,\n {\n ttl: 1800000,\n timeline: baseOptions.timeline,\n useTLS: baseOptions.useTLS\n }\n );\n};\n\nexport default getDefaultStrategy;\n","enum State {\n CONNECTING = 0,\n OPEN = 1,\n CLOSED = 3\n}\n\nexport default State;\n","import Runtime from 'runtime';\nimport RequestHooks from './request_hooks';\nimport Ajax from './ajax';\nimport { default as EventsDispatcher } from '../events/dispatcher';\n\nconst MAX_BUFFER_LENGTH = 256 * 1024;\n\nexport default class HTTPRequest extends EventsDispatcher {\n hooks: RequestHooks;\n method: string;\n url: string;\n position: number;\n xhr: Ajax;\n unloader: Function;\n\n constructor(hooks: RequestHooks, method: string, url: string) {\n super();\n this.hooks = hooks;\n this.method = method;\n this.url = url;\n }\n\n start(payload?: any) {\n this.position = 0;\n this.xhr = this.hooks.getRequest(this);\n\n this.unloader = () => {\n this.close();\n };\n Runtime.addUnloadListener(this.unloader);\n\n this.xhr.open(this.method, this.url, true);\n\n if (this.xhr.setRequestHeader) {\n this.xhr.setRequestHeader('Content-Type', 'application/json'); // ReactNative doesn't set this header by default.\n }\n this.xhr.send(payload);\n }\n\n close() {\n if (this.unloader) {\n Runtime.removeUnloadListener(this.unloader);\n this.unloader = null;\n }\n if (this.xhr) {\n this.hooks.abortRequest(this.xhr);\n this.xhr = null;\n }\n }\n\n onChunk(status: number, data: any) {\n while (true) {\n var chunk = this.advanceBuffer(data);\n if (chunk) {\n this.emit('chunk', { status: status, data: chunk });\n } else {\n break;\n }\n }\n if (this.isBufferTooLong(data)) {\n this.emit('buffer_too_long');\n }\n }\n\n private advanceBuffer(buffer: any[]): any {\n var unreadData = buffer.slice(this.position);\n var endOfLinePosition = unreadData.indexOf('\\n');\n\n if (endOfLinePosition !== -1) {\n this.position += endOfLinePosition + 1;\n return unreadData.slice(0, endOfLinePosition);\n } else {\n // chunk is not finished yet, don't move the buffer pointer\n return null;\n }\n }\n\n private isBufferTooLong(buffer: any): boolean {\n return this.position === buffer.length && buffer.length > MAX_BUFFER_LENGTH;\n }\n}\n","import URLLocation from './url_location';\nimport State from './state';\nimport Socket from '../socket';\nimport SocketHooks from './socket_hooks';\nimport Util from '../util';\nimport Ajax from './ajax';\nimport HTTPRequest from './http_request';\nimport Runtime from 'runtime';\n\nvar autoIncrement = 1;\n\nclass HTTPSocket implements Socket {\n hooks: SocketHooks;\n session: string;\n location: URLLocation;\n readyState: State;\n stream: HTTPRequest;\n\n onopen: () => void;\n onerror: (error: any) => void;\n onclose: (closeEvent: any) => void;\n onmessage: (message: any) => void;\n onactivity: () => void;\n\n constructor(hooks: SocketHooks, url: string) {\n this.hooks = hooks;\n this.session = randomNumber(1000) + '/' + randomString(8);\n this.location = getLocation(url);\n this.readyState = State.CONNECTING;\n this.openStream();\n }\n\n send(payload: any) {\n return this.sendRaw(JSON.stringify([payload]));\n }\n\n ping() {\n this.hooks.sendHeartbeat(this);\n }\n\n close(code: any, reason: any) {\n this.onClose(code, reason, true);\n }\n\n /** For internal use only */\n sendRaw(payload: any): boolean {\n if (this.readyState === State.OPEN) {\n try {\n Runtime.createSocketRequest(\n 'POST',\n getUniqueURL(getSendURL(this.location, this.session))\n ).start(payload);\n return true;\n } catch (e) {\n return false;\n }\n } else {\n return false;\n }\n }\n\n /** For internal use only */\n reconnect() {\n this.closeStream();\n this.openStream();\n }\n\n /** For internal use only */\n onClose(code, reason, wasClean) {\n this.closeStream();\n this.readyState = State.CLOSED;\n if (this.onclose) {\n this.onclose({\n code: code,\n reason: reason,\n wasClean: wasClean\n });\n }\n }\n\n private onChunk(chunk) {\n if (chunk.status !== 200) {\n return;\n }\n if (this.readyState === State.OPEN) {\n this.onActivity();\n }\n\n var payload;\n var type = chunk.data.slice(0, 1);\n switch (type) {\n case 'o':\n payload = JSON.parse(chunk.data.slice(1) || '{}');\n this.onOpen(payload);\n break;\n case 'a':\n payload = JSON.parse(chunk.data.slice(1) || '[]');\n for (var i = 0; i < payload.length; i++) {\n this.onEvent(payload[i]);\n }\n break;\n case 'm':\n payload = JSON.parse(chunk.data.slice(1) || 'null');\n this.onEvent(payload);\n break;\n case 'h':\n this.hooks.onHeartbeat(this);\n break;\n case 'c':\n payload = JSON.parse(chunk.data.slice(1) || '[]');\n this.onClose(payload[0], payload[1], true);\n break;\n }\n }\n\n private onOpen(options) {\n if (this.readyState === State.CONNECTING) {\n if (options && options.hostname) {\n this.location.base = replaceHost(this.location.base, options.hostname);\n }\n this.readyState = State.OPEN;\n\n if (this.onopen) {\n this.onopen();\n }\n } else {\n this.onClose(1006, 'Server lost session', true);\n }\n }\n\n private onEvent(event) {\n if (this.readyState === State.OPEN && this.onmessage) {\n this.onmessage({ data: event });\n }\n }\n\n private onActivity() {\n if (this.onactivity) {\n this.onactivity();\n }\n }\n\n private onError(error) {\n if (this.onerror) {\n this.onerror(error);\n }\n }\n\n private openStream() {\n this.stream = Runtime.createSocketRequest(\n 'POST',\n getUniqueURL(this.hooks.getReceiveURL(this.location, this.session))\n );\n\n this.stream.bind('chunk', chunk => {\n this.onChunk(chunk);\n });\n this.stream.bind('finished', status => {\n this.hooks.onFinished(this, status);\n });\n this.stream.bind('buffer_too_long', () => {\n this.reconnect();\n });\n\n try {\n this.stream.start();\n } catch (error) {\n Util.defer(() => {\n this.onError(error);\n this.onClose(1006, 'Could not start streaming', false);\n });\n }\n }\n\n private closeStream() {\n if (this.stream) {\n this.stream.unbind_all();\n this.stream.close();\n this.stream = null;\n }\n }\n}\n\nfunction getLocation(url): URLLocation {\n var parts = /([^\\?]*)\\/*(\\??.*)/.exec(url);\n return {\n base: parts[1],\n queryString: parts[2]\n };\n}\n\nfunction getSendURL(url: URLLocation, session: string): string {\n return url.base + '/' + session + '/xhr_send';\n}\n\nfunction getUniqueURL(url: string): string {\n var separator = url.indexOf('?') === -1 ? '?' : '&';\n return url + separator + 't=' + +new Date() + '&n=' + autoIncrement++;\n}\n\nfunction replaceHost(url: string, hostname: string): string {\n var urlParts = /(https?:\\/\\/)([^\\/:]+)((\\/|:)?.*)/.exec(url);\n return urlParts[1] + hostname + urlParts[3];\n}\n\nfunction randomNumber(max: number): number {\n return Runtime.randomInt(max);\n}\n\nfunction randomString(length: number): string {\n var result = [];\n\n for (var i = 0; i < length; i++) {\n result.push(randomNumber(32).toString(32));\n }\n\n return result.join('');\n}\n\nexport default HTTPSocket;\n","enum TimelineLevel {\n ERROR = 3,\n INFO = 6,\n DEBUG = 7\n}\n\nexport default TimelineLevel;\n","import SocketHooks from './socket_hooks';\nimport HTTPSocket from './http_socket';\n\nvar hooks: SocketHooks = {\n getReceiveURL: function(url, session) {\n return url.base + '/' + session + '/xhr_streaming' + url.queryString;\n },\n onHeartbeat: function(socket) {\n socket.sendRaw('[]');\n },\n sendHeartbeat: function(socket) {\n socket.sendRaw('[]');\n },\n onFinished: function(socket, status) {\n socket.onClose(1006, 'Connection interrupted (' + status + ')', false);\n }\n};\n\nexport default hooks;\n","import SocketHooks from './socket_hooks';\nimport URLLocation from './url_location';\nimport HTTPSocket from './http_socket';\n\nvar hooks: SocketHooks = {\n getReceiveURL: function(url: URLLocation, session: string): string {\n return url.base + '/' + session + '/xhr' + url.queryString;\n },\n onHeartbeat: function() {\n // next HTTP request will reset server's activity timer\n },\n sendHeartbeat: function(socket) {\n socket.sendRaw('[]');\n },\n onFinished: function(socket, status) {\n if (status === 200) {\n socket.reconnect();\n } else {\n socket.onClose(1006, 'Connection interrupted (' + status + ')', false);\n }\n }\n};\n\nexport default hooks;\n","import HTTPRequest from 'core/http/http_request';\nimport RequestHooks from 'core/http/request_hooks';\nimport Ajax from 'core/http/ajax';\nimport Runtime from 'runtime';\n\nvar hooks: RequestHooks = {\n getRequest: function(socket: HTTPRequest): Ajax {\n var Constructor = Runtime.getXHRAPI();\n var xhr = new Constructor();\n xhr.onreadystatechange = xhr.onprogress = function() {\n switch (xhr.readyState) {\n case 3:\n if (xhr.responseText && xhr.responseText.length > 0) {\n socket.onChunk(xhr.status, xhr.responseText);\n }\n break;\n case 4:\n // this happens only on errors, never after calling close\n if (xhr.responseText && xhr.responseText.length > 0) {\n socket.onChunk(xhr.status, xhr.responseText);\n }\n socket.emit('finished', xhr.status);\n socket.close();\n break;\n }\n };\n return xhr;\n },\n abortRequest: function(xhr: Ajax) {\n xhr.onreadystatechange = null;\n xhr.abort();\n }\n};\n\nexport default hooks;\n","import * as Collections from 'core/utils/collections';\nimport Transports from 'isomorphic/transports/transports';\nimport TimelineSender from 'core/timeline/timeline_sender';\nimport Ajax from 'core/http/ajax';\nimport getDefaultStrategy from './default_strategy';\nimport TransportsTable from 'core/transports/transports_table';\nimport transportConnectionInitializer from './transports/transport_connection_initializer';\nimport HTTPFactory from './http/http';\n\nvar Isomorphic: any = {\n getDefaultStrategy,\n Transports: Transports,\n transportConnectionInitializer,\n HTTPFactory,\n\n setup(PusherClass): void {\n PusherClass.ready();\n },\n\n getLocalStorage(): any {\n return undefined;\n },\n\n getClientFeatures(): any[] {\n return Collections.keys(\n Collections.filterObject({ ws: Transports.ws }, function(t) {\n return t.isSupported({});\n })\n );\n },\n\n getProtocol(): string {\n return 'http:';\n },\n\n isXHRSupported(): boolean {\n return true;\n },\n\n createSocketRequest(method: string, url: string) {\n if (this.isXHRSupported()) {\n return this.HTTPFactory.createXHR(method, url);\n } else {\n throw 'Cross-origin HTTP requests are not supported';\n }\n },\n\n createXHR(): Ajax {\n var Constructor = this.getXHRAPI();\n return new Constructor();\n },\n\n createWebSocket(url: string): any {\n var Constructor = this.getWebSocketAPI();\n return new Constructor(url);\n },\n\n addUnloadListener(listener: any) {},\n removeUnloadListener(listener: any) {}\n};\n\nexport default Isomorphic;\n","/** Initializes the transport.\n *\n * Fetches resources if needed and then transitions to initialized.\n */\nexport default function() {\n var self = this;\n\n self.timeline.info(\n self.buildTimelineMessage({\n transport: self.name + (self.options.useTLS ? 's' : '')\n })\n );\n\n if (self.hooks.isInitialized()) {\n self.changeState('initialized');\n } else {\n self.onClose();\n }\n}\n","import HTTPRequest from 'core/http/http_request';\nimport HTTPSocket from 'core/http/http_socket';\nimport SocketHooks from 'core/http/socket_hooks';\nimport RequestHooks from 'core/http/request_hooks';\nimport streamingHooks from 'core/http/http_streaming_socket';\nimport pollingHooks from 'core/http/http_polling_socket';\nimport xhrHooks from './http_xhr_request';\nimport HTTPFactory from 'core/http/http_factory';\n\nvar HTTP: HTTPFactory = {\n createStreamingSocket(url: string): HTTPSocket {\n return this.createSocket(streamingHooks, url);\n },\n\n createPollingSocket(url: string): HTTPSocket {\n return this.createSocket(pollingHooks, url);\n },\n\n createSocket(hooks: SocketHooks, url: string): HTTPSocket {\n return new HTTPSocket(hooks, url);\n },\n\n createXHR(method: string, url: string): HTTPRequest {\n return this.createRequest(xhrHooks, method, url);\n },\n\n createRequest(hooks: RequestHooks, method: string, url: string): HTTPRequest {\n return new HTTPRequest(hooks, method, url);\n }\n};\n\nexport default HTTP;\n","import { default as EventsDispatcher } from 'core/events/dispatcher';\nimport Reachability from 'core/reachability';\n\nexport class NetInfo extends EventsDispatcher implements Reachability {\n isOnline(): boolean {\n return true;\n }\n}\n\nexport var Network = new NetInfo();\n","import AbstractRuntime from 'runtimes/interface';\nimport { AuthTransport } from 'core/auth/auth_transports';\nimport {\n AuthRequestType,\n AuthTransportCallback,\n InternalAuthOptions\n} from 'core/auth/options';\nimport { HTTPAuthError } from 'core/errors';\n\nvar fetchAuth: AuthTransport = function(\n context: AbstractRuntime,\n query: string,\n authOptions: InternalAuthOptions,\n authRequestType: AuthRequestType,\n callback: AuthTransportCallback\n) {\n var headers = new Headers();\n headers.set('Content-Type', 'application/x-www-form-urlencoded');\n\n for (var headerName in authOptions.headers) {\n headers.set(headerName, authOptions.headers[headerName]);\n }\n\n if (authOptions.headersProvider != null) {\n const dynamicHeaders = authOptions.headersProvider();\n for (var headerName in dynamicHeaders) {\n headers.set(headerName, dynamicHeaders[headerName]);\n }\n }\n\n var body = query;\n var request = new Request(authOptions.endpoint, {\n headers,\n body,\n credentials: 'same-origin',\n method: 'POST'\n });\n\n return fetch(request)\n .then(response => {\n let { status } = response;\n if (status === 200) {\n // manually parse the json so we can provide a more helpful error in\n // failure case\n return response.text();\n }\n throw new HTTPAuthError(\n 200,\n `Could not get ${authRequestType.toString()} info from your auth endpoint, status: ${status}`\n );\n })\n .then(data => {\n let parsedData;\n try {\n parsedData = JSON.parse(data);\n } catch (e) {\n throw new HTTPAuthError(\n 200,\n `JSON returned from ${authRequestType.toString()} endpoint was invalid, yet status code was 200. Data was: ${data}`\n );\n }\n callback(null, parsedData);\n })\n .catch(err => {\n callback(err, null);\n });\n};\n\nexport default fetchAuth;\n","import Isomorphic from 'isomorphic/runtime';\nimport Runtime from '../interface';\nimport { Network } from './net_info';\nimport fetchAuth from './auth/fetch_auth';\nimport { AuthTransports } from 'core/auth/auth_transports';\nimport fetchTimeline from './timeline/fetch_timeline';\n\n// Very verbose but until unavoidable until\n// TypeScript 2.1, when spread attributes will be\n// supported\nconst {\n getDefaultStrategy,\n Transports,\n setup,\n getProtocol,\n isXHRSupported,\n getLocalStorage,\n createXHR,\n createWebSocket,\n addUnloadListener,\n removeUnloadListener,\n transportConnectionInitializer,\n createSocketRequest,\n HTTPFactory\n} = Isomorphic;\n\nconst Worker: Runtime = {\n getDefaultStrategy,\n Transports,\n setup,\n getProtocol,\n isXHRSupported,\n getLocalStorage,\n createXHR,\n createWebSocket,\n addUnloadListener,\n removeUnloadListener,\n transportConnectionInitializer,\n createSocketRequest,\n HTTPFactory,\n\n TimelineTransport: fetchTimeline,\n\n getAuthorizers(): AuthTransports {\n return { ajax: fetchAuth };\n },\n\n getWebSocketAPI() {\n return WebSocket;\n },\n\n getXHRAPI() {\n return XMLHttpRequest;\n },\n\n getNetwork() {\n return Network;\n },\n\n randomInt(max: number): number {\n /**\n * Return values in the range of [0, 1[\n */\n const random = function() {\n const crypto = window.crypto || window['msCrypto'];\n const random = crypto.getRandomValues(new Uint32Array(1))[0];\n\n return random / 2 ** 32;\n };\n\n return Math.floor(random() * max);\n }\n};\n\nexport default Worker;\n","import Logger from 'core/logger';\nimport TimelineSender from 'core/timeline/timeline_sender';\nimport * as Collections from 'core/utils/collections';\nimport Util from 'core/util';\nimport Runtime from 'runtime';\nimport TimelineTransport from 'core/timeline/timeline_transport';\n\nvar getAgent = function(sender: TimelineSender, useTLS: boolean) {\n return function(data: any, callback: Function) {\n var scheme = 'http' + (useTLS ? 's' : '') + '://';\n var url =\n scheme + (sender.host || sender.options.host) + sender.options.path;\n var query = Collections.buildQueryString(data);\n url += '/' + 2 + '?' + query;\n\n fetch(url)\n .then(response => {\n if (response.status !== 200) {\n throw `received ${response.status} from stats.pusher.com`;\n }\n return response.json();\n })\n .then(({ host }) => {\n if (host) {\n sender.host = host;\n }\n })\n .catch(err => {\n Logger.debug('TimelineSender Error: ', err);\n });\n };\n};\n\nvar fetchTimeline = {\n name: 'xhr',\n getAgent\n};\n\nexport default fetchTimeline;\n","import * as Collections from '../utils/collections';\nimport Util from '../util';\nimport { default as Level } from './level';\n\nexport interface TimelineOptions {\n level?: Level;\n limit?: number;\n version?: string;\n cluster?: string;\n features?: string[];\n params?: any;\n}\n\nexport default class Timeline {\n key: string;\n session: number;\n events: any[];\n options: TimelineOptions;\n sent: number;\n uniqueID: number;\n\n constructor(key: string, session: number, options: TimelineOptions) {\n this.key = key;\n this.session = session;\n this.events = [];\n this.options = options || {};\n this.sent = 0;\n this.uniqueID = 0;\n }\n\n log(level, event) {\n if (level <= this.options.level) {\n this.events.push(\n Collections.extend({}, event, { timestamp: Util.now() })\n );\n if (this.options.limit && this.events.length > this.options.limit) {\n this.events.shift();\n }\n }\n }\n\n error(event) {\n this.log(Level.ERROR, event);\n }\n\n info(event) {\n this.log(Level.INFO, event);\n }\n\n debug(event) {\n this.log(Level.DEBUG, event);\n }\n\n isEmpty() {\n return this.events.length === 0;\n }\n\n send(sendfn, callback) {\n var data = Collections.extend(\n {\n session: this.session,\n bundle: this.sent + 1,\n key: this.key,\n lib: 'js',\n version: this.options.version,\n cluster: this.options.cluster,\n features: this.options.features,\n timeline: this.events\n },\n this.options.params\n );\n\n this.events = [];\n sendfn(data, (error, result) => {\n if (!error) {\n this.sent++;\n }\n if (callback) {\n callback(error, result);\n }\n });\n\n return true;\n }\n\n generateUniqueID(): number {\n this.uniqueID++;\n return this.uniqueID;\n }\n}\n","import Factory from '../utils/factory';\nimport Util from '../util';\nimport * as Errors from '../errors';\nimport * as Collections from '../utils/collections';\nimport Strategy from './strategy';\nimport Transport from '../transports/transport';\nimport StrategyOptions from './strategy_options';\nimport Handshake from '../connection/handshake';\n\n/** Provides a strategy interface for transports.\n *\n * @param {String} name\n * @param {Number} priority\n * @param {Class} transport\n * @param {Object} options\n */\nexport default class TransportStrategy implements Strategy {\n name: string;\n priority: number;\n transport: Transport;\n options: StrategyOptions;\n\n constructor(\n name: string,\n priority: number,\n transport: Transport,\n options: StrategyOptions\n ) {\n this.name = name;\n this.priority = priority;\n this.transport = transport;\n this.options = options || {};\n }\n\n /** Returns whether the transport is supported in the browser.\n *\n * @returns {Boolean}\n */\n isSupported(): boolean {\n return this.transport.isSupported({\n useTLS: this.options.useTLS\n });\n }\n\n /** Launches a connection attempt and returns a strategy runner.\n *\n * @param {Function} callback\n * @return {Object} strategy runner\n */\n connect(minPriority: number, callback: Function) {\n if (!this.isSupported()) {\n return failAttempt(new Errors.UnsupportedStrategy(), callback);\n } else if (this.priority < minPriority) {\n return failAttempt(new Errors.TransportPriorityTooLow(), callback);\n }\n\n var connected = false;\n var transport = this.transport.createConnection(\n this.name,\n this.priority,\n this.options.key,\n this.options\n );\n var handshake = null;\n\n var onInitialized = function() {\n transport.unbind('initialized', onInitialized);\n transport.connect();\n };\n var onOpen = function() {\n handshake = Factory.createHandshake(transport, function(result) {\n connected = true;\n unbindListeners();\n callback(null, result);\n });\n };\n var onError = function(error) {\n unbindListeners();\n callback(error);\n };\n var onClosed = function() {\n unbindListeners();\n var serializedTransport;\n\n // The reason for this try/catch block is that on React Native\n // the WebSocket object is circular. Therefore transport.socket will\n // throw errors upon stringification. Collections.safeJSONStringify\n // discards circular references when serializing.\n serializedTransport = Collections.safeJSONStringify(transport);\n callback(new Errors.TransportClosed(serializedTransport));\n };\n\n var unbindListeners = function() {\n transport.unbind('initialized', onInitialized);\n transport.unbind('open', onOpen);\n transport.unbind('error', onError);\n transport.unbind('closed', onClosed);\n };\n\n transport.bind('initialized', onInitialized);\n transport.bind('open', onOpen);\n transport.bind('error', onError);\n transport.bind('closed', onClosed);\n\n // connect will be called automatically after initialization\n transport.initialize();\n\n return {\n abort: () => {\n if (connected) {\n return;\n }\n unbindListeners();\n if (handshake) {\n handshake.close();\n } else {\n transport.close();\n }\n },\n forceMinPriority: p => {\n if (connected) {\n return;\n }\n if (this.priority < p) {\n if (handshake) {\n handshake.close();\n } else {\n transport.close();\n }\n }\n }\n };\n }\n}\n\nfunction failAttempt(error: Error, callback: Function) {\n Util.defer(function() {\n callback(error);\n });\n return {\n abort: function() {},\n forceMinPriority: function() {}\n };\n}\n","import * as Collections from '../utils/collections';\nimport Util from '../util';\nimport TransportManager from '../transports/transport_manager';\nimport * as Errors from '../errors';\nimport Strategy from './strategy';\nimport TransportStrategy from './transport_strategy';\nimport StrategyOptions from '../strategies/strategy_options';\nimport { Config } from '../config';\nimport Runtime from 'runtime';\n\nconst { Transports } = Runtime;\n\nexport var defineTransport = function(\n config: Config,\n name: string,\n type: string,\n priority: number,\n options: StrategyOptions,\n manager?: TransportManager\n): Strategy {\n var transportClass = Transports[type];\n if (!transportClass) {\n throw new Errors.UnsupportedTransport(type);\n }\n\n var enabled =\n (!config.enabledTransports ||\n Collections.arrayIndexOf(config.enabledTransports, name) !== -1) &&\n (!config.disabledTransports ||\n Collections.arrayIndexOf(config.disabledTransports, name) === -1);\n\n var transport;\n if (enabled) {\n options = Object.assign(\n { ignoreNullOrigin: config.ignoreNullOrigin },\n options\n );\n\n transport = new TransportStrategy(\n name,\n priority,\n manager ? manager.getAssistant(transportClass) : transportClass,\n options\n );\n } else {\n transport = UnsupportedStrategy;\n }\n\n return transport;\n};\n\nvar UnsupportedStrategy: Strategy = {\n isSupported: function() {\n return false;\n },\n connect: function(_, callback) {\n var deferred = Util.defer(function() {\n callback(new Errors.UnsupportedStrategy());\n });\n return {\n abort: function() {\n deferred.ensureAborted();\n },\n forceMinPriority: function() {}\n };\n }\n};\n","export enum AuthRequestType {\n UserAuthentication = 'user-authentication',\n ChannelAuthorization = 'channel-authorization'\n}\n\nexport interface ChannelAuthorizationData {\n auth: string;\n channel_data?: string;\n shared_secret?: string;\n}\n\nexport type ChannelAuthorizationCallback = (\n error: Error | null,\n authData: ChannelAuthorizationData | null\n) => void;\n\nexport interface ChannelAuthorizationRequestParams {\n socketId: string;\n channelName: string;\n}\n\nexport interface ChannelAuthorizationHandler {\n (\n params: ChannelAuthorizationRequestParams,\n callback: ChannelAuthorizationCallback\n ): void;\n}\n\nexport interface UserAuthenticationData {\n auth: string;\n user_data: string;\n}\n\nexport type UserAuthenticationCallback = (\n error: Error | null,\n authData: UserAuthenticationData | null\n) => void;\n\nexport interface UserAuthenticationRequestParams {\n socketId: string;\n}\n\nexport interface UserAuthenticationHandler {\n (\n params: UserAuthenticationRequestParams,\n callback: UserAuthenticationCallback\n ): void;\n}\n\nexport type AuthTransportCallback =\n | ChannelAuthorizationCallback\n | UserAuthenticationCallback;\n\nexport interface AuthOptionsT {\n transport: 'ajax' | 'jsonp';\n endpoint: string;\n params?: any;\n headers?: any;\n paramsProvider?: () => any;\n headersProvider?: () => any;\n customHandler?: AuthHandler;\n}\n\nexport declare type UserAuthenticationOptions = AuthOptionsT<\n UserAuthenticationHandler\n>;\nexport declare type ChannelAuthorizationOptions = AuthOptionsT<\n ChannelAuthorizationHandler\n>;\n\nexport interface InternalAuthOptions {\n transport: 'ajax' | 'jsonp';\n endpoint: string;\n params?: any;\n headers?: any;\n paramsProvider?: () => any;\n headersProvider?: () => any;\n}\n","import {\n UserAuthenticationCallback,\n InternalAuthOptions,\n UserAuthenticationHandler,\n UserAuthenticationRequestParams,\n AuthRequestType\n} from './options';\n\nimport Runtime from 'runtime';\n\nconst composeChannelQuery = (\n params: UserAuthenticationRequestParams,\n authOptions: InternalAuthOptions\n) => {\n var query = 'socket_id=' + encodeURIComponent(params.socketId);\n\n for (var key in authOptions.params) {\n query +=\n '&' +\n encodeURIComponent(key) +\n '=' +\n encodeURIComponent(authOptions.params[key]);\n }\n\n if (authOptions.paramsProvider != null) {\n let dynamicParams = authOptions.paramsProvider();\n for (var key in dynamicParams) {\n query +=\n '&' +\n encodeURIComponent(key) +\n '=' +\n encodeURIComponent(dynamicParams[key]);\n }\n }\n\n return query;\n};\n\nconst UserAuthenticator = (\n authOptions: InternalAuthOptions\n): UserAuthenticationHandler => {\n if (typeof Runtime.getAuthorizers()[authOptions.transport] === 'undefined') {\n throw `'${authOptions.transport}' is not a recognized auth transport`;\n }\n\n return (\n params: UserAuthenticationRequestParams,\n callback: UserAuthenticationCallback\n ) => {\n const query = composeChannelQuery(params, authOptions);\n\n Runtime.getAuthorizers()[authOptions.transport](\n Runtime,\n query,\n authOptions,\n AuthRequestType.UserAuthentication,\n callback\n );\n };\n};\n\nexport default UserAuthenticator;\n","import {\n AuthRequestType,\n InternalAuthOptions,\n ChannelAuthorizationHandler,\n ChannelAuthorizationRequestParams,\n ChannelAuthorizationCallback\n} from './options';\n\nimport Runtime from 'runtime';\n\nconst composeChannelQuery = (\n params: ChannelAuthorizationRequestParams,\n authOptions: InternalAuthOptions\n) => {\n var query = 'socket_id=' + encodeURIComponent(params.socketId);\n\n query += '&channel_name=' + encodeURIComponent(params.channelName);\n\n for (var key in authOptions.params) {\n query +=\n '&' +\n encodeURIComponent(key) +\n '=' +\n encodeURIComponent(authOptions.params[key]);\n }\n\n if (authOptions.paramsProvider != null) {\n let dynamicParams = authOptions.paramsProvider();\n for (var key in dynamicParams) {\n query +=\n '&' +\n encodeURIComponent(key) +\n '=' +\n encodeURIComponent(dynamicParams[key]);\n }\n }\n\n return query;\n};\n\nconst ChannelAuthorizer = (\n authOptions: InternalAuthOptions\n): ChannelAuthorizationHandler => {\n if (typeof Runtime.getAuthorizers()[authOptions.transport] === 'undefined') {\n throw `'${authOptions.transport}' is not a recognized auth transport`;\n }\n\n return (\n params: ChannelAuthorizationRequestParams,\n callback: ChannelAuthorizationCallback\n ) => {\n const query = composeChannelQuery(params, authOptions);\n\n Runtime.getAuthorizers()[authOptions.transport](\n Runtime,\n query,\n authOptions,\n AuthRequestType.ChannelAuthorization,\n callback\n );\n };\n};\n\nexport default ChannelAuthorizer;\n","import { Options } from './options';\nimport Defaults from './defaults';\nimport {\n ChannelAuthorizationHandler,\n UserAuthenticationHandler,\n ChannelAuthorizationOptions\n} from './auth/options';\nimport UserAuthenticator from './auth/user_authenticator';\nimport ChannelAuthorizer from './auth/channel_authorizer';\nimport { ChannelAuthorizerProxy } from './auth/deprecated_channel_authorizer';\nimport Runtime from 'runtime';\nimport * as nacl from 'tweetnacl';\n\nexport type AuthTransport = 'ajax' | 'jsonp';\nexport type Transport =\n | 'ws'\n | 'wss'\n | 'xhr_streaming'\n | 'xhr_polling'\n | 'sockjs';\n\nexport interface Config {\n // these are all 'required' config parameters, it's not necessary for the user\n // to set them, but they have configured defaults.\n activityTimeout: number;\n enableStats: boolean;\n httpHost: string;\n httpPath: string;\n httpPort: number;\n httpsPort: number;\n pongTimeout: number;\n statsHost: string;\n unavailableTimeout: number;\n useTLS: boolean;\n wsHost: string;\n wsPath: string;\n wsPort: number;\n wssPort: number;\n userAuthenticator: UserAuthenticationHandler;\n channelAuthorizer: ChannelAuthorizationHandler;\n\n // these are all optional parameters or overrrides. The customer can set these\n // but it's not strictly necessary\n forceTLS?: boolean;\n cluster?: string;\n disabledTransports?: Transport[];\n enabledTransports?: Transport[];\n ignoreNullOrigin?: boolean;\n nacl?: nacl;\n timelineParams?: any;\n}\n\n// getConfig mainly sets the defaults for the options that are not provided\nexport function getConfig(opts: Options, pusher): Config {\n let config: Config = {\n activityTimeout: opts.activityTimeout || Defaults.activityTimeout,\n cluster: opts.cluster,\n httpPath: opts.httpPath || Defaults.httpPath,\n httpPort: opts.httpPort || Defaults.httpPort,\n httpsPort: opts.httpsPort || Defaults.httpsPort,\n pongTimeout: opts.pongTimeout || Defaults.pongTimeout,\n statsHost: opts.statsHost || Defaults.stats_host,\n unavailableTimeout: opts.unavailableTimeout || Defaults.unavailableTimeout,\n wsPath: opts.wsPath || Defaults.wsPath,\n wsPort: opts.wsPort || Defaults.wsPort,\n wssPort: opts.wssPort || Defaults.wssPort,\n\n enableStats: getEnableStatsConfig(opts),\n httpHost: getHttpHost(opts),\n useTLS: shouldUseTLS(opts),\n wsHost: getWebsocketHost(opts),\n\n userAuthenticator: buildUserAuthenticator(opts),\n channelAuthorizer: buildChannelAuthorizer(opts, pusher)\n };\n\n if ('disabledTransports' in opts)\n config.disabledTransports = opts.disabledTransports;\n if ('enabledTransports' in opts)\n config.enabledTransports = opts.enabledTransports;\n if ('ignoreNullOrigin' in opts)\n config.ignoreNullOrigin = opts.ignoreNullOrigin;\n if ('timelineParams' in opts) config.timelineParams = opts.timelineParams;\n if ('nacl' in opts) {\n config.nacl = opts.nacl;\n }\n\n return config;\n}\n\nfunction getHttpHost(opts: Options): string {\n if (opts.httpHost) {\n return opts.httpHost;\n }\n if (opts.cluster) {\n return `sockjs-${opts.cluster}.pusher.com`;\n }\n return Defaults.httpHost;\n}\n\nfunction getWebsocketHost(opts: Options): string {\n if (opts.wsHost) {\n return opts.wsHost;\n }\n return getWebsocketHostFromCluster(opts.cluster);\n}\n\nfunction getWebsocketHostFromCluster(cluster: string): string {\n return `ws-${cluster}.pusher.com`;\n}\n\nfunction shouldUseTLS(opts: Options): boolean {\n if (Runtime.getProtocol() === 'https:') {\n return true;\n } else if (opts.forceTLS === false) {\n return false;\n }\n return true;\n}\n\n// if enableStats is set take the value\n// if disableStats is set take the inverse\n// otherwise default to false\nfunction getEnableStatsConfig(opts: Options): boolean {\n if ('enableStats' in opts) {\n return opts.enableStats;\n }\n if ('disableStats' in opts) {\n return !opts.disableStats;\n }\n return false;\n}\n\nfunction buildUserAuthenticator(opts: Options): UserAuthenticationHandler {\n const userAuthentication = {\n ...Defaults.userAuthentication,\n ...opts.userAuthentication\n };\n if (\n 'customHandler' in userAuthentication &&\n userAuthentication['customHandler'] != null\n ) {\n return userAuthentication['customHandler'];\n }\n\n return UserAuthenticator(userAuthentication);\n}\n\nfunction buildChannelAuth(opts: Options, pusher): ChannelAuthorizationOptions {\n let channelAuthorization: ChannelAuthorizationOptions;\n if ('channelAuthorization' in opts) {\n channelAuthorization = {\n ...Defaults.channelAuthorization,\n ...opts.channelAuthorization\n };\n } else {\n channelAuthorization = {\n transport: opts.authTransport || Defaults.authTransport,\n endpoint: opts.authEndpoint || Defaults.authEndpoint\n };\n if ('auth' in opts) {\n if ('params' in opts.auth) channelAuthorization.params = opts.auth.params;\n if ('headers' in opts.auth)\n channelAuthorization.headers = opts.auth.headers;\n }\n if ('authorizer' in opts)\n channelAuthorization.customHandler = ChannelAuthorizerProxy(\n pusher,\n channelAuthorization,\n opts.authorizer\n );\n }\n return channelAuthorization;\n}\n\nfunction buildChannelAuthorizer(\n opts: Options,\n pusher\n): ChannelAuthorizationHandler {\n const channelAuthorization = buildChannelAuth(opts, pusher);\n if (\n 'customHandler' in channelAuthorization &&\n channelAuthorization['customHandler'] != null\n ) {\n return channelAuthorization['customHandler'];\n }\n\n return ChannelAuthorizer(channelAuthorization);\n}\n","import Channel from '../channels/channel';\nimport {\n ChannelAuthorizationCallback,\n ChannelAuthorizationHandler,\n ChannelAuthorizationRequestParams,\n InternalAuthOptions\n} from './options';\n\nexport interface DeprecatedChannelAuthorizer {\n authorize(socketId: string, callback: ChannelAuthorizationCallback): void;\n}\n\nexport interface ChannelAuthorizerGenerator {\n (\n channel: Channel,\n options: DeprecatedAuthorizerOptions\n ): DeprecatedChannelAuthorizer;\n}\n\nexport interface DeprecatedAuthOptions {\n params?: any;\n headers?: any;\n}\n\nexport interface DeprecatedAuthorizerOptions {\n authTransport: 'ajax' | 'jsonp';\n authEndpoint: string;\n auth?: DeprecatedAuthOptions;\n}\n\nexport const ChannelAuthorizerProxy = (\n pusher,\n authOptions: InternalAuthOptions,\n channelAuthorizerGenerator: ChannelAuthorizerGenerator\n): ChannelAuthorizationHandler => {\n const deprecatedAuthorizerOptions: DeprecatedAuthorizerOptions = {\n authTransport: authOptions.transport,\n authEndpoint: authOptions.endpoint,\n auth: {\n params: authOptions.params,\n headers: authOptions.headers\n }\n };\n return (\n params: ChannelAuthorizationRequestParams,\n callback: ChannelAuthorizationCallback\n ) => {\n const channel = pusher.channel(params.channelName);\n // This line creates a new channel authorizer every time.\n // In the past, this was only done once per channel and reused.\n // We can do that again if we want to keep this behavior intact.\n const channelAuthorizer: DeprecatedChannelAuthorizer = channelAuthorizerGenerator(\n channel,\n deprecatedAuthorizerOptions\n );\n channelAuthorizer.authorize(params.socketId, callback);\n };\n};\n","import Logger from './logger';\nimport Pusher from './pusher';\nimport EventsDispatcher from './events/dispatcher';\n\nexport default class WatchlistFacade extends EventsDispatcher {\n private pusher: Pusher;\n\n public constructor(pusher: Pusher) {\n super(function(eventName, data) {\n Logger.debug(`No callbacks on watchlist events for ${eventName}`);\n });\n\n this.pusher = pusher;\n this.bindWatchlistInternalEvent();\n }\n\n handleEvent(pusherEvent) {\n pusherEvent.data.events.forEach(watchlistEvent => {\n this.emit(watchlistEvent.name, watchlistEvent);\n });\n }\n\n private bindWatchlistInternalEvent() {\n this.pusher.connection.bind('message', pusherEvent => {\n var eventName = pusherEvent.event;\n if (eventName === 'pusher_internal:watchlist_events') {\n this.handleEvent(pusherEvent);\n }\n });\n }\n}\n","function flatPromise() {\n let resolve, reject;\n const promise = new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve, reject };\n}\n\nexport default flatPromise;\n","import Pusher from './pusher';\nimport Logger from './logger';\nimport {\n UserAuthenticationData,\n UserAuthenticationCallback\n} from './auth/options';\nimport Channel from './channels/channel';\nimport WatchlistFacade from './watchlist';\nimport EventsDispatcher from './events/dispatcher';\nimport flatPromise from './utils/flat_promise';\n\nexport default class UserFacade extends EventsDispatcher {\n pusher: Pusher;\n signin_requested: boolean = false;\n user_data: any = null;\n serverToUserChannel: Channel = null;\n signinDonePromise: Promise = null;\n watchlist: WatchlistFacade;\n private _signinDoneResolve: Function = null;\n\n public constructor(pusher: Pusher) {\n super(function(eventName, data) {\n Logger.debug('No callbacks on user for ' + eventName);\n });\n this.pusher = pusher;\n this.pusher.connection.bind('state_change', ({ previous, current }) => {\n if (previous !== 'connected' && current === 'connected') {\n this._signin();\n }\n if (previous === 'connected' && current !== 'connected') {\n this._cleanup();\n this._newSigninPromiseIfNeeded();\n }\n });\n\n this.watchlist = new WatchlistFacade(pusher);\n\n this.pusher.connection.bind('message', event => {\n var eventName = event.event;\n if (eventName === 'pusher:signin_success') {\n this._onSigninSuccess(event.data);\n }\n if (\n this.serverToUserChannel &&\n this.serverToUserChannel.name === event.channel\n ) {\n this.serverToUserChannel.handleEvent(event);\n }\n });\n }\n\n public signin() {\n if (this.signin_requested) {\n return;\n }\n\n this.signin_requested = true;\n this._signin();\n }\n\n private _signin() {\n if (!this.signin_requested) {\n return;\n }\n\n this._newSigninPromiseIfNeeded();\n\n if (this.pusher.connection.state !== 'connected') {\n // Signin will be attempted when the connection is connected\n return;\n }\n\n this.pusher.config.userAuthenticator(\n {\n socketId: this.pusher.connection.socket_id\n },\n this._onAuthorize\n );\n }\n\n private _onAuthorize: UserAuthenticationCallback = (\n err,\n authData: UserAuthenticationData\n ) => {\n if (err) {\n Logger.warn(`Error during signin: ${err}`);\n this._cleanup();\n return;\n }\n\n this.pusher.send_event('pusher:signin', {\n auth: authData.auth,\n user_data: authData.user_data\n });\n\n // Later when we get pusher:singin_success event, the user will be marked as signed in\n };\n\n private _onSigninSuccess(data: any) {\n try {\n this.user_data = JSON.parse(data.user_data);\n } catch (e) {\n Logger.error(`Failed parsing user data after signin: ${data.user_data}`);\n this._cleanup();\n return;\n }\n\n if (typeof this.user_data.id !== 'string' || this.user_data.id === '') {\n Logger.error(\n `user_data doesn't contain an id. user_data: ${this.user_data}`\n );\n this._cleanup();\n return;\n }\n\n // Signin succeeded\n this._signinDoneResolve();\n this._subscribeChannels();\n }\n\n private _subscribeChannels() {\n const ensure_subscribed = channel => {\n if (channel.subscriptionPending && channel.subscriptionCancelled) {\n channel.reinstateSubscription();\n } else if (\n !channel.subscriptionPending &&\n this.pusher.connection.state === 'connected'\n ) {\n channel.subscribe();\n }\n };\n\n this.serverToUserChannel = new Channel(\n `#server-to-user-${this.user_data.id}`,\n this.pusher\n );\n this.serverToUserChannel.bind_global((eventName, data) => {\n if (\n eventName.indexOf('pusher_internal:') === 0 ||\n eventName.indexOf('pusher:') === 0\n ) {\n // ignore internal events\n return;\n }\n this.emit(eventName, data);\n });\n ensure_subscribed(this.serverToUserChannel);\n }\n\n private _cleanup() {\n this.user_data = null;\n if (this.serverToUserChannel) {\n this.serverToUserChannel.unbind_all();\n this.serverToUserChannel.disconnect();\n this.serverToUserChannel = null;\n }\n\n if (this.signin_requested) {\n // If signin is in progress and cleanup is called,\n // Mark the current signin process as done.\n this._signinDoneResolve();\n }\n }\n\n private _newSigninPromiseIfNeeded() {\n if (!this.signin_requested) {\n return;\n }\n\n // If there is a promise and it is not resolved, return without creating a new one.\n if (this.signinDonePromise && !(this.signinDonePromise as any).done) {\n return;\n }\n\n // This promise is never rejected.\n // It gets resolved when the signin process is done whether it failed or succeeded\n const { promise, resolve, reject: _ } = flatPromise();\n (promise as any).done = false;\n const setDone = () => {\n (promise as any).done = true;\n };\n promise.then(setDone).catch(setDone);\n this.signinDonePromise = promise;\n this._signinDoneResolve = resolve;\n }\n}\n","import AbstractRuntime from '../runtimes/interface';\nimport Runtime from 'runtime';\nimport Util from './util';\nimport * as Collections from './utils/collections';\nimport Channels from './channels/channels';\nimport Channel from './channels/channel';\nimport { default as EventsDispatcher } from './events/dispatcher';\nimport Timeline from './timeline/timeline';\nimport TimelineSender from './timeline/timeline_sender';\nimport TimelineLevel from './timeline/level';\nimport { defineTransport } from './strategies/strategy_builder';\nimport ConnectionManager from './connection/connection_manager';\nimport ConnectionManagerOptions from './connection/connection_manager_options';\nimport { PeriodicTimer } from './utils/timers';\nimport Defaults from './defaults';\nimport * as DefaultConfig from './config';\nimport Logger from './logger';\nimport Factory from './utils/factory';\nimport UrlStore from 'core/utils/url_store';\nimport { Options, validateOptions } from './options';\nimport { Config, getConfig } from './config';\nimport StrategyOptions from './strategies/strategy_options';\nimport UserFacade from './user';\n\nexport default class Pusher {\n /* STATIC PROPERTIES */\n static instances: Pusher[] = [];\n static isReady: boolean = false;\n static logToConsole: boolean = false;\n\n // for jsonp\n static Runtime: AbstractRuntime = Runtime;\n static ScriptReceivers: any = (Runtime).ScriptReceivers;\n static DependenciesReceivers: any = (Runtime).DependenciesReceivers;\n static auth_callbacks: any = (Runtime).auth_callbacks;\n\n static ready() {\n Pusher.isReady = true;\n for (var i = 0, l = Pusher.instances.length; i < l; i++) {\n Pusher.instances[i].connect();\n }\n }\n\n static log: (message: any) => void;\n\n private static getClientFeatures(): string[] {\n return Collections.keys(\n Collections.filterObject({ ws: Runtime.Transports.ws }, function(t) {\n return t.isSupported({});\n })\n );\n }\n\n /* INSTANCE PROPERTIES */\n key: string;\n config: Config;\n channels: Channels;\n global_emitter: EventsDispatcher;\n sessionID: number;\n timeline: Timeline;\n timelineSender: TimelineSender;\n connection: ConnectionManager;\n timelineSenderTimer: PeriodicTimer;\n user: UserFacade;\n constructor(app_key: string, options: Options) {\n checkAppKey(app_key);\n validateOptions(options);\n this.key = app_key;\n this.config = getConfig(options, this);\n\n this.channels = Factory.createChannels();\n this.global_emitter = new EventsDispatcher();\n this.sessionID = Runtime.randomInt(1000000000);\n\n this.timeline = new Timeline(this.key, this.sessionID, {\n cluster: this.config.cluster,\n features: Pusher.getClientFeatures(),\n params: this.config.timelineParams || {},\n limit: 50,\n level: TimelineLevel.INFO,\n version: Defaults.VERSION\n });\n if (this.config.enableStats) {\n this.timelineSender = Factory.createTimelineSender(this.timeline, {\n host: this.config.statsHost,\n path: '/timeline/v2/' + Runtime.TimelineTransport.name\n });\n }\n\n var getStrategy = (options: StrategyOptions) => {\n return Runtime.getDefaultStrategy(this.config, options, defineTransport);\n };\n\n this.connection = Factory.createConnectionManager(this.key, {\n getStrategy: getStrategy,\n timeline: this.timeline,\n activityTimeout: this.config.activityTimeout,\n pongTimeout: this.config.pongTimeout,\n unavailableTimeout: this.config.unavailableTimeout,\n useTLS: Boolean(this.config.useTLS)\n });\n\n this.connection.bind('connected', () => {\n this.subscribeAll();\n if (this.timelineSender) {\n this.timelineSender.send(this.connection.isUsingTLS());\n }\n });\n\n this.connection.bind('message', event => {\n var eventName = event.event;\n var internal = eventName.indexOf('pusher_internal:') === 0;\n if (event.channel) {\n var channel = this.channel(event.channel);\n if (channel) {\n channel.handleEvent(event);\n }\n }\n // Emit globally [deprecated]\n if (!internal) {\n this.global_emitter.emit(event.event, event.data);\n }\n });\n this.connection.bind('connecting', () => {\n this.channels.disconnect();\n });\n this.connection.bind('disconnected', () => {\n this.channels.disconnect();\n });\n this.connection.bind('error', err => {\n Logger.warn(err);\n });\n\n Pusher.instances.push(this);\n this.timeline.info({ instances: Pusher.instances.length });\n\n this.user = new UserFacade(this);\n\n if (Pusher.isReady) {\n this.connect();\n }\n }\n\n channel(name: string): Channel {\n return this.channels.find(name);\n }\n\n allChannels(): Channel[] {\n return this.channels.all();\n }\n\n connect() {\n this.connection.connect();\n\n if (this.timelineSender) {\n if (!this.timelineSenderTimer) {\n var usingTLS = this.connection.isUsingTLS();\n var timelineSender = this.timelineSender;\n this.timelineSenderTimer = new PeriodicTimer(60000, function() {\n timelineSender.send(usingTLS);\n });\n }\n }\n }\n\n disconnect() {\n this.connection.disconnect();\n\n if (this.timelineSenderTimer) {\n this.timelineSenderTimer.ensureAborted();\n this.timelineSenderTimer = null;\n }\n }\n\n bind(event_name: string, callback: Function, context?: any): Pusher {\n this.global_emitter.bind(event_name, callback, context);\n return this;\n }\n\n unbind(event_name?: string, callback?: Function, context?: any): Pusher {\n this.global_emitter.unbind(event_name, callback, context);\n return this;\n }\n\n bind_global(callback: Function): Pusher {\n this.global_emitter.bind_global(callback);\n return this;\n }\n\n unbind_global(callback?: Function): Pusher {\n this.global_emitter.unbind_global(callback);\n return this;\n }\n\n unbind_all(callback?: Function): Pusher {\n this.global_emitter.unbind_all();\n return this;\n }\n\n subscribeAll() {\n var channelName;\n for (channelName in this.channels.channels) {\n if (this.channels.channels.hasOwnProperty(channelName)) {\n this.subscribe(channelName);\n }\n }\n }\n\n subscribe(channel_name: string) {\n var channel = this.channels.add(channel_name, this);\n if (channel.subscriptionPending && channel.subscriptionCancelled) {\n channel.reinstateSubscription();\n } else if (\n !channel.subscriptionPending &&\n this.connection.state === 'connected'\n ) {\n channel.subscribe();\n }\n return channel;\n }\n\n unsubscribe(channel_name: string) {\n var channel = this.channels.find(channel_name);\n if (channel && channel.subscriptionPending) {\n channel.cancelSubscription();\n } else {\n channel = this.channels.remove(channel_name);\n if (channel && channel.subscribed) {\n channel.unsubscribe();\n }\n }\n }\n\n send_event(event_name: string, data: any, channel?: string) {\n return this.connection.send_event(event_name, data, channel);\n }\n\n shouldUseTLS(): boolean {\n return this.config.useTLS;\n }\n\n signin() {\n this.user.signin();\n }\n}\n\nfunction checkAppKey(key) {\n if (key === null || key === undefined) {\n throw 'You must pass your app key when you instantiate Pusher.';\n }\n}\n\nRuntime.setup(Pusher);\n","import ConnectionManager from './connection/connection_manager';\nimport {\n ChannelAuthorizationOptions,\n UserAuthenticationOptions\n} from './auth/options';\nimport {\n ChannelAuthorizerGenerator,\n DeprecatedAuthOptions\n} from './auth/deprecated_channel_authorizer';\nimport { AuthTransport, Transport } from './config';\nimport * as nacl from 'tweetnacl';\nimport Logger from './logger';\n\nexport interface Options {\n activityTimeout?: number;\n\n auth?: DeprecatedAuthOptions; // DEPRECATED use channelAuthorization instead\n authEndpoint?: string; // DEPRECATED use channelAuthorization instead\n authTransport?: AuthTransport; // DEPRECATED use channelAuthorization instead\n authorizer?: ChannelAuthorizerGenerator; // DEPRECATED use channelAuthorization instead\n\n channelAuthorization?: ChannelAuthorizationOptions;\n userAuthentication?: UserAuthenticationOptions;\n\n cluster: string;\n enableStats?: boolean;\n disableStats?: boolean;\n disabledTransports?: Transport[];\n enabledTransports?: Transport[];\n forceTLS?: boolean;\n httpHost?: string;\n httpPath?: string;\n httpPort?: number;\n httpsPort?: number;\n ignoreNullOrigin?: boolean;\n nacl?: nacl;\n pongTimeout?: number;\n statsHost?: string;\n timelineParams?: any;\n unavailableTimeout?: number;\n wsHost?: string;\n wsPath?: string;\n wsPort?: number;\n wssPort?: number;\n}\n\nexport function validateOptions(options) {\n if (options == null) {\n throw 'You must pass an options object';\n }\n if (options.cluster == null) {\n throw 'Options object must provide a cluster';\n }\n if ('disableStats' in options) {\n Logger.warn(\n 'The disableStats option is deprecated in favor of enableStats'\n );\n }\n}\n"],"sourceRoot":""}