teckos-client 0.3.3 → 0.3.6

Sign up to get free protection for your applications and to get access to all the features.
Files changed (56) hide show
  1. package/dist/ITeckosClient.d.ts +18 -0
  2. package/dist/TeckosClient.d.ts +35 -0
  3. package/dist/TeckosClientWithJWT.d.ts +12 -0
  4. package/dist/index.d.ts +9 -0
  5. package/dist/index.js +40 -43
  6. package/dist/index.js.map +1 -0
  7. package/dist/index.min.js +1 -1
  8. package/dist/teckos-client.cjs.development.js +611 -0
  9. package/dist/teckos-client.cjs.development.js.map +1 -0
  10. package/dist/teckos-client.cjs.production.min.js +2 -0
  11. package/dist/teckos-client.cjs.production.min.js.map +1 -0
  12. package/dist/teckos-client.esm.js +608 -0
  13. package/dist/teckos-client.esm.js.map +1 -0
  14. package/dist/types/ConnectionState.d.ts +7 -0
  15. package/dist/types/Options.d.ts +10 -0
  16. package/dist/types/Packet.d.ts +6 -0
  17. package/dist/types/PacketType.d.ts +5 -0
  18. package/dist/types/SocketEvent.d.ts +10 -0
  19. package/dist/types/index.d.ts +7 -0
  20. package/dist/util/Converter.d.ts +4 -0
  21. package/dist/util/SocketEventEmitter.d.ts +23 -0
  22. package/es/index.js +34 -39
  23. package/es/index.mjs +1 -1
  24. package/lib/index.js +37 -58
  25. package/package.json +6 -7
  26. package/src/ITeckosClient.ts +2 -3
  27. package/src/TeckosClient.ts +29 -29
  28. package/src/TeckosClientWithJWT.ts +6 -6
  29. package/src/index.ts +3 -3
  30. package/types/ITeckosClient.d.ts +2 -3
  31. package/types/TeckosClient.d.ts +5 -5
  32. package/types/index.d.ts +3 -3
  33. package/src/ITeckosClient.js +0 -2
  34. package/src/ITeckosClient.js.map +0 -1
  35. package/src/TeckosClient.js +0 -235
  36. package/src/TeckosClient.js.map +0 -1
  37. package/src/TeckosClientWithJWT.js +0 -63
  38. package/src/TeckosClientWithJWT.js.map +0 -1
  39. package/src/index.js +0 -8
  40. package/src/index.js.map +0 -1
  41. package/src/types/ConnectionState.js +0 -9
  42. package/src/types/ConnectionState.js.map +0 -1
  43. package/src/types/Options.js +0 -2
  44. package/src/types/Options.js.map +0 -1
  45. package/src/types/Packet.js +0 -2
  46. package/src/types/Packet.js.map +0 -1
  47. package/src/types/PacketType.js +0 -7
  48. package/src/types/PacketType.js.map +0 -1
  49. package/src/types/SocketEvent.js +0 -2
  50. package/src/types/SocketEvent.js.map +0 -1
  51. package/src/types/index.js +0 -4
  52. package/src/types/index.js.map +0 -1
  53. package/src/util/Converter.js +0 -6
  54. package/src/util/Converter.js.map +0 -1
  55. package/src/util/SocketEventEmitter.js +0 -99
  56. package/src/util/SocketEventEmitter.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"teckos-client.esm.js","sources":["../src/util/Converter.ts","../src/types/PacketType.ts","../src/types/ConnectionState.ts","../src/util/SocketEventEmitter.ts","../src/TeckosClient.ts","../src/TeckosClientWithJWT.ts"],"sourcesContent":["import { Packet } from '../types'\n\nconst enc = new TextEncoder()\nconst dec = new TextDecoder()\n\nconst encodePacket = (packet: Packet): ArrayBufferLike => enc.encode(JSON.stringify(packet))\nconst decodePacket = (buffer: ArrayBuffer): Packet =>\n JSON.parse(dec.decode(buffer).toString()) as Packet\nexport { encodePacket, decodePacket }\n","enum PacketType {\n EVENT,\n ACK,\n}\nexport { PacketType }\n","enum ConnectionState {\n DISCONNECTED = 'disconnected',\n CONNECTING = 'connecting',\n CONNECTED = 'connected',\n DISCONNECTING = 'disconnecting',\n}\nexport { ConnectionState }\n","export type Listener = (...args: any[]) => void\n\nclass SocketEventEmitter<T extends string> {\n protected maxListeners = 50\n\n protected handlers: {\n [event: string]: ((...args: any[]) => void)[]\n } = {}\n\n public addListener = (event: T, listener: (...args: any[]) => void): this => {\n if (Object.keys(this.handlers).length === this.maxListeners) {\n throw new Error('Max listeners reached')\n }\n if (typeof listener !== 'function') {\n throw new Error('The given listener is not a function')\n }\n this.handlers[event] = this.handlers[event] || []\n this.handlers[event].push(listener)\n return this\n }\n\n public once = (event: T, listener: (...args: any[]) => void): this => {\n if (Object.keys(this.handlers).length === this.maxListeners) {\n throw new Error('Max listeners reached')\n }\n if (typeof listener !== 'function') {\n throw new Error('The given listener is not a function')\n }\n this.handlers[event] = this.handlers[event] || []\n const onceWrapper = () => {\n listener()\n this.off(event, onceWrapper)\n }\n this.handlers[event].push(onceWrapper)\n return this\n }\n\n public removeListener = (event: T, listener: (...args: any[]) => void): this => {\n if (this.handlers[event]) {\n this.handlers[event] = this.handlers[event].filter((handler) => handler !== listener)\n }\n return this\n }\n\n public off = (event: T, listener: (...args: any[]) => void): this =>\n this.removeListener(event, listener)\n\n public removeAllListeners = (event?: T): this => {\n if (event) {\n delete this.handlers[event]\n } else {\n this.handlers = {}\n }\n return this\n }\n\n public setMaxListeners = (n: number): this => {\n this.maxListeners = n\n return this\n }\n\n public getMaxListeners = (): number => this.maxListeners\n\n public listeners = (event: T): Listener[] => {\n if (this.handlers[event]) {\n return [...this.handlers[event]]\n }\n return []\n }\n\n public rawListeners = (event: T): Listener[] => [...this.handlers[event]]\n\n public listenerCount = (event: T): number => {\n if (this.handlers[event]) {\n return Object.keys(this.handlers[event]).length\n }\n return 0\n }\n\n public prependListener = (event: T, listener: (...args: any[]) => void): this => {\n if (Object.keys(this.handlers).length === this.maxListeners) {\n throw new Error('Max listeners reached')\n }\n this.handlers[event] = this.handlers[event] || []\n this.handlers[event].unshift(listener)\n return this\n }\n\n public prependOnceListener = (event: T, listener: (...args: any[]) => void): this => {\n if (Object.keys(this.handlers).length === this.maxListeners) {\n throw new Error('Max listeners reached')\n }\n this.handlers[event] = this.handlers[event] || []\n const onceWrapper = () => {\n listener()\n this.off(event, onceWrapper)\n }\n this.handlers[event].unshift(onceWrapper)\n return this\n }\n\n public eventNames = (): T[] => Object.keys(this.handlers) as T[]\n\n public on = (event: T, listener: (...args: any[]) => void): this =>\n this.addListener(event, listener)\n\n public emit = (event: T, ...args: any[]): boolean => {\n const listeners = this.listeners(event)\n if (listeners.length > 0) {\n listeners.forEach((listener) => {\n if (listener) listener(args)\n })\n return true\n }\n return false\n }\n}\n\nexport { SocketEventEmitter }\n","import debug from 'debug'\nimport WebSocket from 'isomorphic-ws'\nimport { decodePacket, encodePacket } from './util/Converter'\nimport { ConnectionState, OptionalOptions, Options, Packet, PacketType, SocketEvent } from './types'\nimport { ITeckosClient } from './ITeckosClient'\nimport { SocketEventEmitter } from './util/SocketEventEmitter'\n\nconst d = debug('teckos:client')\n\nconst DEFAULT_OPTIONS: Options = {\n reconnection: true,\n reconnectionDelay: 1000,\n reconnectionDelayMax: 5000,\n reconnectionAttempts: Infinity,\n randomizationFactor: 0.5,\n timeout: 5000,\n debug: false,\n}\n\nclass TeckosClient extends SocketEventEmitter<SocketEvent> implements ITeckosClient {\n protected readonly url: string\n\n protected readonly options: Options\n\n ws: WebSocket | undefined\n\n protected currentReconnectDelay: number\n\n protected currentReconnectionAttempts = 0\n\n protected acks: Map<number, (...args: any[]) => void> = new Map()\n\n protected fnId = 0\n\n protected connectionTimeout: any | undefined\n\n protected reconnectionTimeout: any | undefined\n\n constructor(url: string, options?: OptionalOptions) {\n super()\n this.options = {\n ...DEFAULT_OPTIONS,\n ...options,\n }\n this.currentReconnectDelay = this.options.reconnectionDelay\n this.url = url\n }\n\n protected attachHandler = (): void => {\n if (this.ws) {\n this.ws.onopen = this.handleOpen\n this.ws.onerror = this.handleError\n this.ws.onclose = this.handleClose\n this.ws.onmessage = this.handleMessage\n }\n }\n\n public get webSocket(): WebSocket | undefined {\n return this.ws\n }\n\n public connect = (): void => {\n if (this.options.debug) d(`Connecting to ${this.url}...`)\n\n // This will try to connect immediately\n this.ws = new WebSocket(this.url)\n // Attach handlers\n this.attachHandler()\n // Handle timeout\n this.connectionTimeout = setTimeout(() => {\n if (this.ws && this.ws.readyState === WebSocket.CONNECTING) {\n this.ws.close()\n }\n }, this.options.timeout)\n }\n\n protected reconnect = (): void => {\n this.listeners('reconnect_attempt').forEach((listener) => listener())\n this.connect()\n }\n\n protected getConnectionState(): ConnectionState {\n if (this.ws) {\n switch (this.ws.readyState) {\n case WebSocket.OPEN:\n return ConnectionState.CONNECTED\n case WebSocket.CONNECTING:\n return ConnectionState.CONNECTING\n case WebSocket.CLOSING:\n return ConnectionState.DISCONNECTING\n default:\n return ConnectionState.DISCONNECTED\n }\n }\n return ConnectionState.DISCONNECTED\n }\n\n public get state(): ConnectionState {\n return this.getConnectionState()\n }\n\n get connected(): boolean {\n return this.getConnectionState() === ConnectionState.CONNECTED\n }\n\n get disconnected(): boolean {\n return this.getConnectionState() === ConnectionState.DISCONNECTED\n }\n\n public emit = (event: SocketEvent, ...args: any[]): boolean => {\n args.unshift(event)\n\n const packet: Packet = {\n type: PacketType.EVENT,\n data: args,\n }\n\n if (typeof args[args.length - 1] === 'function') {\n this.acks.set(this.fnId, args.pop())\n packet.id = this.fnId\n this.fnId += 1\n }\n\n return this.sendPackage(packet)\n }\n\n public send = (...args: any[]): boolean => {\n args.unshift('message')\n return this.sendPackage({\n type: PacketType.EVENT,\n data: args,\n })\n }\n\n public sendPackage = (packet: Packet): boolean => {\n if (this.ws !== undefined && this.ws.readyState === WebSocket.OPEN) {\n const buffer = encodePacket(packet)\n if (this.options.debug) d(`[${this.url}] Send packet: ${JSON.stringify(packet)}`)\n this.ws.send(buffer)\n return true\n }\n return false\n }\n\n protected handleMessage = (msg: WebSocket.MessageEvent): void => {\n const packet =\n typeof msg.data === 'string'\n ? (JSON.parse(msg.data) as Packet)\n : decodePacket(msg.data as ArrayBuffer)\n if (this.options.debug) d(`[${this.url}] Got packet: ${JSON.stringify(packet)}`)\n if (packet.type === PacketType.EVENT) {\n const event = packet.data[0] as SocketEvent\n const args = packet.data.slice(1)\n if (event) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n this.listeners(event).forEach((listener) => listener(...args))\n } else {\n throw new Error(\n `[teckos-client@${this.url}] Got invalid event message: ${JSON.stringify(\n msg.data\n )}`\n )\n }\n } else if (packet.type === PacketType.ACK && packet.id !== undefined) {\n // Call assigned function\n const ack = this.acks.get(packet.id)\n if (typeof ack === 'function') {\n ack.apply(this, packet.data)\n this.acks.delete(packet.id)\n }\n } else {\n throw new Error(`[teckos-client@${this.url}] Got invalid message type: ${packet.type}`)\n }\n }\n\n protected handleOpen = (): void => {\n if (this.currentReconnectionAttempts > 0) {\n // Reset reconnection settings to default\n this.currentReconnectDelay = this.options.reconnectionDelay\n this.currentReconnectionAttempts = 0\n\n // Inform listeners\n if (this.options.debug) d(`[${this.url}] Reconnected!`)\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n this.listeners('reconnect').forEach((listener) => listener())\n }\n // Inform listeners\n if (this.options.debug) d(`[${this.url}] Connected!`)\n this.listeners('connect').forEach((listener) => listener())\n }\n\n protected handleError = (error: WebSocket.ErrorEvent): void => {\n if (this.handlers && this.handlers.error) {\n if (this.options.debug)\n d(`[${this.url}] Got error from server: ${JSON.stringify(error)}`)\n this.handlers.error.forEach((listener) => listener(error))\n }\n }\n\n protected handleClose = (): void => {\n // Stop connection timeout\n if (this.connectionTimeout) {\n clearTimeout(this.connectionTimeout)\n }\n // Stop reconnection timeout\n if (this.reconnectionTimeout) {\n clearTimeout(this.reconnectionTimeout)\n }\n\n // Inform listeners\n if (this.currentReconnectionAttempts > 0) {\n if (this.options.debug)\n d(`[${this.url}] Reconnect #${this.currentReconnectionAttempts} failed!`)\n this.listeners('reconnect_error').forEach((listener) => {\n if (listener) listener()\n })\n } else {\n if (this.options.debug) d(`[${this.url}] Disconnected!`)\n this.listeners('disconnect').forEach((listener) => {\n if (listener) listener()\n })\n }\n\n if (this.options.reconnection) {\n // Apply reconnection logic\n this.currentReconnectionAttempts += 1\n\n if (\n this.options.reconnectionAttempts === Infinity ||\n this.currentReconnectionAttempts <= this.options.reconnectionAttempts\n ) {\n const timeout = Math.min(\n this.options.reconnectionDelayMax,\n this.currentReconnectDelay\n )\n // Increase reconnection delay\n this.currentReconnectDelay = Math.round(\n this.currentReconnectDelay +\n this.currentReconnectDelay * this.options.randomizationFactor\n )\n\n if (this.options.debug)\n d(\n `[${this.url}] Try reconnecting (${this.currentReconnectionAttempts}/${this.options.reconnectionAttempts}) in ${timeout}ms to ${this.url}...`\n )\n this.reconnectionTimeout = setTimeout(() => {\n this.reconnect()\n }, timeout)\n } else {\n if (this.options.debug)\n d(\n `[${this.url}] Reconnection maximum of ${this.options.reconnectionAttempts} reached`\n )\n this.listeners('reconnect_failed').forEach((listener) => listener())\n }\n }\n }\n\n public close = (): void => {\n if (this.options.debug) d(`[${this.url}] Closing connection (client-side)`)\n if (this.ws !== undefined) {\n this.ws.onclose = () => {}\n this.ws.close()\n this.listeners('disconnect').forEach((listener) => listener())\n }\n }\n\n public disconnect = (): void => {\n this.close()\n }\n}\n\nexport { TeckosClient }\n","import debug from 'debug'\nimport WebSocket from 'isomorphic-ws'\nimport { TeckosClient } from './TeckosClient'\nimport { OptionalOptions, ConnectionState } from './types'\n\nconst d = debug('teckos:client')\n\nclass TeckosClientWithJWT extends TeckosClient {\n protected readonly token: string\n\n protected readonly initialData: any\n\n protected receivedReady = false\n\n // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\n constructor(url: string, options: OptionalOptions, token: string, initialData?: any) {\n super(url, options)\n this.token = token\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n this.initialData = initialData\n this.on('disconnect', () => {\n this.receivedReady = false\n })\n }\n\n protected getConnectionState(): ConnectionState {\n if (this.ws) {\n switch (this.ws.readyState) {\n case WebSocket.OPEN:\n if (this.receivedReady) {\n return ConnectionState.CONNECTED\n }\n return ConnectionState.CONNECTING\n case WebSocket.CONNECTING:\n return ConnectionState.CONNECTING\n case WebSocket.CLOSING:\n return ConnectionState.DISCONNECTING\n default:\n return ConnectionState.DISCONNECTED\n }\n }\n return ConnectionState.DISCONNECTED\n }\n\n protected handleReadyEvent = (): void => {\n if (this.options.debug) d(`[${this.url}] Connected!`)\n this.receivedReady = true\n if (this.currentReconnectionAttempts > 0) {\n if (this.options.debug) d(`[${this.url}] Reconnected!`)\n this.listeners('reconnect').forEach((listener) => listener())\n // Reset reconnection settings to default\n this.currentReconnectDelay = this.options.reconnectionDelay\n this.currentReconnectionAttempts = 0\n }\n this.listeners('connect').forEach((listener) => listener())\n }\n\n protected handleOpen = (): void => {\n this.receivedReady = false\n this.once('ready', this.handleReadyEvent)\n if (this.options.debug) d('Connection opened, sending token now')\n this.emit('token', {\n token: this.token,\n ...this.initialData,\n })\n }\n}\n\nexport { TeckosClientWithJWT }\n"],"names":["enc","TextEncoder","dec","TextDecoder","encodePacket","packet","encode","JSON","stringify","decodePacket","buffer","parse","decode","toString","PacketType","ConnectionState","SocketEventEmitter","event","listener","Object","keys","handlers","length","maxListeners","Error","push","onceWrapper","off","filter","handler","removeListener","n","unshift","addListener","args","listeners","forEach","d","debug","DEFAULT_OPTIONS","reconnection","reconnectionDelay","reconnectionDelayMax","reconnectionAttempts","Infinity","randomizationFactor","timeout","TeckosClient","url","options","Map","ws","onopen","handleOpen","onerror","handleError","onclose","handleClose","onmessage","handleMessage","WebSocket","attachHandler","connectionTimeout","setTimeout","readyState","CONNECTING","close","connect","type","EVENT","data","acks","set","fnId","pop","id","sendPackage","undefined","OPEN","send","msg","slice","ACK","ack","get","apply","currentReconnectionAttempts","currentReconnectDelay","error","clearTimeout","reconnectionTimeout","Math","min","round","reconnect","getConnectionState","CONNECTED","CLOSING","DISCONNECTING","DISCONNECTED","TeckosClientWithJWT","token","initialData","receivedReady","once","handleReadyEvent","emit","on"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,IAAMA,GAAG,gBAAG,IAAIC,WAAJ,EAAZ;AACA,IAAMC,GAAG,gBAAG,IAAIC,WAAJ,EAAZ;;AAEA,IAAMC,YAAY,GAAG,SAAfA,YAAe,CAACC,MAAD;AAAA,SAAqCL,GAAG,CAACM,MAAJ,CAAWC,IAAI,CAACC,SAAL,CAAeH,MAAf,CAAX,CAArC;AAAA,CAArB;;AACA,IAAMI,Y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AACT,cAAQ,KAAKA,EAAL,CAAQa,UAAhB;AACI,aAAKJ,SAAS,CAACkB,IAAf;AACI,cAAI,KAAKyB,aAAT,EAAwB;AACpB,mBAAOxF,eAAe,CAACiF,SAAvB;AACH;;AACD,iBAAOjF,eAAe,CAACkD,UAAvB;;AACJ,aAAKL,SAAS,CAACK,UAAf;AACI,iBAAOlD,eAAe,CAACkD,UAAvB;;AACJ,aAAKL,SAAS,CAACqC,OAAf;AACI,iBAAOlF,eAAe,CAACmF,aAAvB;;AACJ;AACI,iBAAOnF,eAAe,CAACoF,YAAvB;AAXR;AAaH;;AACD,WAAOpF,eAAe,CAACoF,YAAvB;AACH;;;EAnC6BpD;;;;"}
@@ -0,0 +1,7 @@
1
+ declare enum ConnectionState {
2
+ DISCONNECTED = "disconnected",
3
+ CONNECTING = "connecting",
4
+ CONNECTED = "connected",
5
+ DISCONNECTING = "disconnecting"
6
+ }
7
+ export { ConnectionState };
@@ -0,0 +1,10 @@
1
+ export interface Options {
2
+ reconnection: boolean;
3
+ reconnectionAttempts: number;
4
+ reconnectionDelay: number;
5
+ reconnectionDelayMax: number;
6
+ randomizationFactor: number;
7
+ timeout: number;
8
+ debug: boolean;
9
+ }
10
+ export declare type OptionalOptions = Partial<Options>;
@@ -0,0 +1,6 @@
1
+ import { PacketType } from './PacketType';
2
+ export interface Packet {
3
+ type: PacketType;
4
+ data: any[];
5
+ id?: number;
6
+ }
@@ -0,0 +1,5 @@
1
+ declare enum PacketType {
2
+ EVENT = 0,
3
+ ACK = 1
4
+ }
5
+ export { PacketType };
@@ -0,0 +1,10 @@
1
+ interface BaseSocketEvents {
2
+ connect: 'connect';
3
+ reconnect: 'reconnect';
4
+ disconnect: 'disconnect';
5
+ reconnect_attempt: 'reconnect_attempt';
6
+ reconnect_error: 'reconnect_error';
7
+ reconnect_failed: 'reconnect_failed';
8
+ }
9
+ export declare type SocketEvent = BaseSocketEvents[keyof BaseSocketEvents] | string;
10
+ export {};
@@ -0,0 +1,7 @@
1
+ import { OptionalOptions, Options } from './Options';
2
+ import { PacketType } from './PacketType';
3
+ import { Packet } from './Packet';
4
+ import { SocketEvent } from './SocketEvent';
5
+ import { ConnectionState } from './ConnectionState';
6
+ export { ConnectionState, PacketType };
7
+ export type { Options, OptionalOptions, Packet, SocketEvent };
@@ -0,0 +1,4 @@
1
+ import { Packet } from '../types';
2
+ declare const encodePacket: (packet: Packet) => ArrayBufferLike;
3
+ declare const decodePacket: (buffer: ArrayBuffer) => Packet;
4
+ export { encodePacket, decodePacket };
@@ -0,0 +1,23 @@
1
+ export declare type Listener = (...args: any[]) => void;
2
+ declare class SocketEventEmitter<T extends string> {
3
+ protected maxListeners: number;
4
+ protected handlers: {
5
+ [event: string]: ((...args: any[]) => void)[];
6
+ };
7
+ addListener: (event: T, listener: (...args: any[]) => void) => this;
8
+ once: (event: T, listener: (...args: any[]) => void) => this;
9
+ removeListener: (event: T, listener: (...args: any[]) => void) => this;
10
+ off: (event: T, listener: (...args: any[]) => void) => this;
11
+ removeAllListeners: (event?: T | undefined) => this;
12
+ setMaxListeners: (n: number) => this;
13
+ getMaxListeners: () => number;
14
+ listeners: (event: T) => Listener[];
15
+ rawListeners: (event: T) => Listener[];
16
+ listenerCount: (event: T) => number;
17
+ prependListener: (event: T, listener: (...args: any[]) => void) => this;
18
+ prependOnceListener: (event: T, listener: (...args: any[]) => void) => this;
19
+ eventNames: () => T[];
20
+ on: (event: T, listener: (...args: any[]) => void) => this;
21
+ emit: (event: T, ...args: any[]) => boolean;
22
+ }
23
+ export { SocketEventEmitter };
package/es/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import * as IsomorphicWebSocket from 'isomorphic-ws';
1
+ import WebSocket from 'isomorphic-ws';
2
2
 
3
3
  /**
4
4
  * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js
@@ -159,7 +159,7 @@ const DEFAULT_OPTIONS = {
159
159
  class TeckosClient extends SocketEventEmitter {
160
160
  url;
161
161
  options;
162
- ws;
162
+ _ws;
163
163
  currentReconnectDelay;
164
164
  currentReconnectionAttempts = 0;
165
165
  acks = new Map();
@@ -177,31 +177,26 @@ class TeckosClient extends SocketEventEmitter {
177
177
  }
178
178
 
179
179
  attachHandler = () => {
180
- if (this.ws) {
181
- this.ws.onopen = this.handleOpen;
182
- this.ws.onerror = this.handleError;
183
- this.ws.onclose = this.handleClose;
184
- this.ws.onmessage = this.handleMessage;
180
+ if (this._ws) {
181
+ this._ws.onopen = this.handleOpen;
182
+ this._ws.onerror = this.handleError;
183
+ this._ws.onclose = this.handleClose;
184
+ this._ws.onmessage = this.handleMessage;
185
185
  }
186
186
  };
187
-
188
- get webSocket() {
189
- return this.ws;
190
- }
191
-
192
187
  connect = () => {
193
188
  if (this.options.debug) console.log(`(teckos:client) Connecting to ${this.url}...`); // This will try to connect immediately
194
189
  // eslint-disable-next-line new-cap
195
190
 
196
- this.ws = new IsomorphicWebSocket.WebSocket(this.url); // Attach handlers
191
+ this._ws = new WebSocket(this.url); // Attach handlers
197
192
 
198
193
  this.attachHandler(); // Handle timeout
199
194
 
200
195
  this.connectionTimeout = setTimeout(() => {
201
- if (this.ws && this.ws.readyState === 0
196
+ if (this._ws && this._ws.readyState === 0
202
197
  /* = CONNECTING */
203
198
  ) {
204
- this.ws.close();
199
+ this._ws.close();
205
200
  }
206
201
  }, this.options.timeout);
207
202
  };
@@ -211,25 +206,18 @@ class TeckosClient extends SocketEventEmitter {
211
206
  };
212
207
 
213
208
  getConnectionState() {
214
- if (this.ws) {
215
- switch (this.ws.readyState) {
216
- case 0
217
- /* = CONNECTING */
218
- :
219
- return ConnectionState.CONNECTING;
220
-
221
- case 1
222
- /* = OPEN */
223
- :
209
+ if (this._ws) {
210
+ switch (this._ws.readyState) {
211
+ case WebSocket.OPEN:
224
212
  return ConnectionState.CONNECTED;
225
213
 
226
- case 2
227
- /* = CLOSING */
228
- :
214
+ case WebSocket.CONNECTING:
215
+ return ConnectionState.CONNECTING;
216
+
217
+ case WebSocket.CLOSING:
229
218
  return ConnectionState.DISCONNECTING;
230
219
 
231
220
  default:
232
- /* 3 = CLOSED */
233
221
  return ConnectionState.DISCONNECTED;
234
222
  }
235
223
  }
@@ -241,6 +229,10 @@ class TeckosClient extends SocketEventEmitter {
241
229
  return this.getConnectionState();
242
230
  }
243
231
 
232
+ get ws() {
233
+ return this._ws;
234
+ }
235
+
244
236
  get connected() {
245
237
  return this.getConnectionState() === ConnectionState.CONNECTED;
246
238
  }
@@ -273,12 +265,14 @@ class TeckosClient extends SocketEventEmitter {
273
265
  });
274
266
  };
275
267
  sendPackage = packet => {
276
- if (this.ws !== undefined && this.ws.readyState === 1
268
+ if (this._ws !== undefined && this._ws.readyState === 1
277
269
  /* = OPEN */
278
270
  ) {
279
271
  const buffer = encodePacket(packet);
280
272
  if (this.options.debug) console.log(`(teckos:client) [${this.url}] Send packet: ${JSON.stringify(packet)}`);
281
- this.ws.send(buffer);
273
+
274
+ this._ws.send(buffer);
275
+
282
276
  return true;
283
277
  }
284
278
 
@@ -378,10 +372,11 @@ class TeckosClient extends SocketEventEmitter {
378
372
  close = () => {
379
373
  if (this.options.debug) console.log(`(teckos:client) [${this.url}] Closing connection (client-side)`);
380
374
 
381
- if (this.ws !== undefined) {
382
- this.ws.onclose = () => {};
375
+ if (this._ws !== undefined) {
376
+ this._ws.onclose = () => {};
377
+
378
+ this._ws.close();
383
379
 
384
- this.ws.close();
385
380
  this.listeners('disconnect').forEach(listener => listener());
386
381
  }
387
382
  };
@@ -408,19 +403,19 @@ class TeckosClientWithJWT extends TeckosClient {
408
403
  }
409
404
 
410
405
  getConnectionState() {
411
- if (this.ws) {
412
- switch (this.ws.readyState) {
413
- case IsomorphicWebSocket.WebSocket.OPEN:
406
+ if (this._ws) {
407
+ switch (this._ws.readyState) {
408
+ case WebSocket.OPEN:
414
409
  if (this.receivedReady) {
415
410
  return ConnectionState.CONNECTED;
416
411
  }
417
412
 
418
413
  return ConnectionState.CONNECTING;
419
414
 
420
- case IsomorphicWebSocket.WebSocket.CONNECTING:
415
+ case WebSocket.CONNECTING:
421
416
  return ConnectionState.CONNECTING;
422
417
 
423
- case IsomorphicWebSocket.WebSocket.CLOSING:
418
+ case WebSocket.CLOSING:
424
419
  return ConnectionState.DISCONNECTING;
425
420
 
426
421
  default:
package/es/index.mjs CHANGED
@@ -1 +1 @@
1
- function e(e){return`Minified Redux error #${e}; visit https://redux.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}module.exports=require("ws");const t=new TextEncoder,n=new TextDecoder;var s,i;!function(e){e[e.EVENT=0]="EVENT",e[e.ACK=1]="ACK"}(s||(s={})),function(e){e.DISCONNECTED="disconnected",e.CONNECTING="connecting",e.CONNECTED="connected",e.DISCONNECTING="disconnecting"}(i||(i={}));const o={reconnection:!0,reconnectionDelay:1e3,reconnectionDelayMax:5e3,reconnectionAttempts:1/0,randomizationFactor:.5,timeout:5e3,debug:!1};class r extends class{maxListeners=50;handlers={};addListener=(t,n)=>{if(Object.keys(this.handlers).length===this.maxListeners)throw Error(e(2));if("function"!=typeof n)throw Error(e(3));return this.handlers[t]=this.handlers[t]||[],this.handlers[t].push(n),this};once=(t,n)=>{if(Object.keys(this.handlers).length===this.maxListeners)throw Error(e(2));if("function"!=typeof n)throw Error(e(3));this.handlers[t]=this.handlers[t]||[];const s=()=>{n(),this.off(t,s)};return this.handlers[t].push(s),this};removeListener=(e,t)=>(this.handlers[e]&&(this.handlers[e]=this.handlers[e].filter((e=>e!==t))),this);off=(e,t)=>this.removeListener(e,t);removeAllListeners=e=>(e?delete this.handlers[e]:this.handlers={},this);setMaxListeners=e=>(this.maxListeners=e,this);getMaxListeners=()=>this.maxListeners;listeners=e=>this.handlers[e]?[...this.handlers[e]]:[];rawListeners=e=>[...this.handlers[e]];listenerCount=e=>this.handlers[e]?Object.keys(this.handlers[e]).length:0;prependListener=(t,n)=>{if(Object.keys(this.handlers).length===this.maxListeners)throw Error(e(2));return this.handlers[t]=this.handlers[t]||[],this.handlers[t].unshift(n),this};prependOnceListener=(t,n)=>{if(Object.keys(this.handlers).length===this.maxListeners)throw Error(e(2));this.handlers[t]=this.handlers[t]||[];const s=()=>{n(),this.off(t,s)};return this.handlers[t].unshift(s),this};eventNames=()=>Object.keys(this.handlers);on=(e,t)=>this.addListener(e,t);emit=(e,...t)=>{const n=this.listeners(e);return n.length>0&&(n.forEach((e=>{e&&e(t)})),!0)}}{url;options;ws;currentReconnectDelay;currentReconnectionAttempts=0;acks=new Map;fnId=0;connectionTimeout;reconnectionTimeout;constructor(e,t){super(),this.options={...o,...t},this.currentReconnectDelay=this.options.reconnectionDelay,this.url=e}attachHandler=()=>{this.ws&&(this.ws.onopen=this.handleOpen,this.ws.onerror=this.handleError,this.ws.onclose=this.handleClose,this.ws.onmessage=this.handleMessage)};get webSocket(){return this.ws}connect=()=>{this.options.debug&&console.log(`(teckos:client) Connecting to ${this.url}...`),this.ws=new(void 0)(this.url),this.attachHandler(),this.connectionTimeout=setTimeout((()=>{this.ws&&0===this.ws.readyState&&this.ws.close()}),this.options.timeout)};reconnect=()=>{this.listeners("reconnect_attempt").forEach((e=>e())),this.connect()};getConnectionState(){if(this.ws)switch(this.ws.readyState){case 0:return i.CONNECTING;case 1:return i.CONNECTED;case 2:return i.DISCONNECTING;default:return i.DISCONNECTED}return i.DISCONNECTED}get state(){return this.getConnectionState()}get connected(){return this.getConnectionState()===i.CONNECTED}get disconnected(){return this.getConnectionState()===i.DISCONNECTED}emit=(e,...t)=>{t.unshift(e);const n={type:s.EVENT,data:t};return"function"==typeof t[t.length-1]&&(this.acks.set(this.fnId,t.pop()),n.id=this.fnId,this.fnId+=1),this.sendPackage(n)};send=(...e)=>(e.unshift("message"),this.sendPackage({type:s.EVENT,data:e}));sendPackage=e=>{if(void 0!==this.ws&&1===this.ws.readyState){const n=(e=>t.encode(JSON.stringify(e)))(e);return this.options.debug&&console.log(`(teckos:client) [${this.url}] Send packet: ${JSON.stringify(e)}`),this.ws.send(n),!0}return!1};handleMessage=t=>{const i="string"==typeof t.data?JSON.parse(t.data):JSON.parse(""+n.decode(t.data));if(this.options.debug&&console.log(`(teckos:client) [${this.url}] Got packet: ${JSON.stringify(i)}`),i.type===s.EVENT){const t=i.data[0],n=i.data.slice(1);if(!t)throw Error(e(0));this.listeners(t).forEach((e=>e(...n)))}else{if(i.type!==s.ACK||void 0===i.id)throw Error(e(1));{const e=this.acks.get(i.id);"function"==typeof e&&(e.apply(this,i.data),this.acks.delete(i.id))}}};handleOpen=()=>{this.currentReconnectionAttempts>0&&(this.currentReconnectDelay=this.options.reconnectionDelay,this.currentReconnectionAttempts=0,this.options.debug&&console.log(`(teckos:client) [${this.url}] Reconnected!`),this.listeners("reconnect").forEach((e=>e()))),this.options.debug&&console.log(`(teckos:client) [${this.url}] Connected!`),this.listeners("connect").forEach((e=>e()))};handleError=e=>{this.handlers&&this.handlers.error&&(this.options.debug&&console.log(`(teckos:client) [${this.url}] Got error from server: ${JSON.stringify(e)}`),this.handlers.error.forEach((t=>t(e))))};handleClose=()=>{if(this.connectionTimeout&&clearTimeout(this.connectionTimeout),this.reconnectionTimeout&&clearTimeout(this.reconnectionTimeout),this.currentReconnectionAttempts>0?(this.options.debug&&console.log(`(teckos:client) [${this.url}] Reconnect #${this.currentReconnectionAttempts} failed!`),this.listeners("reconnect_error").forEach((e=>{e&&e()}))):(this.options.debug&&console.log(`(teckos:client) [${this.url}] Disconnected!`),this.listeners("disconnect").forEach((e=>{e&&e()}))),this.options.reconnection)if(this.currentReconnectionAttempts+=1,this.options.reconnectionAttempts!==1/0&&this.currentReconnectionAttempts>this.options.reconnectionAttempts)this.options.debug&&console.log(`(teckos:client) [${this.url}] Reconnection maximum of ${this.options.reconnectionAttempts} reached`),this.listeners("reconnect_failed").forEach((e=>e()));else{const e=Math.min(this.options.reconnectionDelayMax,this.currentReconnectDelay);this.currentReconnectDelay=Math.round(this.currentReconnectDelay+this.currentReconnectDelay*this.options.randomizationFactor),this.options.debug&&console.log(`(teckos:client) [${this.url}] Try reconnecting (${this.currentReconnectionAttempts}/${this.options.reconnectionAttempts}) in ${e}ms to ${this.url}...`),this.reconnectionTimeout=setTimeout((()=>{this.reconnect()}),e)}};close=()=>{this.options.debug&&console.log(`(teckos:client) [${this.url}] Closing connection (client-side)`),void 0!==this.ws&&(this.ws.onclose=()=>{},this.ws.close(),this.listeners("disconnect").forEach((e=>e())))};disconnect=()=>{this.close()}}class c extends r{token;initialData;receivedReady=!1;constructor(e,t,n,s){super(e,t),this.token=n,this.initialData=s,this.on("disconnect",(()=>{this.receivedReady=!1}))}getConnectionState(){if(this.ws)switch(this.ws.readyState){case void 0:return this.receivedReady?i.CONNECTED:i.CONNECTING;case void 0:return i.CONNECTING;case void 0:return i.DISCONNECTING;default:return i.DISCONNECTED}return i.DISCONNECTED}handleReadyEvent=()=>{this.options.debug&&console.log(`(teckos:client) [${this.url}] Connected!`),this.receivedReady=!0,this.currentReconnectionAttempts>0&&(this.options.debug&&console.log(`(teckos:client) [${this.url}] Reconnected!`),this.listeners("reconnect").forEach((e=>e())),this.currentReconnectDelay=this.options.reconnectionDelay,this.currentReconnectionAttempts=0),this.listeners("connect").forEach((e=>e()))};handleOpen=()=>{this.receivedReady=!1,this.once("ready",this.handleReadyEvent),this.options.debug&&console.log("(teckos:client) Connection opened, sending token now"),this.emit("token",{token:this.token,...this.initialData})}}export{i as ConnectionState,s as PacketType,r as TeckosClient,c as TeckosClientWithJWT};
1
+ import t from"isomorphic-ws";function e(t){return`Minified Redux error #${t}; visit https://redux.js.org/Errors?code=${t} for the full message or use the non-minified dev environment for full errors. `}const n=new TextEncoder,s=new TextDecoder;var i,o;!function(t){t[t.EVENT=0]="EVENT",t[t.ACK=1]="ACK"}(i||(i={})),function(t){t.DISCONNECTED="disconnected",t.CONNECTING="connecting",t.CONNECTED="connected",t.DISCONNECTING="disconnecting"}(o||(o={}));const r={reconnection:!0,reconnectionDelay:1e3,reconnectionDelayMax:5e3,reconnectionAttempts:1/0,randomizationFactor:.5,timeout:5e3,debug:!1};class c extends class{maxListeners=50;handlers={};addListener=(t,n)=>{if(Object.keys(this.handlers).length===this.maxListeners)throw Error(e(2));if("function"!=typeof n)throw Error(e(3));return this.handlers[t]=this.handlers[t]||[],this.handlers[t].push(n),this};once=(t,n)=>{if(Object.keys(this.handlers).length===this.maxListeners)throw Error(e(2));if("function"!=typeof n)throw Error(e(3));this.handlers[t]=this.handlers[t]||[];const s=()=>{n(),this.off(t,s)};return this.handlers[t].push(s),this};removeListener=(t,e)=>(this.handlers[t]&&(this.handlers[t]=this.handlers[t].filter((t=>t!==e))),this);off=(t,e)=>this.removeListener(t,e);removeAllListeners=t=>(t?delete this.handlers[t]:this.handlers={},this);setMaxListeners=t=>(this.maxListeners=t,this);getMaxListeners=()=>this.maxListeners;listeners=t=>this.handlers[t]?[...this.handlers[t]]:[];rawListeners=t=>[...this.handlers[t]];listenerCount=t=>this.handlers[t]?Object.keys(this.handlers[t]).length:0;prependListener=(t,n)=>{if(Object.keys(this.handlers).length===this.maxListeners)throw Error(e(2));return this.handlers[t]=this.handlers[t]||[],this.handlers[t].unshift(n),this};prependOnceListener=(t,n)=>{if(Object.keys(this.handlers).length===this.maxListeners)throw Error(e(2));this.handlers[t]=this.handlers[t]||[];const s=()=>{n(),this.off(t,s)};return this.handlers[t].unshift(s),this};eventNames=()=>Object.keys(this.handlers);on=(t,e)=>this.addListener(t,e);emit=(t,...e)=>{const n=this.listeners(t);return n.length>0&&(n.forEach((t=>{t&&t(e)})),!0)}}{url;options;_ws;currentReconnectDelay;currentReconnectionAttempts=0;acks=new Map;fnId=0;connectionTimeout;reconnectionTimeout;constructor(t,e){super(),this.options={...r,...e},this.currentReconnectDelay=this.options.reconnectionDelay,this.url=t}attachHandler=()=>{this._ws&&(this._ws.onopen=this.handleOpen,this._ws.onerror=this.handleError,this._ws.onclose=this.handleClose,this._ws.onmessage=this.handleMessage)};connect=()=>{this.options.debug&&console.log(`(teckos:client) Connecting to ${this.url}...`),this._ws=new t(this.url),this.attachHandler(),this.connectionTimeout=setTimeout((()=>{this._ws&&0===this._ws.readyState&&this._ws.close()}),this.options.timeout)};reconnect=()=>{this.listeners("reconnect_attempt").forEach((t=>t())),this.connect()};getConnectionState(){if(this._ws)switch(this._ws.readyState){case t.OPEN:return o.CONNECTED;case t.CONNECTING:return o.CONNECTING;case t.CLOSING:return o.DISCONNECTING;default:return o.DISCONNECTED}return o.DISCONNECTED}get state(){return this.getConnectionState()}get ws(){return this._ws}get connected(){return this.getConnectionState()===o.CONNECTED}get disconnected(){return this.getConnectionState()===o.DISCONNECTED}emit=(t,...e)=>{e.unshift(t);const n={type:i.EVENT,data:e};return"function"==typeof e[e.length-1]&&(this.acks.set(this.fnId,e.pop()),n.id=this.fnId,this.fnId+=1),this.sendPackage(n)};send=(...t)=>(t.unshift("message"),this.sendPackage({type:i.EVENT,data:t}));sendPackage=t=>{if(void 0!==this._ws&&1===this._ws.readyState){const e=(t=>n.encode(JSON.stringify(t)))(t);return this.options.debug&&console.log(`(teckos:client) [${this.url}] Send packet: ${JSON.stringify(t)}`),this._ws.send(e),!0}return!1};handleMessage=t=>{const n="string"==typeof t.data?JSON.parse(t.data):JSON.parse(""+s.decode(t.data));if(this.options.debug&&console.log(`(teckos:client) [${this.url}] Got packet: ${JSON.stringify(n)}`),n.type===i.EVENT){const t=n.data[0],s=n.data.slice(1);if(!t)throw Error(e(0));this.listeners(t).forEach((t=>t(...s)))}else{if(n.type!==i.ACK||void 0===n.id)throw Error(e(1));{const t=this.acks.get(n.id);"function"==typeof t&&(t.apply(this,n.data),this.acks.delete(n.id))}}};handleOpen=()=>{this.currentReconnectionAttempts>0&&(this.currentReconnectDelay=this.options.reconnectionDelay,this.currentReconnectionAttempts=0,this.options.debug&&console.log(`(teckos:client) [${this.url}] Reconnected!`),this.listeners("reconnect").forEach((t=>t()))),this.options.debug&&console.log(`(teckos:client) [${this.url}] Connected!`),this.listeners("connect").forEach((t=>t()))};handleError=t=>{this.handlers&&this.handlers.error&&(this.options.debug&&console.log(`(teckos:client) [${this.url}] Got error from server: ${JSON.stringify(t)}`),this.handlers.error.forEach((e=>e(t))))};handleClose=()=>{if(this.connectionTimeout&&clearTimeout(this.connectionTimeout),this.reconnectionTimeout&&clearTimeout(this.reconnectionTimeout),this.currentReconnectionAttempts>0?(this.options.debug&&console.log(`(teckos:client) [${this.url}] Reconnect #${this.currentReconnectionAttempts} failed!`),this.listeners("reconnect_error").forEach((t=>{t&&t()}))):(this.options.debug&&console.log(`(teckos:client) [${this.url}] Disconnected!`),this.listeners("disconnect").forEach((t=>{t&&t()}))),this.options.reconnection)if(this.currentReconnectionAttempts+=1,this.options.reconnectionAttempts!==1/0&&this.currentReconnectionAttempts>this.options.reconnectionAttempts)this.options.debug&&console.log(`(teckos:client) [${this.url}] Reconnection maximum of ${this.options.reconnectionAttempts} reached`),this.listeners("reconnect_failed").forEach((t=>t()));else{const t=Math.min(this.options.reconnectionDelayMax,this.currentReconnectDelay);this.currentReconnectDelay=Math.round(this.currentReconnectDelay+this.currentReconnectDelay*this.options.randomizationFactor),this.options.debug&&console.log(`(teckos:client) [${this.url}] Try reconnecting (${this.currentReconnectionAttempts}/${this.options.reconnectionAttempts}) in ${t}ms to ${this.url}...`),this.reconnectionTimeout=setTimeout((()=>{this.reconnect()}),t)}};close=()=>{this.options.debug&&console.log(`(teckos:client) [${this.url}] Closing connection (client-side)`),void 0!==this._ws&&(this._ws.onclose=()=>{},this._ws.close(),this.listeners("disconnect").forEach((t=>t())))};disconnect=()=>{this.close()}}class h extends c{token;initialData;receivedReady=!1;constructor(t,e,n,s){super(t,e),this.token=n,this.initialData=s,this.on("disconnect",(()=>{this.receivedReady=!1}))}getConnectionState(){if(this._ws)switch(this._ws.readyState){case t.OPEN:return this.receivedReady?o.CONNECTED:o.CONNECTING;case t.CONNECTING:return o.CONNECTING;case t.CLOSING:return o.DISCONNECTING;default:return o.DISCONNECTED}return o.DISCONNECTED}handleReadyEvent=()=>{this.options.debug&&console.log(`(teckos:client) [${this.url}] Connected!`),this.receivedReady=!0,this.currentReconnectionAttempts>0&&(this.options.debug&&console.log(`(teckos:client) [${this.url}] Reconnected!`),this.listeners("reconnect").forEach((t=>t())),this.currentReconnectDelay=this.options.reconnectionDelay,this.currentReconnectionAttempts=0),this.listeners("connect").forEach((t=>t()))};handleOpen=()=>{this.receivedReady=!1,this.once("ready",this.handleReadyEvent),this.options.debug&&console.log("(teckos:client) Connection opened, sending token now"),this.emit("token",{token:this.token,...this.initialData})}}export{o as ConnectionState,i as PacketType,c as TeckosClient,h as TeckosClientWithJWT};
package/lib/index.js CHANGED
@@ -2,27 +2,11 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var IsomorphicWebSocket = require('isomorphic-ws');
6
-
7
- function _interopNamespace(e) {
8
- if (e && e.__esModule) return e;
9
- var n = Object.create(null);
10
- if (e) {
11
- Object.keys(e).forEach(function (k) {
12
- if (k !== 'default') {
13
- var d = Object.getOwnPropertyDescriptor(e, k);
14
- Object.defineProperty(n, k, d.get ? d : {
15
- enumerable: true,
16
- get: function () { return e[k]; }
17
- });
18
- }
19
- });
20
- }
21
- n["default"] = e;
22
- return Object.freeze(n);
23
- }
5
+ var WebSocket = require('isomorphic-ws');
6
+
7
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
24
8
 
25
- var IsomorphicWebSocket__namespace = /*#__PURE__*/_interopNamespace(IsomorphicWebSocket);
9
+ var WebSocket__default = /*#__PURE__*/_interopDefaultLegacy(WebSocket);
26
10
 
27
11
  /**
28
12
  * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js
@@ -183,7 +167,7 @@ const DEFAULT_OPTIONS = {
183
167
  class TeckosClient extends SocketEventEmitter {
184
168
  url;
185
169
  options;
186
- ws;
170
+ _ws;
187
171
  currentReconnectDelay;
188
172
  currentReconnectionAttempts = 0;
189
173
  acks = new Map();
@@ -201,31 +185,26 @@ class TeckosClient extends SocketEventEmitter {
201
185
  }
202
186
 
203
187
  attachHandler = () => {
204
- if (this.ws) {
205
- this.ws.onopen = this.handleOpen;
206
- this.ws.onerror = this.handleError;
207
- this.ws.onclose = this.handleClose;
208
- this.ws.onmessage = this.handleMessage;
188
+ if (this._ws) {
189
+ this._ws.onopen = this.handleOpen;
190
+ this._ws.onerror = this.handleError;
191
+ this._ws.onclose = this.handleClose;
192
+ this._ws.onmessage = this.handleMessage;
209
193
  }
210
194
  };
211
-
212
- get webSocket() {
213
- return this.ws;
214
- }
215
-
216
195
  connect = () => {
217
196
  if (this.options.debug) console.log(`(teckos:client) Connecting to ${this.url}...`); // This will try to connect immediately
218
197
  // eslint-disable-next-line new-cap
219
198
 
220
- this.ws = new IsomorphicWebSocket__namespace.WebSocket(this.url); // Attach handlers
199
+ this._ws = new WebSocket__default["default"](this.url); // Attach handlers
221
200
 
222
201
  this.attachHandler(); // Handle timeout
223
202
 
224
203
  this.connectionTimeout = setTimeout(() => {
225
- if (this.ws && this.ws.readyState === 0
204
+ if (this._ws && this._ws.readyState === 0
226
205
  /* = CONNECTING */
227
206
  ) {
228
- this.ws.close();
207
+ this._ws.close();
229
208
  }
230
209
  }, this.options.timeout);
231
210
  };
@@ -235,25 +214,18 @@ class TeckosClient extends SocketEventEmitter {
235
214
  };
236
215
 
237
216
  getConnectionState() {
238
- if (this.ws) {
239
- switch (this.ws.readyState) {
240
- case 0
241
- /* = CONNECTING */
242
- :
243
- return exports.ConnectionState.CONNECTING;
244
-
245
- case 1
246
- /* = OPEN */
247
- :
217
+ if (this._ws) {
218
+ switch (this._ws.readyState) {
219
+ case WebSocket__default["default"].OPEN:
248
220
  return exports.ConnectionState.CONNECTED;
249
221
 
250
- case 2
251
- /* = CLOSING */
252
- :
222
+ case WebSocket__default["default"].CONNECTING:
223
+ return exports.ConnectionState.CONNECTING;
224
+
225
+ case WebSocket__default["default"].CLOSING:
253
226
  return exports.ConnectionState.DISCONNECTING;
254
227
 
255
228
  default:
256
- /* 3 = CLOSED */
257
229
  return exports.ConnectionState.DISCONNECTED;
258
230
  }
259
231
  }
@@ -265,6 +237,10 @@ class TeckosClient extends SocketEventEmitter {
265
237
  return this.getConnectionState();
266
238
  }
267
239
 
240
+ get ws() {
241
+ return this._ws;
242
+ }
243
+
268
244
  get connected() {
269
245
  return this.getConnectionState() === exports.ConnectionState.CONNECTED;
270
246
  }
@@ -297,12 +273,14 @@ class TeckosClient extends SocketEventEmitter {
297
273
  });
298
274
  };
299
275
  sendPackage = packet => {
300
- if (this.ws !== undefined && this.ws.readyState === 1
276
+ if (this._ws !== undefined && this._ws.readyState === 1
301
277
  /* = OPEN */
302
278
  ) {
303
279
  const buffer = encodePacket(packet);
304
280
  if (this.options.debug) console.log(`(teckos:client) [${this.url}] Send packet: ${JSON.stringify(packet)}`);
305
- this.ws.send(buffer);
281
+
282
+ this._ws.send(buffer);
283
+
306
284
  return true;
307
285
  }
308
286
 
@@ -402,10 +380,11 @@ class TeckosClient extends SocketEventEmitter {
402
380
  close = () => {
403
381
  if (this.options.debug) console.log(`(teckos:client) [${this.url}] Closing connection (client-side)`);
404
382
 
405
- if (this.ws !== undefined) {
406
- this.ws.onclose = () => {};
383
+ if (this._ws !== undefined) {
384
+ this._ws.onclose = () => {};
385
+
386
+ this._ws.close();
407
387
 
408
- this.ws.close();
409
388
  this.listeners('disconnect').forEach(listener => listener());
410
389
  }
411
390
  };
@@ -432,19 +411,19 @@ class TeckosClientWithJWT extends TeckosClient {
432
411
  }
433
412
 
434
413
  getConnectionState() {
435
- if (this.ws) {
436
- switch (this.ws.readyState) {
437
- case IsomorphicWebSocket__namespace.WebSocket.OPEN:
414
+ if (this._ws) {
415
+ switch (this._ws.readyState) {
416
+ case WebSocket__default["default"].OPEN:
438
417
  if (this.receivedReady) {
439
418
  return exports.ConnectionState.CONNECTED;
440
419
  }
441
420
 
442
421
  return exports.ConnectionState.CONNECTING;
443
422
 
444
- case IsomorphicWebSocket__namespace.WebSocket.CONNECTING:
423
+ case WebSocket__default["default"].CONNECTING:
445
424
  return exports.ConnectionState.CONNECTING;
446
425
 
447
- case IsomorphicWebSocket__namespace.WebSocket.CLOSING:
426
+ case WebSocket__default["default"].CLOSING:
448
427
  return exports.ConnectionState.DISCONNECTING;
449
428
 
450
429
  default:
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.3.3",
2
+ "version": "0.3.6",
3
3
  "license": "MIT",
4
4
  "main": "lib/index.js",
5
5
  "unpkg": "dist/index.js",
@@ -21,9 +21,9 @@
21
21
  "scripts": {
22
22
  "clean": "rimraf lib dist es coverage types",
23
23
  "dev:web": "webpack serve --config webpack.config.example.web.js",
24
- "dev:node": "DEBUG=example*,teckos* nodemon --watch './src/**/*.ts,./example/node/**/*.ts' --exec 'ts-node' --project tsconfig.example.node.json example/node/index.ts",
25
- "build:example:web": "npm run build && webpack --config webpack.config.example.web.js",
26
- "build:example:node": "npm run build && tsc --p tsconfig.example.node.json",
24
+ "dev:node": "DEBUG=example*,teckos* nodemon --watch './src/**/*.ts,./example/node/**/*.ts' --exec 'ts-node' --project tsconfig.example.node.json example/src/node/index.ts",
25
+ "example:web": "webpack --config webpack.config.example.web.js && echo 'Please open example/dist/web/index.html in your browser'",
26
+ "example:node": "tsc --p tsconfig.example.node.json && node example/dist/node/index.js",
27
27
  "check-types": "tsc --noEmit",
28
28
  "build": "rollup -c",
29
29
  "lint": "eslint --ext js,ts src",
@@ -93,13 +93,11 @@
93
93
  "eslint-config-airbnb-base": "^15.0.0",
94
94
  "eslint-config-airbnb-typescript": "^17.0.0",
95
95
  "eslint-config-prettier": "^8.5.0",
96
- "eslint-config-react-app": "^7.0.1",
97
- "eslint-plugin-flowtype": "^8.0.3",
98
96
  "eslint-plugin-import": "^2.26.0",
99
97
  "eslint-plugin-jsx-a11y": "^6.5.1",
100
98
  "eslint-plugin-prettier": "^4.0.0",
101
99
  "eslint-plugin-promise": "^6.0.0",
102
- "eslint-plugin-react": "^7.30.0",
100
+ "eslint-plugin-react": "^7.30.1",
103
101
  "eslint-plugin-react-hooks": "^4.6.0",
104
102
  "glob": "^8.0.3",
105
103
  "html-webpack-plugin": "^5.5.0",
@@ -115,6 +113,7 @@
115
113
  "size-limit": "^7.0.8",
116
114
  "teckos": "^0.9.6",
117
115
  "ts-jest": "^28.0.5",
116
+ "ts-loader": "^9.3.1",
118
117
  "ts-node": "^10.8.1",
119
118
  "typescript": "^4.7.4",
120
119
  "webpack": "^5.73.0",
@@ -1,10 +1,9 @@
1
- import * as IsomorphicWebSocket from 'isomorphic-ws'
1
+ import WebSocket from 'isomorphic-ws'
2
2
  import { ConnectionState, Packet, SocketEvent } from './types'
3
3
  import { SocketEventEmitter } from './util/SocketEventEmitter'
4
4
 
5
5
  interface ITeckosClient extends SocketEventEmitter<SocketEvent> {
6
- ws: IsomorphicWebSocket.WebSocket | undefined
7
- readonly webSocket: IsomorphicWebSocket.WebSocket | undefined
6
+ readonly ws: WebSocket | undefined
8
7
  readonly state: ConnectionState
9
8
  readonly connected: boolean
10
9
  readonly disconnected: boolean