@dwmt/comlink
Advanced tools
Comparing version 2.0.0-alpha1 to 2.0.0-alpha2
@@ -665,3 +665,9 @@ import Cookies from 'js-cookie'; | ||
let requestObject = await dialect.handler(path, data, options); | ||
return axios(requestObject); | ||
try { | ||
let response = await axios(requestObject); | ||
return response.data; | ||
} catch (err) { | ||
throw new Error(err.response.data.message); | ||
} | ||
} | ||
@@ -901,3 +907,3 @@ | ||
var version = "2.0.0-alpha1"; | ||
var version = "2.0.0-alpha2"; | ||
@@ -904,0 +910,0 @@ var Comlink = { |
@@ -1,1 +0,1 @@ | ||
!function(e,t,n){"use strict";function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=r(t),s=r(n),a="function"==typeof Object.create?function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:function(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e};function i(){}function l(){this._cookie=o.default}function c(){this._store={}}i.prototype.getItem=function(e){console.error("getItem not implemented")},i.prototype.setItem=function(e,t,n){console.error("setItem not implemented")},i.prototype.removeItem=function(e,t){console.error("removeItem not implemented")},i.prototype.clear=function(){console.error("clear not implemented")},a(l,i),l.prototype.getItem=function(e){return this._cookie.get(e)},l.prototype.setItem=function(e,t,n){return this._cookie.set(e,t,n)},l.prototype.removeItem=function(e,t){return this._cookie.remove(e,t)},a(c,i),c.prototype.getItem=function(e){return this._store[e]||null},c.prototype.setItem=function(e,t,n){this._store[e]=t},c.prototype.removeItem=function(e,t){delete this._store[e]},c.prototype.clear=function(){this._store={}};var h={LocalStorage:"undefined"!=typeof window?window.localStorage:i,SessionStorage:"undefined"!=typeof window?window.sessionStorage:i,CookieStorage:new l,NodeStorage:new c};function d(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}const u=require("isomorphic-ws"),p=require("@dwmt/loader/lib/Loader");function f(e,t){let n=new p;return"boolean"!=typeof t.loader||t.loader?(void 0===t.loader&&(n=e.loader),"object"==typeof t.loader&&t.loader.work&&t.loader.terminate&&(n=t.loader),n):n}function m(e){return{type:"http",name:e.name,protocol:e.ssl?"https://":"http://",uri:e.uri,default:e.default||!1,rpc:e.rpc||void 0,onError:e.onError||function(e){console.error(e)},headerHandler:e.headerHandler||async function(e){return!0},loader:e.loader||new p,logger:e.logger,connectable:!1}}function _(e){const t=this,n={type:"ws",name:e.name,protocol:e.ssl?"wss://":"ws://",uri:e.uri,default:e.default||!1,auth:e.auth,authHeader:e.authHeader,rpc:e.rpc,onError:e.onError||function(e){console.error(e)},loader:e.loader||new p,logger:e.logger,connection:null,connectable:!0,alive:!1,answers:{},listeners:{},onConnectionOpen:e.onConnectionOpen||function(){},onConnectionTermination:e.onConnectionTermination||function(){},onConnectionClose:e.onConnectionClose||function(){},onConnectionError:e.onConnectionError||function(){},callbacks:{onConnectionOpen:function(){},onConnectionClose:function(){},onConnectionError:function(){},onConnectionTermination:function(){}},terminate(){t._channels[e.name].connection.close(),t._channels[e.name].connection=null,t._channels[e.name].answers={},t._channels[e.name].listeners={},t._channels[e.name].onConnectionTermination(),t._channels[e.name].callbacks.onConnectionTermination()},connect:()=>new Promise(((r,o)=>{if(null!==t._channels[e.name].connection)return r(!0);const s=[];if(e.auth){const n=t.getHeader(e.authHeader);s.push(n.value)}const a=new u(n.protocol+n.uri,s);t._channels[e.name].connection=a,a.addEventListener("open",(()=>{t._channels[e.name].alive=!0,t._channels[e.name].onConnectionOpen(),t._channels[e.name].callbacks.onConnectionOpen(),r(!0)})),a.addEventListener("close",(()=>{t._channels[e.name].alive=!1,t._channels[e.name].onConnectionClose(),t._channels[e.name].callbacks.onConnectionClose()})),a.addEventListener("error",(n=>{t._channels[e.name].alive=!1,t._channels[e.name].onConnectionError(n),t._channels[e.name].callbacks.onConnectionError(n),o(n)})),e.rpc&&a.addEventListener("message",(function(n){try{const r=JSON.parse(n.data);if(e.rpc&&e.rpc.headerHandler&&e.rpc.headerHandler(r.headers||{}),"rpcResponse"!==r._type&&"rpcError"!==r._type&&void 0!==r._type||!r.id||(void 0!==r.result?t._channels[e.name].answers[r.id].resolve(r.result):t._channels[e.name].answers[r.id].reject({error:r.error})),"event"===r._type){let n=t._channels[e.name].listeners[r.event];if(n.length)for(let e of n)e(r.message)}}catch(e){console.error(e)}}))}))};return n}const{EventEmitter:w}=require("events");var y={Client:class{constructor(e={}){this._axios=s.default,this._ws=u,this._dialects={},this._channels={},this._headers={},this._deafultHTTPChannel=null,this._deafultWSChannel=null,this._deafultRPCChannel=null,this._defaultDialect=null,this._instanceID=d(),this._devtools=e.devtools||!0}get channels(){return Object.keys(this._channels)||[]}disableDevtools(){this._devtools=!1}bindDevtools(){global.window&&(global.window._COMLINK_DEV_TOOLS||(global.window._COMLINK_DEV_TOOLS={}),global.window._COMLINK_DEV_TOOLS[this._instanceID]=this,console.log("[COMLINK] Devtools enabled with instanceID: "+this._instanceID))}async connect(){let e=[];for(let t of Object.keys(this._channels)){let n=this._channels[t];"ws"!==n.type||n.alive||e.push(n.connect())}return Promise.all(e)}channel(e){if(!this._channels[e])throw new Error(`No channel registered with ${e}`);let t=this;const n={};return n.name=this._channels[e].name,n.alive=this._channels[e].alive,this._channels[e].connectable&&(n.connection=this._channels[e].connection,n.connect=this._channels[e].connect,n.terminate=this._channels[e].terminate),n.registerCallback=function(n,r){t._channels[e].callbacks[n]=r},n}registerDialect(e){const t=Object.assign({},e);t.router=t.router||function(e){return{path:e}},t.parameter=t.parameter||function(e){return{parameters:e}},t.optioner=t.optioner||function(){return{}},t.handler=t.handler||function(){return{}},this._dialects[t.name]=t,(t.default||null===this._defaultDialect)&&(this._defaultDialect=t.name)}registerHeader(e){this._headers[e.name]=e}registerChannel(e){if(!e.type in["http","ws"])throw new Error(`[Comlink] Channel type "${e.type}" is not supported!`);if("http"===e.type){const t=m.call(this,e);t.default&&(this._deafultHTTPChannel=t.name),t.default&&t.rpc&&(this._deafultRPCChannel=t.name),this._channels[t.name]=t}if("ws"===e.type){const t=_.call(this,e);t.default&&(this._deafultWSChannel=t.name),t.default&&t.rpc&&(this._deafultRPCChannel=t.name),this._channels[t.name]=t}}get headers(){return Object.keys(this._headers)}checkHeaders(){Object.keys(this._headers).forEach((e=>{const t=this._headers[e];if("automatic"===t.type){const e=t.storage.getItem(t.key);e&&(t.value=e)}}))}getHeader(e){if(!this._headers[e])throw new Error(`No registered header with name ${e}`);return{key:this._headers[e].key,value:this._headers[e].value}}setHeader(e,t){if(!this._headers[e])throw new Error(`No registered header with name ${e}`);this._headers[e].value=t,"automatic"===this._headers[e].type&&this._headers[e].storage.setItem(this._headers[e].key,t)}async get(e,t={}){this.checkDefaultHTTPChannel();const n=t.channel||this._deafultHTTPChannel,r=this._channels[n],o=f(r,t),a=t.onError||r.onError,i=o.work();try{let n=r.protocol+r.uri+"/"+e;/^https?:\/\//i.test(e)&&(n=e);const a=await s.default.get(n,t.axios||{});return await r.headerHandler(a.headers),a}catch(e){throw await r.headerHandler(e.response.headers),await a(e),e}finally{o.terminate(i)}}checkDefaultHTTPChannel(){if(!this._deafultHTTPChannel)throw new Error("[Comlink] No default HTTP channel")}async post(e,t,n={}){this.checkDefaultHTTPChannel();const r=n.channel||this._deafultHTTPChannel,o=this._channels[r],a=f(o,n),i=n.onError||o.onError,l=a.work();try{let r=o.protocol+o.uri+"/"+e;/^https?:\/\//i.test(e)&&(r=e);const i=await s.default.post(r,t,n.axios||{});return await o.headerHandler(i.headers),i}catch(e){throw await o.headerHandler(e.response.headers),await i(e),e}finally{a.terminate(l)}}async put(e,t,n={}){this.checkDefaultHTTPChannel();const r=n.channel||this._deafultHTTPChannel,o=this._channels[r],a=f(o,n),i=n.onError||o.onError,l=a.work();try{let r=o.protocol+o.uri+"/"+e;/^https?:\/\//i.test(e)&&(r=e);const i=await s.default.put(r,t,n.axios||{});return await o.headerHandler(i.headers),i}catch(e){throw await o.headerHandler(e.response.headers),await i(e),e}finally{a.terminate(l)}}async delete(e,t={}){this.checkDefaultHTTPChannel();const n=t.channel||this._deafultHTTPChannel,r=this._channels[n],o=f(r,t),a=t.onError||r.onError,i=o.work();try{let n=r.protocol+r.uri+"/"+e;/^https?:\/\//i.test(e)&&(n=e);const a=await s.default.delete(n,t.axios||{});return await r.headerHandler(a.headers),a}catch(e){throw await r.headerHandler(e.response.headers),await a(e),e}finally{o.terminate(i)}}subscribeToEvent(e,t,n={}){const r=n.channel||this._deafultRPCChannel,o=this._channels[r];o.listeners[e]||(o.listeners[e]=[]),o.listeners[e].push(t)}unsubscribeFromEvent(e,t,n={}){const r=n.channel||this._deafultRPCChannel,o=this._channels[r];o.listeners[e]&&(o.listeners[e]=o.listeners[e].filter((e=>e!==t)))}sendMessage(){throw new Error("Not implemented yet!")}async _rpc(e="request",t,n,r,o){const s=this._channels[r.channel||this._deafultRPCChannel],a=this._dialects[o||this._defaultDialect],i=s.rpc;if(!i.dialects.includes(a.name))throw new Error(`The channel ${s.name} not supports the ${a.name} dialect`);const l=((i[a.name]||{}).idGenerator||i.idGenerator||d)();let c={id:l};(void 0===a.sendMeta||a.sendMeta)&&(c._dialect=a.name,c._type=e);const h=a.router(t),u=a.parameter(n),p=a.optioner(r);c=Object.assign({},c,a.interface,h,u,p),null===s.connection&&await s.connect(),s.connection.send(JSON.stringify(c));const f=new Promise(((e,t)=>{s.answers[l]={resolve:e,reject:t}})),m=new Promise(((e,t)=>{setTimeout((()=>{t(`[Comlink] Maximum retries exceeded for message: ${l}`)}),i.retryInterval*i.maxRetries)}));return Promise.race([f,m])}async _rpcHTTP(e="request",t,n,r,o){const a=this._channels[r.channel||this._deafultRPCChannel],i=this._dialects[o||this._defaultDialect],l=a.rpc;if(!i.type||"http"!==i.type)throw new Error("ComlinkDialect is not supported on HTTPChannel yet!");if("http"===i.type&&"request"!==e)throw new Error("HTTPDialect only supports request now!");if(!l.dialects.includes(i.name))throw new Error(`The channel ${a.name} not supports the ${i.name} dialect`);let c=await i.handler(t,n,r);return s.default(c)}async request(e,t,n={},r){const o=n.channel||this._deafultRPCChannel,s=this._channels[o],a=f(s,n),i=n.onError||s.onError,l=a.work();try{return"http"===s.type?await this._rpcHTTP("request",e,t,n,r):await this._rpc("request",e,t,n,r)}catch(e){throw await i(e,n),e}finally{a.terminate(l)}}async inform(e,t,n={},r){const o=n.channel||this._deafultRPCChannel,s=this._channels[o],a=f(s,n),i=n.onError||s.onError,l=a.work();try{return s.type,await this._rpc("inform",e,t,n,r)}catch(e){throw await i(e),e}finally{a.terminate(l)}}},Server:class{constructor(e){this._dialects={},this._channels={},this._clients={},this.session={},this.eventEmitter=new w,this.logger=e||console}registerDialect(e){this._dialects[e.name]=e}registerChannel(e){if(e.auth&&!e.tokenValidator)throw new Error("For authentication you need a token validator");if("ws"!==e.type)throw new Error("Only websocket listeners implemented yet!");this._channels[e.name]=e,this.session[e.name]={clients:{},tokens:{}}}sendMessageToClient(e,t,n,r){if(!this.session[e].clients[t])throw new Error("No user with given clientID");this.eventEmitter.emit(`sendEventTo:${t}`,{_type:"event",event:n,message:r})}getClientIDByToken(e,t){let n=this.session[e].tokens[t].client;if(!n)throw new Error("No user with given token");return n}getTokenByClientID(e,t){let n=this.session[e].clients[t].token;if(!n)throw new Error("No user with given clientID");return n}isTokenActive(e,t){return!!this.session[e].tokens[t].client}isClientActive(e,t){return!!this.session[e].clients[t].token}applyChannel(e,t){const n=this._channels[e];if(!n)throw new Error(`Channel with name ${e} is not registered!`);t.on("connection",(async(t,r)=>{let o=d();if(this.session[e].clients[o]={},n.auth){const s=r.headers["sec-websocket-protocol"];if(!s||0===s.length)return t.close();if(!await n.tokenValidator(s))return t.close();this.session[e].clients[o].token=s,this.session[e].tokens[s]={client:o},t.id=o}this.eventEmitter.on(`sendEventTo:${o}`,(e=>{t.send(JSON.stringify(e))})),t.on("close",(async()=>{let n=this.session[e].clients[t.id].token;delete this.session[e].clients[t.id],delete this.session[e].tokens[n]})),t.on("message",(async r=>{const o=JSON.parse(r),s=o._dialect;if(!s)return;const a=o.id;this._channels[e].dialects.includes(s)||t.send(JSON.stringify({_type:"rpcError",id:a,error:`The used dialect ${s} is not supported on this channel`}));let i={};if(n.headerInjector)try{let r=await n.headerInjector(this.session[e].clients[t.id].token);i=Object.assign({},r)}catch(e){throw t.send(JSON.stringify({_type:"rpcError",id:a,error:e.message,headers:Object.assign({},i,{serverTime:Date.now()})})),e}let l={};l.token=this.session[e].clients[t.id].token,l.clientID=t.id;try{const e=await this._dialects[s].onRequest(o,l);"request"===o._type&&t.send(JSON.stringify({_type:"rpcResponse",id:a,result:e,headers:Object.assign({},i,{serverTime:Date.now()})}))}catch(e){throw t.send(JSON.stringify({_type:"rpcError",id:a,error:e.message,headers:Object.assign({},i,{serverTime:Date.now()})})),e}}))}))}},Storage:h,version:"2.0.0-alpha1"};e.default=y,Object.defineProperty(e,"__esModule",{value:!0})}(this["@dwmt/comlink"]=this["@dwmt/comlink"]||{},Cookies,axios); | ||
!function(e,t,n){"use strict";function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=r(t),s=r(n),a="function"==typeof Object.create?function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:function(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e};function i(){}function l(){this._cookie=o.default}function c(){this._store={}}i.prototype.getItem=function(e){console.error("getItem not implemented")},i.prototype.setItem=function(e,t,n){console.error("setItem not implemented")},i.prototype.removeItem=function(e,t){console.error("removeItem not implemented")},i.prototype.clear=function(){console.error("clear not implemented")},a(l,i),l.prototype.getItem=function(e){return this._cookie.get(e)},l.prototype.setItem=function(e,t,n){return this._cookie.set(e,t,n)},l.prototype.removeItem=function(e,t){return this._cookie.remove(e,t)},a(c,i),c.prototype.getItem=function(e){return this._store[e]||null},c.prototype.setItem=function(e,t,n){this._store[e]=t},c.prototype.removeItem=function(e,t){delete this._store[e]},c.prototype.clear=function(){this._store={}};var h={LocalStorage:"undefined"!=typeof window?window.localStorage:i,SessionStorage:"undefined"!=typeof window?window.sessionStorage:i,CookieStorage:new l,NodeStorage:new c};function d(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}const u=require("isomorphic-ws"),p=require("@dwmt/loader/lib/Loader");function f(e,t){let n=new p;return"boolean"!=typeof t.loader||t.loader?(void 0===t.loader&&(n=e.loader),"object"==typeof t.loader&&t.loader.work&&t.loader.terminate&&(n=t.loader),n):n}function m(e){return{type:"http",name:e.name,protocol:e.ssl?"https://":"http://",uri:e.uri,default:e.default||!1,rpc:e.rpc||void 0,onError:e.onError||function(e){console.error(e)},headerHandler:e.headerHandler||async function(e){return!0},loader:e.loader||new p,logger:e.logger,connectable:!1}}function _(e){const t=this,n={type:"ws",name:e.name,protocol:e.ssl?"wss://":"ws://",uri:e.uri,default:e.default||!1,auth:e.auth,authHeader:e.authHeader,rpc:e.rpc,onError:e.onError||function(e){console.error(e)},loader:e.loader||new p,logger:e.logger,connection:null,connectable:!0,alive:!1,answers:{},listeners:{},onConnectionOpen:e.onConnectionOpen||function(){},onConnectionTermination:e.onConnectionTermination||function(){},onConnectionClose:e.onConnectionClose||function(){},onConnectionError:e.onConnectionError||function(){},callbacks:{onConnectionOpen:function(){},onConnectionClose:function(){},onConnectionError:function(){},onConnectionTermination:function(){}},terminate(){t._channels[e.name].connection.close(),t._channels[e.name].connection=null,t._channels[e.name].answers={},t._channels[e.name].listeners={},t._channels[e.name].onConnectionTermination(),t._channels[e.name].callbacks.onConnectionTermination()},connect:()=>new Promise(((r,o)=>{if(null!==t._channels[e.name].connection)return r(!0);const s=[];if(e.auth){const n=t.getHeader(e.authHeader);s.push(n.value)}const a=new u(n.protocol+n.uri,s);t._channels[e.name].connection=a,a.addEventListener("open",(()=>{t._channels[e.name].alive=!0,t._channels[e.name].onConnectionOpen(),t._channels[e.name].callbacks.onConnectionOpen(),r(!0)})),a.addEventListener("close",(()=>{t._channels[e.name].alive=!1,t._channels[e.name].onConnectionClose(),t._channels[e.name].callbacks.onConnectionClose()})),a.addEventListener("error",(n=>{t._channels[e.name].alive=!1,t._channels[e.name].onConnectionError(n),t._channels[e.name].callbacks.onConnectionError(n),o(n)})),e.rpc&&a.addEventListener("message",(function(n){try{const r=JSON.parse(n.data);if(e.rpc&&e.rpc.headerHandler&&e.rpc.headerHandler(r.headers||{}),"rpcResponse"!==r._type&&"rpcError"!==r._type&&void 0!==r._type||!r.id||(void 0!==r.result?t._channels[e.name].answers[r.id].resolve(r.result):t._channels[e.name].answers[r.id].reject({error:r.error})),"event"===r._type){let n=t._channels[e.name].listeners[r.event];if(n.length)for(let e of n)e(r.message)}}catch(e){console.error(e)}}))}))};return n}const{EventEmitter:w}=require("events");var y={Client:class{constructor(e={}){this._axios=s.default,this._ws=u,this._dialects={},this._channels={},this._headers={},this._deafultHTTPChannel=null,this._deafultWSChannel=null,this._deafultRPCChannel=null,this._defaultDialect=null,this._instanceID=d(),this._devtools=e.devtools||!0}get channels(){return Object.keys(this._channels)||[]}disableDevtools(){this._devtools=!1}bindDevtools(){global.window&&(global.window._COMLINK_DEV_TOOLS||(global.window._COMLINK_DEV_TOOLS={}),global.window._COMLINK_DEV_TOOLS[this._instanceID]=this,console.log("[COMLINK] Devtools enabled with instanceID: "+this._instanceID))}async connect(){let e=[];for(let t of Object.keys(this._channels)){let n=this._channels[t];"ws"!==n.type||n.alive||e.push(n.connect())}return Promise.all(e)}channel(e){if(!this._channels[e])throw new Error(`No channel registered with ${e}`);let t=this;const n={};return n.name=this._channels[e].name,n.alive=this._channels[e].alive,this._channels[e].connectable&&(n.connection=this._channels[e].connection,n.connect=this._channels[e].connect,n.terminate=this._channels[e].terminate),n.registerCallback=function(n,r){t._channels[e].callbacks[n]=r},n}registerDialect(e){const t=Object.assign({},e);t.router=t.router||function(e){return{path:e}},t.parameter=t.parameter||function(e){return{parameters:e}},t.optioner=t.optioner||function(){return{}},t.handler=t.handler||function(){return{}},this._dialects[t.name]=t,(t.default||null===this._defaultDialect)&&(this._defaultDialect=t.name)}registerHeader(e){this._headers[e.name]=e}registerChannel(e){if(!e.type in["http","ws"])throw new Error(`[Comlink] Channel type "${e.type}" is not supported!`);if("http"===e.type){const t=m.call(this,e);t.default&&(this._deafultHTTPChannel=t.name),t.default&&t.rpc&&(this._deafultRPCChannel=t.name),this._channels[t.name]=t}if("ws"===e.type){const t=_.call(this,e);t.default&&(this._deafultWSChannel=t.name),t.default&&t.rpc&&(this._deafultRPCChannel=t.name),this._channels[t.name]=t}}get headers(){return Object.keys(this._headers)}checkHeaders(){Object.keys(this._headers).forEach((e=>{const t=this._headers[e];if("automatic"===t.type){const e=t.storage.getItem(t.key);e&&(t.value=e)}}))}getHeader(e){if(!this._headers[e])throw new Error(`No registered header with name ${e}`);return{key:this._headers[e].key,value:this._headers[e].value}}setHeader(e,t){if(!this._headers[e])throw new Error(`No registered header with name ${e}`);this._headers[e].value=t,"automatic"===this._headers[e].type&&this._headers[e].storage.setItem(this._headers[e].key,t)}async get(e,t={}){this.checkDefaultHTTPChannel();const n=t.channel||this._deafultHTTPChannel,r=this._channels[n],o=f(r,t),a=t.onError||r.onError,i=o.work();try{let n=r.protocol+r.uri+"/"+e;/^https?:\/\//i.test(e)&&(n=e);const a=await s.default.get(n,t.axios||{});return await r.headerHandler(a.headers),a}catch(e){throw await r.headerHandler(e.response.headers),await a(e),e}finally{o.terminate(i)}}checkDefaultHTTPChannel(){if(!this._deafultHTTPChannel)throw new Error("[Comlink] No default HTTP channel")}async post(e,t,n={}){this.checkDefaultHTTPChannel();const r=n.channel||this._deafultHTTPChannel,o=this._channels[r],a=f(o,n),i=n.onError||o.onError,l=a.work();try{let r=o.protocol+o.uri+"/"+e;/^https?:\/\//i.test(e)&&(r=e);const i=await s.default.post(r,t,n.axios||{});return await o.headerHandler(i.headers),i}catch(e){throw await o.headerHandler(e.response.headers),await i(e),e}finally{a.terminate(l)}}async put(e,t,n={}){this.checkDefaultHTTPChannel();const r=n.channel||this._deafultHTTPChannel,o=this._channels[r],a=f(o,n),i=n.onError||o.onError,l=a.work();try{let r=o.protocol+o.uri+"/"+e;/^https?:\/\//i.test(e)&&(r=e);const i=await s.default.put(r,t,n.axios||{});return await o.headerHandler(i.headers),i}catch(e){throw await o.headerHandler(e.response.headers),await i(e),e}finally{a.terminate(l)}}async delete(e,t={}){this.checkDefaultHTTPChannel();const n=t.channel||this._deafultHTTPChannel,r=this._channels[n],o=f(r,t),a=t.onError||r.onError,i=o.work();try{let n=r.protocol+r.uri+"/"+e;/^https?:\/\//i.test(e)&&(n=e);const a=await s.default.delete(n,t.axios||{});return await r.headerHandler(a.headers),a}catch(e){throw await r.headerHandler(e.response.headers),await a(e),e}finally{o.terminate(i)}}subscribeToEvent(e,t,n={}){const r=n.channel||this._deafultRPCChannel,o=this._channels[r];o.listeners[e]||(o.listeners[e]=[]),o.listeners[e].push(t)}unsubscribeFromEvent(e,t,n={}){const r=n.channel||this._deafultRPCChannel,o=this._channels[r];o.listeners[e]&&(o.listeners[e]=o.listeners[e].filter((e=>e!==t)))}sendMessage(){throw new Error("Not implemented yet!")}async _rpc(e="request",t,n,r,o){const s=this._channels[r.channel||this._deafultRPCChannel],a=this._dialects[o||this._defaultDialect],i=s.rpc;if(!i.dialects.includes(a.name))throw new Error(`The channel ${s.name} not supports the ${a.name} dialect`);const l=((i[a.name]||{}).idGenerator||i.idGenerator||d)();let c={id:l};(void 0===a.sendMeta||a.sendMeta)&&(c._dialect=a.name,c._type=e);const h=a.router(t),u=a.parameter(n),p=a.optioner(r);c=Object.assign({},c,a.interface,h,u,p),null===s.connection&&await s.connect(),s.connection.send(JSON.stringify(c));const f=new Promise(((e,t)=>{s.answers[l]={resolve:e,reject:t}})),m=new Promise(((e,t)=>{setTimeout((()=>{t(`[Comlink] Maximum retries exceeded for message: ${l}`)}),i.retryInterval*i.maxRetries)}));return Promise.race([f,m])}async _rpcHTTP(e="request",t,n,r,o){const a=this._channels[r.channel||this._deafultRPCChannel],i=this._dialects[o||this._defaultDialect],l=a.rpc;if(!i.type||"http"!==i.type)throw new Error("ComlinkDialect is not supported on HTTPChannel yet!");if("http"===i.type&&"request"!==e)throw new Error("HTTPDialect only supports request now!");if(!l.dialects.includes(i.name))throw new Error(`The channel ${a.name} not supports the ${i.name} dialect`);let c=await i.handler(t,n,r);try{return(await s.default(c)).data}catch(e){throw new Error(e.response.data.message)}}async request(e,t,n={},r){const o=n.channel||this._deafultRPCChannel,s=this._channels[o],a=f(s,n),i=n.onError||s.onError,l=a.work();try{return"http"===s.type?await this._rpcHTTP("request",e,t,n,r):await this._rpc("request",e,t,n,r)}catch(e){throw await i(e,n),e}finally{a.terminate(l)}}async inform(e,t,n={},r){const o=n.channel||this._deafultRPCChannel,s=this._channels[o],a=f(s,n),i=n.onError||s.onError,l=a.work();try{return s.type,await this._rpc("inform",e,t,n,r)}catch(e){throw await i(e),e}finally{a.terminate(l)}}},Server:class{constructor(e){this._dialects={},this._channels={},this._clients={},this.session={},this.eventEmitter=new w,this.logger=e||console}registerDialect(e){this._dialects[e.name]=e}registerChannel(e){if(e.auth&&!e.tokenValidator)throw new Error("For authentication you need a token validator");if("ws"!==e.type)throw new Error("Only websocket listeners implemented yet!");this._channels[e.name]=e,this.session[e.name]={clients:{},tokens:{}}}sendMessageToClient(e,t,n,r){if(!this.session[e].clients[t])throw new Error("No user with given clientID");this.eventEmitter.emit(`sendEventTo:${t}`,{_type:"event",event:n,message:r})}getClientIDByToken(e,t){let n=this.session[e].tokens[t].client;if(!n)throw new Error("No user with given token");return n}getTokenByClientID(e,t){let n=this.session[e].clients[t].token;if(!n)throw new Error("No user with given clientID");return n}isTokenActive(e,t){return!!this.session[e].tokens[t].client}isClientActive(e,t){return!!this.session[e].clients[t].token}applyChannel(e,t){const n=this._channels[e];if(!n)throw new Error(`Channel with name ${e} is not registered!`);t.on("connection",(async(t,r)=>{let o=d();if(this.session[e].clients[o]={},n.auth){const s=r.headers["sec-websocket-protocol"];if(!s||0===s.length)return t.close();if(!await n.tokenValidator(s))return t.close();this.session[e].clients[o].token=s,this.session[e].tokens[s]={client:o},t.id=o}this.eventEmitter.on(`sendEventTo:${o}`,(e=>{t.send(JSON.stringify(e))})),t.on("close",(async()=>{let n=this.session[e].clients[t.id].token;delete this.session[e].clients[t.id],delete this.session[e].tokens[n]})),t.on("message",(async r=>{const o=JSON.parse(r),s=o._dialect;if(!s)return;const a=o.id;this._channels[e].dialects.includes(s)||t.send(JSON.stringify({_type:"rpcError",id:a,error:`The used dialect ${s} is not supported on this channel`}));let i={};if(n.headerInjector)try{let r=await n.headerInjector(this.session[e].clients[t.id].token);i=Object.assign({},r)}catch(e){throw t.send(JSON.stringify({_type:"rpcError",id:a,error:e.message,headers:Object.assign({},i,{serverTime:Date.now()})})),e}let l={};l.token=this.session[e].clients[t.id].token,l.clientID=t.id;try{const e=await this._dialects[s].onRequest(o,l);"request"===o._type&&t.send(JSON.stringify({_type:"rpcResponse",id:a,result:e,headers:Object.assign({},i,{serverTime:Date.now()})}))}catch(e){throw t.send(JSON.stringify({_type:"rpcError",id:a,error:e.message,headers:Object.assign({},i,{serverTime:Date.now()})})),e}}))}))}},Storage:h,version:"2.0.0-alpha2"};e.default=y,Object.defineProperty(e,"__esModule",{value:!0})}(this["@dwmt/comlink"]=this["@dwmt/comlink"]||{},Cookies,axios); |
@@ -656,3 +656,9 @@ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var Cookies=require('js-cookie'),axios=require('axios');function _interopDefaultLegacy(e){return e&&typeof e==='object'&&'default'in e?e:{'default':e}}var Cookies__default=/*#__PURE__*/_interopDefaultLegacy(Cookies);var axios__default=/*#__PURE__*/_interopDefaultLegacy(axios);var inherits; | ||
let requestObject = await dialect.handler(path, data, options); | ||
return axios__default['default'](requestObject); | ||
try { | ||
let response = await axios__default['default'](requestObject); | ||
return response.data; | ||
} catch (err) { | ||
throw new Error(err.response.data.message); | ||
} | ||
} | ||
@@ -888,3 +894,3 @@ | ||
}var version = "2.0.0-alpha1";var Comlink = { | ||
}var version = "2.0.0-alpha2";var Comlink = { | ||
Client, | ||
@@ -891,0 +897,0 @@ Server, |
{ | ||
"name": "@dwmt/comlink", | ||
"version": "2.0.0-alpha1", | ||
"version": "2.0.0-alpha2", | ||
"description": "Communication library for lazy enthusiasts", | ||
@@ -5,0 +5,0 @@ "main": "dist/Comlink.js", |
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
100372
2510