diff --git a/src/core/auth/auth_transports.ts b/src/core/auth/auth_transports.ts index 2c4b8a72f..926fa9e5d 100644 --- a/src/core/auth/auth_transports.ts +++ b/src/core/auth/auth_transports.ts @@ -7,7 +7,7 @@ interface AuthTransport { query: string, authOptions: InternalAuthOptions, authRequestType: AuthRequestType, - callback: Function + callback: Function, ): void; } diff --git a/src/core/auth/channel_authorizer.ts b/src/core/auth/channel_authorizer.ts index 659fb73c0..1881f58db 100644 --- a/src/core/auth/channel_authorizer.ts +++ b/src/core/auth/channel_authorizer.ts @@ -3,14 +3,14 @@ import { InternalAuthOptions, ChannelAuthorizationHandler, ChannelAuthorizationRequestParams, - ChannelAuthorizationCallback + ChannelAuthorizationCallback, } from './options'; import Runtime from 'runtime'; const composeChannelQuery = ( params: ChannelAuthorizationRequestParams, - authOptions: InternalAuthOptions + authOptions: InternalAuthOptions, ) => { var query = 'socket_id=' + encodeURIComponent(params.socketId); @@ -39,7 +39,7 @@ const composeChannelQuery = ( }; const ChannelAuthorizer = ( - authOptions: InternalAuthOptions + authOptions: InternalAuthOptions, ): ChannelAuthorizationHandler => { if (typeof Runtime.getAuthorizers()[authOptions.transport] === 'undefined') { throw `'${authOptions.transport}' is not a recognized auth transport`; @@ -47,7 +47,7 @@ const ChannelAuthorizer = ( return ( params: ChannelAuthorizationRequestParams, - callback: ChannelAuthorizationCallback + callback: ChannelAuthorizationCallback, ) => { const query = composeChannelQuery(params, authOptions); @@ -56,7 +56,7 @@ const ChannelAuthorizer = ( query, authOptions, AuthRequestType.ChannelAuthorization, - callback + callback, ); }; }; diff --git a/src/core/auth/deprecated_channel_authorizer.ts b/src/core/auth/deprecated_channel_authorizer.ts index 86f3c6ee6..3e33c6efb 100644 --- a/src/core/auth/deprecated_channel_authorizer.ts +++ b/src/core/auth/deprecated_channel_authorizer.ts @@ -3,7 +3,7 @@ import { ChannelAuthorizationCallback, ChannelAuthorizationHandler, ChannelAuthorizationRequestParams, - InternalAuthOptions + InternalAuthOptions, } from './options'; export interface DeprecatedChannelAuthorizer { @@ -13,7 +13,7 @@ export interface DeprecatedChannelAuthorizer { export interface ChannelAuthorizerGenerator { ( channel: Channel, - options: DeprecatedAuthorizerOptions + options: DeprecatedAuthorizerOptions, ): DeprecatedChannelAuthorizer; } @@ -31,28 +31,26 @@ export interface DeprecatedAuthorizerOptions { export const ChannelAuthorizerProxy = ( pusher, authOptions: InternalAuthOptions, - channelAuthorizerGenerator: ChannelAuthorizerGenerator + channelAuthorizerGenerator: ChannelAuthorizerGenerator, ): ChannelAuthorizationHandler => { const deprecatedAuthorizerOptions: DeprecatedAuthorizerOptions = { authTransport: authOptions.transport, authEndpoint: authOptions.endpoint, auth: { params: authOptions.params, - headers: authOptions.headers - } + headers: authOptions.headers, + }, }; return ( params: ChannelAuthorizationRequestParams, - callback: ChannelAuthorizationCallback + callback: ChannelAuthorizationCallback, ) => { const channel = pusher.channel(params.channelName); // This line creates a new channel authorizer every time. // In the past, this was only done once per channel and reused. // We can do that again if we want to keep this behavior intact. - const channelAuthorizer: DeprecatedChannelAuthorizer = channelAuthorizerGenerator( - channel, - deprecatedAuthorizerOptions - ); + const channelAuthorizer: DeprecatedChannelAuthorizer = + channelAuthorizerGenerator(channel, deprecatedAuthorizerOptions); channelAuthorizer.authorize(params.socketId, callback); }; }; diff --git a/src/core/auth/options.ts b/src/core/auth/options.ts index 26bf62c86..f322e4322 100644 --- a/src/core/auth/options.ts +++ b/src/core/auth/options.ts @@ -1,6 +1,6 @@ export enum AuthRequestType { UserAuthentication = 'user-authentication', - ChannelAuthorization = 'channel-authorization' + ChannelAuthorization = 'channel-authorization', } export interface ChannelAuthorizationData { @@ -11,7 +11,7 @@ export interface ChannelAuthorizationData { export type ChannelAuthorizationCallback = ( error: Error | null, - authData: ChannelAuthorizationData | null + authData: ChannelAuthorizationData | null, ) => void; export interface ChannelAuthorizationRequestParams { @@ -22,7 +22,7 @@ export interface ChannelAuthorizationRequestParams { export interface ChannelAuthorizationHandler { ( params: ChannelAuthorizationRequestParams, - callback: ChannelAuthorizationCallback + callback: ChannelAuthorizationCallback, ): void; } @@ -33,7 +33,7 @@ export interface UserAuthenticationData { export type UserAuthenticationCallback = ( error: Error | null, - authData: UserAuthenticationData | null + authData: UserAuthenticationData | null, ) => void; export interface UserAuthenticationRequestParams { @@ -43,7 +43,7 @@ export interface UserAuthenticationRequestParams { export interface UserAuthenticationHandler { ( params: UserAuthenticationRequestParams, - callback: UserAuthenticationCallback + callback: UserAuthenticationCallback, ): void; } @@ -61,12 +61,10 @@ export interface AuthOptionsT { customHandler?: AuthHandler; } -export declare type UserAuthenticationOptions = AuthOptionsT< - UserAuthenticationHandler ->; -export declare type ChannelAuthorizationOptions = AuthOptionsT< - ChannelAuthorizationHandler ->; +export declare type UserAuthenticationOptions = + AuthOptionsT; +export declare type ChannelAuthorizationOptions = + AuthOptionsT; export interface InternalAuthOptions { transport: 'ajax' | 'jsonp'; diff --git a/src/core/auth/user_authenticator.ts b/src/core/auth/user_authenticator.ts index f2d044231..c267c1cd5 100644 --- a/src/core/auth/user_authenticator.ts +++ b/src/core/auth/user_authenticator.ts @@ -3,14 +3,14 @@ import { InternalAuthOptions, UserAuthenticationHandler, UserAuthenticationRequestParams, - AuthRequestType + AuthRequestType, } from './options'; import Runtime from 'runtime'; const composeChannelQuery = ( params: UserAuthenticationRequestParams, - authOptions: InternalAuthOptions + authOptions: InternalAuthOptions, ) => { var query = 'socket_id=' + encodeURIComponent(params.socketId); @@ -37,7 +37,7 @@ const composeChannelQuery = ( }; const UserAuthenticator = ( - authOptions: InternalAuthOptions + authOptions: InternalAuthOptions, ): UserAuthenticationHandler => { if (typeof Runtime.getAuthorizers()[authOptions.transport] === 'undefined') { throw `'${authOptions.transport}' is not a recognized auth transport`; @@ -45,7 +45,7 @@ const UserAuthenticator = ( return ( params: UserAuthenticationRequestParams, - callback: UserAuthenticationCallback + callback: UserAuthenticationCallback, ) => { const query = composeChannelQuery(params, authOptions); @@ -54,7 +54,7 @@ const UserAuthenticator = ( query, authOptions, AuthRequestType.UserAuthentication, - callback + callback, ); }; }; diff --git a/src/core/base64.ts b/src/core/base64.ts index c42fab87c..7dca4e9e8 100644 --- a/src/core/base64.ts +++ b/src/core/base64.ts @@ -12,22 +12,22 @@ for (var i = 0, l = b64chars.length; i < l; i++) { b64tab[b64chars.charAt(i)] = i; } -var cb_utob = function(c) { +var cb_utob = function (c) { var cc = c.charCodeAt(0); return cc < 0x80 ? c : cc < 0x800 - ? fromCharCode(0xc0 | (cc >>> 6)) + fromCharCode(0x80 | (cc & 0x3f)) - : fromCharCode(0xe0 | ((cc >>> 12) & 0x0f)) + - fromCharCode(0x80 | ((cc >>> 6) & 0x3f)) + - fromCharCode(0x80 | (cc & 0x3f)); + ? fromCharCode(0xc0 | (cc >>> 6)) + fromCharCode(0x80 | (cc & 0x3f)) + : fromCharCode(0xe0 | ((cc >>> 12) & 0x0f)) + + fromCharCode(0x80 | ((cc >>> 6) & 0x3f)) + + fromCharCode(0x80 | (cc & 0x3f)); }; -var utob = function(u) { +var utob = function (u) { return u.replace(/[^\x00-\x7F]/g, cb_utob); }; -var cb_encode = function(ccc) { +var cb_encode = function (ccc) { var padlen = [0, 2, 1][ccc.length % 3]; var ord = (ccc.charCodeAt(0) << 16) | @@ -37,13 +37,13 @@ var cb_encode = function(ccc) { b64chars.charAt(ord >>> 18), b64chars.charAt((ord >>> 12) & 63), padlen >= 2 ? '=' : b64chars.charAt((ord >>> 6) & 63), - padlen >= 1 ? '=' : b64chars.charAt(ord & 63) + padlen >= 1 ? '=' : b64chars.charAt(ord & 63), ]; return chars.join(''); }; var btoa = global.btoa || - function(b) { + function (b) { return b.replace(/[\s\S]{1,3}/g, cb_encode); }; diff --git a/src/core/channels/channel.ts b/src/core/channels/channel.ts index 49587e99a..e69763a34 100644 --- a/src/core/channels/channel.ts +++ b/src/core/channels/channel.ts @@ -7,7 +7,7 @@ import Metadata from './metadata'; import UrlStore from '../utils/url_store'; import { ChannelAuthorizationData, - ChannelAuthorizationCallback + ChannelAuthorizationCallback, } from '../auth/options'; import { HTTPAuthError } from '../errors'; @@ -29,7 +29,7 @@ export default class Channel extends EventsDispatcher { subscriptionCount: null; constructor(name: string, pusher: Pusher) { - super(function(event, data) { + super(function (event, data) { Logger.debug('No callbacks on ' + name + ' for ' + event); }); @@ -52,13 +52,13 @@ export default class Channel extends EventsDispatcher { trigger(event: string, data: any) { if (event.indexOf('client-') !== 0) { throw new Errors.BadEventName( - "Event '" + event + "' does not start with 'client-'" + "Event '" + event + "' does not start with 'client-'", ); } if (!this.subscribed) { var suffix = UrlStore.buildLogSuffix('triggeringClientEvents'); Logger.warn( - `Client event triggered before channel 'subscription_succeeded' event . ${suffix}` + `Client event triggered before channel 'subscription_succeeded' event . ${suffix}`, ); } return this.pusher.send_event(event, data, this.name); @@ -127,19 +127,19 @@ export default class Channel extends EventsDispatcher { {}, { type: 'AuthError', - error: error.message + error: error.message, }, - error instanceof HTTPAuthError ? { status: error.status } : {} - ) + error instanceof HTTPAuthError ? { status: error.status } : {}, + ), ); } else { this.pusher.send_event('pusher:subscribe', { auth: data.auth, channel_data: data.channel_data, - channel: this.name + channel: this.name, }); } - } + }, ); } @@ -147,7 +147,7 @@ export default class Channel extends EventsDispatcher { unsubscribe() { this.subscribed = false; this.pusher.send_event('pusher:unsubscribe', { - channel: this.name + channel: this.name, }); } diff --git a/src/core/channels/channels.ts b/src/core/channels/channels.ts index 381e72fc2..bc53b14e1 100644 --- a/src/core/channels/channels.ts +++ b/src/core/channels/channels.ts @@ -57,7 +57,7 @@ export default class Channels { /** Proxies disconnection signal to all channels. */ disconnect() { - Collections.objectApply(this.channels, function(channel) { + Collections.objectApply(this.channels, function (channel) { channel.disconnect(); }); } @@ -78,7 +78,7 @@ function createChannel(name: string, pusher: Pusher): Channel { return Factory.createPresenceChannel(name, pusher); } else if (name.indexOf('#') === 0) { throw new Errors.BadChannelName( - 'Cannot create a channel with name "' + name + '".' + 'Cannot create a channel with name "' + name + '".', ); } else { return Factory.createChannel(name, pusher); diff --git a/src/core/channels/encrypted_channel.ts b/src/core/channels/encrypted_channel.ts index 5f204dcc8..c171e0952 100644 --- a/src/core/channels/encrypted_channel.ts +++ b/src/core/channels/encrypted_channel.ts @@ -8,7 +8,7 @@ import Dispatcher from '../events/dispatcher'; import { PusherEvent } from '../connection/protocol/message-types'; import { ChannelAuthorizationData, - ChannelAuthorizationCallback + ChannelAuthorizationCallback, } from '../auth/options'; import * as nacl from 'tweetnacl'; @@ -43,22 +43,22 @@ export default class EncryptedChannel extends PrivateChannel { if (!sharedSecret) { callback( new Error( - `No shared_secret key in auth payload for encrypted channel: ${this.name}` + `No shared_secret key in auth payload for encrypted channel: ${this.name}`, ), - null + null, ); return; } this.key = decodeBase64(sharedSecret); delete authData['shared_secret']; callback(null, authData); - } + }, ); } trigger(event: string, data: any): boolean { throw new Errors.UnsupportedFeature( - 'Client events are not currently supported for encrypted channels' + 'Client events are not currently supported for encrypted channels', ); } @@ -82,28 +82,28 @@ export default class EncryptedChannel extends PrivateChannel { private handleEncryptedEvent(event: string, data: any): void { if (!this.key) { Logger.debug( - 'Received encrypted event before key has been retrieved from the authEndpoint' + 'Received encrypted event before key has been retrieved from the authEndpoint', ); return; } if (!data.ciphertext || !data.nonce) { Logger.error( 'Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: ' + - data + data, ); return; } let cipherText = decodeBase64(data.ciphertext); if (cipherText.length < this.nacl.secretbox.overheadLength) { Logger.error( - `Expected encrypted event ciphertext length to be ${this.nacl.secretbox.overheadLength}, got: ${cipherText.length}` + `Expected encrypted event ciphertext length to be ${this.nacl.secretbox.overheadLength}, got: ${cipherText.length}`, ); return; } let nonce = decodeBase64(data.nonce); if (nonce.length < this.nacl.secretbox.nonceLength) { Logger.error( - `Expected encrypted event nonce length to be ${this.nacl.secretbox.nonceLength}, got: ${nonce.length}` + `Expected encrypted event nonce length to be ${this.nacl.secretbox.nonceLength}, got: ${nonce.length}`, ); return; } @@ -111,21 +111,21 @@ export default class EncryptedChannel extends PrivateChannel { let bytes = this.nacl.secretbox.open(cipherText, nonce, this.key); if (bytes === null) { Logger.debug( - 'Failed to decrypt an event, probably because it was encrypted with a different key. Fetching a new key from the authEndpoint...' + 'Failed to decrypt an event, probably because it was encrypted with a different key. Fetching a new key from the authEndpoint...', ); // Try a single time to retrieve a new auth key and decrypt the event with it // If this fails, a new key will be requested when a new message is received this.authorize(this.pusher.connection.socket_id, (error, authData) => { if (error) { Logger.error( - `Failed to make a request to the authEndpoint: ${authData}. Unable to fetch new key, so dropping encrypted event` + `Failed to make a request to the authEndpoint: ${authData}. Unable to fetch new key, so dropping encrypted event`, ); return; } bytes = this.nacl.secretbox.open(cipherText, nonce, this.key); if (bytes === null) { Logger.error( - `Failed to decrypt event with new key. Dropping encrypted event` + `Failed to decrypt event with new key. Dropping encrypted event`, ); return; } diff --git a/src/core/channels/members.ts b/src/core/channels/members.ts index f7b08d233..6adc099db 100644 --- a/src/core/channels/members.ts +++ b/src/core/channels/members.ts @@ -22,7 +22,7 @@ export default class Members { if (Object.prototype.hasOwnProperty.call(this.members, id)) { return { id: id, - info: this.members[id] + info: this.members[id], }; } else { return null; diff --git a/src/core/channels/presence_channel.ts b/src/core/channels/presence_channel.ts index 9352cce53..718575615 100644 --- a/src/core/channels/presence_channel.ts +++ b/src/core/channels/presence_channel.ts @@ -43,7 +43,7 @@ export default class PresenceChannel extends PrivateChannel { Logger.error( `Invalid auth response for channel '${this.name}', ` + `expected 'channel_data' field. ${suffix}, ` + - `or the user should be signed in.` + `or the user should be signed in.`, ); callback('Invalid auth response'); return; diff --git a/src/core/channels/private_channel.ts b/src/core/channels/private_channel.ts index 2a79a1b97..14f01eb4b 100644 --- a/src/core/channels/private_channel.ts +++ b/src/core/channels/private_channel.ts @@ -17,9 +17,9 @@ export default class PrivateChannel extends Channel { return this.pusher.config.channelAuthorizer( { channelName: this.name, - socketId: socketId + socketId: socketId, }, - callback + callback, ); } } diff --git a/src/core/config.ts b/src/core/config.ts index e5860f3c9..d9022f7cb 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -3,7 +3,7 @@ import Defaults from './defaults'; import { ChannelAuthorizationHandler, UserAuthenticationHandler, - ChannelAuthorizationOptions + ChannelAuthorizationOptions, } from './auth/options'; import UserAuthenticator from './auth/user_authenticator'; import ChannelAuthorizer from './auth/channel_authorizer'; @@ -71,7 +71,7 @@ export function getConfig(opts: Options, pusher): Config { wsHost: getWebsocketHost(opts), userAuthenticator: buildUserAuthenticator(opts), - channelAuthorizer: buildChannelAuthorizer(opts, pusher) + channelAuthorizer: buildChannelAuthorizer(opts, pusher), }; if ('disabledTransports' in opts) @@ -134,7 +134,7 @@ function getEnableStatsConfig(opts: Options): boolean { function buildUserAuthenticator(opts: Options): UserAuthenticationHandler { const userAuthentication = { ...Defaults.userAuthentication, - ...opts.userAuthentication + ...opts.userAuthentication, }; if ( 'customHandler' in userAuthentication && @@ -151,12 +151,12 @@ function buildChannelAuth(opts: Options, pusher): ChannelAuthorizationOptions { if ('channelAuthorization' in opts) { channelAuthorization = { ...Defaults.channelAuthorization, - ...opts.channelAuthorization + ...opts.channelAuthorization, }; } else { channelAuthorization = { transport: opts.authTransport || Defaults.authTransport, - endpoint: opts.authEndpoint || Defaults.authEndpoint + endpoint: opts.authEndpoint || Defaults.authEndpoint, }; if ('auth' in opts) { if ('params' in opts.auth) channelAuthorization.params = opts.auth.params; @@ -167,7 +167,7 @@ function buildChannelAuth(opts: Options, pusher): ChannelAuthorizationOptions { channelAuthorization.customHandler = ChannelAuthorizerProxy( pusher, channelAuthorization, - opts.authorizer + opts.authorizer, ); } return channelAuthorization; @@ -175,7 +175,7 @@ function buildChannelAuth(opts: Options, pusher): ChannelAuthorizationOptions { function buildChannelAuthorizer( opts: Options, - pusher + pusher, ): ChannelAuthorizationHandler { const channelAuthorization = buildChannelAuth(opts, pusher); if ( diff --git a/src/core/connection/connection.ts b/src/core/connection/connection.ts index b96489f33..810c31781 100644 --- a/src/core/connection/connection.ts +++ b/src/core/connection/connection.ts @@ -94,7 +94,7 @@ export default class Connection extends EventsDispatcher implements Socket { this.emit('error', { type: 'MessageParseError', error: e, - data: messageEvent.data + data: messageEvent.data, }); } @@ -105,7 +105,7 @@ export default class Connection extends EventsDispatcher implements Socket { case 'pusher:error': this.emit('error', { type: 'PusherError', - data: pusherEvent.data + data: pusherEvent.data, }); break; case 'pusher:ping': @@ -121,10 +121,10 @@ export default class Connection extends EventsDispatcher implements Socket { activity: () => { this.emit('activity'); }, - error: error => { + error: (error) => { this.emit('error', error); }, - closed: closeEvent => { + closed: (closeEvent) => { unbindListeners(); if (closeEvent && closeEvent.code) { @@ -133,7 +133,7 @@ export default class Connection extends EventsDispatcher implements Socket { this.transport = null; this.emit('closed'); - } + }, }; var unbindListeners = () => { diff --git a/src/core/connection/connection_manager.ts b/src/core/connection/connection_manager.ts index f913da446..1d5cc1a7f 100644 --- a/src/core/connection/connection_manager.ts +++ b/src/core/connection/connection_manager.ts @@ -14,7 +14,7 @@ import Runtime from 'runtime'; import { ErrorCallbacks, HandshakeCallbacks, - ConnectionCallbacks + ConnectionCallbacks, } from './callbacks'; import Action from './protocol/action'; @@ -74,7 +74,7 @@ export default class ConnectionManager extends EventsDispatcher { this.errorCallbacks = this.buildErrorCallbacks(); this.connectionCallbacks = this.buildConnectionCallbacks( - this.errorCallbacks + this.errorCallbacks, ); this.handshakeCallbacks = this.buildHandshakeCallbacks(this.errorCallbacks); @@ -159,7 +159,7 @@ export default class ConnectionManager extends EventsDispatcher { if (handshake.action === 'error') { this.emit('error', { type: 'HandshakeError', - error: handshake.error + error: handshake.error, }); this.timeline.error({ handshakeError: handshake.error }); } else { @@ -192,7 +192,7 @@ export default class ConnectionManager extends EventsDispatcher { this.strategy = this.options.getStrategy({ key: this.key, timeline: this.timeline, - useTLS: this.usingTLS + useTLS: this.usingTLS, }); } @@ -253,10 +253,10 @@ export default class ConnectionManager extends EventsDispatcher { } private buildConnectionCallbacks( - errorCallbacks: ErrorCallbacks + errorCallbacks: ErrorCallbacks, ): ConnectionCallbacks { return Collections.extend({}, errorCallbacks, { - message: message => { + message: (message) => { // includes pong messages from server this.resetActivityCheck(); this.emit('message', message); @@ -267,7 +267,7 @@ export default class ConnectionManager extends EventsDispatcher { activity: () => { this.resetActivityCheck(); }, - error: error => { + error: (error) => { // just emit error to user - socket will already be closed by browser this.emit('error', error); }, @@ -276,30 +276,30 @@ export default class ConnectionManager extends EventsDispatcher { if (this.shouldRetry()) { this.retryIn(1000); } - } + }, }); } private buildHandshakeCallbacks( - errorCallbacks: ErrorCallbacks + errorCallbacks: ErrorCallbacks, ): HandshakeCallbacks { return Collections.extend({}, errorCallbacks, { connected: (handshake: HandshakePayload) => { this.activityTimeout = Math.min( this.options.activityTimeout, handshake.activityTimeout, - handshake.connection.activityTimeout || Infinity + handshake.connection.activityTimeout || Infinity, ); this.clearUnavailableTimer(); this.setConnection(handshake.connection); this.socket_id = this.connection.id; this.updateState('connected', { socket_id: this.socket_id }); - } + }, }); } private buildErrorCallbacks(): ErrorCallbacks { - let withErrorEmitted = callback => { + let withErrorEmitted = (callback) => { return (result: Action | HandshakePayload) => { if (result.error) { this.emit('error', { type: 'WebSocketError', error: result.error }); @@ -322,7 +322,7 @@ export default class ConnectionManager extends EventsDispatcher { }), retry: withErrorEmitted(() => { this.retryIn(0); - }) + }), }; } @@ -357,7 +357,7 @@ export default class ConnectionManager extends EventsDispatcher { } Logger.debug( 'State changed', - previousState + ' -> ' + newStateDescription + previousState + ' -> ' + newStateDescription, ); this.timeline.info({ state: newState, params: data }); this.emit('state_change', { previous: previousState, current: newState }); diff --git a/src/core/connection/handshake/index.ts b/src/core/connection/handshake/index.ts index a0f12e8ee..0b676bcdc 100644 --- a/src/core/connection/handshake/index.ts +++ b/src/core/connection/handshake/index.ts @@ -29,7 +29,7 @@ export default class Handshake { constructor( transport: TransportConnection, - callback: (HandshakePayload) => void + callback: (HandshakePayload) => void, ) { this.transport = transport; this.callback = callback; @@ -42,7 +42,7 @@ export default class Handshake { } private bindListeners() { - this.onMessage = m => { + this.onMessage = (m) => { this.unbindListeners(); var result; @@ -57,7 +57,7 @@ export default class Handshake { if (result.action === 'connected') { this.finish('connected', { connection: new Connection(result.id, this.transport), - activityTimeout: result.activityTimeout + activityTimeout: result.activityTimeout, }); } else { this.finish(result.action, { error: result.error }); @@ -65,7 +65,7 @@ export default class Handshake { } }; - this.onClosed = closeEvent => { + this.onClosed = (closeEvent) => { this.unbindListeners(); var action = Protocol.getCloseAction(closeEvent) || 'backoff'; @@ -84,7 +84,7 @@ export default class Handshake { private finish(action: string, params: any) { this.callback( - Collections.extend({ transport: this.transport, action: action }, params) + Collections.extend({ transport: this.transport, action: action }, params), ); } } diff --git a/src/core/connection/protocol/protocol.ts b/src/core/connection/protocol/protocol.ts index 74c287a73..929cda5f6 100644 --- a/src/core/connection/protocol/protocol.ts +++ b/src/core/connection/protocol/protocol.ts @@ -20,7 +20,7 @@ const Protocol = { * @param {MessageEvent} messageEvent * @return {PusherEvent} */ - decodeMessage: function(messageEvent: MessageEvent): PusherEvent { + decodeMessage: function (messageEvent: MessageEvent): PusherEvent { try { var messageData = JSON.parse(messageEvent.data); var pusherEventData = messageData.data; @@ -32,7 +32,7 @@ const Protocol = { var pusherEvent: PusherEvent = { event: messageData.event, channel: messageData.channel, - data: pusherEventData + data: pusherEventData, }; if (messageData.user_id) { pusherEvent.user_id = messageData.user_id; @@ -49,7 +49,7 @@ const Protocol = { * @param {PusherEvent} event * @return {String} */ - encodeMessage: function(event: PusherEvent): string { + encodeMessage: function (event: PusherEvent): string { return JSON.stringify(event); }, @@ -67,7 +67,7 @@ const Protocol = { * @param {String} message * @result Object */ - processHandshake: function(messageEvent: MessageEvent): Action { + processHandshake: function (messageEvent: MessageEvent): Action { var message = Protocol.decodeMessage(messageEvent); if (message.event === 'pusher:connection_established') { @@ -77,14 +77,14 @@ const Protocol = { return { action: 'connected', id: message.data.socket_id, - activityTimeout: message.data.activity_timeout * 1000 + activityTimeout: message.data.activity_timeout * 1000, }; } else if (message.event === 'pusher:error') { // From protocol 6 close codes are sent only once, so this only // happens when connection does not support close codes return { action: this.getCloseAction(message.data), - error: this.getCloseError(message.data) + error: this.getCloseError(message.data), }; } else { throw 'Invalid handshake'; @@ -101,7 +101,7 @@ const Protocol = { * @param {CloseEvent} closeEvent * @return {String} close action name */ - getCloseAction: function(closeEvent): string { + getCloseAction: function (closeEvent): string { if (closeEvent.code < 4000) { // ignore 1000 CLOSE_NORMAL, 1001 CLOSE_GOING_AWAY, // 1005 CLOSE_NO_STATUS, 1006 CLOSE_ABNORMAL @@ -136,19 +136,19 @@ const Protocol = { * @param {CloseEvent} closeEvent * @return {Object} error object */ - getCloseError: function(closeEvent): any { + getCloseError: function (closeEvent): any { if (closeEvent.code !== 1000 && closeEvent.code !== 1001) { return { type: 'PusherError', data: { code: closeEvent.code, - message: closeEvent.reason || closeEvent.message - } + message: closeEvent.reason || closeEvent.message, + }, }; } else { return null; } - } + }, }; export default Protocol; diff --git a/src/core/defaults.ts b/src/core/defaults.ts index ec81beac7..6957b8ff1 100644 --- a/src/core/defaults.ts +++ b/src/core/defaults.ts @@ -1,6 +1,6 @@ import { ChannelAuthorizationOptions, - UserAuthenticationOptions + UserAuthenticationOptions, } from './auth/options'; import { AuthTransport } from './config'; @@ -50,17 +50,17 @@ var Defaults: DefaultConfig = { unavailableTimeout: 10000, userAuthentication: { endpoint: '/pusher/user-auth', - transport: 'ajax' + transport: 'ajax', }, channelAuthorization: { endpoint: '/pusher/auth', - transport: 'ajax' + transport: 'ajax', }, // CDN configuration cdn_http: CDN_HTTP, cdn_https: CDN_HTTPS, - dependency_suffix: DEPENDENCY_SUFFIX + dependency_suffix: DEPENDENCY_SUFFIX, }; export default Defaults; diff --git a/src/core/events/callback_registry.ts b/src/core/events/callback_registry.ts index 74d124073..5ec2eb9a3 100644 --- a/src/core/events/callback_registry.ts +++ b/src/core/events/callback_registry.ts @@ -19,7 +19,7 @@ export default class CallbackRegistry { this._callbacks[prefixedEventName] || []; this._callbacks[prefixedEventName].push({ fn: callback, - context: context + context: context, }); } @@ -41,31 +41,31 @@ export default class CallbackRegistry { private removeCallback(names: string[], callback: Function, context: any) { Collections.apply( names, - function(name) { + function (name) { this._callbacks[name] = Collections.filter( this._callbacks[name] || [], - function(binding) { + function (binding) { return ( (callback && callback !== binding.fn) || (context && context !== binding.context) ); - } + }, ); if (this._callbacks[name].length === 0) { delete this._callbacks[name]; } }, - this + this, ); } private removeAllCallbacks(names: string[]) { Collections.apply( names, - function(name) { + function (name) { delete this._callbacks[name]; }, - this + this, ); } } diff --git a/src/core/events/dispatcher.ts b/src/core/events/dispatcher.ts index c1149bae3..474f7ca33 100644 --- a/src/core/events/dispatcher.ts +++ b/src/core/events/dispatcher.ts @@ -41,7 +41,7 @@ export default class Dispatcher { this.global_callbacks = Collections.filter( this.global_callbacks || [], - c => c !== callback + (c) => c !== callback, ); return this; diff --git a/src/core/http/ajax.ts b/src/core/http/ajax.ts index 2760d36cb..23c0252c7 100644 --- a/src/core/http/ajax.ts +++ b/src/core/http/ajax.ts @@ -4,7 +4,7 @@ interface Ajax { url: string, async?: boolean, user?: string, - password?: string + password?: string, ): void; send(payload?: any): void; setRequestHeader(key: string, value: string): void; diff --git a/src/core/http/http_polling_socket.ts b/src/core/http/http_polling_socket.ts index cd91a191a..6c225cc6d 100644 --- a/src/core/http/http_polling_socket.ts +++ b/src/core/http/http_polling_socket.ts @@ -3,22 +3,22 @@ import URLLocation from './url_location'; import HTTPSocket from './http_socket'; var hooks: SocketHooks = { - getReceiveURL: function(url: URLLocation, session: string): string { + getReceiveURL: function (url: URLLocation, session: string): string { return url.base + '/' + session + '/xhr' + url.queryString; }, - onHeartbeat: function() { + onHeartbeat: function () { // next HTTP request will reset server's activity timer }, - sendHeartbeat: function(socket) { + sendHeartbeat: function (socket) { socket.sendRaw('[]'); }, - onFinished: function(socket, status) { + onFinished: function (socket, status) { if (status === 200) { socket.reconnect(); } else { socket.onClose(1006, 'Connection interrupted (' + status + ')', false); } - } + }, }; export default hooks; diff --git a/src/core/http/http_socket.ts b/src/core/http/http_socket.ts index 68271f23e..d1b1409c2 100644 --- a/src/core/http/http_socket.ts +++ b/src/core/http/http_socket.ts @@ -48,7 +48,7 @@ class HTTPSocket implements Socket { try { Runtime.createSocketRequest( 'POST', - getUniqueURL(getSendURL(this.location, this.session)) + getUniqueURL(getSendURL(this.location, this.session)), ).start(payload); return true; } catch (e) { @@ -73,7 +73,7 @@ class HTTPSocket implements Socket { this.onclose({ code: code, reason: reason, - wasClean: wasClean + wasClean: wasClean, }); } } @@ -149,13 +149,13 @@ class HTTPSocket implements Socket { private openStream() { this.stream = Runtime.createSocketRequest( 'POST', - getUniqueURL(this.hooks.getReceiveURL(this.location, this.session)) + getUniqueURL(this.hooks.getReceiveURL(this.location, this.session)), ); - this.stream.bind('chunk', chunk => { + this.stream.bind('chunk', (chunk) => { this.onChunk(chunk); }); - this.stream.bind('finished', status => { + this.stream.bind('finished', (status) => { this.hooks.onFinished(this, status); }); this.stream.bind('buffer_too_long', () => { @@ -185,7 +185,7 @@ function getLocation(url): URLLocation { var parts = /([^\?]*)\/*(\??.*)/.exec(url); return { base: parts[1], - queryString: parts[2] + queryString: parts[2], }; } diff --git a/src/core/http/http_streaming_socket.ts b/src/core/http/http_streaming_socket.ts index 163ee65d7..f71ea9ed2 100644 --- a/src/core/http/http_streaming_socket.ts +++ b/src/core/http/http_streaming_socket.ts @@ -2,18 +2,18 @@ import SocketHooks from './socket_hooks'; import HTTPSocket from './http_socket'; var hooks: SocketHooks = { - getReceiveURL: function(url, session) { + getReceiveURL: function (url, session) { return url.base + '/' + session + '/xhr_streaming' + url.queryString; }, - onHeartbeat: function(socket) { + onHeartbeat: function (socket) { socket.sendRaw('[]'); }, - sendHeartbeat: function(socket) { + sendHeartbeat: function (socket) { socket.sendRaw('[]'); }, - onFinished: function(socket, status) { + onFinished: function (socket, status) { socket.onClose(1006, 'Connection interrupted (' + status + ')', false); - } + }, }; export default hooks; diff --git a/src/core/http/state.ts b/src/core/http/state.ts index 5089cfbd9..9cfaa1d0f 100644 --- a/src/core/http/state.ts +++ b/src/core/http/state.ts @@ -1,7 +1,7 @@ enum State { CONNECTING = 0, OPEN = 1, - CLOSED = 3 + CLOSED = 3, } export default State; diff --git a/src/core/options.ts b/src/core/options.ts index baf974eee..1e5cff250 100644 --- a/src/core/options.ts +++ b/src/core/options.ts @@ -1,11 +1,11 @@ import ConnectionManager from './connection/connection_manager'; import { ChannelAuthorizationOptions, - UserAuthenticationOptions + UserAuthenticationOptions, } from './auth/options'; import { ChannelAuthorizerGenerator, - DeprecatedAuthOptions + DeprecatedAuthOptions, } from './auth/deprecated_channel_authorizer'; import { AuthTransport, Transport } from './config'; import * as nacl from 'tweetnacl'; @@ -53,7 +53,7 @@ export function validateOptions(options) { } if ('disableStats' in options) { Logger.warn( - 'The disableStats option is deprecated in favor of enableStats' + 'The disableStats option is deprecated in favor of enableStats', ); } } diff --git a/src/core/pusher.ts b/src/core/pusher.ts index 0d9616094..0c16fc206 100644 --- a/src/core/pusher.ts +++ b/src/core/pusher.ts @@ -45,9 +45,9 @@ export default class Pusher { private static getClientFeatures(): string[] { return Collections.keys( - Collections.filterObject({ ws: Runtime.Transports.ws }, function(t) { + Collections.filterObject({ ws: Runtime.Transports.ws }, function (t) { return t.isSupported({}); - }) + }), ); } @@ -78,12 +78,12 @@ export default class Pusher { params: this.config.timelineParams || {}, limit: 50, level: TimelineLevel.INFO, - version: Defaults.VERSION + version: Defaults.VERSION, }); if (this.config.enableStats) { this.timelineSender = Factory.createTimelineSender(this.timeline, { host: this.config.statsHost, - path: '/timeline/v2/' + Runtime.TimelineTransport.name + path: '/timeline/v2/' + Runtime.TimelineTransport.name, }); } @@ -97,7 +97,7 @@ export default class Pusher { activityTimeout: this.config.activityTimeout, pongTimeout: this.config.pongTimeout, unavailableTimeout: this.config.unavailableTimeout, - useTLS: Boolean(this.config.useTLS) + useTLS: Boolean(this.config.useTLS), }); this.connection.bind('connected', () => { @@ -107,7 +107,7 @@ export default class Pusher { } }); - this.connection.bind('message', event => { + this.connection.bind('message', (event) => { var eventName = event.event; var internal = eventName.indexOf('pusher_internal:') === 0; if (event.channel) { @@ -127,7 +127,7 @@ export default class Pusher { this.connection.bind('disconnected', () => { this.channels.disconnect(); }); - this.connection.bind('error', err => { + this.connection.bind('error', (err) => { Logger.warn(err); }); @@ -156,7 +156,7 @@ export default class Pusher { if (!this.timelineSenderTimer) { var usingTLS = this.connection.isUsingTLS(); var timelineSender = this.timelineSender; - this.timelineSenderTimer = new PeriodicTimer(60000, function() { + this.timelineSenderTimer = new PeriodicTimer(60000, function () { timelineSender.send(usingTLS); }); } diff --git a/src/core/strategies/best_connected_ever_strategy.ts b/src/core/strategies/best_connected_ever_strategy.ts index 6f4ea365a..1c243acaf 100644 --- a/src/core/strategies/best_connected_ever_strategy.ts +++ b/src/core/strategies/best_connected_ever_strategy.ts @@ -18,8 +18,8 @@ export default class BestConnectedEverStrategy implements Strategy { } connect(minPriority: number, callback: Function) { - return connect(this.strategies, minPriority, function(i, runners) { - return function(error, handshake) { + return connect(this.strategies, minPriority, function (i, runners) { + return function (error, handshake) { runners[i].error = error; if (error) { if (allRunnersFailed(runners)) { @@ -27,7 +27,7 @@ export default class BestConnectedEverStrategy implements Strategy { } return; } - Collections.apply(runners, function(runner) { + Collections.apply(runners, function (runner) { runner.forceMinPriority(handshake.transport.priority); }); callback(null, handshake); @@ -50,25 +50,25 @@ export default class BestConnectedEverStrategy implements Strategy { function connect( strategies: Strategy[], minPriority: number, - callbackBuilder: Function + callbackBuilder: Function, ) { - var runners = Collections.map(strategies, function(strategy, i, _, rs) { + var runners = Collections.map(strategies, function (strategy, i, _, rs) { return strategy.connect(minPriority, callbackBuilder(i, rs)); }); return { - abort: function() { + abort: function () { Collections.apply(runners, abortRunner); }, - forceMinPriority: function(p) { - Collections.apply(runners, function(runner) { + forceMinPriority: function (p) { + Collections.apply(runners, function (runner) { runner.forceMinPriority(p); }); - } + }, }; } function allRunnersFailed(runners): boolean { - return Collections.all(runners, function(runner) { + return Collections.all(runners, function (runner) { return Boolean(runner.error); }); } diff --git a/src/core/strategies/delayed_strategy.ts b/src/core/strategies/delayed_strategy.ts index bca1969e8..295cf6df5 100644 --- a/src/core/strategies/delayed_strategy.ts +++ b/src/core/strategies/delayed_strategy.ts @@ -26,23 +26,23 @@ export default class DelayedStrategy implements Strategy { connect(minPriority: number, callback: Function) { var strategy = this.strategy; var runner; - var timer = new Timer(this.options.delay, function() { + var timer = new Timer(this.options.delay, function () { runner = strategy.connect(minPriority, callback); }); return { - abort: function() { + abort: function () { timer.ensureAborted(); if (runner) { runner.abort(); } }, - forceMinPriority: function(p) { + forceMinPriority: function (p) { minPriority = p; if (runner) { runner.forceMinPriority(p); } - } + }, }; } } diff --git a/src/core/strategies/first_connected_strategy.ts b/src/core/strategies/first_connected_strategy.ts index c8ff1293c..12c4dcb29 100644 --- a/src/core/strategies/first_connected_strategy.ts +++ b/src/core/strategies/first_connected_strategy.ts @@ -17,12 +17,15 @@ export default class FirstConnectedStrategy implements Strategy { } connect(minPriority: number, callback: Function): StrategyRunner { - var runner = this.strategy.connect(minPriority, function(error, handshake) { - if (handshake) { - runner.abort(); - } - callback(error, handshake); - }); + var runner = this.strategy.connect( + minPriority, + function (error, handshake) { + if (handshake) { + runner.abort(); + } + callback(error, handshake); + }, + ); return runner; } } diff --git a/src/core/strategies/if_strategy.ts b/src/core/strategies/if_strategy.ts index e497b30c1..4965f5f72 100644 --- a/src/core/strategies/if_strategy.ts +++ b/src/core/strategies/if_strategy.ts @@ -15,7 +15,7 @@ export default class IfStrategy implements Strategy { constructor( test: () => boolean, trueBranch: Strategy, - falseBranch: Strategy + falseBranch: Strategy, ) { this.test = test; this.trueBranch = trueBranch; diff --git a/src/core/strategies/sequential_strategy.ts b/src/core/strategies/sequential_strategy.ts index 01c5c19c6..f07be8eb5 100644 --- a/src/core/strategies/sequential_strategy.ts +++ b/src/core/strategies/sequential_strategy.ts @@ -59,7 +59,7 @@ export default class SequentialStrategy implements Strategy { strategies[current], minPriority, { timeout, failFast: this.failFast }, - tryNextStrategy + tryNextStrategy, ); } else { callback(true); @@ -71,19 +71,19 @@ export default class SequentialStrategy implements Strategy { strategies[current], minPriority, { timeout: timeout, failFast: this.failFast }, - tryNextStrategy + tryNextStrategy, ); return { - abort: function() { + abort: function () { runner.abort(); }, - forceMinPriority: function(p) { + forceMinPriority: function (p) { minPriority = p; if (runner) { runner.forceMinPriority(p); } - } + }, }; } @@ -91,19 +91,19 @@ export default class SequentialStrategy implements Strategy { strategy: Strategy, minPriority: number, options: StrategyOptions, - callback: Function + callback: Function, ) { var timer = null; var runner = null; if (options.timeout > 0) { - timer = new Timer(options.timeout, function() { + timer = new Timer(options.timeout, function () { runner.abort(); callback(true); }); } - runner = strategy.connect(minPriority, function(error, handshake) { + runner = strategy.connect(minPriority, function (error, handshake) { if (error && timer && timer.isRunning() && !options.failFast) { // advance to the next strategy after the timeout return; @@ -115,15 +115,15 @@ export default class SequentialStrategy implements Strategy { }); return { - abort: function() { + abort: function () { if (timer) { timer.ensureAborted(); } runner.abort(); }, - forceMinPriority: function(p) { + forceMinPriority: function (p) { runner.forceMinPriority(p); - } + }, }; } } diff --git a/src/core/strategies/strategy_builder.ts b/src/core/strategies/strategy_builder.ts index 008866352..06493a643 100644 --- a/src/core/strategies/strategy_builder.ts +++ b/src/core/strategies/strategy_builder.ts @@ -10,13 +10,13 @@ import Runtime from 'runtime'; const { Transports } = Runtime; -export var defineTransport = function( +export var defineTransport = function ( config: Config, name: string, type: string, priority: number, options: StrategyOptions, - manager?: TransportManager + manager?: TransportManager, ): Strategy { var transportClass = Transports[type]; if (!transportClass) { @@ -33,14 +33,14 @@ export var defineTransport = function( if (enabled) { options = Object.assign( { ignoreNullOrigin: config.ignoreNullOrigin }, - options + options, ); transport = new TransportStrategy( name, priority, manager ? manager.getAssistant(transportClass) : transportClass, - options + options, ); } else { transport = UnsupportedStrategy; @@ -50,18 +50,18 @@ export var defineTransport = function( }; var UnsupportedStrategy: Strategy = { - isSupported: function() { + isSupported: function () { return false; }, - connect: function(_, callback) { - var deferred = Util.defer(function() { + connect: function (_, callback) { + var deferred = Util.defer(function () { callback(new Errors.UnsupportedStrategy()); }); return { - abort: function() { + abort: function () { deferred.ensureAborted(); }, - forceMinPriority: function() {} + forceMinPriority: function () {}, }; - } + }, }; diff --git a/src/core/strategies/transport_strategy.ts b/src/core/strategies/transport_strategy.ts index 0e9477d3a..19cefd06d 100644 --- a/src/core/strategies/transport_strategy.ts +++ b/src/core/strategies/transport_strategy.ts @@ -24,7 +24,7 @@ export default class TransportStrategy implements Strategy { name: string, priority: number, transport: Transport, - options: StrategyOptions + options: StrategyOptions, ) { this.name = name; this.priority = priority; @@ -38,7 +38,7 @@ export default class TransportStrategy implements Strategy { */ isSupported(): boolean { return this.transport.isSupported({ - useTLS: this.options.useTLS + useTLS: this.options.useTLS, }); } @@ -59,26 +59,26 @@ export default class TransportStrategy implements Strategy { this.name, this.priority, this.options.key, - this.options + this.options, ); var handshake = null; - var onInitialized = function() { + var onInitialized = function () { transport.unbind('initialized', onInitialized); transport.connect(); }; - var onOpen = function() { - handshake = Factory.createHandshake(transport, function(result) { + var onOpen = function () { + handshake = Factory.createHandshake(transport, function (result) { connected = true; unbindListeners(); callback(null, result); }); }; - var onError = function(error) { + var onError = function (error) { unbindListeners(); callback(error); }; - var onClosed = function() { + var onClosed = function () { unbindListeners(); var serializedTransport; @@ -90,7 +90,7 @@ export default class TransportStrategy implements Strategy { callback(new Errors.TransportClosed(serializedTransport)); }; - var unbindListeners = function() { + var unbindListeners = function () { transport.unbind('initialized', onInitialized); transport.unbind('open', onOpen); transport.unbind('error', onError); @@ -117,7 +117,7 @@ export default class TransportStrategy implements Strategy { transport.close(); } }, - forceMinPriority: p => { + forceMinPriority: (p) => { if (connected) { return; } @@ -128,17 +128,17 @@ export default class TransportStrategy implements Strategy { transport.close(); } } - } + }, }; } } function failAttempt(error: Error, callback: Function) { - Util.defer(function() { + Util.defer(function () { callback(error); }); return { - abort: function() {}, - forceMinPriority: function() {} + abort: function () {}, + forceMinPriority: function () {}, }; } diff --git a/src/core/strategies/websocket_prioritized_cached_strategy.ts b/src/core/strategies/websocket_prioritized_cached_strategy.ts index edd647dc4..9c778be78 100644 --- a/src/core/strategies/websocket_prioritized_cached_strategy.ts +++ b/src/core/strategies/websocket_prioritized_cached_strategy.ts @@ -28,7 +28,7 @@ export default class WebSocketPrioritizedCachedStrategy implements Strategy { constructor( strategy: Strategy, transports: TransportStrategyDictionary, - options: StrategyOptions + options: StrategyOptions, ) { this.strategy = strategy; this.transports = transports; @@ -54,13 +54,13 @@ export default class WebSocketPrioritizedCachedStrategy implements Strategy { this.timeline.info({ cached: true, transport: info.transport, - latency: info.latency + latency: info.latency, }); strategies.push( new SequentialStrategy([transport], { timeout: info.latency * 2 + 1000, - failFast: true - }) + failFast: true, + }), ); } else { cacheSkipCount++; @@ -85,22 +85,22 @@ export default class WebSocketPrioritizedCachedStrategy implements Strategy { usingTLS, handshake.transport.name, Util.now() - startTimestamp, - cacheSkipCount + cacheSkipCount, ); callback(null, handshake); } }); return { - abort: function() { + abort: function () { runner.abort(); }, - forceMinPriority: function(p) { + forceMinPriority: function (p) { minPriority = p; if (runner) { runner.forceMinPriority(p); } - } + }, }; } } @@ -128,7 +128,7 @@ function storeTransportCache( usingTLS: boolean, transport: TransportStrategy, latency: number, - cacheSkipCount: number + cacheSkipCount: number, ) { var storage = Runtime.getLocalStorage(); if (storage) { @@ -137,7 +137,7 @@ function storeTransportCache( timestamp: Util.now(), transport: transport, latency: latency, - cacheSkipCount: cacheSkipCount + cacheSkipCount: cacheSkipCount, }); } catch (e) { // catch over quota exceptions raised by localStorage diff --git a/src/core/timeline/level.ts b/src/core/timeline/level.ts index f12818a6f..d1fe39fe0 100644 --- a/src/core/timeline/level.ts +++ b/src/core/timeline/level.ts @@ -1,7 +1,7 @@ enum TimelineLevel { ERROR = 3, INFO = 6, - DEBUG = 7 + DEBUG = 7, } export default TimelineLevel; diff --git a/src/core/timeline/timeline.ts b/src/core/timeline/timeline.ts index 041449867..119312963 100644 --- a/src/core/timeline/timeline.ts +++ b/src/core/timeline/timeline.ts @@ -31,7 +31,7 @@ export default class Timeline { log(level, event) { if (level <= this.options.level) { this.events.push( - Collections.extend({}, event, { timestamp: Util.now() }) + Collections.extend({}, event, { timestamp: Util.now() }), ); if (this.options.limit && this.events.length > this.options.limit) { this.events.shift(); @@ -65,9 +65,9 @@ export default class Timeline { version: this.options.version, cluster: this.options.cluster, features: this.options.features, - timeline: this.events + timeline: this.events, }, - this.options.params + this.options.params, ); this.events = []; diff --git a/src/core/timeline/timeline_sender.ts b/src/core/timeline/timeline_sender.ts index 3d8b6d393..98af5c384 100644 --- a/src/core/timeline/timeline_sender.ts +++ b/src/core/timeline/timeline_sender.ts @@ -27,7 +27,7 @@ export default class TimelineSender { this.timeline.send( Runtime.TimelineTransport.getAgent(this, useTLS), - callback + callback, ); } } diff --git a/src/core/timeline/timeline_transport.ts b/src/core/timeline/timeline_transport.ts index c3a7a894c..87b657a47 100644 --- a/src/core/timeline/timeline_transport.ts +++ b/src/core/timeline/timeline_transport.ts @@ -4,7 +4,7 @@ interface TimelineTransport { name: string; getAgent: ( sender: TimelineSender, - useTLS: boolean + useTLS: boolean, ) => (data: any, callback: Function) => void; } diff --git a/src/core/transports/assistant_to_the_transport_manager.ts b/src/core/transports/assistant_to_the_transport_manager.ts index c5f62cd9e..6aecb5c88 100644 --- a/src/core/transports/assistant_to_the_transport_manager.ts +++ b/src/core/transports/assistant_to_the_transport_manager.ts @@ -28,7 +28,7 @@ export default class AssistantToTheTransportManager { constructor( manager: TransportManager, transport: Transport, - options: PingDelayOptions + options: PingDelayOptions, ) { this.manager = manager; this.transport = transport; @@ -51,26 +51,26 @@ export default class AssistantToTheTransportManager { name: string, priority: number, key: string, - options: Object + options: Object, ): TransportConnection { options = Collections.extend({}, options, { - activityTimeout: this.pingDelay + activityTimeout: this.pingDelay, }); var connection = this.transport.createConnection( name, priority, key, - options + options, ); var openTimestamp = null; - var onOpen = function() { + var onOpen = function () { connection.unbind('open', onOpen); connection.bind('closed', onClosed); openTimestamp = Util.now(); }; - var onClosed = closeEvent => { + var onClosed = (closeEvent) => { connection.unbind('closed', onClosed); if (closeEvent.code === 1002 || closeEvent.code === 1003) { diff --git a/src/core/transports/transport.ts b/src/core/transports/transport.ts index 9e94841b2..f1ef2d824 100644 --- a/src/core/transports/transport.ts +++ b/src/core/transports/transport.ts @@ -47,7 +47,7 @@ export default class Transport { name: string, priority: number, key: string, - options: any + options: any, ): TransportConnection { return new TransportConnection(this.hooks, name, priority, key, options); } diff --git a/src/core/transports/transport_connection.ts b/src/core/transports/transport_connection.ts index b8e76b7f8..67d2ff7ef 100644 --- a/src/core/transports/transport_connection.ts +++ b/src/core/transports/transport_connection.ts @@ -55,7 +55,7 @@ export default class TransportConnection extends EventsDispatcher { name: string, priority: number, key: string, - options: TransportConnectionOptions + options: TransportConnectionOptions, ) { super(); this.initialize = Runtime.transportConnectionInitializer; @@ -157,7 +157,7 @@ export default class TransportConnection extends EventsDispatcher { if (this.hooks.beforeOpen) { this.hooks.beforeOpen( this.socket, - this.hooks.urls.getPath(this.key, this.options) + this.hooks.urls.getPath(this.key, this.options), ); } this.changeState('open'); @@ -174,7 +174,7 @@ export default class TransportConnection extends EventsDispatcher { this.changeState('closed', { code: closeEvent.code, reason: closeEvent.reason, - wasClean: closeEvent.wasClean + wasClean: closeEvent.wasClean, }); } else { this.changeState('closed'); @@ -195,13 +195,13 @@ export default class TransportConnection extends EventsDispatcher { this.socket.onopen = () => { this.onOpen(); }; - this.socket.onerror = error => { + this.socket.onerror = (error) => { this.onError(error); }; - this.socket.onclose = closeEvent => { + this.socket.onclose = (closeEvent) => { this.onClose(closeEvent); }; - this.socket.onmessage = message => { + this.socket.onmessage = (message) => { this.onMessage(message); }; @@ -229,8 +229,8 @@ export default class TransportConnection extends EventsDispatcher { this.timeline.info( this.buildTimelineMessage({ state: state, - params: params - }) + params: params, + }), ); this.emit(state, params); } diff --git a/src/core/transports/transport_manager.ts b/src/core/transports/transport_manager.ts index 5dbb85a4a..5120db1b5 100644 --- a/src/core/transports/transport_manager.ts +++ b/src/core/transports/transport_manager.ts @@ -33,7 +33,7 @@ export default class TransportManager { getAssistant(transport: Transport): AssistantToTheTransportManager { return Factory.createAssistantToTheTransportManager(this, transport, { minPingDelay: this.options.minPingDelay, - maxPingDelay: this.options.maxPingDelay + maxPingDelay: this.options.maxPingDelay, }); } diff --git a/src/core/transports/url_schemes.ts b/src/core/transports/url_schemes.ts index a1ea200fb..8008522a6 100644 --- a/src/core/transports/url_schemes.ts +++ b/src/core/transports/url_schemes.ts @@ -4,7 +4,7 @@ import { default as URLScheme, URLSchemeParams } from './url_scheme'; function getGenericURL( baseScheme: string, params: URLSchemeParams, - path: string + path: string, ): string { var scheme = baseScheme + (params.useTLS ? 's' : ''); var host = params.useTLS ? params.hostTLS : params.hostNonTLS; @@ -24,24 +24,24 @@ function getGenericPath(key: string, queryString?: string): string { } export var ws: URLScheme = { - getInitial: function(key: string, params: URLSchemeParams): string { + getInitial: function (key: string, params: URLSchemeParams): string { var path = (params.httpPath || '') + getGenericPath(key, 'flash=false'); return getGenericURL('ws', params, path); - } + }, }; export var http: URLScheme = { - getInitial: function(key: string, params: URLSchemeParams): string { + getInitial: function (key: string, params: URLSchemeParams): string { var path = (params.httpPath || '/pusher') + getGenericPath(key); return getGenericURL('http', params, path); - } + }, }; export var sockjs: URLScheme = { - getInitial: function(key: string, params: URLSchemeParams): string { + getInitial: function (key: string, params: URLSchemeParams): string { return getGenericURL('http', params, params.httpPath || '/pusher'); }, - getPath: function(key: string, params: URLSchemeParams): string { + getPath: function (key: string, params: URLSchemeParams): string { return getGenericPath(key); - } + }, }; diff --git a/src/core/user.ts b/src/core/user.ts index 02e57b54c..95790e0fd 100644 --- a/src/core/user.ts +++ b/src/core/user.ts @@ -2,7 +2,7 @@ import Pusher from './pusher'; import Logger from './logger'; import { UserAuthenticationData, - UserAuthenticationCallback + UserAuthenticationCallback, } from './auth/options'; import Channel from './channels/channel'; import WatchlistFacade from './watchlist'; @@ -19,7 +19,7 @@ export default class UserFacade extends EventsDispatcher { private _signinDoneResolve: Function = null; public constructor(pusher: Pusher) { - super(function(eventName, data) { + super(function (eventName, data) { Logger.debug('No callbacks on user for ' + eventName); }); this.pusher = pusher; @@ -35,7 +35,7 @@ export default class UserFacade extends EventsDispatcher { this.watchlist = new WatchlistFacade(pusher); - this.pusher.connection.bind('message', event => { + this.pusher.connection.bind('message', (event) => { var eventName = event.event; if (eventName === 'pusher:signin_success') { this._onSigninSuccess(event.data); @@ -72,15 +72,15 @@ export default class UserFacade extends EventsDispatcher { this.pusher.config.userAuthenticator( { - socketId: this.pusher.connection.socket_id + socketId: this.pusher.connection.socket_id, }, - this._onAuthorize + this._onAuthorize, ); } private _onAuthorize: UserAuthenticationCallback = ( err, - authData: UserAuthenticationData + authData: UserAuthenticationData, ) => { if (err) { Logger.warn(`Error during signin: ${err}`); @@ -90,7 +90,7 @@ export default class UserFacade extends EventsDispatcher { this.pusher.send_event('pusher:signin', { auth: authData.auth, - user_data: authData.user_data + user_data: authData.user_data, }); // Later when we get pusher:singin_success event, the user will be marked as signed in @@ -107,7 +107,7 @@ export default class UserFacade extends EventsDispatcher { if (typeof this.user_data.id !== 'string' || this.user_data.id === '') { Logger.error( - `user_data doesn't contain an id. user_data: ${this.user_data}` + `user_data doesn't contain an id. user_data: ${this.user_data}`, ); this._cleanup(); return; @@ -119,7 +119,7 @@ export default class UserFacade extends EventsDispatcher { } private _subscribeChannels() { - const ensure_subscribed = channel => { + const ensure_subscribed = (channel) => { if (channel.subscriptionPending && channel.subscriptionCancelled) { channel.reinstateSubscription(); } else if ( @@ -132,7 +132,7 @@ export default class UserFacade extends EventsDispatcher { this.serverToUserChannel = new Channel( `#server-to-user-${this.user_data.id}`, - this.pusher + this.pusher, ); this.serverToUserChannel.bind_global((eventName, data) => { if ( diff --git a/src/core/util.ts b/src/core/util.ts index a271eaf3c..05bd01530 100644 --- a/src/core/util.ts +++ b/src/core/util.ts @@ -25,10 +25,10 @@ var Util = { */ method(name: string, ...args: any[]): Function { var boundArguments = Array.prototype.slice.call(arguments, 1); - return function(object) { + return function (object) { return object[name].apply(object, boundArguments.concat(arguments)); }; - } + }, }; export default Util; diff --git a/src/core/utils/collections.ts b/src/core/utils/collections.ts index 23b07d9be..7a339a396 100644 --- a/src/core/utils/collections.ts +++ b/src/core/utils/collections.ts @@ -87,7 +87,7 @@ export function objectApply(object: any, f: Function) { */ export function keys(object: any): string[] { var keys = []; - objectApply(object, function(_, key) { + objectApply(object, function (_, key) { keys.push(key); }); return keys; @@ -100,7 +100,7 @@ export function keys(object: any): string[] { */ export function values(object: any): any[] { var values = []; - objectApply(object, function(value) { + objectApply(object, function (value) { values.push(value); }); return values; @@ -154,7 +154,7 @@ export function map(array: any[], f: Function): any[] { */ export function mapObject(object: any, f: Function): any { var result = {}; - objectApply(object, function(value, key) { + objectApply(object, function (value, key) { result[key] = f(value); }); return result; @@ -174,7 +174,7 @@ export function mapObject(object: any, f: Function): any { export function filter(array: any[], test: Function): any[] { test = test || - function(value) { + function (value) { return !!value; }; @@ -200,7 +200,7 @@ export function filter(array: any[], test: Function): any[] { */ export function filterObject(object: Object, test: Function) { var result = {}; - objectApply(object, function(value, key) { + objectApply(object, function (value, key) { if ((test && test(value, key, object, result)) || Boolean(value)) { result[key] = value; } @@ -215,7 +215,7 @@ export function filterObject(object: Object, test: Function) { */ export function flatten(object: Object): any[] { var result = []; - objectApply(object, function(value, key) { + objectApply(object, function (value, key) { result.push([key, value]); }); return result; @@ -260,7 +260,7 @@ export function all(array: any[], test: Function): boolean { } export function encodeParamsObject(data): string { - return mapObject(data, function(value) { + return mapObject(data, function (value) { if (typeof value === 'object') { value = safeJSONStringify(value); } @@ -269,13 +269,13 @@ export function encodeParamsObject(data): string { } export function buildQueryString(data: any): string { - var params = filterObject(data, function(value) { + var params = filterObject(data, function (value) { return value !== undefined; }); var query = map( flatten(encodeParamsObject(params)), - Util.method('join', '=') + Util.method('join', '='), ).join('&'); return query; @@ -322,7 +322,7 @@ export function decycleObject(object: any): any { if (Object.prototype.hasOwnProperty.call(value, name)) { nu[name] = derez( value[name], - path + '[' + JSON.stringify(name) + ']' + path + '[' + JSON.stringify(name) + ']', ); } } diff --git a/src/core/utils/factory.ts b/src/core/utils/factory.ts index 5bf84e9a1..7209fd875 100644 --- a/src/core/utils/factory.ts +++ b/src/core/utils/factory.ts @@ -10,7 +10,7 @@ import HTTPSocket from '../http/http_socket'; import Timeline from '../timeline/timeline'; import { default as TimelineSender, - TimelineSenderOptions + TimelineSenderOptions, } from '../timeline/timeline_sender'; import PresenceChannel from '../channels/presence_channel'; import PrivateChannel from '../channels/private_channel'; @@ -31,7 +31,7 @@ var Factory = { createConnectionManager( key: string, - options: ConnectionManagerOptions + options: ConnectionManagerOptions, ): ConnectionManager { return new ConnectionManager(key, options); }, @@ -51,7 +51,7 @@ var Factory = { createEncryptedChannel( name: string, pusher: Pusher, - nacl: nacl + nacl: nacl, ): EncryptedChannel { return new EncryptedChannel(name, pusher, nacl); }, @@ -62,7 +62,7 @@ var Factory = { createHandshake( transport: TransportConnection, - callback: (HandshakePayload) => void + callback: (HandshakePayload) => void, ): Handshake { return new Handshake(transport, callback); }, @@ -70,10 +70,10 @@ var Factory = { createAssistantToTheTransportManager( manager: TransportManager, transport: Transport, - options: PingDelayOptions + options: PingDelayOptions, ): AssistantToTheTransportManager { return new AssistantToTheTransportManager(manager, transport, options); - } + }, }; export default Factory; diff --git a/src/core/utils/timers/abstract_timer.ts b/src/core/utils/timers/abstract_timer.ts index 30ee74df3..e70d4b35b 100644 --- a/src/core/utils/timers/abstract_timer.ts +++ b/src/core/utils/timers/abstract_timer.ts @@ -9,7 +9,7 @@ abstract class Timer { set: Scheduler, clear: Canceller, delay: Delay, - callback: TimedCallback + callback: TimedCallback, ) { this.clear = clear; this.timer = set(() => { diff --git a/src/core/utils/timers/index.ts b/src/core/utils/timers/index.ts index 564497006..9d42f5a34 100644 --- a/src/core/utils/timers/index.ts +++ b/src/core/utils/timers/index.ts @@ -17,7 +17,7 @@ function clearInterval(timer) { */ export class OneOffTimer extends Timer { constructor(delay: Delay, callback: TimedCallback) { - super(setTimeout, clearTimeout, delay, function(timer) { + super(setTimeout, clearTimeout, delay, function (timer) { callback(); return null; }); @@ -31,7 +31,7 @@ export class OneOffTimer extends Timer { */ export class PeriodicTimer extends Timer { constructor(delay: Delay, callback: TimedCallback) { - super(setInterval, clearInterval, delay, function(timer) { + super(setInterval, clearInterval, delay, function (timer) { callback(); return timer; }); diff --git a/src/core/utils/url_store.ts b/src/core/utils/url_store.ts index f0aa430d1..7c95f83b6 100644 --- a/src/core/utils/url_store.ts +++ b/src/core/utils/url_store.ts @@ -6,22 +6,22 @@ const urlStore = { baseUrl: 'https://pusher.com', urls: { authenticationEndpoint: { - path: '/docs/channels/server_api/authenticating_users' + path: '/docs/channels/server_api/authenticating_users', }, authorizationEndpoint: { - path: '/docs/channels/server_api/authorizing-users/' + path: '/docs/channels/server_api/authorizing-users/', }, javascriptQuickStart: { - path: '/docs/javascript_quick_start' + path: '/docs/javascript_quick_start', }, triggeringClientEvents: { - path: '/docs/client_api_guide/client_events#trigger-events' + path: '/docs/client_api_guide/client_events#trigger-events', }, encryptedChannelSupport: { fullUrl: - 'https://github.com/pusher/pusher-js/tree/cc491015371a4bde5743d1c87a0fbac0feb53195#encrypted-channel-support' - } - } + 'https://github.com/pusher/pusher-js/tree/cc491015371a4bde5743d1c87a0fbac0feb53195#encrypted-channel-support', + }, + }, }; /** Builds a consistent string with links to pusher documentation @@ -29,7 +29,7 @@ const urlStore = { * @param {string} key - relevant key in the url_store.urls object * @return {string} suffix string to append to log message */ -const buildLogSuffix = function(key: string): string { +const buildLogSuffix = function (key: string): string { const urlPrefix = 'See:'; const urlObj = urlStore.urls[key]; if (!urlObj) return ''; diff --git a/src/core/watchlist.ts b/src/core/watchlist.ts index 4395790aa..7ffca4a6c 100644 --- a/src/core/watchlist.ts +++ b/src/core/watchlist.ts @@ -6,7 +6,7 @@ export default class WatchlistFacade extends EventsDispatcher { private pusher: Pusher; public constructor(pusher: Pusher) { - super(function(eventName, data) { + super(function (eventName, data) { Logger.debug(`No callbacks on watchlist events for ${eventName}`); }); @@ -15,13 +15,13 @@ export default class WatchlistFacade extends EventsDispatcher { } handleEvent(pusherEvent) { - pusherEvent.data.events.forEach(watchlistEvent => { + pusherEvent.data.events.forEach((watchlistEvent) => { this.emit(watchlistEvent.name, watchlistEvent); }); } private bindWatchlistInternalEvent() { - this.pusher.connection.bind('message', pusherEvent => { + this.pusher.connection.bind('message', (pusherEvent) => { var eventName = pusherEvent.event; if (eventName === 'pusher_internal:watchlist_events') { this.handleEvent(pusherEvent); diff --git a/src/d.ts/module/module.d.ts b/src/d.ts/module/module.d.ts index b2dd1e559..52eb2203d 100644 --- a/src/d.ts/module/module.d.ts +++ b/src/d.ts/module/module.d.ts @@ -7,6 +7,6 @@ declare var require: { (paths: string[], callback: (...modules: any[]) => void): void; ensure: ( paths: string[], - callback: (require: (path: string) => T) => void + callback: (require: (path: string) => T) => void, ) => void; }; diff --git a/src/runtimes/interface.ts b/src/runtimes/interface.ts index 070a2fc25..02d13e8b5 100644 --- a/src/runtimes/interface.ts +++ b/src/runtimes/interface.ts @@ -35,7 +35,7 @@ interface Runtime { getDefaultStrategy( config: Config, options: StrategyOptions, - defineTransport: Function + defineTransport: Function, ): Strategy; Transports: TransportsTable; getWebSocketAPI(): new (url: string) => Socket; diff --git a/src/runtimes/isomorphic/auth/xhr_auth.ts b/src/runtimes/isomorphic/auth/xhr_auth.ts index 91edea64b..2750efef2 100644 --- a/src/runtimes/isomorphic/auth/xhr_auth.ts +++ b/src/runtimes/isomorphic/auth/xhr_auth.ts @@ -8,16 +8,16 @@ import UrlStore from 'core/utils/url_store'; import { AuthRequestType, AuthTransportCallback, - InternalAuthOptions + InternalAuthOptions, } from 'core/auth/options'; import { HTTPAuthError } from 'core/errors'; -const ajax: AuthTransport = function( +const ajax: AuthTransport = function ( context: AbstractRuntime, query: string, authOptions: InternalAuthOptions, authRequestType: AuthRequestType, - callback: AuthTransportCallback + callback: AuthTransportCallback, ) { const xhr = Runtime.createXHR(); xhr.open('POST', authOptions.endpoint, true); @@ -34,7 +34,7 @@ const ajax: AuthTransport = function( } } - xhr.onreadystatechange = function() { + xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { let data; @@ -49,9 +49,9 @@ const ajax: AuthTransport = function( 200, `JSON returned from ${authRequestType.toString()} endpoint was invalid, yet status code was 200. Data was: ${ xhr.responseText - }` + }`, ), - null + null, ); } @@ -67,7 +67,7 @@ const ajax: AuthTransport = function( break; case AuthRequestType.ChannelAuthorization: suffix = `Clients must be authorized to join private or presence channels. ${UrlStore.buildLogSuffix( - 'authorizationEndpoint' + 'authorizationEndpoint', )}`; break; } @@ -75,9 +75,9 @@ const ajax: AuthTransport = function( new HTTPAuthError( xhr.status, `Unable to retrieve auth string from ${authRequestType.toString()} endpoint - ` + - `received status: ${xhr.status} from ${authOptions.endpoint}. ${suffix}` + `received status: ${xhr.status} from ${authOptions.endpoint}. ${suffix}`, ), - null + null, ); } } diff --git a/src/runtimes/isomorphic/default_strategy.ts b/src/runtimes/isomorphic/default_strategy.ts index f7429887b..4ea7d8f73 100644 --- a/src/runtimes/isomorphic/default_strategy.ts +++ b/src/runtimes/isomorphic/default_strategy.ts @@ -4,7 +4,7 @@ import Strategy from 'core/strategies/strategy'; import SequentialStrategy from 'core/strategies/sequential_strategy'; import BestConnectedEverStrategy from 'core/strategies/best_connected_ever_strategy'; import WebSocketPrioritizedCachedStrategy, { - TransportStrategyDictionary + TransportStrategyDictionary, } from 'core/strategies/websocket_prioritized_cached_strategy'; import DelayedStrategy from 'core/strategies/delayed_strategy'; import IfStrategy from 'core/strategies/if_strategy'; @@ -13,15 +13,15 @@ import { Config } from 'core/config'; import StrategyOptions from 'core/strategies/strategy_options'; function testSupportsStrategy(strategy: Strategy) { - return function() { + return function () { return strategy.isSupported(); }; } -var getDefaultStrategy = function( +var getDefaultStrategy = function ( config: Config, baseOptions: StrategyOptions, - defineTransport: Function + defineTransport: Function, ): Strategy { var definedTransports = {}; @@ -30,7 +30,7 @@ var getDefaultStrategy = function( type: string, priority: number, options: StrategyOptions, - manager?: TransportManager + manager?: TransportManager, ) { var transport = defineTransport( config, @@ -38,7 +38,7 @@ var getDefaultStrategy = function( type, priority, options, - manager + manager, ); definedTransports[name] = transport; @@ -49,30 +49,30 @@ var getDefaultStrategy = function( var ws_options: StrategyOptions = Object.assign({}, baseOptions, { hostNonTLS: config.wsHost + ':' + config.wsPort, hostTLS: config.wsHost + ':' + config.wssPort, - httpPath: config.wsPath + httpPath: config.wsPath, }); var wss_options: StrategyOptions = Collections.extend({}, ws_options, { - useTLS: true + useTLS: true, }); var http_options: StrategyOptions = Object.assign({}, baseOptions, { hostNonTLS: config.httpHost + ':' + config.httpPort, hostTLS: config.httpHost + ':' + config.httpsPort, - httpPath: config.httpPath + httpPath: config.httpPath, }); var timeouts = { loop: true, timeout: 15000, - timeoutLimit: 60000 + timeoutLimit: 60000, }; var ws_manager = new TransportManager({ minPingDelay: 10000, - maxPingDelay: config.activityTimeout + maxPingDelay: config.activityTimeout, }); var streaming_manager = new TransportManager({ lives: 2, minPingDelay: 10000, - maxPingDelay: config.activityTimeout + maxPingDelay: config.activityTimeout, }); var ws_transport = defineTransportStrategy( @@ -80,34 +80,34 @@ var getDefaultStrategy = function( 'ws', 3, ws_options, - ws_manager + ws_manager, ); var wss_transport = defineTransportStrategy( 'wss', 'ws', 3, wss_options, - ws_manager + ws_manager, ); var xhr_streaming_transport = defineTransportStrategy( 'xhr_streaming', 'xhr_streaming', 1, http_options, - streaming_manager + streaming_manager, ); var xhr_polling_transport = defineTransportStrategy( 'xhr_polling', 'xhr_polling', 1, - http_options + http_options, ); var ws_loop = new SequentialStrategy([ws_transport], timeouts); var wss_loop = new SequentialStrategy([wss_transport], timeouts); var streaming_loop = new SequentialStrategy( [xhr_streaming_transport], - timeouts + timeouts, ); var polling_loop = new SequentialStrategy([xhr_polling_transport], timeouts); @@ -117,38 +117,38 @@ var getDefaultStrategy = function( testSupportsStrategy(streaming_loop), new BestConnectedEverStrategy([ streaming_loop, - new DelayedStrategy(polling_loop, { delay: 4000 }) + new DelayedStrategy(polling_loop, { delay: 4000 }), ]), - polling_loop - ) + polling_loop, + ), ], - timeouts + timeouts, ); var wsStrategy; if (baseOptions.useTLS) { wsStrategy = new BestConnectedEverStrategy([ ws_loop, - new DelayedStrategy(http_loop, { delay: 2000 }) + new DelayedStrategy(http_loop, { delay: 2000 }), ]); } else { wsStrategy = new BestConnectedEverStrategy([ ws_loop, new DelayedStrategy(wss_loop, { delay: 2000 }), - new DelayedStrategy(http_loop, { delay: 5000 }) + new DelayedStrategy(http_loop, { delay: 5000 }), ]); } return new WebSocketPrioritizedCachedStrategy( new FirstConnectedStrategy( - new IfStrategy(testSupportsStrategy(ws_transport), wsStrategy, http_loop) + new IfStrategy(testSupportsStrategy(ws_transport), wsStrategy, http_loop), ), definedTransports, { ttl: 1800000, timeline: baseOptions.timeline, - useTLS: baseOptions.useTLS - } + useTLS: baseOptions.useTLS, + }, ); }; diff --git a/src/runtimes/isomorphic/http/http.ts b/src/runtimes/isomorphic/http/http.ts index abfe9e101..0da84d5cb 100644 --- a/src/runtimes/isomorphic/http/http.ts +++ b/src/runtimes/isomorphic/http/http.ts @@ -26,7 +26,7 @@ var HTTP: HTTPFactory = { createRequest(hooks: RequestHooks, method: string, url: string): HTTPRequest { return new HTTPRequest(hooks, method, url); - } + }, }; export default HTTP; diff --git a/src/runtimes/isomorphic/http/http_xhr_request.ts b/src/runtimes/isomorphic/http/http_xhr_request.ts index 38c244c21..a36024807 100644 --- a/src/runtimes/isomorphic/http/http_xhr_request.ts +++ b/src/runtimes/isomorphic/http/http_xhr_request.ts @@ -4,10 +4,10 @@ import Ajax from 'core/http/ajax'; import Runtime from 'runtime'; var hooks: RequestHooks = { - getRequest: function(socket: HTTPRequest): Ajax { + getRequest: function (socket: HTTPRequest): Ajax { var Constructor = Runtime.getXHRAPI(); var xhr = new Constructor(); - xhr.onreadystatechange = xhr.onprogress = function() { + xhr.onreadystatechange = xhr.onprogress = function () { switch (xhr.readyState) { case 3: if (xhr.responseText && xhr.responseText.length > 0) { @@ -26,10 +26,10 @@ var hooks: RequestHooks = { }; return xhr; }, - abortRequest: function(xhr: Ajax) { + abortRequest: function (xhr: Ajax) { xhr.onreadystatechange = null; xhr.abort(); - } + }, }; export default hooks; diff --git a/src/runtimes/isomorphic/runtime.ts b/src/runtimes/isomorphic/runtime.ts index 251b6ed56..62ba20ff6 100644 --- a/src/runtimes/isomorphic/runtime.ts +++ b/src/runtimes/isomorphic/runtime.ts @@ -23,9 +23,9 @@ var Isomorphic: any = { getClientFeatures(): any[] { return Collections.keys( - Collections.filterObject({ ws: Transports.ws }, function(t) { + Collections.filterObject({ ws: Transports.ws }, function (t) { return t.isSupported({}); - }) + }), ); }, @@ -56,7 +56,7 @@ var Isomorphic: any = { }, addUnloadListener(listener: any) {}, - removeUnloadListener(listener: any) {} + removeUnloadListener(listener: any) {}, }; export default Isomorphic; diff --git a/src/runtimes/isomorphic/timeline/xhr_timeline.ts b/src/runtimes/isomorphic/timeline/xhr_timeline.ts index 110e65206..c9fb2c0ea 100644 --- a/src/runtimes/isomorphic/timeline/xhr_timeline.ts +++ b/src/runtimes/isomorphic/timeline/xhr_timeline.ts @@ -5,8 +5,8 @@ import Util from 'core/util'; import Runtime from 'runtime'; import TimelineTransport from 'core/timeline/timeline_transport'; -var getAgent = function(sender: TimelineSender, useTLS: boolean) { - return function(data: any, callback: Function) { +var getAgent = function (sender: TimelineSender, useTLS: boolean) { + return function (data: any, callback: Function) { var scheme = 'http' + (useTLS ? 's' : '') + '://'; var url = scheme + (sender.host || sender.options.host) + sender.options.path; @@ -17,12 +17,12 @@ var getAgent = function(sender: TimelineSender, useTLS: boolean) { var xhr = Runtime.createXHR(); xhr.open('GET', url, true); - xhr.onreadystatechange = function() { + xhr.onreadystatechange = function () { if (xhr.readyState === 4) { let { status, responseText } = xhr; if (status !== 200) { Logger.debug( - `TimelineSender Error: received ${status} from stats.pusher.com` + `TimelineSender Error: received ${status} from stats.pusher.com`, ); return; } @@ -44,7 +44,7 @@ var getAgent = function(sender: TimelineSender, useTLS: boolean) { var xhr = { name: 'xhr', - getAgent + getAgent, }; export default xhr; diff --git a/src/runtimes/isomorphic/transports/transport_connection_initializer.ts b/src/runtimes/isomorphic/transports/transport_connection_initializer.ts index d606a902b..b7a73887f 100644 --- a/src/runtimes/isomorphic/transports/transport_connection_initializer.ts +++ b/src/runtimes/isomorphic/transports/transport_connection_initializer.ts @@ -2,13 +2,13 @@ * * Fetches resources if needed and then transitions to initialized. */ -export default function() { +export default function () { var self = this; self.timeline.info( self.buildTimelineMessage({ - transport: self.name + (self.options.useTLS ? 's' : '') - }) + transport: self.name + (self.options.useTLS ? 's' : ''), + }), ); if (self.hooks.isInitialized()) { diff --git a/src/runtimes/isomorphic/transports/transports.ts b/src/runtimes/isomorphic/transports/transports.ts index 6cb631e98..d209829dd 100644 --- a/src/runtimes/isomorphic/transports/transports.ts +++ b/src/runtimes/isomorphic/transports/transports.ts @@ -17,65 +17,67 @@ var WSTransport = new Transport({ handlesActivityChecks: false, supportsPing: false, - isInitialized: function() { + isInitialized: function () { return Boolean(Runtime.getWebSocketAPI()); }, - isSupported: function(): boolean { + isSupported: function (): boolean { return Boolean(Runtime.getWebSocketAPI()); }, - getSocket: function(url) { + getSocket: function (url) { return Runtime.createWebSocket(url); - } + }, }); var httpConfiguration = { urls: URLSchemes.http, handlesActivityChecks: false, supportsPing: true, - isInitialized: function() { + isInitialized: function () { return true; - } + }, }; export var streamingConfiguration = Collections.extend( { - getSocket: function(url) { + getSocket: function (url) { return Runtime.HTTPFactory.createStreamingSocket(url); - } + }, }, - httpConfiguration + httpConfiguration, ); export var pollingConfiguration = Collections.extend( { - getSocket: function(url) { + getSocket: function (url) { return Runtime.HTTPFactory.createPollingSocket(url); - } + }, }, - httpConfiguration + httpConfiguration, ); var xhrConfiguration = { - isSupported: function(): boolean { + isSupported: function (): boolean { return Runtime.isXHRSupported(); - } + }, }; /** HTTP streaming transport using CORS-enabled XMLHttpRequest. */ var XHRStreamingTransport = new Transport( ( Collections.extend({}, streamingConfiguration, xhrConfiguration) - ) + ), ); /** HTTP long-polling transport using CORS-enabled XMLHttpRequest. */ var XHRPollingTransport = new Transport( - Collections.extend({}, pollingConfiguration, xhrConfiguration) + ( + Collections.extend({}, pollingConfiguration, xhrConfiguration) + ), ); var Transports: TransportsTable = { ws: WSTransport, xhr_streaming: XHRStreamingTransport, - xhr_polling: XHRPollingTransport + xhr_polling: XHRPollingTransport, }; export default Transports; diff --git a/src/runtimes/node/runtime.ts b/src/runtimes/node/runtime.ts index 09bd5e5fd..146fee956 100644 --- a/src/runtimes/node/runtime.ts +++ b/src/runtimes/node/runtime.ts @@ -24,7 +24,7 @@ const { removeUnloadListener, transportConnectionInitializer, createSocketRequest, - HTTPFactory + HTTPFactory, } = Isomorphic; const NodeJS: Runtime = { @@ -62,7 +62,7 @@ const NodeJS: Runtime = { randomInt(max: number): number { return randomInt(max); - } + }, }; export default NodeJS; diff --git a/src/runtimes/react-native/net_info.ts b/src/runtimes/react-native/net_info.ts index 6da12b460..45ddfa01c 100644 --- a/src/runtimes/react-native/net_info.ts +++ b/src/runtimes/react-native/net_info.ts @@ -14,11 +14,11 @@ export class NetInfo extends EventsDispatcher implements Reachability { super(); this.online = true; - NativeNetInfo.fetch().then(connectionState => { + NativeNetInfo.fetch().then((connectionState) => { this.online = hasOnlineConnectionState(connectionState); }); - NativeNetInfo.addEventListener(connectionState => { + NativeNetInfo.addEventListener((connectionState) => { var isNowOnline = hasOnlineConnectionState(connectionState); // React Native counts the switch from Wi-Fi to Cellular diff --git a/src/runtimes/react-native/runtime.ts b/src/runtimes/react-native/runtime.ts index 50536f191..6f06888b9 100644 --- a/src/runtimes/react-native/runtime.ts +++ b/src/runtimes/react-native/runtime.ts @@ -21,7 +21,7 @@ const { removeUnloadListener, transportConnectionInitializer, createSocketRequest, - HTTPFactory + HTTPFactory, } = Isomorphic; const ReactNative: Runtime = { @@ -59,7 +59,7 @@ const ReactNative: Runtime = { randomInt(max: number): number { return Math.floor(Math.random() * max); - } + }, }; export default ReactNative; diff --git a/src/runtimes/web/auth/jsonp_auth.ts b/src/runtimes/web/auth/jsonp_auth.ts index f4934b2d3..4bc708e67 100644 --- a/src/runtimes/web/auth/jsonp_auth.ts +++ b/src/runtimes/web/auth/jsonp_auth.ts @@ -6,22 +6,22 @@ import { AuthTransport } from 'core/auth/auth_transports'; import { AuthRequestType, AuthTransportCallback, - InternalAuthOptions + InternalAuthOptions, } from 'core/auth/options'; -var jsonp: AuthTransport = function( +var jsonp: AuthTransport = function ( context: Browser, query: string, authOptions: InternalAuthOptions, authRequestType: AuthRequestType, - callback: AuthTransportCallback + callback: AuthTransportCallback, ) { if ( authOptions.headers !== undefined || authOptions.headersProvider != null ) { Logger.warn( - `To send headers with the ${authRequestType.toString()} request, you must use AJAX, rather than JSONP.` + `To send headers with the ${authRequestType.toString()} request, you must use AJAX, rather than JSONP.`, ); } @@ -31,7 +31,7 @@ var jsonp: AuthTransport = function( var document = context.getDocument(); var script = document.createElement('script'); // Hacked wrapper. - context.auth_callbacks[callbackName] = function(data) { + context.auth_callbacks[callbackName] = function (data) { callback(null, data); }; diff --git a/src/runtimes/web/default_strategy.ts b/src/runtimes/web/default_strategy.ts index ec274fa3f..48aeeb2ca 100644 --- a/src/runtimes/web/default_strategy.ts +++ b/src/runtimes/web/default_strategy.ts @@ -5,7 +5,7 @@ import StrategyOptions from 'core/strategies/strategy_options'; import SequentialStrategy from 'core/strategies/sequential_strategy'; import BestConnectedEverStrategy from 'core/strategies/best_connected_ever_strategy'; import WebSocketPrioritizedCachedStrategy, { - TransportStrategyDictionary + TransportStrategyDictionary, } from 'core/strategies/websocket_prioritized_cached_strategy'; import DelayedStrategy from 'core/strategies/delayed_strategy'; import IfStrategy from 'core/strategies/if_strategy'; @@ -13,15 +13,15 @@ import FirstConnectedStrategy from 'core/strategies/first_connected_strategy'; import { Config } from 'core/config'; function testSupportsStrategy(strategy: Strategy) { - return function() { + return function () { return strategy.isSupported(); }; } -var getDefaultStrategy = function( +var getDefaultStrategy = function ( config: Config, baseOptions: StrategyOptions, - defineTransport: Function + defineTransport: Function, ): Strategy { var definedTransports = {}; @@ -30,7 +30,7 @@ var getDefaultStrategy = function( type: string, priority: number, options: StrategyOptions, - manager?: TransportManager + manager?: TransportManager, ) { var transport = defineTransport( config, @@ -38,7 +38,7 @@ var getDefaultStrategy = function( type, priority, options, - manager + manager, ); definedTransports[name] = transport; @@ -49,31 +49,31 @@ var getDefaultStrategy = function( var ws_options: StrategyOptions = Object.assign({}, baseOptions, { hostNonTLS: config.wsHost + ':' + config.wsPort, hostTLS: config.wsHost + ':' + config.wssPort, - httpPath: config.wsPath + httpPath: config.wsPath, }); var wss_options: StrategyOptions = Object.assign({}, ws_options, { - useTLS: true + useTLS: true, }); var sockjs_options: StrategyOptions = Object.assign({}, baseOptions, { hostNonTLS: config.httpHost + ':' + config.httpPort, hostTLS: config.httpHost + ':' + config.httpsPort, - httpPath: config.httpPath + httpPath: config.httpPath, }); var timeouts = { loop: true, timeout: 15000, - timeoutLimit: 60000 + timeoutLimit: 60000, }; var ws_manager = new TransportManager({ minPingDelay: 10000, - maxPingDelay: config.activityTimeout + maxPingDelay: config.activityTimeout, }); var streaming_manager = new TransportManager({ lives: 2, minPingDelay: 10000, - maxPingDelay: config.activityTimeout + maxPingDelay: config.activityTimeout, }); var ws_transport = defineTransportStrategy( @@ -81,46 +81,46 @@ var getDefaultStrategy = function( 'ws', 3, ws_options, - ws_manager + ws_manager, ); var wss_transport = defineTransportStrategy( 'wss', 'ws', 3, wss_options, - ws_manager + ws_manager, ); var sockjs_transport = defineTransportStrategy( 'sockjs', 'sockjs', 1, - sockjs_options + sockjs_options, ); var xhr_streaming_transport = defineTransportStrategy( 'xhr_streaming', 'xhr_streaming', 1, sockjs_options, - streaming_manager + streaming_manager, ); var xdr_streaming_transport = defineTransportStrategy( 'xdr_streaming', 'xdr_streaming', 1, sockjs_options, - streaming_manager + streaming_manager, ); var xhr_polling_transport = defineTransportStrategy( 'xhr_polling', 'xhr_polling', 1, - sockjs_options + sockjs_options, ); var xdr_polling_transport = defineTransportStrategy( 'xdr_polling', 'xdr_polling', 1, - sockjs_options + sockjs_options, ); var ws_loop = new SequentialStrategy([ws_transport], timeouts); @@ -131,20 +131,20 @@ var getDefaultStrategy = function( new IfStrategy( testSupportsStrategy(xhr_streaming_transport), xhr_streaming_transport, - xdr_streaming_transport - ) + xdr_streaming_transport, + ), ], - timeouts + timeouts, ); var polling_loop = new SequentialStrategy( [ new IfStrategy( testSupportsStrategy(xhr_polling_transport), xhr_polling_transport, - xdr_polling_transport - ) + xdr_polling_transport, + ), ], - timeouts + timeouts, ); var http_loop = new SequentialStrategy( @@ -153,31 +153,31 @@ var getDefaultStrategy = function( testSupportsStrategy(streaming_loop), new BestConnectedEverStrategy([ streaming_loop, - new DelayedStrategy(polling_loop, { delay: 4000 }) + new DelayedStrategy(polling_loop, { delay: 4000 }), ]), - polling_loop - ) + polling_loop, + ), ], - timeouts + timeouts, ); var http_fallback_loop = new IfStrategy( testSupportsStrategy(http_loop), http_loop, - sockjs_loop + sockjs_loop, ); var wsStrategy; if (baseOptions.useTLS) { wsStrategy = new BestConnectedEverStrategy([ ws_loop, - new DelayedStrategy(http_fallback_loop, { delay: 2000 }) + new DelayedStrategy(http_fallback_loop, { delay: 2000 }), ]); } else { wsStrategy = new BestConnectedEverStrategy([ ws_loop, new DelayedStrategy(wss_loop, { delay: 2000 }), - new DelayedStrategy(http_fallback_loop, { delay: 5000 }) + new DelayedStrategy(http_fallback_loop, { delay: 5000 }), ]); } @@ -186,15 +186,15 @@ var getDefaultStrategy = function( new IfStrategy( testSupportsStrategy(ws_transport), wsStrategy, - http_fallback_loop - ) + http_fallback_loop, + ), ), definedTransports, { ttl: 1800000, timeline: baseOptions.timeline, - useTLS: baseOptions.useTLS - } + useTLS: baseOptions.useTLS, + }, ); }; diff --git a/src/runtimes/web/dom/dependencies.ts b/src/runtimes/web/dom/dependencies.ts index 00c3aad3b..a21bea00e 100644 --- a/src/runtimes/web/dom/dependencies.ts +++ b/src/runtimes/web/dom/dependencies.ts @@ -4,7 +4,7 @@ import DependencyLoader from './dependency_loader'; export var DependenciesReceivers = new ScriptReceiverFactory( '_pusher_dependencies', - 'Pusher.DependenciesReceivers' + 'Pusher.DependenciesReceivers', ); export var Dependencies = new DependencyLoader({ @@ -12,5 +12,5 @@ export var Dependencies = new DependencyLoader({ cdn_https: Defaults.cdn_https, version: Defaults.VERSION, suffix: Defaults.dependency_suffix, - receivers: DependenciesReceivers + receivers: DependenciesReceivers, }); diff --git a/src/runtimes/web/dom/dependency_loader.ts b/src/runtimes/web/dom/dependency_loader.ts index 0c1833d3b..0cdc70c78 100644 --- a/src/runtimes/web/dom/dependency_loader.ts +++ b/src/runtimes/web/dom/dependency_loader.ts @@ -1,6 +1,6 @@ import { ScriptReceivers, - ScriptReceiverFactory + ScriptReceiverFactory, } from './script_receiver_factory'; import Runtime from 'runtime'; import ScriptRequest from './script_request'; @@ -45,14 +45,14 @@ export default class DependencyLoader { self.loading[name] = [callback]; var request = Runtime.createScriptRequest(self.getPath(name, options)); - var receiver = self.receivers.create(function(error) { + var receiver = self.receivers.create(function (error) { self.receivers.remove(receiver); if (self.loading[name]) { var callbacks = self.loading[name]; delete self.loading[name]; - var successCallback = function(wasSuccessful) { + var successCallback = function (wasSuccessful) { if (!wasSuccessful) { request.cleanup(); } diff --git a/src/runtimes/web/dom/script_receiver_factory.ts b/src/runtimes/web/dom/script_receiver_factory.ts index 3b44ce469..74b190437 100644 --- a/src/runtimes/web/dom/script_receiver_factory.ts +++ b/src/runtimes/web/dom/script_receiver_factory.ts @@ -35,7 +35,7 @@ export class ScriptReceiverFactory { var name = this.name + '[' + number + ']'; var called = false; - var callbackWrapper = function() { + var callbackWrapper = function () { if (!called) { callback.apply(null, arguments); called = true; @@ -53,5 +53,5 @@ export class ScriptReceiverFactory { export var ScriptReceivers = new ScriptReceiverFactory( '_pusher_script_', - 'Pusher.ScriptReceivers' + 'Pusher.ScriptReceivers', ); diff --git a/src/runtimes/web/dom/script_request.ts b/src/runtimes/web/dom/script_request.ts index 88dbf3130..561c340a8 100644 --- a/src/runtimes/web/dom/script_request.ts +++ b/src/runtimes/web/dom/script_request.ts @@ -29,14 +29,14 @@ export default class ScriptRequest { self.script.charset = 'UTF-8'; if (self.script.addEventListener) { - self.script.onerror = function() { + self.script.onerror = function () { receiver.callback(errorString); }; - self.script.onload = function() { + self.script.onload = function () { receiver.callback(null); }; } else { - self.script.onreadystatechange = function() { + self.script.onreadystatechange = function () { if ( self.script.readyState === 'loaded' || self.script.readyState === 'complete' diff --git a/src/runtimes/web/http/http.ts b/src/runtimes/web/http/http.ts index 08054e418..67968d13a 100644 --- a/src/runtimes/web/http/http.ts +++ b/src/runtimes/web/http/http.ts @@ -1,7 +1,7 @@ import xdrHooks from './http_xdomain_request'; import HTTP from 'isomorphic/http/http'; -HTTP.createXDR = function(method, url) { +HTTP.createXDR = function (method, url) { return this.createRequest(xdrHooks, method, url); }; diff --git a/src/runtimes/web/http/http_xdomain_request.ts b/src/runtimes/web/http/http_xdomain_request.ts index 966b9e637..ffe7a5fbf 100644 --- a/src/runtimes/web/http/http_xdomain_request.ts +++ b/src/runtimes/web/http/http_xdomain_request.ts @@ -4,22 +4,22 @@ import Ajax from 'core/http/ajax'; import * as Errors from 'core/errors'; var hooks: RequestHooks = { - getRequest: function(socket: HTTPRequest): Ajax { + getRequest: function (socket: HTTPRequest): Ajax { var xdr = new (window).XDomainRequest(); - xdr.ontimeout = function() { + xdr.ontimeout = function () { socket.emit('error', new Errors.RequestTimedOut()); socket.close(); }; - xdr.onerror = function(e) { + xdr.onerror = function (e) { socket.emit('error', e); socket.close(); }; - xdr.onprogress = function() { + xdr.onprogress = function () { if (xdr.responseText && xdr.responseText.length > 0) { socket.onChunk(200, xdr.responseText); } }; - xdr.onload = function() { + xdr.onload = function () { if (xdr.responseText && xdr.responseText.length > 0) { socket.onChunk(200, xdr.responseText); } @@ -28,10 +28,10 @@ var hooks: RequestHooks = { }; return xdr; }, - abortRequest: function(xdr: Ajax) { + abortRequest: function (xdr: Ajax) { xdr.ontimeout = xdr.onerror = xdr.onprogress = xdr.onload = null; xdr.abort(); - } + }, }; export default hooks; diff --git a/src/runtimes/web/net_info.ts b/src/runtimes/web/net_info.ts index e9a80d918..d27621be4 100644 --- a/src/runtimes/web/net_info.ts +++ b/src/runtimes/web/net_info.ts @@ -15,17 +15,17 @@ export class NetInfo extends EventsDispatcher implements Reachability { if (window.addEventListener !== undefined) { window.addEventListener( 'online', - function() { + function () { self.emit('online'); }, - false + false, ); window.addEventListener( 'offline', - function() { + function () { self.emit('offline'); }, - false + false, ); } } diff --git a/src/runtimes/web/runtime.ts b/src/runtimes/web/runtime.ts index b599f0d6b..66804fca4 100644 --- a/src/runtimes/web/runtime.ts +++ b/src/runtimes/web/runtime.ts @@ -160,7 +160,7 @@ var Runtime: Browser = { /** * Return values in the range of [0, 1[ */ - const random = function() { + const random = function () { const crypto = window.crypto || window['msCrypto']; const random = crypto.getRandomValues(new Uint32Array(1))[0]; @@ -168,7 +168,7 @@ var Runtime: Browser = { }; return Math.floor(random() * max); - } + }, }; export default Runtime; diff --git a/src/runtimes/web/timeline/jsonp_timeline.ts b/src/runtimes/web/timeline/jsonp_timeline.ts index f67a0639c..e641c0332 100644 --- a/src/runtimes/web/timeline/jsonp_timeline.ts +++ b/src/runtimes/web/timeline/jsonp_timeline.ts @@ -4,14 +4,14 @@ import Browser from 'runtime'; import { AuthTransport } from 'core/auth/auth_transports'; import { ScriptReceivers } from '../dom/script_receiver_factory'; -var getAgent = function(sender: TimelineSender, useTLS: boolean) { - return function(data: any, callback: Function) { +var getAgent = function (sender: TimelineSender, useTLS: boolean) { + return function (data: any, callback: Function) { var scheme = 'http' + (useTLS ? 's' : '') + '://'; var url = scheme + (sender.host || sender.options.host) + sender.options.path; var request = Browser.createJSONPRequest(url, data); - var receiver = Browser.ScriptReceivers.create(function(error, result) { + var receiver = Browser.ScriptReceivers.create(function (error, result) { ScriptReceivers.remove(receiver); request.cleanup(); @@ -28,7 +28,7 @@ var getAgent = function(sender: TimelineSender, useTLS: boolean) { var jsonp = { name: 'jsonp', - getAgent + getAgent, }; export default jsonp; diff --git a/src/runtimes/web/transports/transport_connection_initializer.ts b/src/runtimes/web/transports/transport_connection_initializer.ts index fa1e4dda6..880cab973 100644 --- a/src/runtimes/web/transports/transport_connection_initializer.ts +++ b/src/runtimes/web/transports/transport_connection_initializer.ts @@ -4,13 +4,13 @@ import { Dependencies } from '../dom/dependencies'; * * Fetches resources if needed and then transitions to initialized. */ -export default function() { +export default function () { var self = this; self.timeline.info( self.buildTimelineMessage({ - transport: self.name + (self.options.useTLS ? 's' : '') - }) + transport: self.name + (self.options.useTLS ? 's' : ''), + }), ); if (self.hooks.isInitialized()) { @@ -20,7 +20,7 @@ export default function() { Dependencies.load( self.hooks.file, { useTLS: self.options.useTLS }, - function(error, callback) { + function (error, callback) { if (self.hooks.isInitialized()) { self.changeState('initialized'); callback(true); @@ -31,7 +31,7 @@ export default function() { self.onClose(); callback(false); } - } + }, ); } else { self.onClose(); diff --git a/src/runtimes/web/transports/transports.ts b/src/runtimes/web/transports/transports.ts index 907a685f5..d61300cbd 100644 --- a/src/runtimes/web/transports/transports.ts +++ b/src/runtimes/web/transports/transports.ts @@ -1,7 +1,7 @@ import { default as Transports, streamingConfiguration, - pollingConfiguration + pollingConfiguration, } from 'isomorphic/transports/transports'; import Transport from 'core/transports/transport'; import TransportHooks from 'core/transports/transport_hooks'; @@ -16,46 +16,48 @@ var SockJSTransport = new Transport({ handlesActivityChecks: true, supportsPing: false, - isSupported: function() { + isSupported: function () { return true; }, - isInitialized: function() { + isInitialized: function () { return window.SockJS !== undefined; }, - getSocket: function(url, options) { + getSocket: function (url, options) { return new window.SockJS(url, null, { js_path: Dependencies.getPath('sockjs', { - useTLS: options.useTLS + useTLS: options.useTLS, }), - ignore_null_origin: options.ignoreNullOrigin + ignore_null_origin: options.ignoreNullOrigin, }); }, - beforeOpen: function(socket, path) { + beforeOpen: function (socket, path) { socket.send( JSON.stringify({ - path: path - }) + path: path, + }), ); - } + }, }); var xdrConfiguration = { - isSupported: function(environment): boolean { + isSupported: function (environment): boolean { var yes = Runtime.isXDRSupported(environment.useTLS); return yes; - } + }, }; /** HTTP streaming transport using XDomainRequest (IE 8,9). */ var XDRStreamingTransport = new Transport( ( Collections.extend({}, streamingConfiguration, xdrConfiguration) - ) + ), ); /** HTTP long-polling transport using XDomainRequest (IE 8,9). */ var XDRPollingTransport = new Transport( - Collections.extend({}, pollingConfiguration, xdrConfiguration) + ( + Collections.extend({}, pollingConfiguration, xdrConfiguration) + ), ); Transports.xdr_streaming = XDRStreamingTransport; diff --git a/src/runtimes/worker/auth/fetch_auth.ts b/src/runtimes/worker/auth/fetch_auth.ts index 3a4c6e69f..6b608ea39 100644 --- a/src/runtimes/worker/auth/fetch_auth.ts +++ b/src/runtimes/worker/auth/fetch_auth.ts @@ -3,16 +3,16 @@ import { AuthTransport } from 'core/auth/auth_transports'; import { AuthRequestType, AuthTransportCallback, - InternalAuthOptions + InternalAuthOptions, } from 'core/auth/options'; import { HTTPAuthError } from 'core/errors'; -var fetchAuth: AuthTransport = function( +var fetchAuth: AuthTransport = function ( context: AbstractRuntime, query: string, authOptions: InternalAuthOptions, authRequestType: AuthRequestType, - callback: AuthTransportCallback + callback: AuthTransportCallback, ) { var headers = new Headers(); headers.set('Content-Type', 'application/x-www-form-urlencoded'); @@ -33,11 +33,11 @@ var fetchAuth: AuthTransport = function( headers, body, credentials: 'same-origin', - method: 'POST' + method: 'POST', }); return fetch(request) - .then(response => { + .then((response) => { let { status } = response; if (status === 200) { // manually parse the json so we can provide a more helpful error in @@ -46,22 +46,22 @@ var fetchAuth: AuthTransport = function( } throw new HTTPAuthError( status, - `Could not get ${authRequestType.toString()} info from your auth endpoint, status: ${status}` + `Could not get ${authRequestType.toString()} info from your auth endpoint, status: ${status}`, ); }) - .then(data => { + .then((data) => { let parsedData; try { parsedData = JSON.parse(data); } catch (e) { throw new HTTPAuthError( 200, - `JSON returned from ${authRequestType.toString()} endpoint was invalid, yet status code was 200. Data was: ${data}` + `JSON returned from ${authRequestType.toString()} endpoint was invalid, yet status code was 200. Data was: ${data}`, ); } callback(null, parsedData); }) - .catch(err => { + .catch((err) => { callback(err, null); }); }; diff --git a/src/runtimes/worker/runtime.ts b/src/runtimes/worker/runtime.ts index 616e2d83d..135c2a946 100644 --- a/src/runtimes/worker/runtime.ts +++ b/src/runtimes/worker/runtime.ts @@ -21,7 +21,7 @@ const { removeUnloadListener, transportConnectionInitializer, createSocketRequest, - HTTPFactory + HTTPFactory, } = Isomorphic; const Worker: Runtime = { @@ -61,7 +61,7 @@ const Worker: Runtime = { /** * Return values in the range of [0, 1[ */ - const random = function() { + const random = function () { const crypto = globalThis.crypto || globalThis['msCrypto']; const random = crypto.getRandomValues(new Uint32Array(1))[0]; @@ -69,7 +69,7 @@ const Worker: Runtime = { }; return Math.floor(random() * max); - } + }, }; export default Worker; diff --git a/src/runtimes/worker/timeline/fetch_timeline.ts b/src/runtimes/worker/timeline/fetch_timeline.ts index 0a27cbb71..5deb50fe9 100644 --- a/src/runtimes/worker/timeline/fetch_timeline.ts +++ b/src/runtimes/worker/timeline/fetch_timeline.ts @@ -5,8 +5,8 @@ import Util from 'core/util'; import Runtime from 'runtime'; import TimelineTransport from 'core/timeline/timeline_transport'; -var getAgent = function(sender: TimelineSender, useTLS: boolean) { - return function(data: any, callback: Function) { +var getAgent = function (sender: TimelineSender, useTLS: boolean) { + return function (data: any, callback: Function) { var scheme = 'http' + (useTLS ? 's' : '') + '://'; var url = scheme + (sender.host || sender.options.host) + sender.options.path; @@ -14,7 +14,7 @@ var getAgent = function(sender: TimelineSender, useTLS: boolean) { url += '/' + 2 + '?' + query; fetch(url) - .then(response => { + .then((response) => { if (response.status !== 200) { throw `received ${response.status} from stats.pusher.com`; } @@ -25,7 +25,7 @@ var getAgent = function(sender: TimelineSender, useTLS: boolean) { sender.host = host; } }) - .catch(err => { + .catch((err) => { Logger.debug('TimelineSender Error: ', err); }); }; @@ -33,7 +33,7 @@ var getAgent = function(sender: TimelineSender, useTLS: boolean) { var fetchTimeline = { name: 'xhr', - getAgent + getAgent, }; export default fetchTimeline; diff --git a/webpack/config.node.js b/webpack/config.node.js index 5fcef1519..1cf8cdb4c 100644 --- a/webpack/config.node.js +++ b/webpack/config.node.js @@ -5,22 +5,22 @@ var webpack = require('webpack'); module.exports = merge({}, configShared, { entry: { - pusher: './src/core/pusher-with-encryption.js' + pusher: './src/core/pusher-with-encryption.js', }, output: { library: 'Pusher', libraryTarget: 'commonjs2', path: path.join(__dirname, '../dist/node'), - filename: 'pusher.js' + filename: 'pusher.js', }, target: 'node', resolve: { // in order to import the appropriate runtime.ts - modules: ['src/runtimes/node'] + modules: ['src/runtimes/node'], }, plugins: [ new webpack.DefinePlugin({ - RUNTIME: JSON.stringify('node') - }) - ] + RUNTIME: JSON.stringify('node'), + }), + ], }); diff --git a/webpack/config.react-native.js b/webpack/config.react-native.js index b23f7eba6..d67e6652e 100644 --- a/webpack/config.react-native.js +++ b/webpack/config.react-native.js @@ -1,6 +1,6 @@ var path = require('path'); -var NormalModuleReplacementPlugin = require('webpack') - .NormalModuleReplacementPlugin; +var NormalModuleReplacementPlugin = + require('webpack').NormalModuleReplacementPlugin; var version = require('../package').version; const { merge } = require('webpack-merge'); var configShared = require('./config.shared'); @@ -9,27 +9,27 @@ var buffer = require('buffer'); module.exports = merge({}, configShared, { entry: { - pusher: './src/core/pusher-with-encryption.js' + pusher: './src/core/pusher-with-encryption.js', }, output: { library: 'Pusher', libraryTarget: 'commonjs2', path: path.join(__dirname, '../dist/react-native'), - filename: 'pusher.js' + filename: 'pusher.js', }, externals: { // our Reachability implementation needs to reference @react-native-community/netinfo. - '@react-native-community/netinfo': '@react-native-community/netinfo' + '@react-native-community/netinfo': '@react-native-community/netinfo', }, resolve: { - modules: ['src/runtimes/react-native'] + modules: ['src/runtimes/react-native'], }, plugins: [ new webpack.DefinePlugin({ - RUNTIME: JSON.stringify('react-native') + RUNTIME: JSON.stringify('react-native'), }), new webpack.ProvidePlugin({ - Buffer: ['buffer', 'Buffer'] - }) - ] + Buffer: ['buffer', 'Buffer'], + }), + ], }); diff --git a/webpack/config.shared.js b/webpack/config.shared.js index 9883059a6..9f839e500 100644 --- a/webpack/config.shared.js +++ b/webpack/config.shared.js @@ -11,16 +11,16 @@ var minimize = process.env.MINIMIZE === 'false' ? false : true; module.exports = { mode: process.env.MODE || 'production', optimization: { - minimize: minimize + minimize: minimize, }, entry: { - pusher: './src/core/pusher.js' + pusher: './src/core/pusher.js', }, devtool: 'source-map', resolve: { extensions: ['.webpack.js', '.web.js', '.ts', '.js'], // add runtimes for easier importing of isomorphic runtime modules - modules: ['src', 'src/runtimes', 'node_modules'] + modules: ['src', 'src/runtimes', 'node_modules'], }, module: { rules: [ @@ -28,15 +28,15 @@ module.exports = { { test: /\.js$/, enforce: 'pre', - use: ['source-map-loader'] - } - ] + use: ['source-map-loader'], + }, + ], }, node: { // nacl uses Buffer on node.js but has a different code path for the browser. // We don't need webpack to include a Buffer polyfill when seeing the usage, // as it won't be used. - Buffer: false + Buffer: false, }, plugins: [ new webpack.BannerPlugin({ banner: banner, raw: true }), @@ -44,7 +44,7 @@ module.exports = { VERSION: JSON.stringify(Config.version), CDN_HTTP: JSON.stringify(Config.cdn_http), CDN_HTTPS: JSON.stringify(Config.cdn_https), - DEPENDENCY_SUFFIX: JSON.stringify(Config.dependency_suffix) - }) - ] + DEPENDENCY_SUFFIX: JSON.stringify(Config.dependency_suffix), + }), + ], }; diff --git a/webpack/config.web.js b/webpack/config.web.js index d009a64c0..755639caf 100644 --- a/webpack/config.web.js +++ b/webpack/config.web.js @@ -16,21 +16,21 @@ if (process.env.INCLUDE_TWEETNACL === 'true') { module.exports = merge({}, configShared, { entry: { - pusher: entry + pusher: entry, }, output: { library: 'Pusher', path: path.join(__dirname, '../dist/web'), filename: filename, - libraryTarget: 'umd' + libraryTarget: 'umd', }, resolve: { - modules: ['src/runtimes/web'] + modules: ['src/runtimes/web'], }, plugins: [ new webpack.DefinePlugin({ global: 'window', - RUNTIME: JSON.stringify('web') - }) - ] + RUNTIME: JSON.stringify('web'), + }), + ], }); diff --git a/webpack/config.worker.js b/webpack/config.worker.js index ab97cf915..b6283826f 100644 --- a/webpack/config.worker.js +++ b/webpack/config.worker.js @@ -1,6 +1,6 @@ var path = require('path'); -var NormalModuleReplacementPlugin = require('webpack') - .NormalModuleReplacementPlugin; +var NormalModuleReplacementPlugin = + require('webpack').NormalModuleReplacementPlugin; var version = require('../package').version; const { merge } = require('webpack-merge'); var webpack = require('webpack'); @@ -18,25 +18,25 @@ if (process.env.INCLUDE_TWEETNACL === 'true') { var config = merge(configShared, { entry: { - pusher: entry + pusher: entry, }, output: { library: 'Pusher', path: path.join(__dirname, '../dist/worker'), filename: filename, libraryTarget: 'umd', - globalObject: 'this' + globalObject: 'this', }, resolve: { // in order to import the appropriate runtime.ts - modules: ['src/runtimes/worker'] + modules: ['src/runtimes/worker'], }, plugins: [ new webpack.DefinePlugin({ global: 'self', - RUNTIME: JSON.stringify('worker') - }) - ] + RUNTIME: JSON.stringify('worker'), + }), + ], }); module.exports = config; diff --git a/webpack/dev.server.js b/webpack/dev.server.js index e8c8faafe..0043bea26 100644 --- a/webpack/dev.server.js +++ b/webpack/dev.server.js @@ -6,12 +6,12 @@ var port = parseInt(process.env.PORT) || 5555; config.entry.app = [ 'webpack-dev-server/client?http://localhost:' + port + '/', - 'webpack/hot/dev-server' + 'webpack/hot/dev-server', ]; var compiler = webpack(config); var server = new WebpackDevServer(compiler, { - hot: true + hot: true, }); server.listen(port); diff --git a/webpack/hosting_config.js b/webpack/hosting_config.js index 3a1c806b7..b105d4a7f 100644 --- a/webpack/hosting_config.js +++ b/webpack/hosting_config.js @@ -2,5 +2,5 @@ module.exports = { version: process.env.VERSION || require('../package').version, cdn_http: process.env.CDN_HTTP || 'http://js.pusher.com', cdn_https: process.env.CDN_HTTPS || 'https://js.pusher.com', - dependency_suffix: process.env.MINIFY ? '.min' : '' + dependency_suffix: process.env.MINIFY ? '.min' : '', };