wspromisify
Advanced tools
Comparing version 1.0.1 to 1.1.1
@@ -1,357 +0,2 @@ | ||
/*! ***************************************************************************** | ||
Copyright (c) Microsoft Corporation. All rights reserved. | ||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use | ||
this file except in compliance with the License. You may obtain a copy of the | ||
License at http://www.apache.org/licenses/LICENSE-2.0 | ||
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED | ||
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, | ||
MERCHANTABLITY OR NON-INFRINGEMENT. | ||
See the Apache Version 2.0 License for specific language governing permissions | ||
and limitations under the License. | ||
***************************************************************************** */ | ||
/* global Reflect, Promise */ | ||
function __awaiter(thisArg, _arguments, P, generator) { | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
} | ||
// SHA1 has been taken from https://github.com/jbt/js-crypto | ||
// Thank you, James, for this tiny implementation! | ||
var SHA1 = (str1) => { | ||
for ( | ||
var blockstart = 0, | ||
i = 0, | ||
W = [], | ||
A, B, C, D, F, G, | ||
H = [A=0x67452301, B=0xEFCDAB89, ~A, ~B, 0xC3D2E1F0], | ||
word_array = [], | ||
temp2, | ||
s = unescape(encodeURI(str1)), | ||
str_len = s.length; | ||
i <= str_len; | ||
){ | ||
word_array[i >> 2] |= (s.charCodeAt(i)||128) << (8 * (3 - i++ % 4)); | ||
} | ||
word_array[temp2 = ((str_len + 8) >> 2) | 15] = str_len << 3; | ||
for (; blockstart <= temp2; blockstart += 16) { | ||
A = H; i = 0; | ||
for (; i < 80; | ||
A = [[ | ||
(G = ((s = A[0]) << 5 | s >>> 27) + A[4] + (W[i] = (i<16) ? ~~word_array[blockstart + i] : G << 1 | G >>> 31) + 1518500249) + ((B = A[1]) & (C = A[2]) | ~B & (D = A[3])), | ||
F = G + (B ^ C ^ D) + 341275144, | ||
G + (B & C | B & D | C & D) + 882459459, | ||
F + 1535694389 | ||
][0|((i++) / 20)] | 0, s, B << 30 | B >>> 2, C, D] | ||
) { | ||
G = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; | ||
} | ||
for(i = 5; i; ) H[--i] = H[i] + A[i] | 0; | ||
} | ||
for(str1 = ''; i < 40; )str1 += (H[i >> 3] >> (7 - i++ % 8) * 4 & 15).toString(16); | ||
return str1; | ||
}; | ||
const add_event = (o, e, handler) => { | ||
return o.addEventListener(e, handler); | ||
}; | ||
const once = (fn) => { | ||
let has_been_cached = false; | ||
let cached = null; | ||
return (...args) => { | ||
if (has_been_cached) { | ||
return cached; | ||
} | ||
else { | ||
has_been_cached = true; | ||
return cached = fn(...args); | ||
} | ||
}; | ||
}; | ||
const init = function (ws) { | ||
const config = this.config; | ||
this.open = true; | ||
this.onReadyQueue.forEach((fn) => fn()); | ||
this.onReadyQueue = []; | ||
const { id_key, data_key } = config.server; | ||
// Send all pending messages. | ||
this.messages.forEach((message) => message.send()); | ||
// It's reconnecting. | ||
if (this.reconnect_timeout !== null) { | ||
clearInterval(this.reconnect_timeout); | ||
this.reconnect_timeout = null; | ||
} | ||
add_event(ws, 'close', (e) => __awaiter(this, void 0, void 0, function* () { | ||
this.log('Closed.'); | ||
this.open = false; | ||
this.onCloseQueue.forEach((fn) => fn()); | ||
this.onCloseQueue = []; | ||
// Auto reconnect. | ||
const reconnect = config.reconnect; | ||
if (typeof reconnect === 'number' && | ||
!isNaN(reconnect) && | ||
!this.forcibly_closed) { | ||
const reconnectFunc = () => __awaiter(this, void 0, void 0, function* () { | ||
this.log('Trying to reconnect...'); | ||
if (this.ws !== null) { | ||
this.ws.close(); | ||
this.ws = null; | ||
} | ||
// If some error occured, try again. | ||
const status = yield this.connect(); | ||
if (status !== null) { | ||
this.reconnect_timeout = setTimeout(reconnectFunc, reconnect * 1000); | ||
} | ||
}); | ||
// No need for await. | ||
reconnectFunc(); | ||
} | ||
else { | ||
this.ws = null; | ||
this.open = null; | ||
} | ||
// reset the flag to reuse. | ||
this.forcibly_closed = false; | ||
})); | ||
add_event(ws, 'message', (e) => { | ||
try { | ||
const data = JSON.parse(e.data); | ||
if (data[id_key]) { | ||
const q = this.queue[data[id_key]]; | ||
if (q) { | ||
// Debug, Log. | ||
const time = q.sent_time ? (Date.now() - q.sent_time) : null; | ||
this.log('Message.', data[data_key], time); | ||
// Play. | ||
q.ff(data[data_key]); | ||
clearTimeout(q.timeout); | ||
delete this.queue[data[id_key]]; | ||
} | ||
} | ||
} | ||
catch (err) { | ||
console.error(err, `JSON.parse error. Got: ${e.data}`); | ||
} | ||
}); | ||
}; | ||
// --------------------------------------------------------------------------- | ||
const connectLib = function (ff) { | ||
if (this.open === true) { | ||
return ff(1); | ||
} | ||
const config = this.config; | ||
const ws = config.socket || config.adapter(`ws://${config.url}`, config.protocols); | ||
this.ws = ws; | ||
add_event(ws, 'error', once((e) => { | ||
this.ws = null; | ||
this.log('Error status 3.'); | ||
// Some network error: Connection refused or so. | ||
return ff(3); | ||
})); | ||
// Because 'open' won't be envoked on opened socket. | ||
if (config.socket && ws.readyState === 1) { | ||
init.call(this, ws); | ||
ff(null); | ||
} | ||
else { | ||
add_event(ws, 'open', once((e) => { | ||
this.log('Opened.'); | ||
init.call(this, ws); | ||
return ff(null); | ||
})); | ||
} | ||
}; | ||
/* .send(your_data) wraps request to server with {id: `hash`, data: `actually your data`}, | ||
returns a Promise, that will be rejected after a timeout or | ||
resolved if server returns the same signature: {id: `same_hash`, data: `response data`} | ||
*/ | ||
const sett = (a, b) => setTimeout(b, a); | ||
const default_config = { | ||
data_type: 'json', | ||
// Debug features. | ||
log: ((event = '', time = 0, message = '') => null), | ||
timer: false, | ||
// Set up. | ||
url: 'localhost', | ||
timeout: 1400, | ||
reconnect: 2, | ||
lazy: false, | ||
socket: null, | ||
adapter: ((host, protocols) => new WebSocket(host, protocols)), | ||
protocols: [], | ||
server: { | ||
id_key: 'id', | ||
data_key: 'data' | ||
} | ||
}; | ||
class WebSocketClient { | ||
constructor(user_config = {}) { | ||
this.open = null; | ||
this.ws = null; | ||
this.forcibly_closed = false; | ||
this.reconnect_timeout = null; | ||
this.queue = {}; | ||
this.messages = []; | ||
this.onReadyQueue = []; | ||
this.onCloseQueue = []; | ||
this.config = {}; | ||
// Config. | ||
const config = {}; | ||
Object.assign(config, default_config); | ||
Object.assign(config, user_config); | ||
this.config = config; | ||
// Init. | ||
this.init_flush(); | ||
// Flags. | ||
this.open = false; | ||
this.reconnect_timeout = null; | ||
this.forcibly_closed = false; | ||
if (!config.lazy) { | ||
this.connect(); | ||
} | ||
} | ||
init_flush() { | ||
this.queue = {}; // data queuse | ||
this.messages = []; // send() queue | ||
} | ||
log(event, message = null, time = null) { | ||
const config = this.config; | ||
event = `WSP: ${event}`; | ||
if (time !== null) { | ||
config.log(event, time, message); | ||
} | ||
else { | ||
if (config.timer) { | ||
config.log(event, null, message); | ||
} | ||
else { | ||
config.log(event, message); | ||
} | ||
} | ||
} | ||
connect() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return new Promise((ff, rj) => { | ||
connectLib.call(this, ff); | ||
}); | ||
}); | ||
} | ||
get socket() { | ||
return this.ws; | ||
} | ||
ready() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return new Promise((ff, rj) => { | ||
if (this.open) { | ||
return true; | ||
} | ||
else { | ||
this.onReadyQueue.push(ff); | ||
} | ||
}); | ||
}); | ||
} | ||
on(event_name, handler, predicate) { | ||
return add_event(this.ws, event_name, event => { | ||
if (!predicate || predicate(event)) { | ||
handler(event); | ||
} | ||
}); | ||
} | ||
close() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return new Promise((ff, rj) => { | ||
if (this.ws === null) { | ||
rj('WSP: closing a non-inited socket!'); | ||
} | ||
else { | ||
this.open = null; | ||
this.onCloseQueue.push(() => { | ||
this.init_flush(); | ||
this.ws = null; | ||
this.forcibly_closed = true; | ||
ff(); | ||
}); | ||
this.ws.close(); | ||
} | ||
}); | ||
}); | ||
} | ||
send(user_message, opts = {}) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
this.log('Send.', user_message); | ||
const config = this.config; | ||
const message = {}; | ||
const id_key = config.server.id_key; | ||
const data_key = config.server.data_key; | ||
const first_time_lazy = config.lazy && !this.open; | ||
// const data_type = opts.data_type || config.data_type | ||
message[data_key] = user_message; // is_json ? JSON.stringify(user_message | ||
message[id_key] = SHA1('' + ((Math.random() * 1e5) | 0)).slice(0, 20); | ||
if (typeof opts.top === 'object') { | ||
if (opts.top[data_key]) { | ||
throw new Error('Attempting to set data key/token via send() options!'); | ||
} | ||
Object.assign(message, opts.top); | ||
} | ||
if (this.open === true) { | ||
this.ws.send(JSON.stringify(message)); | ||
} | ||
else if (this.open === false || first_time_lazy) { | ||
this.messages.push({ send: () => this.ws.send(JSON.stringify(message)) }); | ||
if (first_time_lazy) { | ||
this.connect(); | ||
} | ||
} | ||
else if (this.open === null) { | ||
throw new Error('Attempting to send via closed WebSocket connection!'); | ||
} | ||
return new Promise((ff, rj) => { | ||
this.queue[message[id_key]] = { | ||
ff, | ||
data_type: config.data_type, | ||
sent_time: config.timer ? Date.now() : null, | ||
timeout: sett(config.timeout, () => { | ||
if (this.queue[message[id_key]]) { | ||
rj({ | ||
'Websocket timeout expired: ': config.timeout, | ||
'for the message': message | ||
}); | ||
delete this.queue[message[id_key]]; | ||
} | ||
}) | ||
}; | ||
}); | ||
}); | ||
} | ||
} | ||
export default WebSocketClient; | ||
function __awaiter(e,t,n,o){return new(n||(n=Promise))(function(i,s){function c(e){try{l(o.next(e))}catch(e){s(e)}}function r(e){try{l(o.throw(e))}catch(e){s(e)}}function l(e){e.done?i(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,i,s,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&(i=t[3])),s=c+(n^o^i)+341275144,c+(n&o|n&i|o&i)+882459459,s+1535694389][0|u++/20],f,n<<30|n>>>2,o,i])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 i=t.decode(e.data);if(i[n]){const e=this.queue[i[n]];if(e){const t=e.sent_time?Date.now()-e.sent_time:null;this.log("Message.",i[o],t),e.ff(i[o]),clearTimeout(e.timeout),delete this.queue[i[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)=>{if(this.open)return!0;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={},i=(n.server.id_key,n.server.data_key),s=n.lazy&&!this.open,c=SHA1(""+(1e5*Math.random()|0)).slice(0,20);if("object"==typeof t.top){if(t.top[i])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||s)this.messages.push({send:()=>this.ws.send(n.encode(c,e,n))}),s&&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])})}})})}}export default WebSocketClient; | ||
//# sourceMappingURL=ws.esm.js.map |
@@ -211,2 +211,3 @@ 'use strict'; | ||
protocols: [], | ||
pipes: [], | ||
server: { | ||
@@ -327,2 +328,3 @@ id_key: 'id', | ||
} | ||
config.pipes.forEach((pipe) => message[data_key] = pipe(message[data_key])); | ||
if (this.open === true) { | ||
@@ -332,3 +334,5 @@ this.ws.send(JSON.stringify(message)); | ||
else if (this.open === false || first_time_lazy) { | ||
this.messages.push({ send: () => this.ws.send(JSON.stringify(message)) }); | ||
this.messages.push({ | ||
send: () => this.ws.send(JSON.stringify(message)) | ||
}); | ||
if (first_time_lazy) { | ||
@@ -335,0 +339,0 @@ this.connect(); |
@@ -65,10 +65,6 @@ { | ||
"scripts": { | ||
"ci": "npm run lint && npm run test", | ||
"lint": "./node_modules/.bin/tslint 'src/**/*.ts'", | ||
"test": "npm run test:compile && npm run test:exec", | ||
"ennv": "env", | ||
"test:compile": "./node_modules/.bin/tsc -p ./test/", | ||
"test:run": "npm run test:exec && npm run test:report", | ||
"test:exec": "./node_modules/.bin/nyc ./node_modules/.bin/ava ./test/dist/test/src/index.js", | ||
"test:report": "npm run ennv && ./node_modules/.bin/nyc report --reporter=json && ./node_modules/.bin/codecov -f coverage/*.json -t ${CODECOV_TOKEN}", | ||
"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", | ||
@@ -79,3 +75,3 @@ "prod:cjs": "rollup -c --config src/rollup.config.js --environment INCLUDE_DEPS,BUILD:cjs", | ||
}, | ||
"version": "1.0.1", | ||
"version": "1.1.1", | ||
"devDependencies": { | ||
@@ -86,4 +82,2 @@ "@types/node": "^8.0.58", | ||
"ava": "^0.24.0", | ||
"codecov": "*", | ||
"nyc": "*", | ||
"axios": "^0.17.1", | ||
@@ -97,6 +91,7 @@ "express": "^4.16.2", | ||
"rollup-plugin-resolve-aliases": "^0.2.0", | ||
"rollup-plugin-sourcemaps": "^0.4.2", | ||
"rollup-plugin-typescript2": "^0.8.4", | ||
"rollup-plugin-uglify": "^4.0.0", | ||
"tslint": "^5.8.0", | ||
"typescript": "^2.6.2", | ||
"uglify-es": "^3.3.9", | ||
"ws": "^3.3.2" | ||
@@ -103,0 +98,0 @@ }, |
@@ -10,3 +10,3 @@ # WebsocketPromisify | ||
// If you detected some bug, wants or some stuff to be added, feel free to open an issue! | ||
// If you detected some bug, want some stuff to be added, feel free to open an issue! | ||
Large data support (chunking), plugins, streams and different server-side implementations are coming. | ||
@@ -22,5 +22,6 @@ To see a Node.js server-side part example, please, take a look on test/mock in github repo. | ||
- Automatically reconnects. | ||
- You can use the WebSocket (or your ws-like implementation) further in other stuff (socket property). | ||
- You can usEncodere the WebSocket (or your ws-like implementation) further in other stuff (socket property). | ||
- And provide your own socket instance via socket config prop. | ||
- Any id and data keys to negotiate with your back-end. | ||
- Any (serialiser)/Decoder(deserialiser). | ||
- Lazy connect: connects only if something sent, then send all of them! | ||
@@ -32,3 +33,3 @@ - Supports middleware-adapter. E.g. you can use 'ws' package in Node! | ||
- Rejects if sent into closed socket or after some timeout without response. | ||
- If something sent before connection is estabilished, it sends when its ready. | ||
- If something sent before connection is estabilished, it sends when it's ready. | ||
@@ -38,4 +39,6 @@ How it on Server Side ? | ||
1. Serialized JSON is sent by this lib = {id: 'generated_id', data: your data} | ||
... or some entity from your .encode function(message_id, message_data) | ||
2. Some Server processing... | ||
3. Serialized JSON is sent back by the Server = {id: 'the same generated_id', data: feedback data} | ||
... or some entity that could be parsed by your .decode function(raw_data) | ||
``` | ||
@@ -56,3 +59,3 @@ | ||
url: 'localhost', | ||
// Timeout after sending a message before it dropes with error. | ||
// Timeout after sending a message before it drops with error. | ||
timeout: 1400, | ||
@@ -67,2 +70,8 @@ // Reconnect timeout in seconds or null. | ||
adapter: ((host, protocols) => new WebSocket(host, protocols)), | ||
// You can replace original serialisation to your own or even binary stuff. | ||
encode: (message_id, message_data, config) => data, | ||
// You can replace original deserialisation to your own or even | ||
// making the message object from binary data. | ||
// id_key and data_key could be taken from the config argument. | ||
decode: (raw_message) => { message_id, message_data }, | ||
// WebSocket constructor's protocol field. | ||
@@ -124,3 +133,3 @@ protocols: [], | ||
// You can wait for ready by calling await ws.ready() or send it right now: | ||
// the messages will be sent as soon as the connection opened. | ||
// the messages will be sent as soon as the connection is opened. | ||
const data = await ws.send({catSaid: 'Meow!'}) | ||
@@ -127,0 +136,0 @@ console.log({data}) |
@@ -60,3 +60,3 @@ | ||
try { | ||
const data = JSON.parse(e.data) | ||
const data = config.decode(e.data) | ||
if(data[id_key]) { | ||
@@ -75,3 +75,3 @@ const q = this.queue[data[id_key]] | ||
} catch (err) { | ||
console.error(err, `JSON.parse error. Got: ${e.data}`) | ||
console.error(err, `Decode error. Got: ${e.data}`) | ||
} | ||
@@ -110,3 +110,2 @@ }) | ||
} | ||
} | ||
@@ -113,0 +112,0 @@ |
import commonjs from 'rollup-plugin-commonjs' | ||
import resolve from 'rollup-plugin-node-resolve' | ||
import typescript from 'rollup-plugin-typescript2' | ||
import sourcemaps from 'rollup-plugin-sourcemaps' | ||
import * as uglifyES from 'uglify-es' | ||
import { uglify } from 'rollup-plugin-uglify' | ||
export default { | ||
@@ -28,4 +28,4 @@ input: 'src/WS.ts', | ||
}), | ||
sourcemaps(), | ||
uglify({}, uglifyES.minify) | ||
] | ||
} |
@@ -0,0 +0,0 @@ { |
@@ -0,0 +0,0 @@ |
@@ -27,3 +27,9 @@ | ||
adapter: ((host, protocols) => new WebSocket(host, protocols)), | ||
encode: (key, data, { server }) => JSON.stringify({ | ||
[server.id_key]: key, | ||
[server.data_key]: data | ||
}), | ||
decode: (rawMessage) => JSON.parse(rawMessage), | ||
protocols: [], | ||
pipes: [], | ||
server: { | ||
@@ -36,3 +42,3 @@ id_key: 'id', | ||
class WebSocketClient implements WebSocketClient { | ||
class WebSocketClient implements types.WebSocketClient { | ||
@@ -96,3 +102,3 @@ private open = null | ||
public async close() { | ||
public async close(): types.AsyncErrCode { | ||
return new Promise((ff, rj) => { | ||
@@ -114,4 +120,4 @@ if(this.ws === null) { | ||
public async send(user_message, opts = <types.SendOptions>{}) { | ||
this.log('Send.', user_message) | ||
public async send(message_data, opts = <types.SendOptions>{}): types.AsyncErrCode { | ||
this.log('Send.', message_data) | ||
const config = this.config | ||
@@ -122,6 +128,4 @@ const message = {} | ||
const first_time_lazy = config.lazy && !this.open | ||
// const data_type = opts.data_type || config.data_type | ||
message[data_key] = user_message // is_json ? JSON.stringify(user_message | ||
message[id_key] = SHA1('' + ((Math.random()*1e5)|0)).slice(0, 20) | ||
const message_id = SHA1('' + ((Math.random()*1e5)|0)).slice(0, 20) | ||
if(typeof opts.top === 'object') { | ||
@@ -134,6 +138,12 @@ if(opts.top[data_key]) { | ||
config.pipes.forEach( | ||
(pipe) => message_data = pipe(message_data) | ||
) | ||
if(this.open === true) { | ||
this.ws.send(JSON.stringify(message)) | ||
this.ws.send(config.encode(message_id, message_data, config)) | ||
} else if(this.open === false || first_time_lazy) { | ||
this.messages.push({send: () => this.ws.send(JSON.stringify(message))}) | ||
this.messages.push({ | ||
send: () => this.ws.send(config.encode(message_id, message_data, config)) | ||
}) | ||
if(first_time_lazy) { | ||
@@ -147,3 +157,3 @@ this.connect() | ||
return new Promise((ff, rj) => { | ||
this.queue[message[id_key]] = { | ||
this.queue[message_id] = { | ||
ff, | ||
@@ -153,3 +163,3 @@ data_type: config.data_type, | ||
timeout: sett(config.timeout, () => { | ||
if(this.queue[message[id_key]]) { | ||
if(this.queue[message_id]) { | ||
rj({ | ||
@@ -159,3 +169,3 @@ 'Websocket timeout expired: ': config.timeout, | ||
}) | ||
delete this.queue[message[id_key]] | ||
delete this.queue[message_id] | ||
} | ||
@@ -162,0 +172,0 @@ }) |
@@ -0,0 +0,0 @@ import test from 'ava' |
@@ -0,0 +0,0 @@ |
@@ -0,0 +0,0 @@ |
@@ -0,0 +0,0 @@ |
@@ -0,0 +0,0 @@ |
@@ -0,0 +0,0 @@ |
@@ -0,0 +0,0 @@ |
@@ -24,3 +24,3 @@ import echo from './echo' | ||
ready, | ||
existing_socket, | ||
existing_socket | ||
} |
@@ -0,0 +0,0 @@ |
@@ -0,0 +0,0 @@ |
@@ -0,0 +0,0 @@ |
@@ -0,0 +0,0 @@ |
@@ -0,0 +0,0 @@ |
@@ -0,0 +0,0 @@ |
import WSP from '../../src/WS' | ||
import WSP from '../../dist/ws.esm' | ||
import axios from 'axios' | ||
@@ -4,0 +4,0 @@ import * as WS from 'ws' |
@@ -8,3 +8,4 @@ { | ||
"allowJs": true, | ||
"target": "esnext", | ||
"target": "es5", | ||
"sourceMap": true, | ||
"module": "commonjs", | ||
@@ -11,0 +12,0 @@ "outDir": "./dist" |
export = WebSocketClient | ||
export = wsc | ||
declare namespace WebSocketClient { | ||
declare namespace wsc { | ||
@@ -15,21 +15,30 @@ /** Stuff that in use by this lib. */ | ||
} | ||
export type AsyncErrCode = Promise<number | null | {}> | ||
export type EventHandler = (e: any) => void | ||
export type DataPipe = (message: any) => any | ||
export type DataType = 'json' | 'string' | ||
export interface Config { | ||
data_type: DataType, | ||
data_type: DataType | ||
log (event: string, time?: number, message?: any): void | ||
log (event: string, message?: any): void | ||
timer: boolean, | ||
url: string, | ||
timeout: number, | ||
reconnect: number, // Reconnect timeout in seconds or null. | ||
lazy: boolean, | ||
socket: Socket, | ||
adapter: ((host: string, protocols?: string[]) => Socket), | ||
protocols: string[], | ||
timer: boolean | ||
url: string | ||
timeout: number | ||
reconnect: number | ||
lazy: boolean | ||
socket: Socket | ||
adapter: (host: string, protocols?: string[]) => Socket | ||
encode: (key: string, message: any, config: Config) => any | ||
decode: (rawMessage: any) => { | ||
[id_or_data_key: string]: string | ||
} | ||
protocols: string[] | ||
pipes: DataPipe[] | ||
server: { | ||
id_key: string, | ||
id_key: string | ||
data_key: string | ||
@@ -42,17 +51,16 @@ } | ||
export interface SendOptions { | ||
top: any, | ||
top: any | ||
data_type: DataType | ||
} | ||
} | ||
declare class WebSocketClient { | ||
on( | ||
event_name: string, | ||
handler: (event: string) => void, | ||
predicate?: (event: string) => boolean | ||
) | ||
close(): Promise<void> | ||
send(user_message, opts: WebSocketClient.SendOptions): Promise<number | null> | ||
constructor(user_config: WebSocketClient.UserConfig) | ||
export class WebSocketClient { | ||
on( | ||
event_name: string, | ||
handler: (event: string) => void, | ||
predicate?: (event: string) => boolean | ||
) | ||
close(): Promise<void | {}> | ||
send(user_message: any, opts: wsc.SendOptions): AsyncErrCode | ||
constructor(user_config: wsc.UserConfig) | ||
} | ||
} |
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
72110
18
34
137
1144