UNPKG

@adonisjs/websocket-client

Version:

Websocket client for AdonisJs

2 lines (1 loc) 16.1 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e.adonis=e.adonis||{},e.adonis.Ws=t())}(this,function(){"use strict";var e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},t=function(e){return function(){var t=e.apply(this,arguments);return new Promise(function(e,n){return function r(i,o){try{var s=t[i](o),c=s.value}catch(e){return void n(e)}if(!s.done)return Promise.resolve(c).then(function(e){r("next",e)},function(e){r("throw",e)});e(c)}("next")})}},n=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},r=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},o=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)},s=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t},c=function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)},u=new WeakMap,a=new WeakMap,f=Promise.resolve();function h(e){if("string"!=typeof e)throw new TypeError("eventName must be a string")}function l(e){if("function"!=typeof e)throw new TypeError("listener must be a function")}function p(e,t){var n=a.get(e);return n.has(t)||n.set(t,new Set),n.get(t)}var v=function(){function e(){n(this,e),u.set(this,new Set),a.set(this,new Map)}return r(e,[{key:"on",value:function(e,t){return h(e),l(t),p(this,e).add(t),this.off.bind(this,e,t)}},{key:"off",value:function(e,t){h(e),l(t),p(this,e).delete(t)}},{key:"once",value:function(e){var t=this;return new Promise(function(n){h(e);var r=t.on(e,function(e){r(),n(e)})})}},{key:"emit",value:function(){var e=t(regeneratorRuntime.mark(function e(n,r){var i,o,s,a,l=this;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return h(n),i=p(this,n),o=u.get(this),s=[].concat(c(i)),a=[].concat(c(o)),e.next=7,f;case 7:return e.abrupt("return",Promise.all([].concat(c(s.map(function(){var e=t(regeneratorRuntime.mark(function e(t){return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!i.has(t)){e.next=2;break}return e.abrupt("return",t(r));case 2:case"end":return e.stop()}},e,l)}));return function(t){return e.apply(this,arguments)}}())),c(a.map(function(){var e=t(regeneratorRuntime.mark(function e(t){return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!o.has(t)){e.next=2;break}return e.abrupt("return",t(n,r));case 2:case"end":return e.stop()}},e,l)}));return function(t){return e.apply(this,arguments)}}())))));case 8:case"end":return e.stop()}},e,this)}));return function(t,n){return e.apply(this,arguments)}}()},{key:"emitSerial",value:function(){var e=t(regeneratorRuntime.mark(function e(t,n){var r,i,o,s,a,l,v,y,d,k,m,b,_,w,g,E;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return h(t),r=p(this,t),i=u.get(this),o=[].concat(c(r)),s=[].concat(c(i)),e.next=7,f;case 7:a=!0,l=!1,v=void 0,e.prev=10,y=o[Symbol.iterator]();case 12:if(a=(d=y.next()).done){e.next=20;break}if(k=d.value,!r.has(k)){e.next=17;break}return e.next=17,k(n);case 17:a=!0,e.next=12;break;case 20:e.next=26;break;case 22:e.prev=22,e.t0=e.catch(10),l=!0,v=e.t0;case 26:e.prev=26,e.prev=27,!a&&y.return&&y.return();case 29:if(e.prev=29,!l){e.next=32;break}throw v;case 32:return e.finish(29);case 33:return e.finish(26);case 34:m=!0,b=!1,_=void 0,e.prev=37,w=s[Symbol.iterator]();case 39:if(m=(g=w.next()).done){e.next=47;break}if(E=g.value,!i.has(E)){e.next=44;break}return e.next=44,E(t,n);case 44:m=!0,e.next=39;break;case 47:e.next=53;break;case 49:e.prev=49,e.t1=e.catch(37),b=!0,_=e.t1;case 53:e.prev=53,e.prev=54,!m&&w.return&&w.return();case 56:if(e.prev=56,!b){e.next=59;break}throw _;case 59:return e.finish(56);case 60:return e.finish(53);case 61:case"end":return e.stop()}},e,this,[[10,22,26,34],[27,,29,33],[37,49,53,61],[54,,56,60]])}));return function(t,n){return e.apply(this,arguments)}}()},{key:"onAny",value:function(e){return l(e),u.get(this).add(e),this.offAny.bind(this,e)}},{key:"offAny",value:function(e){l(e),u.get(this).delete(e)}},{key:"clearListeners",value:function(e){if("string"==typeof e)p(this,e).clear();else{u.get(this).clear();var t=!0,n=!1,r=void 0;try{for(var i,o=a.get(this).values()[Symbol.iterator]();!(t=(i=o.next()).done);t=!0){i.value.clear()}}catch(e){n=!0,r=e}finally{try{!t&&o.return&&o.return()}finally{if(n)throw r}}}}},{key:"listenerCount",value:function(e){if("string"==typeof e)return u.get(this).size+p(this,e).size;void 0!==e&&h(e);var t=u.get(this).size,n=!0,r=!1,i=void 0;try{for(var o,s=a.get(this).values()[Symbol.iterator]();!(n=(o=s.next()).done);n=!0){t+=o.value.size}}catch(e){r=!0,i=e}finally{try{!n&&s.return&&s.return()}finally{if(r)throw i}}return t}}]),e}();v.Typed=function(e){function t(){return n(this,t),s(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return o(t,v),t}(),Object.defineProperty(v.Typed,"Typed",{enumerable:!1,value:void 0});var y=v,d=function(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})};function k(e,t){return t.encode?t.strict?d(e):encodeURIComponent(e):e}var m=function(e,t){!1===(t=i({encode:!0,strict:!0,arrayFormat:"none"},t)).sort&&(t.sort=function(){});var n=function(e){switch(e.arrayFormat){case"index":return function(t,n,r){return null===n?[k(t,e),"[",r,"]"].join(""):[k(t,e),"[",k(r,e),"]=",k(n,e)].join("")};case"bracket":return function(t,n){return null===n?k(t,e):[k(t,e),"[]=",k(n,e)].join("")};default:return function(t,n){return null===n?k(t,e):[k(t,e),"=",k(n,e)].join("")}}}(t);return e?Object.keys(e).sort(t.sort).map(function(r){var i=e[r];if(void 0===i)return"";if(null===i)return k(r,t);if(Array.isArray(i)){var o=[],s=!0,c=!1,u=void 0;try{for(var a,f=i.slice()[Symbol.iterator]();!(s=(a=f.next()).done);s=!0){var h=a.value;void 0!==h&&o.push(n(r,h,o.length))}}catch(e){c=!0,u=e}finally{try{!s&&f.return&&f.return()}finally{if(c)throw u}}return o.join("&")}return k(r,t)+"="+k(i,t)}).filter(function(e){return e.length>0}).join("&"):""};"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function b(e,t){return e(t={exports:{}},t.exports),t.exports}var _=b(function(t,n){t.exports=function(){var t="function"==typeof Symbol&&"symbol"==e(Symbol.iterator)?function(t){return void 0===t?"undefined":e(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":void 0===t?"undefined":e(t)},n={OPEN:0,JOIN:1,LEAVE:2,JOIN_ACK:3,JOIN_ERROR:4,LEAVE_ACK:5,LEAVE_ERROR:6,EVENT:7,PING:8,PONG:9};function r(e,t,n){return n.forEach(function(e){!function(e,t){if(!e||"string"!=typeof e)throw new Error(t)}(t[e],"expected "+e+" to be a valid string")}),{t:e,d:t}}var o={};return Object.keys(n).forEach(function(e){var r=e.toLowerCase().replace(/^\w|_(\w)/g,function(e,t){return t?t.toUpperCase():e.toUpperCase()});o["is"+r+"Packet"]=function(r){return!(!r||"object"!==(void 0===r?"undefined":t(r))||r.t!==n[e])}}),o.hasTopic=function(e){return!!(e&&e.d&&e.d.topic)},o.isValidJoinPacket=o.hasTopic,o.isValidLeavePacket=o.hasTopic,o.isValidEventPacket=o.hasTopic,o.joinPacket=function(e){return r(n.JOIN,{topic:e},["topic"])},o.leavePacket=function(e){return r(n.LEAVE,{topic:e},["topic"])},o.joinAckPacket=function(e){return r(n.JOIN_ACK,{topic:e},["topic"])},o.joinErrorPacket=function(e,t){return r(n.JOIN_ERROR,{topic:e,message:t},["topic","message"])},o.leaveAckPacket=function(e){return r(n.LEAVE_ACK,{topic:e},["topic"])},o.leaveErrorPacket=function(e,t){return r(n.LEAVE_ERROR,{topic:e,message:t},["topic","message"])},o.eventPacket=function(e,t,i){return r(n.EVENT,{topic:e,event:t,data:i=i||""},["topic","event"])},o.pingPacket=function(){return{t:n.PING}},o.pongPacket=function(){return{t:n.PONG}},i({codes:n},o)}()}),w=(b(function(e){e.exports=function(){}}),function(){function e(t,r){n(this,e),this.topic=t,this.connection=r,this.emitter=new y,this._state="pending",this._emitBuffer=[]}return r(e,[{key:"joinAck",value:function(){var e=this;this.state="open",this.emitter.emit("ready",this),this._emitBuffer.forEach(function(t){return e.emit(t.event,t.data)}),this._emitBuffer=[]}},{key:"joinError",value:function(e){this.state="error",this.emitter.emit("error",e),this.serverClose()}},{key:"leaveAck",value:function(){this.state="closed",this.serverClose()}},{key:"leaveError",value:function(e){this.emitter.emit("leaveError",e)}},{key:"on",value:function(){var e;(e=this.emitter).on.apply(e,arguments)}},{key:"once",value:function(){var e;(e=this.emitter).once.apply(e,arguments)}},{key:"off",value:function(){var e;(e=this.emitter).off.apply(e,arguments)}},{key:"emit",value:function(e,t){"pending"!==this.state?this.connection.sendEvent(this.topic,e,t):this._emitBuffer.push({event:e,data:t})}},{key:"serverClose",value:function(){var e=this;return this.emitter.emit("close",this).then(function(){e._emitBuffer=[],e.emitter.clearListeners()}).catch(function(){e._emitBuffer=[],e.emitter.clearListeners()})}},{key:"serverEvent",value:function(e){var t=e.event,n=e.data;this.emitter.emit(t,n)}},{key:"serverError",value:function(){this.state="error"}},{key:"close",value:function(){this.state="closing",this.connection.sendPacket(_.leavePacket(this.topic))}},{key:"terminate",value:function(){this.leaveAck()}},{key:"state",get:function(){return this._state},set:function(e){if(-1===!this.constructor.states.indexOf(e))throw new Error(e+" is not a valid socket state");this._state=e}}],[{key:"states",get:function(){return["pending","open","closed","closing","error"]}}]),e}()),g={name:"json",encode:function(e,t){var n=null;try{n=JSON.stringify(e)}catch(e){return t(e)}t(null,n)},decode:function(e,t){var n=null;try{n=JSON.parse(e)}catch(e){return t(e)}t(null,n)}},E="https:"===window.location.protocol?"wss":"ws",P=function(e){function t(e,r){n(this,t);var o=s(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return e=e||E+"://"+window.location.host,o.options=i({path:"adonis-ws",reconnection:!0,reconnectionAttempts:10,reconnectionDelay:1e3,query:null,encoder:g},r),o._connectionState="idle",o._reconnectionAttempts=0,o._packetsQueue=[],o._processingQueue=!1,o._pingTimer=null,o._extendedQuery={},o._url=e.replace(/\/$/,"")+"/"+o.options.path,o.subscriptions={},o.removeSubscription=function(e){var t=e.topic;delete o.subscriptions[t]},o}return o(t,y),r(t,[{key:"_cleanup",value:function(){clearInterval(this._pingTimer),this.ws=null,this._pingTimer=null}},{key:"_subscriptionsIterator",value:function(e){var t=this;Object.keys(this.subscriptions).forEach(function(n){return e(t.subscriptions[n],n)})}},{key:"_ensureSubscription",value:function(e,t){var n=this.getSubscription(e.d.topic);n&&t(n,e)}},{key:"_processQueue",value:function(){var e=this;!this._processingQueue&&this._packetsQueue.length&&(this._processingQueue=!0,this.options.encoder.encode(this._packetsQueue.shift(),function(t,n){t||(e.write(n),e._processingQueue=!1,e._processQueue())}))}},{key:"_onOpen",value:function(){}},{key:"_onError",value:function(e){this._subscriptionsIterator(function(e){return e.serverError()}),this.emit("error",e)}},{key:"_reconnect",value:function(){var e=this;this._reconnectionAttempts++,this.emit("reconnect",this._reconnectionAttempts),setTimeout(function(){e._connectionState="reconnect",e.connect()},this.options.reconnectionDelay*this._reconnectionAttempts)}},{key:"_onClose",value:function(e){var t=this;this._cleanup(),this._subscriptionsIterator(function(e){return e.terminate()}),this.emit("close",this).then(function(){t.shouldReconnect?t._reconnect():t.clearListeners()}).catch(function(){t.shouldReconnect?t._reconnect():t.clearListeners()})}},{key:"_onMessage",value:function(e){var t=this;this.options.encoder.decode(e.data,function(e,n){e||t._handleMessage(n)})}},{key:"_handleMessage",value:function(e){_.isOpenPacket(e)?this._handleOpen(e):_.isJoinAckPacket(e)?this._handleJoinAck(e):_.isJoinErrorPacket(e)?this._handleJoinError(e):_.isLeaveAckPacket(e)?this._handleLeaveAck(e):_.isLeaveErrorPacket(e)?this._handleLeaveError(e):_.isLeavePacket(e)?this._handleServerLeave(e):_.isEventPacket(e)?this._handleEvent(e):_.isPongPacket(e)}},{key:"_handleOpen",value:function(e){var t=this;this._connectionState="open",this.emit("open",e.d),this._pingTimer=setInterval(function(){t.sendPacket(_.pingPacket())},e.d.clientInterval),this._subscriptionsIterator(function(e){t._sendSubscriptionPacket(e.topic)})}},{key:"_handleJoinAck",value:function(e){this._ensureSubscription(e,function(e){return e.joinAck()})}},{key:"_handleJoinError",value:function(e){this._ensureSubscription(e,function(e,t){return e.joinError(t.d)})}},{key:"_handleLeaveAck",value:function(e){this._ensureSubscription(e,function(e){return e.leaveAck()})}},{key:"_handleLeaveError",value:function(e){this._ensureSubscription(e,function(e,t){return e.leaveError(t.d)})}},{key:"_handleServerLeave",value:function(e){this._ensureSubscription(e,function(e,t){return e.leaveAck()})}},{key:"_handleEvent",value:function(e){this._ensureSubscription(e,function(e,t){return e.serverEvent(t.d)})}},{key:"_sendSubscriptionPacket",value:function(e){this.sendPacket(_.joinPacket(e))}},{key:"connect",value:function(){var e=this,t=m(i({},this.options.query,this._extendedQuery)),n=t?this._url+"?"+t:this._url;return this.ws=new window.WebSocket(n),this.ws.onclose=function(t){return e._onClose(t)},this.ws.onerror=function(t){return e._onError(t)},this.ws.onopen=function(t){return e._onOpen(t)},this.ws.onmessage=function(t){return e._onMessage(t)},this}},{key:"write",value:function(e){this.ws.readyState===window.WebSocket.OPEN&&this.ws.send(e)}},{key:"sendPacket",value:function(e){this._packetsQueue.push(e),this._processQueue()}},{key:"getSubscription",value:function(e){return this.subscriptions[e]}},{key:"hasSubcription",value:function(e){return!!this.getSubscription(e)}},{key:"subscribe",value:function(e){if(!e||"string"!=typeof e)throw new Error("subscribe method expects topic to be a valid string");if(this.subscriptions[e])throw new Error("Cannot subscribe to same topic twice. Instead use getSubscription");var t=new w(e,this);return t.on("close",this.removeSubscription),this.subscriptions[e]=t,"open"===this._connectionState&&this._sendSubscriptionPacket(e),t}},{key:"sendEvent",value:function(e,t,n){if(!e||!t)throw new Error("topic and event name is required to call sendEvent method");var r=this.getSubscription(e);if(!r)throw new Error("There is no active subscription for "+e+" topic");if("open"!==r.state)throw new Error("Cannot emit since subscription socket is in "+this.state+" state");this.sendPacket(_.eventPacket(e,t,n))}},{key:"withJwtToken",value:function(e){return this._extendedQuery.token=e,this}},{key:"withBasicAuth",value:function(e,t){return this._extendedQuery.basic=window.btoa(e+":"+t),this}},{key:"withApiToken",value:function(e){return this._extendedQuery.token=e,this}},{key:"close",value:function(){this._connectionState="terminated",this.ws.close()}},{key:"shouldReconnect",get:function(){return"terminated"!==this._connectionState&&this.options.reconnection&&this.options.reconnectionAttempts>this._reconnectionAttempts}}]),t}();return function(e,t){return new P(e,t)}});