@dasf/dasf-messaging
Version:
Typescript bindings for the DASF RPC messaging protocol.
115 lines (77 loc) • 31.4 kB
JavaScript
(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(n){Object.defineProperty(n,"__esModule",{value:!0}),function(r){r[r.DISABLE=0]="DISABLE",r[r.ENABLE=1]="ENABLE",r[r.LOGGING=2]="LOGGING"}(n.OperationMode||(n.OperationMode={})),function(r){r[r.CASE_STRICT=1]="CASE_STRICT",r[r.CASE_INSENSITIVE=2]="CASE_INSENSITIVE"}(n.PropertyMatchingRule||(n.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"}(n.ValueCheckingMode||(n.ValueCheckingMode={}))}(F)),F}var P={},N;function q(){if(N)return P;N=1,Object.defineProperty(P,"__esModule",{value:!0});var n=function(){function a(){}return a.MAPPING_PROPERTY="__jsonconvert__mapping__",a.MAPPER_PROPERTY="__jsonconvert__mapper__",a.CLASS_IDENTIFIER="__jsonconvert__class_identifier__",a}();P.Settings=n;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 n=function(){function r(){}return r}();return M.Any=n,M}var T;function W(){if(T)return v;T=1,Object.defineProperty(v,"__esModule",{value:!0});var n=D(),r=q(),a=_(),f=function(){function c(e,t,i,s){this._operationMode=n.OperationMode.ENABLE,this._valueCheckingMode=n.ValueCheckingMode.ALLOW_OBJECT_NULL,this._ignorePrimitiveChecks=!1,this._propertyMatchingRule=n.PropertyMatchingRule.CASE_STRICT,this._ignoreRequiredCheck=!1,e!==void 0&&e in n.OperationMode&&(this.operationMode=e),t!==void 0&&t in n.ValueCheckingMode&&(this.valueCheckingMode=t),i!==void 0&&(this.ignorePrimitiveChecks=i),s!==void 0&&(this.propertyMatchingRule=s)}return Object.defineProperty(c.prototype,"operationMode",{get:function(){return this._operationMode},set:function(e){e in n.OperationMode&&(this._operationMode=e)},enumerable:!0,configurable:!0}),Object.defineProperty(c.prototype,"valueCheckingMode",{get:function(){return this._valueCheckingMode},set:function(e){e in n.ValueCheckingMode&&(this._valueCheckingMode=e)},enumerable:!0,configurable:!0}),Object.defineProperty(c.prototype,"ignorePrimitiveChecks",{get:function(){return this._ignorePrimitiveChecks},set:function(e){this._ignorePrimitiveChecks=e},enumerable:!0,configurable:!0}),Object.defineProperty(c.prototype,"propertyMatchingRule",{get:function(){return this._propertyMatchingRule},set:function(e){e in n.PropertyMatchingRule&&(this._propertyMatchingRule=e)},enumerable:!0,configurable:!0}),Object.defineProperty(c.prototype,"ignoreRequiredCheck",{get:function(){return this._ignoreRequiredCheck},set:function(e){this._ignoreRequiredCheck=e},enumerable:!0,configurable:!0}),c.prototype.serialize=function(e,t){if(this.operationMode===n.OperationMode.DISABLE)return e;if(e instanceof Array)return this.serializeArray(e,t);if(typeof e=="object")return this.serializeObject(e,t);throw new Error(`Fatal error in JsonConvert. Passed parameter data in JsonConvert.serialize() is not in valid format (object or array).
`)},c.prototype.serializeObject=function(e,t){if(this.operationMode===n.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===n.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===n.OperationMode.LOGGING&&(console.log("----------"),console.log("Receiving JavaScript instance:"),console.log(e));var i={},s;t?s=new t:s=e;for(var l=0,p=Object.keys(s);l<p.length;l++){var y=p[l];try{this.serializeObject_loopProperty(e,s,y,i)}catch(m){throw this.operationMode===n.OperationMode.LOGGING&&(console.log("Failed to serialize property:"),console.log(m),console.log("----------")),m}}return this.operationMode===n.OperationMode.LOGGING&&(console.log("Returning JSON object:"),console.log(i),console.log("----------")),i},c.prototype.serializeArray=function(e,t){if(this.operationMode===n.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===n.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===n.OperationMode.LOGGING&&(console.log("----------"),console.log("Receiving JavaScript array:"),console.log(e));for(var i=[],s=0,l=e;s<l.length;s++){var p=l[s];i.push(this.serializeObject(p,t))}return this.operationMode===n.OperationMode.LOGGING&&(console.log("Returning JSON array:"),console.log(i),console.log("----------")),i},c.prototype.deserialize=function(e,t){if(this.operationMode===n.OperationMode.DISABLE)return e;if(e instanceof Array)return this.deserializeArray(e,t);if(typeof e=="object")return this.deserializeObject(e,t);throw new Error(`Fatal error in JsonConvert. Passed parameter json in JsonConvert.deserialize() is not in valid JSON format (object or array).
`)},c.prototype.deserializeObject=function(e,t){if(this.operationMode===n.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===n.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===n.OperationMode.LOGGING&&(console.log("----------"),console.log("Receiving JSON object:"),console.log(e));for(var i=new t,s=0,l=Object.keys(i);s<l.length;s++){var p=l[s];try{this.deserializeObject_loopProperty(i,p,e)}catch(y){throw this.operationMode===n.OperationMode.LOGGING&&(console.log("Failed to deserialize property:"),console.log(y),console.log("----------")),y}}return this.operationMode===n.OperationMode.LOGGING&&(console.log("Returning CLASS instance:"),console.log(i),console.log("----------")),i},c.prototype.deserializeArray=function(e,t){if(this.operationMode===n.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===n.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===n.OperationMode.DISABLE)return e;this.operationMode===n.OperationMode.LOGGING&&(console.log("----------"),console.log("Receiving JSON array:"),console.log(e));for(var i=[],s=0,l=e;s<l.length;s++){var p=l[s];i.push(this.deserializeObject(p,t))}return this.operationMode===n.OperationMode.LOGGING&&(console.log("Returning array of CLASS instances:"),console.log(i),console.log("----------")),i},c.prototype.serializeObject_loopProperty=function(e,t,i,s){var l=this.getClassPropertyMappingOptions(t,i);if(l!==null){var p=l.jsonPropertyName,y=l.expectedJsonType,m=l.isOptional,S=l.customConverter,C=e[i];if(typeof C>"u"){if(m||this._ignoreRequiredCheck)return;throw new Error('Fatal error in JsonConvert. Failed to map the JavaScript instance of class "'+t[r.Settings.CLASS_IDENTIFIER]+'" to JSON because the defined class property "'+i+`" does not exist or is not defined:
Class property:
`+i+`
JSON property:
`+p+`
`)}if(!(m&&C===null))try{s[p]=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 "'+t[r.Settings.CLASS_IDENTIFIER]+`" to JSON because of a type error.
Class property:
`+i+`
Class property value:
`+C+`
Expected type:
`+this.getExpectedType(y)+`
Runtime type:
`+this.getTrueType(C)+`
JSON property:
`+p+`
`+J.message+`
`)}}},c.prototype.deserializeObject_loopProperty=function(e,t,i){var s=this.getClassPropertyMappingOptions(e,t);if(s!==null){var l=s.jsonPropertyName,p=s.expectedJsonType,y=s.isOptional,m=s.customConverter,S=void 0;try{S=this.getObjectValue(i,l)}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 "'+l+`" does not exist:
Class property:
`+t+`
JSON property:
`+l+`
`)}if(!(y&&S===null))try{e[t]=m!==null?m.deserialize(S):this.verifyProperty(p,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:
`+t+`
Expected type:
`+this.getExpectedType(p)+`
JSON property:
`+l+`
JSON type:
`+this.getJsonType(S)+`
JSON value:
`+JSON.stringify(S)+`
`+C.message+`
`)}}},c.prototype.getClassPropertyMappingOptions=function(e,t){var i=e[r.Settings.MAPPING_PROPERTY];if(typeof i>"u")return null;for(var s=Object.getPrototypeOf(e);s!=null;){var l=s[r.Settings.CLASS_IDENTIFIER];if(l){var p=l+"."+t;if(typeof i[p]<"u")return i[p]}s=Object.getPrototypeOf(s)}return null},c.prototype.verifyProperty=function(e,t,i){if(e===a.Any||e===null||e===Object)return t;if(!(e instanceof Array)&&!(t instanceof Array))if(typeof e<"u"&&e.prototype.hasOwnProperty(r.Settings.CLASS_IDENTIFIER)){if(t===null){if(this.valueCheckingMode!==n.ValueCheckingMode.DISALLOW_NULL)return null;throw new Error(" Reason: Given value is null.")}return i?this.serializeObject(t,e):this.deserializeObject(t,e)}else if(e===a.Any||e===null||e===Object){if(t===null){if(this.valueCheckingMode!==n.ValueCheckingMode.DISALLOW_NULL)return null;throw new Error(" Reason: Given value is null.")}return t}else if(e===String||e===Number||e===Boolean){if(t===null){if(this.valueCheckingMode===n.ValueCheckingMode.ALLOW_NULL)return null;throw new Error(" Reason: Given value is null.")}if(e===String&&typeof t=="string"||e===Number&&typeof t=="number"||e===Boolean&&typeof t=="boolean")return t;if(this.ignorePrimitiveChecks)return t;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&&t instanceof Array){var s=[];if(t.length===0)return s;if(e.length===0)return t;for(var l=e.length<t.length,p=0;p<t.length;p++)l&&p>=e.length&&(e[p]=e[p-1]),s[p]=this.verifyProperty(e[p],t[p],i);return s}if(e instanceof Array&&t instanceof Object){var s=[];if(t.length===0)return s;if(e.length===0)return t;var l=e.length<Object.keys(t).length,p=0;for(var y in t)l&&p>=e.length&&(e[p]=e[p-1]),s[y]=this.verifyProperty(e[p],t[y]),p++;return s}if(e instanceof Array){if(t===null){if(this.valueCheckingMode!==n.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 t 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.")},c.prototype.getObjectValue=function(e,t){if(this.propertyMatchingRule===n.PropertyMatchingRule.CASE_INSENSITIVE){var i=Object.keys(e).reduce(function(s,l){return s[l.toLowerCase()]=l,s},{});t=i[t.toLowerCase()]}if(!(t in e))throw new Error;return e[t]},c.prototype.getExpectedType=function(e){var t="";if(e instanceof Array){t="[";for(var i=0;i<e.length;i++)i>0&&(t+=","),t+=this.getExpectedType(e[i]);return t+="]",t}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":"?????"},c.prototype.getJsonType=function(e){if(e===null)return"null";var t="";if(e instanceof Array){t="[";for(var i=0;i<e.length;i++)i>0&&(t+=","),t+=this.getJsonType(e[i]);return t+="]",t}else return typeof e},c.prototype.getTrueType=function(e){return typeof e},c}();return v.JsonConvert=f,v}var A={},G;function B(){if(G)return A;G=1,Object.defineProperty(A,"__esModule",{value:!0});var n=q(),r=_();function a(e){e[n.Settings.MAPPER_PROPERTY]=""}A.JsonConverter=a;function f(e){var t="",i=function(l){l.prototype[n.Settings.CLASS_IDENTIFIER]=t.length>0?t:l.name;var p=l.prototype[n.Settings.MAPPING_PROPERTY];if(p)for(var y=Object.keys(p).filter(function(J){return J.indexOf(n.Settings.CLASS_IDENTIFIER+".")===0}),m=0,S=y;m<S.length;m++){var C=S[m];p[C.replace(n.Settings.CLASS_IDENTIFIER,l.prototype[n.Settings.CLASS_IDENTIFIER])]=p[C],delete p[C]}},s=typeof e;switch(s){case"string":return t=e,i;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 c(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return function(i,s){var l=s,p=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:
`+s+`
Leave the decorator parameters empty if you do not wish to pass the first parameter.
`);l=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:
`+s+`
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:
`+s+`
Use "Any" to allow any type. You can import this class from "json2typescript".
`);l=e[0],p=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:
`+s+`
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:
`+s+`
Use "Any" to allow any type. You can import this class from "json2typescript".
`);l=e[0],p=e[1],y=e[2];break}typeof i[n.Settings.MAPPING_PROPERTY]>"u"&&(i[n.Settings.MAPPING_PROPERTY]=[]);var m=new n.MappingOptions;if(m.classPropertyName=s,m.jsonPropertyName=l,m.isOptional=y||!1,typeof p<"u"&&p!==null&&typeof p[n.Settings.MAPPER_PROPERTY]<"u"?m.customConverter=new p:m.expectedJsonType=p,typeof i[n.Settings.MAPPING_PROPERTY][n.Settings.CLASS_IDENTIFIER+"."+s]>"u")i[n.Settings.MAPPING_PROPERTY][n.Settings.CLASS_IDENTIFIER+"."+s]=m;else throw new Error(`Fatal error in JsonConvert. It is not allowed to add multiple decorators for the same property.
Class property:
`+s+`
`)}}return A.JsonProperty=c,A}var U;function Y(){if(U)return g;U=1,Object.defineProperty(g,"__esModule",{value:!0});var n=W();g.JsonConvert=n.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=(n,r,a,f)=>{for(var c=f>1?void 0:f?H(r,a):r,e=n.length-1,t;e>=0;e--)(t=n[e])&&(c=(f?t(r,a,c):t(c))||c);return f&&c&&V(r,a,c),c},R=(n=>(n.Ping="ping",n.Pong="pong",n.Info="info",n.ApiInfo="api_info",n.Request="request",n.Response="response",n.Log="log",n.Progress="progress",n))(R||{}),E=(n=>(n.ResponseTopic="response_topic",n.RequestContext="requestContext",n.RequestMessageId="requestMessageId",n.MessageType="messageType",n.SourceTopic="source_topic",n.Fragment="fragment",n.NumFragments="num_fragments",n.Status="status",n))(E||{}),z=(n=>(n.Success="success",n.Error="error",n.Running="running",n))(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 w=class{constructor(n){u(this,"messageId","");n&&(this.messageId=n)}};d([h.JsonProperty("messageId",String)],w.prototype,"messageId",2),w=d([h.JsonObject("DASFAcknowledgment")],w),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(n){return JSON.stringify(n)}deserialize(n){return n}};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()){console.error(f),this.responseResolvers.delete(f.context);const c=this.responseRejectHandler.get(f.context);c?(this.responseRejectHandler.delete(f.context),c(new Error(f.errorMsg))):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=>{var f;try{const c=JSON.parse(a.data),e=this.jsonCoder.deserializeObject(c,o.DASFModuleResponse);this.acknowledgeMessage(e);const t=e.getRequestContext();if(this.finishedContexts.has(t))return;if(e.getMessageType()==R.Progress){const i=this.jsonCoder.deserializeObject(JSON.parse(atob(c.payload)),o.DASFProgressReport),s=this.progressCallbacks.get(t);s&&s({message:i,props:e.properties})}else{if(e.isFragmented())if(this.contextResponseFragments.has(t)){let s=this.contextResponseFragments.get(t);if(s)if(s.push(e),s.length==e.getNumberOfFragments()){s=s.sort((p,y)=>p.getFragmentId()-y.getFragmentId());let l="";for(const p of s)l+=p.payload;e.payload=l,this.contextResponseFragments.delete(t)}else return}else{this.contextResponseFragments.set(t,[e]);return}const i=this.responseResolvers.get(t);if(i){const s=this.responseRejectHandler.get(t);if(this.responseResolvers.delete(t),this.progressCallbacks.delete(t),this.responseRejectHandler.delete(t),this.finishedContexts.add(t),e!=null&&e.properties&&((f=e.properties)==null?void 0:f.status)=="error"){let l;if(typeof e.payload<"u"?l=new Error(atob(e.payload)):l=new Error("Failed processing request "+t),typeof s<"u")s(l);else throw console.error(l),l}else i(e)}else console.warn("received a response for an unknown context: "+t,e)}}catch(c){console.error(c)}})})}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(c=>c.properties&&c.properties.status=="error"?"Error: "+atob(c.payload):JSON.parse(atob(c.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:c,reject:e}=Promise.withResolvers();return this.hasConnectionError()?e(new Error(this.connectionError)):(this.responseResolvers.set(r.context,c),this.responseRejectHandler.set(r.context,e),typeof a<"u"&&this.progressCallbacks.set(r.context,a),this.connected.then(t=>{const i=JSON.stringify(r);t.outgoingChannel.send(i)})),f}acknowledgeMessage(r){const a=this.jsonCoder.serializeObject(new w(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:c,reject:e}=Promise.withResolvers();return this.sendMessage(r).then(t=>{if(t.properties)try{const i=JSON.parse(t.properties[a]);a==R.ApiInfo?c(this.jsonCoder.deserializeObject(i,o.ModuleApiInfo)):c(i)}catch(i){console.warn(`Unable to retrieve backend module ${a}, got: `,t.properties[a]),e(i)}}),f}hasConnectionError(){return this.connectionError.length>0}}class Q{constructor(r,a,f="",c=""){u(this,"topic");u(this,"consumeTopic");u(this,"DASFConsumerURL");u(this,"DASFProducerURL");this.topic=a,this.consumeTopic=this.generateConsumeTopic(a),this.DASFConsumerURL=(c||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 b=class b{constructor(r,a,f,c,e="ws"){u(this,"topic");u(this,"consumeTopic");u(this,"DASFConsumerURL");u(this,"DASFProducerURL");this.topic=c,this.consumeTopic=this.generateConsumeTopic(c),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,c,e,t){let i=b.BASE_DASF_URL.replace("%host%",r).replace("%port%",a).replace("%namespace%",f).replace("%type%",c).replace("%topic%",e).replace("%protocol%",t);return c=="consumer"&&(i+=this.generateSubscriptionPrefix()+"?subscriptionType=Exclusive"),i}generateConsumeTopic(r){return r+"_"+this.generateRequestToken()}generateSubscriptionPrefix(){return"web-frontend-"+new Date().toISOString()}generateRequestToken(){return Math.random().toString(16).slice(2)}};u(b,"BASE_DASF_URL","%protocol%://%host%:%port%/ws/v2/%type%/non-persistent/public/%namespace%/%topic%/");let L=b;o.DASFConnection=$,o.MessageType=R,o.PropertyKeys=E,o.PulsarUrlBuilder=L,o.Status=z,o.WebsocketUrlBuilder=Q,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"})});