wampy
Version:
Amazingly fast, feature-rich, lightweight WAMP Javascript client (for browser and node.js)
17 lines • 30.6 kB
JavaScript
;var __wampy_single_min__=(()=>{var u={HELLO:1,WELCOME:2,ABORT:3,CHALLENGE:4,AUTHENTICATE:5,GOODBYE:6,ERROR:8,PUBLISH:16,PUBLISHED:17,SUBSCRIBE:32,SUBSCRIBED:33,UNSUBSCRIBE:34,UNSUBSCRIBED:35,EVENT:36,CALL:48,CANCEL:49,RESULT:50,REGISTER:64,REGISTERED:65,UNREGISTER:66,UNREGISTERED:67,INVOCATION:68,INTERRUPT:69,YIELD:70},w={code:0,error:null},g={SUCCESS:"Success!",URI_ERROR:"Topic URI doesn't meet requirements!",NO_BROKER:"Server doesn't provide broker role!",NO_CALLBACK_SPEC:"No required callback function specified!",INVALID_PARAM:"Invalid parameter(s) specified!",NO_SERIALIZER_AVAILABLE:"Server has chosen a serializer, which is not available!",NON_EXIST_UNSUBSCRIBE:"Trying to unsubscribe from non existent subscription!",NO_DEALER:"Server doesn't provide dealer role!",RPC_ALREADY_REGISTERED:"RPC already registered!",NON_EXIST_RPC_UNREG:"Received rpc unregistration for non existent rpc!",NON_EXIST_RPC_INVOCATION:"Received invocation for non existent rpc!",NON_EXIST_RPC_REQ_ID:"No RPC calls in action with specified request ID!",NO_REALM:"No realm specified!",NO_WS_OR_URL:"No websocket provided or URL specified is incorrect!",NO_CRA_CB_OR_ID:"No onChallenge callback or authid was provided for authentication!",CHALLENGE_EXCEPTION:"Exception raised during challenge processing",PPT_NOT_SUPPORTED:"Payload Passthru Mode is not supported by the router",PPT_INVALID_SCHEME:"Provided PPT scheme is invalid",PPT_SRLZ_INVALID:"Provided PPT serializer is invalid or not supported",PPT_SRLZ_ERR:"Can not serialize/deserialize payload",PROTOCOL_VIOLATION:"Protocol violation",WAMP_ABORT:"Router aborted connection",WAMP_GENERAL_ERROR:"Wamp error",WEBSOCKET_ERROR:"Websocket error",FEATURE_NOT_SUPPORTED:"Feature not supported"},sr=["cbor"],er=typeof process=="object"&&Object.prototype.toString.call(process)==="[object process]",tr=/^_[a-z0-9_]{3,}$/;var B=class extends Error{code=1;constructor(){super(g.URI_ERROR),this.name="UriError"}},N=class extends Error{code=2;constructor(){super(g.NO_BROKER),this.name="NoBrokerError"}},v=class extends Error{code=3;constructor(){super(g.NO_CALLBACK_SPEC),this.name="NoCallbackError"}},E=class extends Error{code=4;parameter;constructor(r){super(g.INVALID_PARAM),this.name="InvalidParamError",this.parameter=r}},x=class extends Error{code=6;constructor(){super(g.NO_SERIALIZER_AVAILABLE),this.name="NoSerializerAvailableError"}},U=class extends Error{code=7;constructor(){super(g.NON_EXIST_UNSUBSCRIBE),this.name="NonExistUnsubscribeError"}},W=class extends Error{code=12;constructor(){super(g.NO_DEALER),this.name="NoDealerError"}},L=class extends Error{code=15;constructor(){super(g.RPC_ALREADY_REGISTERED),this.name="RPCAlreadyRegisteredError"}},M=class extends Error{code=17;constructor(){super(g.NON_EXIST_RPC_UNREG),this.name="NonExistRPCUnregistrationError"}},q=class extends Error{code=20;constructor(){super(g.NON_EXIST_RPC_REQ_ID),this.name="NonExistRPCReqIdError"}},D=class extends Error{code=21;constructor(){super(g.NO_REALM),this.name="NoRealmError"}},j=class extends Error{code=22;constructor(){super(g.NO_WS_OR_URL),this.name="NoWsOrUrlError"}},C=class extends Error{code=23;errorUri="wamp.error.cannot_authenticate";constructor(){super(g.NO_CRA_CB_OR_ID),this.name="NoCRACallbackOrIdError"}},G=class extends Error{code=24;errorUri="wamp.error.cannot_authenticate";constructor(){super(g.CHALLENGE_EXCEPTION),this.name="ChallengeExceptionError"}},S=class extends Error{code=25;constructor(){super(g.PPT_NOT_SUPPORTED),this.name="PPTNotSupportedError"}},z=class extends Error{code=26;constructor(){super(g.PPT_INVALID_SCHEME),this.name="PPTInvalidSchemeError"}},k=class extends Error{code=27;constructor(){super(g.PPT_SRLZ_INVALID),this.name="PPTSerializerInvalidError"}},I=class extends Error{code=28;constructor(){super(g.PPT_SRLZ_ERR),this.name="PPTSerializationError"}},V=class extends Error{code=29;errorUri;constructor(r,s){super(s||g.PROTOCOL_VIOLATION),this.name="ProtocolViolationError",this.errorUri=r}},H=class extends Error{code=30;errorUri;details;constructor({error:r,details:s}){super(g.WAMP_ABORT),this.name="AbortedError",this.errorUri=r,this.details=s}},P=class extends Error{code=31;errorUri;details;argsList;argsDict;constructor({error:r,details:s,argsList:e,argsDict:t}){super(g.WAMP_GENERAL_ERROR),this.name="WampError",this.errorUri=r,this.details=s,this.argsList=e,this.argsDict=t}},$=class extends P{code=32;constructor({error:r,details:s,argsList:e,argsDict:t}){super({error:r,details:s,argsList:e,argsDict:t}),this.name="SubscribeError"}},K=class extends P{code=33;constructor({error:r,details:s,argsList:e,argsDict:t}){super({error:r,details:s,argsList:e,argsDict:t}),this.name="UnsubscribeError"}},F=class extends P{code=34;constructor({error:r,details:s,argsList:e,argsDict:t}){super({error:r,details:s,argsList:e,argsDict:t}),this.name="PublishError"}},X=class extends P{code=35;constructor({error:r,details:s,argsList:e,argsDict:t}){super({error:r,details:s,argsList:e,argsDict:t}),this.name="RegisterError"}},Q=class extends P{code=36;constructor({error:r,details:s,argsList:e,argsDict:t}){super({error:r,details:s,argsList:e,argsDict:t}),this.name="UnregisterError"}},A=class extends P{code=37;constructor({error:r,details:s,argsList:e,argsDict:t}){super({error:r,details:s,argsList:e,argsDict:t}),this.name="CallError"}},O=class extends Error{code=38;error;constructor(r){super(g.WEBSOCKET_ERROR),this.name="WebsocketError",this.error=r}},Y=class extends Error{code=39;role;feature;constructor(r,s){super(g.FEATURE_NOT_SUPPORTED),this.name="FeatureNotSupportedError",this.role=r,this.feature=s}};function nr(l){return/^ws(s)?:\/\//.test(l)}function cr(l){return nr(l)?l:null}function lr(l){if(l&&nr(l))return l;let s=globalThis.location.protocol==="https:"?"wss://":"ws://",e=globalThis.location.port?`:${globalThis.location.port}`:"";return l?l.startsWith("/")?`${s}${globalThis.location.hostname}${e}${l}`:`${s}${l}`:`${s}${globalThis.location.hostname}${e}/ws`}function ur(l,r){return globalThis?.WebSocket?new globalThis.WebSocket(l,r):null}function rr({url:l,protocols:r,options:s,isBrowserMock:e}={}){let{ws:t,additionalHeaders:o,wsRequestOptions:c}=s||{},i=er&&!e;if(!t&&i)return null;let h=i?cr(l):lr(l);return h?t?new t(h,r,null,o,c):ur(h,r):null}function f(){let l={};return l.promise=new Promise(function(r,s){l.onSuccess=r,l.onError=s}),l}var T=class{protocol="json";isBinary=!1;encode(r){return JSON.stringify(r)}decode(r){return JSON.parse(r)}};var ir=new T,Z=class{version="v8.0.0";_url;_protocols;_wamp_features;_cache;_ws;_wsQueue;_requests;_calls;_subscriptionsById;_subscriptionsByKey;_rpcRegs;_rpcNames;_options;constructor(r,s){this._url=typeof r=="string"?r:null,this._protocols=["wamp.2.json"],this._wamp_features={agent:"Wampy.js "+this.version,roles:{publisher:{features:{subscriber_blackwhite_listing:!0,publisher_exclusion:!0,publisher_identification:!0,payload_passthru_mode:!0}},subscriber:{features:{pattern_based_subscription:!0,publication_trustlevels:!0,publisher_identification:!0,payload_passthru_mode:!0}},caller:{features:{caller_identification:!0,progressive_call_results:!0,call_canceling:!0,call_timeout:!0,payload_passthru_mode:!0}},callee:{features:{caller_identification:!0,call_trustlevels:!0,pattern_based_registration:!0,shared_registration:!0,payload_passthru_mode:!0}}}},this._cache={sessionId:null,reqId:0,server_wamp_features:{roles:{}},isSayingGoodbye:!1,opStatus:{code:0,error:null,reqId:0},timer:null,reconnectingAttempts:0,connectPromise:null,closePromise:null},this._ws=null,this._wsQueue=[],this._requests={},this._calls={},this._subscriptionsById=new Map,this._subscriptionsByKey=new Map,this._rpcRegs={},this._rpcNames=new Set,this._options={debug:!1,logger:null,autoReconnect:!0,reconnectInterval:2*1e3,maxRetries:25,realm:null,helloCustomDetails:null,uriValidation:"strict",authid:null,authmethods:[],authextra:{},authPlugins:{},authMode:"manual",onChallenge:null,onClose:null,onError:null,onReconnect:null,onReconnectSuccess:null,ws:null,additionalHeaders:null,wsRequestOptions:null,serializer:ir,payloadSerializers:{json:ir}},this._isPlainObject(s)?this._options={...this._options,...s}:this._isPlainObject(r)&&(this._options={...this._options,...r})}_log(...r){if(this._options.debug&&this._options.logger)return this._options.logger(r)}_getReqId(){return++this._cache.reqId}_isPlainObject(r){let s=r?.constructor,e=s?.prototype;return Object.prototype.toString.call(r)==="[object Object]"&&typeof s=="function"&&Object.prototype.toString.call(e)==="[object Object]"&&Object.hasOwnProperty.call(e,"isPrototypeOf")}_setWsProtocols(){this._protocols=["wamp.2."+this._options.serializer.protocol]}_fillOpStatusByError(r){this._cache.opStatus={code:r.code,error:r,reqId:0}}_preReqChecks(r,s){if(this._cache.sessionId&&!this._cache.server_wamp_features.roles[s]){let e={dealer:new W,broker:new N};return this._fillOpStatusByError(e[s]),!1}return r&&!this._validateURI(r.topic,r.patternBased,r.allowWAMP)?(this._fillOpStatusByError(new B),!1):!0}_checkRouterFeature(r,s){return this._cache.server_wamp_features.roles[r].features[s]?!0:(this._fillOpStatusByError(new Y(r,s)),!1)}_checkPPTOptions(r,s){return this._checkRouterFeature(r,"payload_passthru_mode")?s.ppt_scheme.search(/^(wamp$|mqtt$|x_)/)<0?(this._fillOpStatusByError(new z),!1):s.ppt_scheme==="wamp"&&!sr.includes(s.ppt_serializer)?(this._fillOpStatusByError(new k),!1):!0:(this._fillOpStatusByError(new S),!1)}_validateURI(r,s,e){let t=this._options.uriValidation==="strict",o=this._options.uriValidation==="loose";if(!t&&!o||r.startsWith("wamp.")&&!e)return!1;let i,h;return t?(i=/^(\w+\.)*(\w+)$/,h=/^(\w+\.{1,2})*(\w+)$/):o&&(i=/^([^\s#.]+\.)*([^\s#.]+)$/,h=/^([^\s#.]+\.{1,2})*([^\s#.]+)$/),(s?h:i).test(r)}_packPPTPayload(r,s){let e=r,t=e?.argsList&&!Array.isArray(e.argsList),o=e?.argsDict&&!this._isPlainObject(e.argsDict);if(t||o){let R=t?e.argsList:e.argsDict;return this._fillOpStatusByError(new E(String(R))),{err:!0,payloadItems:[]}}let c=this._isPlainObject(r),{argsList:i,argsDict:h}=e??{},n,d;c&&!i&&!h?d=r:c?(n=i,d=h):Array.isArray(r)?n=r:n=[r];let a=[];if(!s.ppt_scheme)return n&&a.push(n),d&&(n||a.push([]),a.push(d)),{err:!1,payloadItems:a};let p={args:n,kwargs:d},_=p;if(s.ppt_serializer&&s.ppt_serializer!=="native"){let R=this._options.payloadSerializers[s.ppt_serializer];if(!R)return this._fillOpStatusByError(new k),{err:!0,payloadItems:a};try{_=R.encode(p)}catch{return this._fillOpStatusByError(new I),{err:!0,payloadItems:a}}}return a.push([_]),{err:!1,payloadItems:a}}_unpackPPTPayload(r,s,e){let t;if(!this._checkPPTOptions(r,e))return{err:this._cache.opStatus.error||!1};if(e.ppt_serializer&&e.ppt_serializer!=="native"){let o=this._options.payloadSerializers[e.ppt_serializer];if(!o)return{err:new k};try{t=o.decode(s)}catch{return{err:new I}}}else t=s;return{err:!1,args:t.args,kwargs:t.kwargs}}_encode(r){try{return this._options.serializer.encode(r)}catch{this._hardClose("wamp.error.protocol_violation","Can not encode message",!0)}}_decode(r){try{return this._options.serializer.decode(r)}catch{return this._hardClose("wamp.error.protocol_violation","Can not decode received message"),[]}}_hardClose(r,s,e=!1){this._log(s),this._wsQueue=[],e||this._send([u.ABORT,{message:s},r]);let t=new V(r,s);this._cache.connectPromise&&(this._cache.connectPromise.onError(t),this._cache.connectPromise=null),this._options.onError&&this._options.onError(t),this._ws.close()}_send(r){if(r&&this._wsQueue.push(this._encode(r)),this._ws&&this._ws.readyState===1&&this._cache.sessionId)for(;this._wsQueue.length>0;)this._ws.send(this._wsQueue.shift())}async _reject_ongoing_promises(r){let s=[];for(let e of Object.values(this._calls))e.onError&&s.push(e.onError(r));for(let e of Object.values(this._requests))e.callbacks?.onError&&s.push(e.callbacks.onError(r));await Promise.allSettled(s),this._requests={},this._calls={}}_resetState(){this._wsQueue=[],this._subscriptionsById.clear(),this._subscriptionsByKey.clear(),this._requests={},this._calls={},this._rpcRegs={},this._rpcNames=new Set,this._cache={reqId:0,reconnectingAttempts:0,opStatus:w,closePromise:null,connectPromise:null}}_initWsCallbacks(){this._ws.onopen=()=>this._wsOnOpen(),this._ws.onclose=async r=>this._wsOnClose(r),this._ws.onmessage=r=>this._wsOnMessage(r),this._ws.onerror=async r=>this._wsOnError(r)}_wsOnOpen(){let{helloCustomDetails:r,authmethods:s,authid:e,authextra:t,serializer:o,onError:c,realm:i}=this._options,h=this._ws.protocol?.split(".")?.[2],n=h===o.protocol;if(this._log(`Websocket connected. Server has chosen protocol: "${h}"`),!n)if(h==="json")this._options.serializer=new T;else{let p=new x;this._fillOpStatusByError(p),this._cache.connectPromise&&(this._cache.connectPromise.onError(p),this._cache.connectPromise=null),c&&c(p)}o.isBinary&&(this._ws.binaryType="arraybuffer");let d={...r,...this._wamp_features,...e?{authid:e,authmethods:s,authextra:t}:{}},a=this._encode([u.HELLO,i,d]);a&&this._ws.send(a)}async _wsOnClose(r){this._log("websocket disconnected. Info: ",r),await this._reject_ongoing_promises(new O("Connection closed")),(this._cache.sessionId||this._cache.reconnectingAttempts)&&this._options.autoReconnect&&(this._options.maxRetries===0||this._cache.reconnectingAttempts<this._options.maxRetries)&&!this._cache.isSayingGoodbye?(this._cache.sessionId=null,this._cache.timer=setTimeout(()=>{this._wsReconnect()},this._options.reconnectInterval)):(this._options.onClose&&this._options.onClose(),this._cache.closePromise&&(this._cache.closePromise.onSuccess(void 0),this._cache.closePromise=null),this._resetState(),this._ws=null)}async _wsOnMessage(r){let s=this._decode(r.data);this._log("websocket message received: ",s);let e=s[0],o={[u.WELCOME]:()=>this._onWelcomeMessage(s),[u.ABORT]:()=>this._onAbortMessage(s),[u.CHALLENGE]:()=>this._onChallengeMessage(s),[u.GOODBYE]:()=>this._onGoodbyeMessage(),[u.ERROR]:()=>this._onErrorMessage(s),[u.SUBSCRIBED]:()=>this._onSubscribedMessage(s),[u.UNSUBSCRIBED]:()=>this._onUnsubscribedMessage(s),[u.PUBLISHED]:()=>this._onPublishedMessage(s),[u.EVENT]:()=>this._onEventMessage(s),[u.RESULT]:()=>this._onResultMessage(s),[u.REGISTERED]:()=>this._onRegisteredMessage(s),[u.UNREGISTERED]:()=>this._onUnregisteredMessage(s),[u.INVOCATION]:()=>this._onInvocationMessage(s)}[e],c="wamp.error.protocol_violation";if(!o)return this._hardClose(c,`Received non-compliant WAMP message: "${e}"`);let i=[u.WELCOME,u.CHALLENGE].includes(e),h=!i&&e!==u.ABORT;if(i&&this._cache.sessionId)return this._hardClose(c,`Received message "${e}" after session was established`);if(h&&!this._cache.sessionId)return this._hardClose(c,`Received message "${e}" before session was established`);this._isRequestIdValid(s)&&await o()}_isRequestIdValid([r,s]){return!!(![u.SUBSCRIBED,u.UNSUBSCRIBED,u.PUBLISHED,u.RESULT,u.REGISTERED,u.UNREGISTERED].includes(r)||r===u.RESULT&&this._calls[s]||this._requests[s])}async _onWelcomeMessage([,r,s]){this._cache.sessionId=r,this._cache.server_wamp_features=s,this._cache.reconnectingAttempts?(this._cache.reconnectingAttempts=0,this._options.onReconnectSuccess&&await this._options.onReconnectSuccess(s),await Promise.allSettled([this._renewSubscriptions(),this._renewRegistrations()])):(this._cache.connectPromise.onSuccess(s),this._cache.connectPromise=null),this._send()}async _onAbortMessage([,r,s]){let e=new H({error:s,details:r});this._cache.connectPromise&&(this._cache.connectPromise.onError(e),this._cache.connectPromise=null),this._options.onError&&await this._options.onError(e),this._ws.close()}async _onChallengeMessage([,r,s]){let e,{authid:t,authMode:o,onChallenge:c,onError:i,authPlugins:h}=this._options;if(t&&o==="manual"&&typeof c=="function")e=new Promise(n=>{n(c(r,s))});else if(t&&o==="auto"&&typeof h[r]=="function")e=new Promise(n=>{n(h[r](r,s))});else{let n=new C;return this._fillOpStatusByError(n),this._ws.send(this._encode([u.ABORT,{message:n.message},"wamp.error.cannot_authenticate"])),i&&await i(n),this._ws.close()}try{let n=await e;this._ws.send(this._encode([u.AUTHENTICATE,n,{}]))}catch{let n=new G;this._fillOpStatusByError(n),this._ws.send(this._encode([u.ABORT,{message:n.message},"wamp.error.cannot_authenticate"])),i&&await i(n),this._ws.close()}}async _onGoodbyeMessage(){this._cache.isSayingGoodbye||(this._cache.isSayingGoodbye=!0,this._send([u.GOODBYE,{},"wamp.close.goodbye_and_out"])),this._cache.sessionId=null,this._ws.close()}async _onErrorMessage([,r,s,e,t,o,c]){let i={error:t,details:e,argsList:o,argsDict:c},n={[u.SUBSCRIBE]:new $(i),[u.UNSUBSCRIBE]:new K(i),[u.PUBLISH]:new F(i),[u.REGISTER]:new X(i),[u.UNREGISTER]:new Q(i),[u.CALL]:new A(i)}[r];if(!n)return this._hardClose("wamp.error.protocol_violation","Received invalid ERROR message");if(r===u.CALL){let d=this._calls[s];d?.onError&&await d.onError(n),delete this._calls[s]}else{let d=this._requests[s];d?.callbacks?.onError&&await d.callbacks.onError(n),delete this._requests[s]}}async _onSubscribedMessage([,r,s]){let{topic:e,advancedOptions:t,callbacks:o}=this._requests[r],c={id:s,topic:e,advancedOptions:t,callbacks:[o.onEvent]},i=this._getSubscriptionKey(e,t);this._subscriptionsById.set(s,c),this._subscriptionsByKey.set(i,c),o.onSuccess&&await o.onSuccess({topic:e,requestId:r,subscriptionId:s,subscriptionKey:i}),delete this._requests[r]}async _onUnsubscribedMessage([,r]){let{topic:s,advancedOptions:e,callbacks:t}=this._requests[r],o=this._getSubscriptionKey(s,e),c=this._subscriptionsByKey.get(o).id;this._subscriptionsByKey.delete(o),this._subscriptionsById.delete(c),t.onSuccess&&await t.onSuccess({topic:s,requestId:r}),delete this._requests[r]}async _onPublishedMessage([,r,s]){let{topic:e,callbacks:t}=this._requests[r];t?.onSuccess&&await t.onSuccess({topic:e,requestId:r,publicationId:s}),delete this._requests[r]}async _onEventMessage([,r,s,e,t,o]){let c=this._subscriptionsById.get(r);if(!c)return;let i=t,h=o;if(e.ppt_scheme){let a=t[0],p=this._unpackPPTPayload("broker",a,e);if(p.err)return this._log(p.err.message);i=p.args,h=p.kwargs}let n={details:e,argsList:i,argsDict:h},d=c.callbacks.map(a=>a(n));await Promise.all(d)}async _onResultMessage([,r,s,e,t]){let o=e,c=t;if(s.ppt_scheme){let h=e[0],n=this._unpackPPTPayload("dealer",h,s);if(n.err){this._log(n.err.message),this._cache.opStatus=n.err,await this._calls[r].onError(new A({details:s,error:"wamp.error.invocation_exception",argsList:[n.err.message],argsDict:void 0})),delete this._calls[r];return}o=n.args,c=n.kwargs}let i={details:s,argsList:o,argsDict:c};s.progress?await this._calls[r].onProgress(i):(await this._calls[r].onSuccess(i),delete this._calls[r])}async _onRegisteredMessage([,r,s]){let{topic:e,callbacks:t,options:o}=this._requests[r];this._rpcRegs[s]={id:s,callbacks:[t.rpc],options:o},this._rpcRegs[e]=this._rpcRegs[s],this._rpcNames.add(e),t?.onSuccess&&await t.onSuccess({topic:e,requestId:r,registrationId:s}),delete this._requests[r]}async _onUnregisteredMessage([,r]){let{topic:s,callbacks:e}=this._requests[r];delete this._rpcRegs[this._rpcRegs[s].id],delete this._rpcRegs[s],this._rpcNames.has(s)&&this._rpcNames.delete(s),e?.onSuccess&&await e.onSuccess({topic:s,requestId:r}),delete this._requests[r]}async _onInvocationMessage([,r,s,e,t,o]){let c=this,i=({error:a,details:p,argsList:_,argsDict:R})=>{let b=[u.ERROR,u.INVOCATION,r,p||{},a||"wamp.error.invocation_exception"];Array.isArray(_)&&b.push(_),c._isPlainObject(R)&&(Array.isArray(_)||b.push([]),b.push(R)),c._send(b)};if(!this._rpcRegs[s])return this._log(g.NON_EXIST_RPC_INVOCATION),i({error:"wamp.error.no_such_procedure"});let h=t,n=o;if(e?.ppt_scheme){let a=t[0],p=this._unpackPPTPayload("dealer",a,e);if(p.err)return this._log(p.err.message),p.err instanceof S?this._hardClose("wamp.error.protocol_violation","Received INVOCATION in PPT Mode, while Dealer didn't announce it"):i({details:e,error:"wamp.error.invocation_exception",argsList:[p.err.message]});h=p.args,n=p.kwargs}let d=a=>{let p=a?.options||{},{ppt_scheme:_,ppt_serializer:R,ppt_cipher:b,ppt_keyid:y}=p;if(_&&!this._checkPPTOptions("dealer",p))return this._cache.opStatus.error instanceof S?this._hardClose("wamp.error.protocol_violation","Trying to send YIELD in PPT Mode, while Dealer didn't announce it"):i({details:p,error:"wamp.error.invalid_option",argsList:[this._cache.opStatus.error.message]});let{err:m,payloadItems:J}=a?this._packPPTPayload(a,p):{};if(m)return i({details:p,error:"wamp.error.invocation_exception",argsList:[this._cache.opStatus.error.message]});let ar={...p,..._?{ppt_scheme:_}:{},...R?{ppt_serializer:R}:{},...b?{ppt_cipher:b}:{},...y?{ppt_keyid:y}:{},...this._extractCustomOptions(p)};c._send([u.YIELD,r,ar,...J||[]])};try{let a=await this._rpcRegs[s].callbacks[0]({details:e,argsList:h,argsDict:n,result_handler:d,error_handler:i});d(a)}catch(a){i(a)}}async _wsOnError(r){this._log("websocket error");let s=new O(r);await this._reject_ongoing_promises(s),this._cache.connectPromise&&(this._cache.connectPromise.onError(s),this._cache.connectPromise=null),this._options.onError&&this._options.onError(s)}_wsReconnect(){this._log("websocket reconnecting..."),this._options.onReconnect&&this._options.onReconnect(),this._cache.reconnectingAttempts++,this._ws=rr({url:this._url,protocols:this._protocols,options:this._options}),this._initWsCallbacks()}async _renewSubscriptions(){let r,s=new Map(this._subscriptionsById);this._subscriptionsById.clear(),this._subscriptionsByKey.clear();for(let e of s.values())for(r=e.callbacks.length;r--;)try{await this.subscribe(e.topic,e.callbacks[r],e.advancedOptions)}catch(t){this._log(`cannot resubscribe to topic: ${e.topic}`,t),this._options.onError&&this._options.onError(t)}}async _renewRegistrations(){let r=this._rpcRegs,s=this._rpcNames;this._rpcRegs={},this._rpcNames=new Set;for(let e of s)try{await this.register(e,r[e].callbacks[0],r[e].options)}catch(t){this._log(`cannot renew registration of rpc: ${e}`,t),this._options.onError&&this._options.onError(t)}}_getSubscriptionKey(r,s){return`${r}${s?`-${JSON.stringify(s)}`:""}`}getOptions(){return this._options}setOptions(r){if(this._isPlainObject(r))return this._options={...this._options,...r},this}getOpStatus(){return this._cache.opStatus}getSessionId(){return this._cache.sessionId}async connect(r){if(r&&(this._url=r),!this._options.realm){let t=new D;throw this._fillOpStatusByError(t),t}let s=(this._options.authid?1:0)+(Array.isArray(this._options.authmethods)&&this._options.authmethods.length>0?1:0)+(typeof this._options.onChallenge=="function"||Object.keys(this._options.authPlugins).length>0?1:0);if(s>0&&s<3){let t=new C;throw this._fillOpStatusByError(t),t}if(this._setWsProtocols(),this._ws=rr({url:this._url,protocols:this._protocols,options:this._options}),!this._ws){let t=new j;throw this._fillOpStatusByError(t),t}this._initWsCallbacks();let e=f();return this._cache.connectPromise=e,e.promise}async disconnect(){if(this._cache.sessionId){let r=f();return this._cache.opStatus={...w,reqId:0},this._cache.closePromise=r,this._cache.isSayingGoodbye=!0,this._send([u.GOODBYE,{},"wamp.close.system_shutdown"]),r.promise}else this._ws&&this._ws.close();return!0}abort(){return!this._cache.sessionId&&this._ws.readyState===1&&(this._send([u.ABORT,{},"wamp.error.abort"]),this._cache.sessionId=null),this._ws.close(),this._cache.opStatus={...w,reqId:0},this}async subscribe(r,s,e){if(!this._isPlainObject(e)&&e!==void 0){let _=new E("advancedOptions");throw this._fillOpStatusByError(_),_}let{match:o,get_retained:c}=e||{},i=!1;if(o){if(!["exact","prefix","wildcard"].includes(o)){let _=new E("match");throw this._fillOpStatusByError(_),_}i=o!=="exact"}if(c&&typeof c!="boolean"){let _=new E("get_retained");throw this._fillOpStatusByError(_),_}if(!this._preReqChecks({topic:r,patternBased:i,allowWAMP:!0},"broker"))throw this._cache.opStatus.error;if(typeof s!="function"){let _=new v;throw this._fillOpStatusByError(_),_}let h=this._getSubscriptionKey(r,e),n=this._subscriptionsByKey.get(h);if(n&&n.callbacks.length>0)return n.callbacks.includes(s)||n.callbacks.push(s),{topic:r,requestId:0,subscriptionId:n.id,subscriptionKey:h};let d=this._getReqId(),a=f();a.onEvent=s,this._requests[d]={topic:r,callbacks:a,advancedOptions:e};let p={match:o,get_retained:c,...this._extractCustomOptions(e)};return this._send([u.SUBSCRIBE,d,p,r]),this._cache.opStatus={...w,reqId:d||0},a.promise}async unsubscribe(r,s){if(!this._preReqChecks(null,"broker"))throw this._cache.opStatus.error;let e=this._subscriptionsById.get(r)||this._subscriptionsByKey.get(r);if(!e){let c=new U;throw this._fillOpStatusByError(c),c}if(e.callbacks=typeof s=="function"?e.callbacks.filter(c=>c!==s):[],e.callbacks.length>0)return this._cache.opStatus={...w,reqId:0},!0;let o=this._getReqId();return this._requests[o]={topic:e.topic,callbacks:f()},this._send([u.UNSUBSCRIBE,o,e.id]),this._cache.opStatus={...w,reqId:o},this._requests[o].callbacks.promise}async publish(r,s,e){if(!this._preReqChecks({topic:r,patternBased:!1,allowWAMP:!1},"broker"))throw this._cache.opStatus.error;let t=this._isPlainObject(e);if(e&&!t){let m=new E("advancedOptions");throw this._fillOpStatusByError(m),m}let o={},c=(m,J)=>{if(e[m])if(Array.isArray(e[m])&&e[m].length>0)o[m]=e[m];else if(typeof e[m]===J)o[m]=[e[m]];else return!1;return!0};if(t&&(!c("exclude","number")||!c("exclude_authid","string")||!c("exclude_authrole","string")||!c("eligible","number")||!c("eligible_authid","string")||!c("eligible_authrole","string"))){let m=new E("advancedOptions");throw this._fillOpStatusByError(m),m}let{ppt_scheme:i,ppt_serializer:h,ppt_cipher:n,ppt_keyid:d,exclude_me:a,disclose_me:p,retain:_}=e||{};if(_&&typeof _!="boolean"){let m=new E("retain");throw this._fillOpStatusByError(m),m}if(i&&!this._checkPPTOptions("broker",e))throw this._cache.opStatus.error;o={acknowledge:!0,...o,...i?{ppt_scheme:i}:{},...i?{ppt_scheme:i}:{},...h?{ppt_serializer:h}:{},...n?{ppt_cipher:n}:{},...d?{ppt_keyid:d}:{},...a?{exclude_me:a}:{},...p?{disclose_me:p}:{},...this._extractCustomOptions(e)};let{err:R,payloadItems:b}=s?this._packPPTPayload(s,o):{},y=this._getReqId();if(R)throw this._cache.opStatus.error;return this._requests[y]={topic:r,callbacks:f()},this._cache.opStatus={...w,reqId:y},this._send([u.PUBLISH,y,o,r,...b||[]]),this._requests[y].callbacks.promise}_extractCustomOptions(r){let s={};for(let e in r||{})tr.test(e)&&(s[e]=r[e]);return s}_getCallMessageOptionsFromAdvancedOptions(r){let{timeout:s,progress:e,progress_callback:t,disclose_me:o,ppt_scheme:c,ppt_serializer:i,ppt_cipher:h,ppt_keyid:n,...d}=r||{},a={};return t&&(a.receive_progress=!0),e&&(a.progress=!0),o&&(a.disclose_me=!0),s&&(a.timeout=s),c&&(a.ppt_scheme=c),i&&(a.ppt_serializer=i),h&&(a.ppt_cipher=h),n&&(a.ppt_keyid=n),{...a,...this._extractCustomOptions(d)}}_callInternal(r,s,e){if(!this._preReqChecks({topic:r,patternBased:!1,allowWAMP:!0},"dealer"))throw this._cache.opStatus.error;if(e&&!this._isPlainObject(e)){let _=new E("advancedOptions");throw this._fillOpStatusByError(_),_}let{timeout:t,progress_callback:o,ppt_scheme:c}=e||{},i=t&&typeof t!="number";if(i||o&&typeof o!="function"){let _=i?"timeout":"progress_callback",R=new E(_);throw this._fillOpStatusByError(R),R}if(c&&!this._checkPPTOptions("dealer",e))throw this._cache.opStatus.error;let n;do n=this._getReqId();while(n in this._calls);let d=this._getCallMessageOptionsFromAdvancedOptions(e),{err:a,payloadItems:p}=s?this._packPPTPayload(s,d):{};if(a)throw this._cache.opStatus.error;return this._send([u.CALL,n,d,r,...p||[]]),this._cache.opStatus={...w,reqId:n},this._calls[n]=f(),o&&(this._calls[n].onProgress=o),n}async call(r,s,e){let t=this._callInternal(r,s,e);return this._calls[t].promise}progressiveCall(r,s,e){if(!this._checkRouterFeature("dealer","progressive_call_invocations"))throw this._cache.opStatus.error;e=e||{},e.progress=!0;let t=this._callInternal(r,s,e),o=this._getCallMessageOptionsFromAdvancedOptions(e),c=(i,h)=>{if(h&&!this._isPlainObject(h)){let _=new E("advancedOptions");throw this._fillOpStatusByError(_),_}let n=o,{progress:d}=h||{};if(d!==void 0)if(typeof d=="boolean")n.progress=d;else{let _=new E("progress");throw this._fillOpStatusByError(_),_}let{err:a,payloadItems:p}=i?this._packPPTPayload(i,o):{};if(a)throw this._cache.opStatus.error;this._send([u.CALL,t,o,r,...p||[]]),this._cache.opStatus={...w,reqId:t}};return{result:this._calls[t].promise,sendData:c}}cancel(r,s){if(!this._preReqChecks(null,"dealer")||!this._checkRouterFeature("dealer","call_canceling"))throw this._cache.opStatus.error;if(!r||!this._calls[r]){let o=new q;throw this._fillOpStatusByError(o),o}if(!this._isPlainObject(s)&&s!==void 0){let o=new E("advancedOptions");throw this._fillOpStatusByError(o),o}let e;if(this._isPlainObject(s)&&Object.hasOwnProperty.call(s,"mode")){if(!["skip","kill","killnowait"].includes(s.mode)){let o=new E("mode");throw this._fillOpStatusByError(o),o}e=s.mode}let t={...e?{mode:e}:{},...this._extractCustomOptions(s)};return this._send([u.CANCEL,r,t]),this._cache.opStatus={...w,reqId:r},!0}async register(r,s,e){if(this._rpcRegs[r]?.callbacks?.length){let a=new L;throw this._fillOpStatusByError(a),a}if(typeof s!="function"){let a=new v;throw this._fillOpStatusByError(a),a}if(e&&!this._isPlainObject(e)){let a=new E("advancedOptions");throw this._fillOpStatusByError(a),a}let{match:t,invoke:o}=e||{},c=t&&!["exact","prefix","wildcard"].includes(t),i=o&&!["single","roundrobin","random","first","last"].includes(o);if(c||i){let a=c?"match":"invoke",p=new E(a);throw this._fillOpStatusByError(p),p}if(!this._preReqChecks({topic:r,patternBased:!!t,allowWAMP:!1},"dealer"))throw this._cache.opStatus.error;let h=this._getReqId(),n=f(),d={...t?{match:t}:{},...o?{invoke:o}:{},...this._extractCustomOptions(e)};return s&&(n.rpc=s),this._requests[h]={topic:r,callbacks:n,options:d},this._send([u.REGISTER,h,d,r]),this._cache.opStatus={...w,reqId:h},n.promise}async unregister(r){if(!this._preReqChecks({topic:r,patternBased:!1,allowWAMP:!1},"dealer"))throw this._cache.opStatus.error;if(!this._rpcRegs[r]){let t=new M;throw this._fillOpStatusByError(t),t}let s=this._getReqId(),e=f();return this._requests[s]={topic:r,callbacks:e},this._send([u.UNREGISTER,s,this._rpcRegs[r].id]),this._cache.opStatus={...w,reqId:s},e.promise}};globalThis.Wampy=Z;})();
/**
* Project: wampy.js
*
* https://github.com/KSDaemon/wampy.js
*
* A lightweight client-side implementation of
* WAMP (The WebSocket Application Messaging Protocol v2)
* https://wamp-proto.org
*
* Provides asynchronous RPC/PubSub over WebSocket.
*
* Copyright 2014 KSDaemon. Licensed under the MIT License.
* See @license text at http://www.opensource.org/licenses/mit-license.php
*
*/
//# sourceMappingURL=wampy.min.js.map