wspromisify
Advanced tools
Comparing version 1.1.3 to 2.0.0
"use strict";function __awaiter(e,t,n,o){return new(n||(n=Promise))(function(s,i){function c(e){try{l(o.next(e))}catch(e){i(e)}}function r(e){try{l(o.throw(e))}catch(e){i(e)}}function l(e){e.done?s(e.value):new n(function(t){t(e.value)}).then(c,r)}l((o=o.apply(e,t||[])).next())})}var SHA1=e=>{for(var t,n,o,s,i,c,r,l=0,u=0,h=[],a=[t=1732584193,n=4023233417,~t,~n,3285377520],d=[],f=unescape(encodeURI(e)),_=f.length;u<=_;)d[u>>2]|=(f.charCodeAt(u)||128)<<8*(3-u++%4);for(d[r=_+8>>2|15]=_<<3;l<=r;l+=16){for(t=a,u=0;u<80;t=[0|[(c=((f=t[0])<<5|f>>>27)+t[4]+(h[u]=u<16?~~d[l+u]:c<<1|c>>>31)+1518500249)+((n=t[1])&(o=t[2])|~n&(s=t[3])),i=c+(n^o^s)+341275144,c+(n&o|n&s|o&s)+882459459,i+1535694389][0|u++/20],f,n<<30|n>>>2,o,s])c=h[u-3]^h[u-8]^h[u-14]^h[u-16];for(u=5;u;)a[--u]=a[u]+t[u]|0}for(e="";u<40;)e+=(a[u>>3]>>4*(7-u++%8)&15).toString(16);return e};const add_event=(e,t,n)=>e.addEventListener(t,n),once=e=>{let t=!1,n=null;return(...o)=>t?n:(t=!0,n=e(...o))},init=function(e){const t=this.config;this.open=!0,this.onReadyQueue.forEach(e=>e()),this.onReadyQueue=[];const{id_key:n,data_key:o}=t.server;this.messages.forEach(e=>e.send()),null!==this.reconnect_timeout&&(clearInterval(this.reconnect_timeout),this.reconnect_timeout=null),add_event(e,"close",e=>__awaiter(this,void 0,void 0,function*(){this.log("Closed."),this.open=!1,this.onCloseQueue.forEach(e=>e()),this.onCloseQueue=[];const e=t.reconnect;if("number"!=typeof e||isNaN(e)||this.forcibly_closed)this.ws=null,this.open=null;else{const t=()=>__awaiter(this,void 0,void 0,function*(){this.log("Trying to reconnect..."),null!==this.ws&&(this.ws.close(),this.ws=null),null!==(yield this.connect())&&(this.reconnect_timeout=setTimeout(t,1e3*e))});t()}this.forcibly_closed=!1})),add_event(e,"message",e=>{try{const s=t.decode(e.data);if(s[n]){const e=this.queue[s[n]];if(e){const t=e.sent_time?Date.now()-e.sent_time:null;this.log("Message.",s[o],t),e.ff(s[o]),clearTimeout(e.timeout),delete this.queue[s[n]]}}}catch(t){console.error(t,`Decode error. Got: ${e.data}`)}})},connectLib=function(e){if(!0===this.open)return e(1);const t=this.config,n=t.socket||t.adapter(`ws://${t.url}`,t.protocols);this.ws=n,add_event(n,"error",once(t=>(this.ws=null,this.log("Error status 3."),e(3)))),t.socket&&1===n.readyState?(init.call(this,n),e(null)):add_event(n,"open",once(t=>(this.log("Opened."),init.call(this,n),e(null))))},sett=(e,t)=>setTimeout(t,e),default_config={data_type:"json",log:(e="",t=0,n="")=>null,timer:!1,url:"localhost",timeout:1400,reconnect:2,lazy:!1,socket:null,adapter:(e,t)=>new WebSocket(e,t),encode:(e,t,{server:n})=>JSON.stringify({[n.id_key]:e,[n.data_key]:t}),decode:e=>JSON.parse(e),protocols:[],pipes:[],server:{id_key:"id",data_key:"data"}};class WebSocketClient{constructor(e={}){this.open=null,this.ws=null,this.forcibly_closed=!1,this.reconnect_timeout=null,this.queue={},this.messages=[],this.onReadyQueue=[],this.onCloseQueue=[],this.config={};const t={};Object.assign(t,default_config),Object.assign(t,e),this.config=t,this.init_flush(),this.open=!1,this.reconnect_timeout=null,this.forcibly_closed=!1,t.lazy||this.connect()}init_flush(){this.queue={},this.messages=[]}log(e,t=null,n=null){const o=this.config;e=`WSP: ${e}`,null!==n?o.log(e,n,t):o.timer?o.log(e,null,t):o.log(e,t)}connect(){return __awaiter(this,void 0,void 0,function*(){return new Promise((e,t)=>{connectLib.call(this,e)})})}get socket(){return this.ws}ready(){return __awaiter(this,void 0,void 0,function*(){return new Promise((e,t)=>{this.open?e():this.onReadyQueue.push(e)})})}on(e,t,n){return add_event(this.ws,e,e=>{n&&!n(e)||t(e)})}close(){return __awaiter(this,void 0,void 0,function*(){return new Promise((e,t)=>{null===this.ws?t("WSP: closing a non-inited socket!"):(this.open=null,this.onCloseQueue.push(()=>{this.init_flush(),this.ws=null,this.forcibly_closed=!0,e()}),this.ws.close())})})}send(e,t={}){return __awaiter(this,void 0,void 0,function*(){this.log("Send.",e);const n=this.config,o={},s=(n.server.id_key,n.server.data_key),i=n.lazy&&!this.open,c=SHA1(""+(1e5*Math.random()|0)).slice(0,20);if("object"==typeof t.top){if(t.top[s])throw new Error("Attempting to set data key/token via send() options!");Object.assign(o,t.top)}if(n.pipes.forEach(t=>e=t(e)),!0===this.open)this.ws.send(n.encode(c,e,n));else if(!1===this.open||i)this.messages.push({send:()=>this.ws.send(n.encode(c,e,n))}),i&&this.connect();else if(null===this.open)throw new Error("Attempting to send via closed WebSocket connection!");return new Promise((e,t)=>{this.queue[c]={ff:e,data_type:n.data_type,sent_time:n.timer?Date.now():null,timeout:sett(n.timeout,()=>{this.queue[c]&&(t({"Websocket timeout expired: ":n.timeout,"for the message":o}),delete this.queue[c])})}})})}}module.exports=WebSocketClient; | ||
//# sourceMappingURL=ws.js.map |
@@ -22,2 +22,3 @@ { | ||
"Middleware", | ||
"JSON", | ||
"Data", | ||
@@ -38,11 +39,11 @@ "transport", | ||
"lint": "./node_modules/.bin/tslint 'src/**/*.ts'", | ||
"test": "npm run test:compile && npm run test:exec", | ||
"test": "npm run prod:es && npm run test:compile && npm run test:exec", | ||
"test:compile": "./node_modules/.bin/tsc -p ./test/", | ||
"test:exec": "npm run prod:es && ./node_modules/.bin/ava ./test/dist/test/src/index.js", | ||
"dev": "rollup --watch -c --config src/rollup.config.js --environment INCLUDE_DEPS,BUILD:development", | ||
"prod:cjs": "rollup -c --config src/rollup.config.js --environment INCLUDE_DEPS,BUILD:cjs", | ||
"prod:es": "rollup -c --config src/rollup.config.js --environment INCLUDE_DEPS,BUILD:es", | ||
"test:exec": "./node_modules/.bin/ava ./test/dist/test/src/index.js", | ||
"dev": "rollup --watch -c --config rollup.config.js --environment INCLUDE_DEPS,BUILD:development", | ||
"prod:cjs": "rollup -c --config rollup.config.js --environment INCLUDE_DEPS,BUILD:cjs", | ||
"prod:es": "rollup -c --config rollup.config.js --environment INCLUDE_DEPS,BUILD:es", | ||
"prod": "npm run prod:es && npm run prod:cjs" | ||
}, | ||
"version": "1.1.3", | ||
"version": "2.0.0", | ||
"devDependencies": { | ||
@@ -56,2 +57,3 @@ "@types/node": "^8.0.58", | ||
"ramda": "^0.25.0", | ||
"randomatic": "^3.1.1", | ||
"rollup": "^0.52.1", | ||
@@ -69,3 +71,3 @@ "rollup-plugin-alias": "^1.4.0", | ||
}, | ||
"types": "./index.d.ts" | ||
"types": "./dist/src/WS.d.ts" | ||
} |
@@ -1,4 +0,2 @@ | ||
import * as types from '../types' | ||
import './types' | ||
import { | ||
@@ -10,10 +8,10 @@ once, | ||
const init = function(ws: types.Socket) { | ||
const init = function(ws: wsc.Socket) { | ||
const config = this.config | ||
this.open = true | ||
this.onReadyQueue.forEach((fn) => fn()) | ||
this.onReadyQueue.forEach((fn: Function) => fn()) | ||
this.onReadyQueue = [] | ||
const {id_key, data_key} = config.server | ||
// Send all pending messages. | ||
this.messages.forEach((message) => message.send()) | ||
this.messages.forEach((message: any) => message.send()) | ||
// It's reconnecting. | ||
@@ -20,0 +18,0 @@ if(this.reconnect_timeout !== null) { |
@@ -0,13 +1,11 @@ | ||
import './types' | ||
import * as types from '../types' | ||
const add_event = (o: types.Socket, e: string, handler: types.EventHandler) => { | ||
const add_event = (o: wsc.Socket, e: string, handler: wsc.EventHandler) => { | ||
return o.addEventListener(e, handler) | ||
} | ||
const once = (fn) => { | ||
const once = (fn: Function) => { | ||
let has_been_cached = false | ||
let cached = null | ||
return (...args) => { | ||
return (...args: any) => { | ||
if(has_been_cached) { | ||
@@ -14,0 +12,0 @@ return cached |
import SHA1 from './SHA1.js' | ||
import * as types from '../types' | ||
import SHA1 from './SHA1' | ||
import connectLib from './connectLib' | ||
import { add_event } from './utils' | ||
import './types' | ||
@@ -12,6 +12,8 @@ /* .send(your_data) wraps request to server with {id: `hash`, data: `actually your data`}, | ||
const sett = ( | ||
a: number, | ||
b: { (): void; (...args: any[]): void; } | ||
) => setTimeout(b, a) | ||
const sett = (a, b) => setTimeout(b, a) | ||
const default_config = <types.Config>{ | ||
const default_config = <wsc.Config>{ | ||
data_type: 'json', // ToDo some other stuff maybe. | ||
@@ -42,3 +44,3 @@ // Debug features. | ||
class WebSocketClient implements types.WebSocketClient { | ||
class WebSocketClient implements wsc.WebSocketClient { | ||
@@ -53,3 +55,3 @@ private open = null | ||
private onCloseQueue = [] | ||
private config = <types.Config>{} | ||
private config = <wsc.Config>{} | ||
@@ -95,3 +97,7 @@ private init_flush(): void { | ||
public on(event_name, handler, predicate?) { | ||
public on( | ||
event_name: string, | ||
handler: (data: any) => any, | ||
predicate?: (data: any) => boolean | ||
) { | ||
return add_event(this.ws, event_name, event => { | ||
@@ -104,3 +110,3 @@ if(!predicate || predicate(event)) { | ||
public async close(): types.AsyncErrCode { | ||
public async close(): wsc.AsyncErrCode { | ||
return new Promise((ff, rj) => { | ||
@@ -122,3 +128,3 @@ if(this.ws === null) { | ||
public async send(message_data, opts = <types.SendOptions>{}): types.AsyncErrCode { | ||
public async send(message_data: any, opts = <wsc.SendOptions>{}): wsc.AsyncErrCode { | ||
this.log('Send.', message_data) | ||
@@ -175,5 +181,5 @@ const config = this.config | ||
constructor(user_config = {}) { | ||
constructor(user_config: wsc.UserConfig = {}) { | ||
// Config. | ||
const config = {} as types.Config | ||
const config = {} as wsc.Config | ||
Object.assign(config, default_config) | ||
@@ -180,0 +186,0 @@ Object.assign(config, user_config) |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
39
912
61607
19