UNPKG

@dasf/dasf-messaging

Version:

Typescript bindings for the DASF RPC messaging protocol.

115 lines (77 loc) 31.2 kB
(function(o,g){typeof exports=="object"&&typeof module<"u"?g(exports):typeof define=="function"&&define.amd?define(["exports"],g):(o=typeof globalThis<"u"?globalThis:o||self,g(o["dasf-messaging"]={}))})(this,function(o){"use strict";var X=Object.defineProperty;var Z=(o,g,v)=>g in o?X(o,g,{enumerable:!0,configurable:!0,writable:!0,value:v}):o[g]=v;var u=(o,g,v)=>Z(o,typeof g!="symbol"?g+"":g,v);var g={},v={},F={},j;function D(){return j||(j=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),function(r){r[r.DISABLE=0]="DISABLE",r[r.ENABLE=1]="ENABLE",r[r.LOGGING=2]="LOGGING"}(t.OperationMode||(t.OperationMode={})),function(r){r[r.CASE_STRICT=1]="CASE_STRICT",r[r.CASE_INSENSITIVE=2]="CASE_INSENSITIVE"}(t.PropertyMatchingRule||(t.PropertyMatchingRule={})),function(r){r[r.ALLOW_NULL=1]="ALLOW_NULL",r[r.ALLOW_OBJECT_NULL=2]="ALLOW_OBJECT_NULL",r[r.DISALLOW_NULL=3]="DISALLOW_NULL"}(t.ValueCheckingMode||(t.ValueCheckingMode={}))}(F)),F}var P={},N;function q(){if(N)return P;N=1,Object.defineProperty(P,"__esModule",{value:!0});var t=function(){function a(){}return a.MAPPING_PROPERTY="__jsonconvert__mapping__",a.MAPPER_PROPERTY="__jsonconvert__mapper__",a.CLASS_IDENTIFIER="__jsonconvert__class_identifier__",a}();P.Settings=t;var r=function(){function a(){this.classPropertyName="",this.jsonPropertyName="",this.expectedJsonType=void 0,this.isOptional=!1,this.customConverter=null}return a}();return P.MappingOptions=r,P}var M={},k;function _(){if(k)return M;k=1,Object.defineProperty(M,"__esModule",{value:!0});var t=function(){function r(){}return r}();return M.Any=t,M}var T;function W(){if(T)return v;T=1,Object.defineProperty(v,"__esModule",{value:!0});var t=D(),r=q(),a=_(),f=function(){function i(e,n,s,c){this._operationMode=t.OperationMode.ENABLE,this._valueCheckingMode=t.ValueCheckingMode.ALLOW_OBJECT_NULL,this._ignorePrimitiveChecks=!1,this._propertyMatchingRule=t.PropertyMatchingRule.CASE_STRICT,this._ignoreRequiredCheck=!1,e!==void 0&&e in t.OperationMode&&(this.operationMode=e),n!==void 0&&n in t.ValueCheckingMode&&(this.valueCheckingMode=n),s!==void 0&&(this.ignorePrimitiveChecks=s),c!==void 0&&(this.propertyMatchingRule=c)}return Object.defineProperty(i.prototype,"operationMode",{get:function(){return this._operationMode},set:function(e){e in t.OperationMode&&(this._operationMode=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"valueCheckingMode",{get:function(){return this._valueCheckingMode},set:function(e){e in t.ValueCheckingMode&&(this._valueCheckingMode=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"ignorePrimitiveChecks",{get:function(){return this._ignorePrimitiveChecks},set:function(e){this._ignorePrimitiveChecks=e},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"propertyMatchingRule",{get:function(){return this._propertyMatchingRule},set:function(e){e in t.PropertyMatchingRule&&(this._propertyMatchingRule=e)},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"ignoreRequiredCheck",{get:function(){return this._ignoreRequiredCheck},set:function(e){this._ignoreRequiredCheck=e},enumerable:!0,configurable:!0}),i.prototype.serialize=function(e,n){if(this.operationMode===t.OperationMode.DISABLE)return e;if(e instanceof Array)return this.serializeArray(e,n);if(typeof e=="object")return this.serializeObject(e,n);throw new Error(`Fatal error in JsonConvert. Passed parameter data in JsonConvert.serialize() is not in valid format (object or array). `)},i.prototype.serializeObject=function(e,n){if(this.operationMode===t.OperationMode.DISABLE)return e;if(e===void 0)throw new Error(`Fatal error in JsonConvert. Passed parameter instance in JsonConvert.serializeObject() is undefined. This is not a valid JSON format. `);if(e===null){if(this.valueCheckingMode===t.ValueCheckingMode.DISALLOW_NULL)throw new Error(`Fatal error in JsonConvert. Passed parameter instance in JsonConvert.serializeObject() is undefined. You have specified to disallow null values. `);return e}else if(typeof e!="object"||e instanceof Array)throw new Error(`Fatal error in JsonConvert. Passed parameter instance in JsonConvert.serializeObject() is not of type object. `);this.operationMode===t.OperationMode.LOGGING&&(console.log("----------"),console.log("Receiving JavaScript instance:"),console.log(e));var s={},c;n?c=new n:c=e;for(var p=0,l=Object.keys(c);p<l.length;p++){var y=l[p];try{this.serializeObject_loopProperty(e,c,y,s)}catch(m){throw this.operationMode===t.OperationMode.LOGGING&&(console.log("Failed to serialize property:"),console.log(m),console.log("----------")),m}}return this.operationMode===t.OperationMode.LOGGING&&(console.log("Returning JSON object:"),console.log(s),console.log("----------")),s},i.prototype.serializeArray=function(e,n){if(this.operationMode===t.OperationMode.DISABLE)return e;if(e===void 0)throw new Error(`Fatal error in JsonConvert. Passed parameter instanceArray in JsonConvert.serializeArray() is undefined. This is not a valid JSON format. `);if(e===null){if(this.valueCheckingMode===t.ValueCheckingMode.DISALLOW_NULL)throw new Error(`Fatal error in JsonConvert. Passed parameter instanceArray in JsonConvert.serializeArray() is undefined. You have specified to disallow null values. `);return e}else if(typeof e!="object"||!(e instanceof Array))throw new Error(`Fatal error in JsonConvert. Passed parameter instanceArray in JsonConvert.serializeArray() is not of type array. `);this.operationMode===t.OperationMode.LOGGING&&(console.log("----------"),console.log("Receiving JavaScript array:"),console.log(e));for(var s=[],c=0,p=e;c<p.length;c++){var l=p[c];s.push(this.serializeObject(l,n))}return this.operationMode===t.OperationMode.LOGGING&&(console.log("Returning JSON array:"),console.log(s),console.log("----------")),s},i.prototype.deserialize=function(e,n){if(this.operationMode===t.OperationMode.DISABLE)return e;if(e instanceof Array)return this.deserializeArray(e,n);if(typeof e=="object")return this.deserializeObject(e,n);throw new Error(`Fatal error in JsonConvert. Passed parameter json in JsonConvert.deserialize() is not in valid JSON format (object or array). `)},i.prototype.deserializeObject=function(e,n){if(this.operationMode===t.OperationMode.DISABLE)return e;if(e===void 0)throw new Error(`Fatal error in JsonConvert. Passed parameter jsonObject in JsonConvert.deserializeObject() is undefined. This is not a valid JSON format. `);if(e===null){if(this.valueCheckingMode===t.ValueCheckingMode.DISALLOW_NULL)throw new Error(`Fatal error in JsonConvert. Passed parameter jsonObject in JsonConvert.deserializeObject() is undefined. You have specified to disallow null values. `);return e}else if(typeof e!="object"||e instanceof Array)throw new Error(`Fatal error in JsonConvert. Passed parameter jsonObject in JsonConvert.deserializeObject() is not of type object. `);this.operationMode===t.OperationMode.LOGGING&&(console.log("----------"),console.log("Receiving JSON object:"),console.log(e));for(var s=new n,c=0,p=Object.keys(s);c<p.length;c++){var l=p[c];try{this.deserializeObject_loopProperty(s,l,e)}catch(y){throw this.operationMode===t.OperationMode.LOGGING&&(console.log("Failed to deserialize property:"),console.log(y),console.log("----------")),y}}return this.operationMode===t.OperationMode.LOGGING&&(console.log("Returning CLASS instance:"),console.log(s),console.log("----------")),s},i.prototype.deserializeArray=function(e,n){if(this.operationMode===t.OperationMode.DISABLE)return e;if(e===void 0)throw new Error(`Fatal error in JsonConvert. Passed parameter jsonArray in JsonConvert.deserializeObject() is undefined. This is not a valid JSON format. `);if(e===null){if(this.valueCheckingMode===t.ValueCheckingMode.DISALLOW_NULL)throw new Error(`Fatal error in JsonConvert. Passed parameter jsonArray in JsonConvert.deserializeObject() is undefined. You have specified to disallow null values. `);return e}else if(typeof e!="object"||!(e instanceof Array))throw new Error(`Fatal error in JsonConvert. Passed parameter jsonArray in JsonConvert.deserializeArray() is not of type array. `);if(this.operationMode===t.OperationMode.DISABLE)return e;this.operationMode===t.OperationMode.LOGGING&&(console.log("----------"),console.log("Receiving JSON array:"),console.log(e));for(var s=[],c=0,p=e;c<p.length;c++){var l=p[c];s.push(this.deserializeObject(l,n))}return this.operationMode===t.OperationMode.LOGGING&&(console.log("Returning array of CLASS instances:"),console.log(s),console.log("----------")),s},i.prototype.serializeObject_loopProperty=function(e,n,s,c){var p=this.getClassPropertyMappingOptions(n,s);if(p!==null){var l=p.jsonPropertyName,y=p.expectedJsonType,m=p.isOptional,S=p.customConverter,C=e[s];if(typeof C>"u"){if(m||this._ignoreRequiredCheck)return;throw new Error('Fatal error in JsonConvert. Failed to map the JavaScript instance of class "'+n[r.Settings.CLASS_IDENTIFIER]+'" to JSON because the defined class property "'+s+`" does not exist or is not defined: Class property: `+s+` JSON property: `+l+` `)}if(!(m&&C===null))try{c[l]=S!==null?S.serialize(C):this.verifyProperty(y,C,!0)}catch(J){throw new Error('Fatal error in JsonConvert. Failed to map the JavaScript instance of class "'+n[r.Settings.CLASS_IDENTIFIER]+`" to JSON because of a type error. Class property: `+s+` Class property value: `+C+` Expected type: `+this.getExpectedType(y)+` Runtime type: `+this.getTrueType(C)+` JSON property: `+l+` `+J.message+` `)}}},i.prototype.deserializeObject_loopProperty=function(e,n,s){var c=this.getClassPropertyMappingOptions(e,n);if(c!==null){var p=c.jsonPropertyName,l=c.expectedJsonType,y=c.isOptional,m=c.customConverter,S=void 0;try{S=this.getObjectValue(s,p)}catch{}if(typeof S>"u"){if(y||this._ignoreRequiredCheck)return;throw new Error('Fatal error in JsonConvert. Failed to map the JSON object to the class "'+e[r.Settings.CLASS_IDENTIFIER]+'" because the defined JSON property "'+p+`" does not exist: Class property: `+n+` JSON property: `+p+` `)}if(!(y&&S===null))try{e[n]=m!==null?m.deserialize(S):this.verifyProperty(l,S)}catch(C){throw new Error('Fatal error in JsonConvert. Failed to map the JSON object to the class "'+e[r.Settings.CLASS_IDENTIFIER]+`" because of a type error. Class property: `+n+` Expected type: `+this.getExpectedType(l)+` JSON property: `+p+` JSON type: `+this.getJsonType(S)+` JSON value: `+JSON.stringify(S)+` `+C.message+` `)}}},i.prototype.getClassPropertyMappingOptions=function(e,n){var s=e[r.Settings.MAPPING_PROPERTY];if(typeof s>"u")return null;for(var c=Object.getPrototypeOf(e);c!=null;){var p=c[r.Settings.CLASS_IDENTIFIER];if(p){var l=p+"."+n;if(typeof s[l]<"u")return s[l]}c=Object.getPrototypeOf(c)}return null},i.prototype.verifyProperty=function(e,n,s){if(e===a.Any||e===null||e===Object)return n;if(!(e instanceof Array)&&!(n instanceof Array))if(typeof e<"u"&&e.prototype.hasOwnProperty(r.Settings.CLASS_IDENTIFIER)){if(n===null){if(this.valueCheckingMode!==t.ValueCheckingMode.DISALLOW_NULL)return null;throw new Error(" Reason: Given value is null.")}return s?this.serializeObject(n,e):this.deserializeObject(n,e)}else if(e===a.Any||e===null||e===Object){if(n===null){if(this.valueCheckingMode!==t.ValueCheckingMode.DISALLOW_NULL)return null;throw new Error(" Reason: Given value is null.")}return n}else if(e===String||e===Number||e===Boolean){if(n===null){if(this.valueCheckingMode===t.ValueCheckingMode.ALLOW_NULL)return null;throw new Error(" Reason: Given value is null.")}if(e===String&&typeof n=="string"||e===Number&&typeof n=="number"||e===Boolean&&typeof n=="boolean")return n;if(this.ignorePrimitiveChecks)return n;throw new Error(" Reason: Given object does not match the expected primitive type.")}else throw new Error(` Reason: Expected type is unknown. There might be multiple reasons for this: - You are missing the decorator @JsonObject (for object mapping) - You are missing the decorator @JsonConverter (for custom mapping) before your class definition - Your given class is undefined in the decorator because of circular dependencies`);if(e instanceof Array&&n instanceof Array){var c=[];if(n.length===0)return c;if(e.length===0)return n;for(var p=e.length<n.length,l=0;l<n.length;l++)p&&l>=e.length&&(e[l]=e[l-1]),c[l]=this.verifyProperty(e[l],n[l],s);return c}if(e instanceof Array&&n instanceof Object){var c=[];if(n.length===0)return c;if(e.length===0)return n;var p=e.length<Object.keys(n).length,l=0;for(var y in n)p&&l>=e.length&&(e[l]=e[l-1]),c[y]=this.verifyProperty(e[l],n[y]),l++;return c}if(e instanceof Array){if(n===null){if(this.valueCheckingMode!==t.ValueCheckingMode.DISALLOW_NULL)return null;throw new Error(" Reason: Given value is null.")}throw new Error(" Reason: Expected type is array, but given value is non-array.")}throw n instanceof Array?new Error(" Reason: Given value is array, but expected a non-array type."):new Error(" Reason: Mapping failed because of an unknown error.")},i.prototype.getObjectValue=function(e,n){if(this.propertyMatchingRule===t.PropertyMatchingRule.CASE_INSENSITIVE){var s=Object.keys(e).reduce(function(c,p){return c[p.toLowerCase()]=p,c},{});n=s[n.toLowerCase()]}if(!(n in e))throw new Error;return e[n]},i.prototype.getExpectedType=function(e){var n="";if(e instanceof Array){n="[";for(var s=0;s<e.length;s++)s>0&&(n+=","),n+=this.getExpectedType(e[s]);return n+="]",n}else return e===a.Any||e===null||e===Object?"any":e===String||e===Boolean||e===Number?new e().constructor.name.toLowerCase():typeof e=="function"?new e().constructor.name:e===void 0?"undefined":"?????"},i.prototype.getJsonType=function(e){if(e===null)return"null";var n="";if(e instanceof Array){n="[";for(var s=0;s<e.length;s++)s>0&&(n+=","),n+=this.getJsonType(e[s]);return n+="]",n}else return typeof e},i.prototype.getTrueType=function(e){return typeof e},i}();return v.JsonConvert=f,v}var A={},G;function B(){if(G)return A;G=1,Object.defineProperty(A,"__esModule",{value:!0});var t=q(),r=_();function a(e){e[t.Settings.MAPPER_PROPERTY]=""}A.JsonConverter=a;function f(e){var n="",s=function(p){p.prototype[t.Settings.CLASS_IDENTIFIER]=n.length>0?n:p.name;var l=p.prototype[t.Settings.MAPPING_PROPERTY];if(l)for(var y=Object.keys(l).filter(function(J){return J.indexOf(t.Settings.CLASS_IDENTIFIER+".")===0}),m=0,S=y;m<S.length;m++){var C=S[m];l[C.replace(t.Settings.CLASS_IDENTIFIER,p.prototype[t.Settings.CLASS_IDENTIFIER])]=l[C],delete l[C]}},c=typeof e;switch(c){case"string":return n=e,s;case"function":case"undefined":default:throw new Error(`Fatal error in JsonConvert. It is mandatory to pass a string as parameter in the @JsonObject decorator. Use @JsonObject(classId) where classId is a string. `)}}A.JsonObject=f;function i(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return function(s,c){var p=c,l=r.Any,y=!1;switch(e.length){case 1:if(e[0]===void 0)throw new Error(`Fatal error in JsonConvert. It is not allowed to explicitly pass "undefined" as first parameter in the @JsonProperty decorator. Class property: `+c+` Leave the decorator parameters empty if you do not wish to pass the first parameter. `);p=e[0];break;case 2:if(e[0]===void 0)throw new Error(`Fatal error in JsonConvert. It is not allowed to explicitly pass "undefined" as first parameter in the @JsonProperty decorator. Class property: `+c+` Leave the decorator parameters empty if you do not wish to pass the first parameter. `);if(e[1]===void 0)throw new Error(`Fatal error in JsonConvert. It is not allowed to explicitly pass "undefined" as second parameter in the @JsonProperty decorator. Class property: `+c+` Use "Any" to allow any type. You can import this class from "json2typescript". `);p=e[0],l=e[1];break;case 3:if(e[0]===void 0)throw new Error(`Fatal error in JsonConvert. It is not allowed to explicitly pass "undefined" as first parameter in the @JsonProperty decorator. Class property: `+c+` Leave the decorator parameters empty if you do not wish to pass the first parameter. `);if(e[1]===void 0)throw new Error(`Fatal error in JsonConvert. It is not allowed to explicitly pass "undefined" as second parameter in the @JsonProperty decorator. Class property: `+c+` Use "Any" to allow any type. You can import this class from "json2typescript". `);p=e[0],l=e[1],y=e[2];break}typeof s[t.Settings.MAPPING_PROPERTY]>"u"&&(s[t.Settings.MAPPING_PROPERTY]=[]);var m=new t.MappingOptions;if(m.classPropertyName=c,m.jsonPropertyName=p,m.isOptional=y||!1,typeof l<"u"&&l!==null&&typeof l[t.Settings.MAPPER_PROPERTY]<"u"?m.customConverter=new l:m.expectedJsonType=l,typeof s[t.Settings.MAPPING_PROPERTY][t.Settings.CLASS_IDENTIFIER+"."+c]>"u")s[t.Settings.MAPPING_PROPERTY][t.Settings.CLASS_IDENTIFIER+"."+c]=m;else throw new Error(`Fatal error in JsonConvert. It is not allowed to add multiple decorators for the same property. Class property: `+c+` `)}}return A.JsonProperty=i,A}var U;function Y(){if(U)return g;U=1,Object.defineProperty(g,"__esModule",{value:!0});var t=W();g.JsonConvert=t.JsonConvert;var r=D();g.ValueCheckingMode=r.ValueCheckingMode,g.OperationMode=r.OperationMode;var a=B();g.JsonObject=a.JsonObject,g.JsonProperty=a.JsonProperty,g.JsonConverter=a.JsonConverter;var f=_();return g.Any=f.Any,g}var h=Y(),V=Object.defineProperty,H=Object.getOwnPropertyDescriptor,d=(t,r,a,f)=>{for(var i=f>1?void 0:f?H(r,a):r,e=t.length-1,n;e>=0;e--)(n=t[e])&&(i=(f?n(r,a,i):n(i))||i);return f&&i&&V(r,a,i),i},R=(t=>(t.Ping="ping",t.Pong="pong",t.Info="info",t.ApiInfo="api_info",t.Request="request",t.Response="response",t.Log="log",t.Progress="progress",t))(R||{}),E=(t=>(t.ResponseTopic="response_topic",t.RequestContext="requestContext",t.RequestMessageId="requestMessageId",t.MessageType="messageType",t.SourceTopic="source_topic",t.Fragment="fragment",t.NumFragments="num_fragments",t.Status="status",t))(E||{}),z=(t=>(t.Success="success",t.Error="error",t.Running="running",t))(z||{});o.DASFModuleRequest=class{constructor(){u(this,"payload","");u(this,"context","");u(this,"properties")}static createMessage(r){const a=new o.DASFModuleRequest;return a.properties={},a.properties.messageType=r,a}static createRequestMessage(r){const a=o.DASFModuleRequest.createMessage("request");return typeof r<"u"&&(a.payload=btoa(JSON.stringify(r))),a}static createPingMessage(){return o.DASFModuleRequest.createMessage("ping")}static createPongMessage(){return o.DASFModuleRequest.createMessage("pong")}static createInfoMessage(){return o.DASFModuleRequest.createMessage("info")}static createApiInfoMessage(){return o.DASFModuleRequest.createMessage("api_info")}getMessageType(){if(this.properties)return this.properties.messageType;throw new Error("Missing or empty message type property")}},d([h.JsonProperty("payload",String)],o.DASFModuleRequest.prototype,"payload",2),d([h.JsonProperty("properties",h.Any)],o.DASFModuleRequest.prototype,"properties",2),o.DASFModuleRequest=d([h.JsonObject("DASFModuleRequest")],o.DASFModuleRequest);let O=class{constructor(){u(this,"result","");u(this,"messageId","");u(this,"errorMsg","");u(this,"context","")}isOk(){return this.result=="ok"}};d([h.JsonProperty("result",String)],O.prototype,"result",2),d([h.JsonProperty("messageId",String,!0)],O.prototype,"messageId",2),d([h.JsonProperty("errorMsg",String,!0)],O.prototype,"errorMsg",2),d([h.JsonProperty("context",String,!0)],O.prototype,"context",2),O=d([h.JsonObject("DASFModuleRequestReceipt")],O);let b=class{constructor(t){u(this,"messageId","");t&&(this.messageId=t)}};d([h.JsonProperty("messageId",String)],b.prototype,"messageId",2),b=d([h.JsonObject("DASFAcknowledgment")],b),o.DASFModuleResponse=class{constructor(){u(this,"messageId","");u(this,"payload","");u(this,"publishTime","");u(this,"properties")}getMessageType(){if(this.properties){const r=this.properties.messageType;if(r&&r.trim().length>0)return r}throw new Error("Missing or empty message type property")}getRequestContext(){if(this.properties){const r=this.properties.requestContext;if(r)return r}throw new Error("Missing or empty request context property")}getRequestMessageId(){if(this.properties){const r=this.properties.requestMessageId;if(r)return r}throw new Error("Missing or empty request messageId property")}isFragmented(){return this.properties!=null&&Object.prototype.hasOwnProperty.call(this.properties,"num_fragments")&&Object.prototype.hasOwnProperty.call(this.properties,"fragment")}getFragmentId(){if(this.properties&&this.isFragmented())return this.properties.fragment;throw new Error("Unable to request fragment id from unfragmented response.")}getNumberOfFragments(){if(this.properties&&this.isFragmented())return this.properties.num_fragments;throw new Error("Unable to request number of fragments from unfragmented response.")}},d([h.JsonProperty("messageId",String)],o.DASFModuleResponse.prototype,"messageId",2),d([h.JsonProperty("payload",String)],o.DASFModuleResponse.prototype,"payload",2),d([h.JsonProperty("publishTime",String)],o.DASFModuleResponse.prototype,"publishTime",2),d([h.JsonProperty("properties")],o.DASFModuleResponse.prototype,"properties",2),o.DASFModuleResponse=d([h.JsonObject("DASFModuleResponse")],o.DASFModuleResponse),o.DASFProgressReport=class{constructor(){u(this,"report_type","");u(this,"report_id","");u(this,"step_message","");u(this,"steps",0);u(this,"status","running");u(this,"children")}hasError(){return this.status=="error"}hasSuccess(){return this.status=="success"}isRunning(){return this.status=="running"}isComplete(){return!this.isRunning()}},d([h.JsonProperty("report_type",String)],o.DASFProgressReport.prototype,"report_type",2),d([h.JsonProperty("report_id",String)],o.DASFProgressReport.prototype,"report_id",2),d([h.JsonProperty("step_message",String)],o.DASFProgressReport.prototype,"step_message",2),d([h.JsonProperty("steps",Number)],o.DASFProgressReport.prototype,"steps",2),d([h.JsonProperty("status",String)],o.DASFProgressReport.prototype,"status",2),d([h.JsonProperty("children",[o.DASFProgressReport])],o.DASFProgressReport.prototype,"children",2),o.DASFProgressReport=d([h.JsonObject("DASFProgressReport")],o.DASFProgressReport);let I=class{serialize(t){return JSON.stringify(t)}deserialize(t){return t}};I=d([h.JsonConverter],I),o.FunctionApiInfo=class{constructor(){u(this,"name","");u(this,"rpcSchema",{});u(this,"returnSchema",{})}},d([h.JsonProperty("name",String)],o.FunctionApiInfo.prototype,"name",2),d([h.JsonProperty("rpc_schema",I)],o.FunctionApiInfo.prototype,"rpcSchema",2),d([h.JsonProperty("return_schema",I)],o.FunctionApiInfo.prototype,"returnSchema",2),o.FunctionApiInfo=d([h.JsonObject("FunctionApiInfo")],o.FunctionApiInfo),o.ClassApiInfo=class{constructor(){u(this,"name","");u(this,"rpcSchema",{});u(this,"methods",[])}},d([h.JsonProperty("name",String)],o.ClassApiInfo.prototype,"name",2),d([h.JsonProperty("rpc_schema",I)],o.ClassApiInfo.prototype,"rpcSchema",2),d([h.JsonProperty("methods",[o.FunctionApiInfo])],o.ClassApiInfo.prototype,"methods",2),o.ClassApiInfo=d([h.JsonObject("ClassApiInfo")],o.ClassApiInfo),o.ModuleApiInfo=class{constructor(){u(this,"classes",[]);u(this,"functions",[]);u(this,"rpcSchema",{})}},d([h.JsonProperty("classes",[o.ClassApiInfo])],o.ModuleApiInfo.prototype,"classes",2),d([h.JsonProperty("functions",[o.FunctionApiInfo])],o.ModuleApiInfo.prototype,"functions",2),d([h.JsonProperty("rpc_schema",I)],o.ModuleApiInfo.prototype,"rpcSchema",2),o.ModuleApiInfo=d([h.JsonObject("ModuleApiInfo")],o.ModuleApiInfo);class ${constructor(r,a){u(this,"outgoingChannel");u(this,"incomingChannel");u(this,"DASFProducerURL");u(this,"DASFConsumerURL");u(this,"consumeTopic");u(this,"jsonCoder");u(this,"contextCounter",0);u(this,"responseResolvers",new Map);u(this,"progressCallbacks",new Map);u(this,"responseRejectHandler",new Map);u(this,"finishedContexts",new Set);u(this,"contextResponseFragments",new Map);u(this,"pendingRequests",[]);u(this,"waitingForPong",!1);u(this,"connectionTimeout",1e4);u(this,"connectionError","");u(this,"onConnectionError");u(this,"startedReconnectOutgoing",!0);u(this,"startedReconnectIncoming",!0);this.onConnectionError=a,this.consumeTopic=r.consumeTopic,this.DASFProducerURL=r.DASFProducerURL,this.DASFConsumerURL=r.DASFConsumerURL,this.jsonCoder=new h.JsonConvert,this.connect(),setInterval(()=>this.checkConnection(),this.connectionTimeout)}connect(){this.startedReconnectIncoming=!0,this.startedReconnectOutgoing=!0,this.outgoingChannel=new WebSocket(this.DASFProducerURL),this.incomingChannel=new WebSocket(this.DASFConsumerURL),this.registerListener()}isConnected(){return this.outgoingChannel&&this.incomingChannel&&this.outgoingChannel.readyState==WebSocket.OPEN&&this.incomingChannel.readyState==WebSocket.OPEN}isConnecting(){return this.outgoingChannel&&this.incomingChannel&&this.outgoingChannel.readyState!=WebSocket.OPEN&&this.incomingChannel.readyState!=WebSocket.OPEN}get connected(){const r=(a,f)=>{this.hasConnectionError()?f(new Error(this.connectionError)):this.assureConnected()?a(this):setTimeout(()=>r(a,f),100)};return new Promise(r)}assureConnected(){return this.isConnected()?!0:(this.startedReconnectIncoming||this.startedReconnectOutgoing||this.isConnecting()||this.connect(),!1)}hasPendingRequests(){return this.pendingRequests.length>0}sendPendingRequests(){if(this.hasPendingRequests()){const r=this.pendingRequests.shift();this.outgoingChannel.send(JSON.stringify(r)),setTimeout(()=>this.sendPendingRequests(),200)}}registerListener(){const r=a=>{this.startedReconnectOutgoing=!1,this.startedReconnectIncoming=!1,!this.hasConnectionError()&&this.isConnecting()&&(this.connectionError="Connection to "+a.target.url+" failed.",this.onConnectionError&&this.onConnectionError(this.connectionError))};this.outgoingChannel.addEventListener("error",r),this.incomingChannel.addEventListener("error",r),this.outgoingChannel.addEventListener("open",()=>{this.startedReconnectOutgoing=!1,this.connectionError="",this.outgoingChannel.addEventListener("message",a=>{const f=this.jsonCoder.deserializeObject(JSON.parse(a.data),O);if(f.isOk())this.responseRejectHandler.delete(f.context);else{console.error(f),this.responseResolvers.delete(f.context);const i=this.responseRejectHandler.get(f.context);i?(this.responseRejectHandler.delete(f.context),i(f)):console.error("received error receipt for an unknwon context: "+f.context)}})}),this.incomingChannel.addEventListener("open",()=>{this.startedReconnectIncoming=!1,this.connectionError="",this.incomingChannel.addEventListener("message",a=>{try{const f=JSON.parse(a.data),i=this.jsonCoder.deserializeObject(f,o.DASFModuleResponse);this.acknowledgeMessage(i);const e=i.getRequestContext();if(this.finishedContexts.has(e))return;if(i.getMessageType()==R.Progress){const n=this.jsonCoder.deserializeObject(JSON.parse(atob(f.payload)),o.DASFProgressReport),s=this.progressCallbacks.get(e);s&&s({message:n,props:i.properties})}else{if(i.isFragmented())if(this.contextResponseFragments.has(e)){let s=this.contextResponseFragments.get(e);if(s)if(s.push(i),s.length==i.getNumberOfFragments()){s=s.sort((p,l)=>p.getFragmentId()-l.getFragmentId());let c="";for(const p of s)c+=p.payload;i.payload=c,this.contextResponseFragments.delete(e)}else return}else{this.contextResponseFragments.set(e,[i]);return}const n=this.responseResolvers.get(e);n?(this.responseResolvers.delete(e),this.progressCallbacks.delete(e),this.responseRejectHandler.delete(e),this.finishedContexts.add(e),n(i)):console.warn("received a response for an unknown context: "+e,i)}}catch(f){console.error(f)}})})}checkConnection(){if(this.waitingForPong&&console.warn("Ping to backend module timed out."),this.startedReconnectOutgoing||this.startedReconnectIncoming)return;this.waitingForPong=!0;const r=o.DASFModuleRequest.createPingMessage();this.sendMessage(r).then(()=>{this.waitingForPong=!1,this.sendPendingRequests()}).catch(a=>{console.warn(a.errorMsg)})}async sendRequest(r,a){const f=o.DASFModuleRequest.createRequestMessage(r);return this.sendMessage(f,a).then(i=>i.properties&&i.properties.status=="error"?"Error: "+atob(i.payload):JSON.parse(atob(i.payload)))}async sendMessage(r,a){if(r.context=String(++this.contextCounter),!r.properties)throw new Error("missing request properties");r.properties[E.ResponseTopic]=this.consumeTopic,r.properties[E.RequestContext]=r.context;const{promise:f,resolve:i,reject:e}=Promise.withResolvers();if(!this.hasConnectionError())this.responseResolvers.set(r.context,i),this.responseRejectHandler.set(r.context,e),typeof a<"u"&&this.progressCallbacks.set(r.context,a),this.connected.then(n=>{const s=JSON.stringify(r);n.outgoingChannel.send(s)});else{const n=new O;n.context=r.context,n.errorMsg=this.connectionError,e(n)}return f}acknowledgeMessage(r){const a=this.jsonCoder.serializeObject(new b(r.messageId));this.incomingChannel.send(JSON.stringify(a))}close(){this.outgoingChannel.close(),this.incomingChannel.close()}getModuleInfo(){return this.sendInfoRequest(o.DASFModuleRequest.createInfoMessage(),R.Info)}getApiInfo(){return this.sendInfoRequest(o.DASFModuleRequest.createApiInfoMessage(),R.ApiInfo)}sendInfoRequest(r,a=R.Info){const{promise:f,resolve:i,reject:e}=Promise.withResolvers();return this.sendMessage(r).then(n=>{if(n.properties)try{const s=JSON.parse(n.properties[a]);a==R.ApiInfo?i(this.jsonCoder.deserializeObject(s,o.ModuleApiInfo)):i(s)}catch(s){console.warn(`Unable to retrieve backend module ${a}, got: `,n.properties[a]),e(s)}}),f}hasConnectionError(){return this.connectionError.length>0}}class Q{constructor(r,a,f="",i=""){u(this,"topic");u(this,"consumeTopic");u(this,"DASFConsumerURL");u(this,"DASFProducerURL");this.topic=a,this.consumeTopic=this.generateConsumeTopic(a),this.DASFConsumerURL=(i||this.buildUrl(r,this.consumeTopic))+"/"+this.generateSubscriptionPrefix(),this.DASFProducerURL=f||this.buildUrl(r,this.topic)}buildUrl(r,a){return r+"/"+a}generateConsumeTopic(r){return r+"_"+this.generateRequestToken()}generateSubscriptionPrefix(){return"web-frontend-"+new Date().toISOString()}generateRequestToken(){return Math.random().toString(16).slice(2)}}const w=class w{constructor(r,a,f,i,e="ws"){u(this,"topic");u(this,"consumeTopic");u(this,"DASFConsumerURL");u(this,"DASFProducerURL");this.topic=i,this.consumeTopic=this.generateConsumeTopic(i),this.DASFConsumerURL=this.buildUrl(r,a,f,"consumer",this.consumeTopic,e),this.DASFProducerURL=this.buildUrl(r,a,f,"producer",this.topic,e)}buildUrl(r,a,f,i,e,n){let s=w.BASE_DASF_URL.replace("%host%",r).replace("%port%",a).replace("%namespace%",f).replace("%type%",i).replace("%topic%",e).replace("%protocol%",n);return i=="consumer"&&(s+=this.generateSubscriptionPrefix()+"?subscriptionType=Exclusive"),s}generateConsumeTopic(r){return r+"_"+this.generateRequestToken()}generateSubscriptionPrefix(){return"web-frontend-"+new Date().toISOString()}generateRequestToken(){return Math.random().toString(16).slice(2)}};u(w,"BASE_DASF_URL","%protocol%://%host%:%port%/ws/v2/%type%/non-persistent/public/%namespace%/%topic%/");let L=w;o.DASFConnection=$,o.MessageType=R,o.PropertyKeys=E,o.PulsarUrlBuilder=L,o.Status=z,o.WebsocketUrlBuilder=Q,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"})});