UNPKG

token-sockjs-client

Version:

Client libraries for Node-Token-Sockjs server

1 lines 9.5 kB
!function(a){var b=5e3,c=10,d=5,e=["on","addListener","removeListener","removeAllListeners"],f=function(){},g=function(a){return Math.min(a*d,b)},h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",i=function(){var a,b="";for(a=0;a<10;a++)b+=h.charAt(Math.random()*h.length|0);return b};Object.size=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&c++;return c},Object.shallowCopy=function(a){var b,c={};for(b in a)a.hasOwnProperty(b)&&(c[b]=a[b]);return c},Object.keys||(Object.keys=function(){"use strict";var a=Object.prototype.hasOwnProperty,b=!{toString:null}.propertyIsEnumerable("toString"),c=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],d=c.length;return function(e){if("object"!=typeof e&&("function"!=typeof e||null===e))throw new TypeError("Object.keys called on non-object");var f,g,h=[];for(f in e)a.call(e,f)&&h.push(f);if(b)for(g=0;g<d;g++)a.call(e,c[g])&&h.push(c[g]);return h}}());var j=function(a,b){this._socket=a,this._inTransit={},this._emitter=b};j.prototype.sendMessage=function(a,b){"string"==typeof a&&(a=JSON.parse(a)),a.uuid=i(),this._inTransit[a.rpc]||(this._inTransit[a.rpc]={}),this._inTransit[a.rpc][a.uuid]=b||f,this._socket.send(JSON.stringify(a))},j.prototype.handleResponse=function(a){var b=null;a.rpc&&a.uuid&&(b=this._inTransit[a.rpc][a.uuid]),b&&"function"==typeof b&&(a.error?b(a.error):b(null,a.resp),delete this._inTransit[a.rpc][a.uuid],0===Object.size(this._inTransit[a.rpc])&&delete this._inTransit[a.rpc]),a.channel&&this._emitter.emit("message",a.channel,a.message)};var k=function(a,b,c,d){var e={};a?e.error=a.message||a:e.data=b;var f={rpc:"_rpc",fid:d.fid,resp:e};c._socket.send(JSON.stringify(f))},l=function(a,b,c){if("subscribe"===b)a._channels[c.channel]=!0;else if("unsubscribe"===b)delete a._channels[c.channel];else if("rpc"===b){var d=a._actions;c.command.split(".").forEach(function(a){d=d&&d[a]?d[a]:null}),d&&"function"==typeof d&&d(c.args,function(b,d){k(b,d,a,c)})}},m=function(a){a._connectTimer=setTimeout(function(a){p(a,function(b){b?(a._emitter.emit("reconnect",b),m(a)):a._emitter.emit("reconnect")})},a._connectDelay,a),a._connectDelay=g(a._connectDelay)},n=function(a,b){var c,d=[];for(c in a)if(a.hasOwnProperty(c)&&!("string"==typeof a[c]&&a[c].length<1)){var e=b?b+"["+c+"]":c,f=a[c];d.push("object"==typeof f?n(f,e):encodeURIComponent(e)+"="+encodeURIComponent(f))}return d.join("&")},o=function(b,c,d){if(b=Object.shallowCopy(b),b.dataType&&"jsonp"===b.dataType.toLowerCase()){var e="token_callback_"+(new Date).getTime()+"_"+Math.round(1e16*Math.random()).toString(36),f=a.document.createElement("script");a[e]=function(b){if(a.document.body.removeChild(f),delete a[e],"string"==typeof b)try{b=JSON.parse(b)}catch(c){return d(new Error(b||"Error making jsonp request!"))}d(b&&b.error?b.error:null,b)},f.onerror=function(b){return a.document.body.removeChild(f),delete a[e],d(new Error("Error making jsonp request!")),!1},f.onload=function(a){return!1},f.src=b.url+(b.url.indexOf("?")>0?"&":"?")+"callback="+e+"&"+n(c||{}),a.document.body.appendChild(f)}else{var g=new a.XMLHttpRequest;b.url+=(c&&b.url.indexOf("?")>0?"&":"?")+n(c||{}),g.open(b.method,b.url,!0),g.onreadystatechange=function(){if(4===g.readyState){var a=g.target?g.target.responseText:g.responseText;try{a=JSON.parse(a)}catch(b){}g.status>=200&&g.status<300?d(null,a):d(a&&a.error?new Error(a.error):a instanceof Error?a:new Error(a||"Error making HTTP request"))}},g.setRequestHeader("Accept","application/json"),g.send()}},p=function(b,d){o(b._opts,b._authentication,function(e,f){return!e&&f&&f.token?(b._token=f.token,b._socket=new a.SockJS(b._apiRoute+b._socketPrefix,null,b._sockjs),b._socket.onopen=function(){b._monitor.sendMessage({rpc:"auth",token:b._token},function(a,e){d="string"==typeof d?b._emitter.emit.bind(b._emitter,d):d,a?d(a):(delete b._closed,clearInterval(b._connectTimer),delete b._connectTimer,b._connectDelay=c,r(b),d())})},b._monitor=new j(b._socket,b._emitter),b._socket.onmessage=function(a){try{a.data=JSON.parse(a.data)}catch(c){return}a.data.internal?l(b,a.data.command,a.data.data):b._monitor.handleResponse(a.data)},void(b._socket.onclose=function(){b._closed=!0,b._reconnect&&m(b)})):(e=e||new Error("No token found!"),"string"==typeof d?b._emitter.emit(d,e):d(e))})},q=function(a,b){a._closed?a._queue.push({fn:b}):b()},r=function(a){for(var b in a._channels)a.subscribe(b);a._queue.forEach(function(a){a.fn&&"function"==typeof a.fn&&a.fn()}),a._queue=[]},s=function(b,d){var f=this;f._emitter=new EventEmitter,e.forEach(function(a){f[a]=f._emitter[a]}),f._closed=!0,b||(b={}),f._ready||"function"!=typeof b.ready||f.ready(b.ready),f._onreconnect||"function"!=typeof b.onreconnect||f.onreconnect(b.onreconnect),b.host||(b.host=a.location.host),f._reconnect="undefined"==typeof b.reconnect||b.reconnect,f._channels={},f._ping=b.ping||!1,f._sockjs=b.sockjs||{},f._apiRoute=b.host.indexOf("http")<0?a.location.protocol+"//"+b.host:b.host,f._socketPrefix=b.socketPrefix||"/sockets",f._tokenPath=b.tokenPath||"/socket/token",f._actions="object"==typeof d?d:{},f._authentication=b.authentication||{},f._queue=[],f._connectDelay=c,f._connectTimer=null,f._opts={method:"GET",url:f._apiRoute+f._tokenPath,dataType:b.host!==a.location.host?"jsonp":"json"},f._ping&&f._ping>0&&(f._pingTimer=setInterval(function(){f._closed||f.rpc("_ping",{})},f._ping)),p(f,"ready")};s.prototype.ready=function(a){this._emitter.on("ready",a)},s.prototype.onreconnect=function(a){this._emitter.on("reconnect",a)},s.prototype.channels=function(){return Object.keys(this._channels)},s.prototype.rpc=function(a,b,c){var d=this;q(d,function(){d._monitor.sendMessage({rpc:a,req:b},c)})},s.prototype.register=function(a){this._actions=a},s.prototype.subscribe=function(a,b){var c=this;q(c,function(){c._channels[a]=!0,c._monitor.sendMessage({rpc:"_subscribe",req:{channel:a}},b)})},s.prototype.unsubscribe=function(a,b){var c=this;q(c,function(){delete c._channels[a],c._monitor.sendMessage({rpc:"_unsubscribe",req:{channel:a}},b)})},s.prototype.publish=function(a,b,c){var d=this;q(d,function(){d._monitor.sendMessage({rpc:"_publish",req:{channel:a,data:b}},c)})},s.prototype.broadcast=function(a,b){var c=this;q(c,function(){c._monitor.sendMessage({rpc:"_broadcast",req:{data:a}},b)})},s.prototype.onmessage=function(a){this._emitter.on("message",a)},s.prototype.end=function(a){this._emitter.removeAllListeners("ready"),this._emitter.removeAllListeners("reconnect"),this._emitter.removeAllListeners("message"),this._closed=!0,this._socket.onclose=a,this._socket.close()},a.TokenSocket=s}("undefined"==typeof window?{}:window),function(){"use strict";function a(){}function b(a,b){for(var c=a.length;c--;)if(a[c].listener===b)return c;return-1}function c(a){return function(){return this[a].apply(this,arguments)}}var d=a.prototype,e=this,f=e.EventEmitter;d.getListeners=function(a){var b,c,d=this._getEvents();if(a instanceof RegExp){b={};for(c in d)d.hasOwnProperty(c)&&a.test(c)&&(b[c]=d[c])}else b=d[a]||(d[a]=[]);return b},d.flattenListeners=function(a){var b,c=[];for(b=0;b<a.length;b+=1)c.push(a[b].listener);return c},d.getListenersAsObject=function(a){var b,c=this.getListeners(a);return c instanceof Array&&(b={},b[a]=c),b||c},d.addListener=function(a,c){var d,e=this.getListenersAsObject(a),f="object"==typeof c;for(d in e)e.hasOwnProperty(d)&&b(e[d],c)===-1&&e[d].push(f?c:{listener:c,once:!1});return this},d.on=c("addListener"),d.addOnceListener=function(a,b){return this.addListener(a,{listener:b,once:!0})},d.once=c("addOnceListener"),d.defineEvent=function(a){return this.getListeners(a),this},d.defineEvents=function(a){for(var b=0;b<a.length;b+=1)this.defineEvent(a[b]);return this},d.removeListener=function(a,c){var d,e,f=this.getListenersAsObject(a);for(e in f)f.hasOwnProperty(e)&&(d=b(f[e],c),d!==-1&&f[e].splice(d,1));return this},d.off=c("removeListener"),d.addListeners=function(a,b){return this.manipulateListeners(!1,a,b)},d.removeListeners=function(a,b){return this.manipulateListeners(!0,a,b)},d.manipulateListeners=function(a,b,c){var d,e,f=a?this.removeListener:this.addListener,g=a?this.removeListeners:this.addListeners;if("object"!=typeof b||b instanceof RegExp)for(d=c.length;d--;)f.call(this,b,c[d]);else for(d in b)b.hasOwnProperty(d)&&(e=b[d])&&("function"==typeof e?f.call(this,d,e):g.call(this,d,e));return this},d.removeEvent=function(a){var b,c=typeof a,d=this._getEvents();if("string"===c)delete d[a];else if(a instanceof RegExp)for(b in d)d.hasOwnProperty(b)&&a.test(b)&&delete d[b];else delete this._events;return this},d.removeAllListeners=c("removeEvent"),d.emitEvent=function(a,b){var c,d,e,f,g,h=this.getListenersAsObject(a);for(f in h)if(h.hasOwnProperty(f))for(c=h[f].slice(0),e=c.length;e--;)d=c[e],d.once===!0&&this.removeListener(a,d.listener),g=d.listener.apply(this,b||[]),g===this._getOnceReturnValue()&&this.removeListener(a,d.listener);return this},d.trigger=c("emitEvent"),d.emit=function(a){var b=Array.prototype.slice.call(arguments,1);return this.emitEvent(a,b)},d.setOnceReturnValue=function(a){return this._onceReturnValue=a,this},d._getOnceReturnValue=function(){return!this.hasOwnProperty("_onceReturnValue")||this._onceReturnValue},d._getEvents=function(){return this._events||(this._events={})},a.noConflict=function(){return e.EventEmitter=f,a},"function"==typeof define&&define.amd?define(function(){return a}):"object"==typeof module&&module.exports?module.exports=a:e.EventEmitter=a}.call(this);