@remix_labs/machine-starter 2.2598.0-dev → 2.2601.0-dev

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- var GROOVEBOX_BUILD = "2825";
1
+ var GROOVEBOX_BUILD = "2828";
2
2
  export { GROOVEBOX_BUILD }
@@ -1,2 +1,2 @@
1
1
  /*! For license information please see machine-wasm.js.LICENSE.txt */
2
- (()=>{"use strict";var e={811:(e,t)=>{var r=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,s=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,a=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,i=/\\([\u000b\u0020-\u00ff])/g,n=/([\\"])/g,o=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;function l(e){var t=String(e);if(a.test(t))return t;if(t.length>0&&!s.test(t))throw new TypeError("invalid parameter value");return'"'+t.replace(n,"\\$1")+'"'}function c(e){this.parameters=Object.create(null),this.type=e}t.format=function(e){if(!e||"object"!=typeof e)throw new TypeError("argument obj is required");var t=e.parameters,r=e.type;if(!r||!o.test(r))throw new TypeError("invalid type");var s=r;if(t&&"object"==typeof t)for(var i,n=Object.keys(t).sort(),c=0;c<n.length;c++){if(i=n[c],!a.test(i))throw new TypeError("invalid parameter name");s+="; "+i+"="+l(t[i])}return s},t.parse=function(e){if(!e)throw new TypeError("argument string is required");var t="object"==typeof e?function(e){var t;if("function"==typeof e.getHeader?t=e.getHeader("content-type"):"object"==typeof e.headers&&(t=e.headers&&e.headers["content-type"]),"string"!=typeof t)throw new TypeError("content-type header is missing from object");return t}(e):e;if("string"!=typeof t)throw new TypeError("argument string is required to be a string");var s=t.indexOf(";"),a=-1!==s?t.slice(0,s).trim():t.trim();if(!o.test(a))throw new TypeError("invalid media type");var n=new c(a.toLowerCase());if(-1!==s){var l,u,h;for(r.lastIndex=s;u=r.exec(t);){if(u.index!==s)throw new TypeError("invalid parameter format");s+=u[0].length,l=u[1].toLowerCase(),34===(h=u[2]).charCodeAt(0)&&-1!==(h=h.slice(1,-1)).indexOf("\\")&&(h=h.replace(i,"$1")),n.parameters[l]=h}if(s!==t.length)throw new TypeError("invalid parameter format")}return n}}},t={};function r(s){var a=t[s];if(void 0!==a)return a.exports;var i=t[s]={exports:{}};return e[s](i,i.exports,r),i.exports}r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),(()=>{let e=function(e){};globalThis.ThisIsNode;class t{constructor(e,t,r){this.rmxType=e,this.sender=t,this.payload="string"==typeof r?JSON.parse(r):r,this.eof=!1,this.localOnly=!1,this.header={_rmx_type:e,_rmx_encoding:"json",_rmx_sender:t},this.topic="",this.retained=!1}received(e,t){return this.topic=e,this.retained=t,this}publish(e,t,r){return this.topic=t,this.retained=r,{_rmx_type:"msg_hub_publish",header:this.header,reqId:e,topic:t,payload:JSON.stringify(this.payload),retained:r,localOnly:!1}}}class s{constructor(e,t,r){if("string"!=typeof r)throw new Error("payload must be string");this.rmxType=e,this.sender=t,this.payload=r,this.eof=!1,this.localOnly=!1,this.header={_rmx_type:e,_rmx_encoding:"json",_rmx_sender:t},this.topic="",this.retained=!1}received(e,t){return this.topic=e,this.retained=t,this}publish(e,t,r){return this.topic=t,this.retained=r,{_rmx_type:"msg_hub_publish",header:this.header,reqId:e,topic:t,payload:this.payload,retained:r,localOnly:!1}}}class a{constructor(e,t,r){this.rmxType=e,this.sender=t,this.payload=r,this.eof=!1,this.localOnly=!1,this.header={_rmx_type:e,_rmx_encoding:"text",_rmx_sender:t},this.topic="",this.retained=!1}received(e,t){return this.topic=e,this.retained=t,this}publish(e,t,r){return this.topic=t,this.retained=r,{_rmx_type:"msg_hub_publish",header:this.header,reqId:e,topic:t,payload:this.payload,retained:r,localOnly:!1}}}class i{constructor(e,t,r){this.rmxType=e,this.sender=t,this.payload=r,this.eof=!1,this.localOnly=!1,this.header={_rmx_type:e,_rmx_encoding:"binary",_rmx_sender:t},this.topic="",this.retained=!1}received(e,t){return this.topic=e,this.retained=t,this}publish(e,t,r){return this.topic=t,this.retained=r,{_rmx_type:"msg_hub_publish",header:this.header,reqId:e,topic:t,payload:this.payload,retained:r,localOnly:!1}}}class n{constructor(e,t,r){this.rmxType=e,this.sender=t,this.payload=r,this.eof=!1,this.localOnly=!0,this.header={_rmx_type:e,_rmx_encoding:"local",_rmx_sender:t},this.topic="",this.retained=!1}received(e,t){return this.topic=e,this.retained=t,this}publish(e,t,r){return this.topic=t,this.retained=r,{_rmx_type:"msg_hub_publish",header:this.header,reqId:e,topic:t,payload:this.payload,retained:r,localOnly:!0}}}class o{constructor(){this.rmxType="",this.sender="",this.payload=null,this.eof=!0,this.localOnly=!1,this.header={_rmx_type:"",_rmx_encoding:"eof",_rmx_sender:""},this.topic="",this.retained=!1}}function l(e){if(e.eof)return new o;switch(e.header._rmx_encoding){case"text":return new a(e.header._rmx_type,e.header._rmx_sender,e.payload).received(e.topic,e.retained);case"json":return new t(e.header._rmx_type,e.header._rmx_sender,e.payload).received(e.topic,e.retained);case"binary":return new i(e.header._rmx_type,e.header._rmx_sender,e.payload).received(e.topic,e.retained);case"local":return new n(e.header._rmx_type,e.header._rmx_sender,e.payload).received(e.topic,e.retained);default:throw new Error("bad _rmx_encoding: "+e.header._rmx_encoding)}}class c{constructor(e,t,r){this.channel=e,this.topic=t,this.subId=r,this.buffer=new Array,this.eof=!1,this.notify=()=>null,e.expect.set(r,(e=>{null!=e.data.error?console.warn("got an unexpected error message: "+e.data.error):(this.buffer.push(l(e.data)),this.eof=this.eof||e.data.eof,this.notify())}))}next(){return new Promise(((e,t)=>{this.buffer.length>0?e(this.buffer.shift()):this.notify=()=>{this.notify=()=>null,this.buffer.length>0&&e(this.buffer.shift())}}))}unsubscribe(){return new Promise(((e,t)=>{let r=this.channel.reqId+1;this.channel.reqId=r,this.channel.expect.set(r,(s=>{this.channel.expect.delete(r),null==s.data.error?e(s.data):t(s.data)}));let s={_rmx_type:"msg_hub_unsubscribe",topic:this.topic,reqId:r,subId:this.subId};this.channel.port.postMessage(s)}))}}class u{constructor(e){this.port=e,this.expect=new Map,this.reqId=0,this.port.onmessage=e=>{try{let t=this.expect.get(e.data.reqId);e.eof&&this.expect.delete(e.data.reqId),t(e)}catch(e){console.error("Exception when receiving a message in hub-client: ",e)}}}publish(e,t,r){return new Promise(((s,a)=>{let i=this.reqId+1;this.reqId=i,this.expect.set(i,(e=>{this.expect.delete(i),null==e.data.error?s(null):a(e.data)}));let n=t.publish(i,e,r);this.port.postMessage(n)}))}send(e,t){return this.publish(e,t,!1)}set(e,t){return this.publish(e,t,!0)}get(e){return new Promise(((t,r)=>{let s=this.reqId+1;this.reqId=s,this.expect.set(s,(e=>{this.expect.delete(s),null==e.data.error?void 0!==e.data.payload?t(l(e.data.payload)):t(void 0):r(e.data)}));let a={_rmx_type:"msg_hub_get",header:{_rmx_type:"msg_hub_get",_rmx_encoding:"json",_rmx_sender:this.sender},reqId:s,topic:e,payload:"null",retained:!1,localOnly:!0};this.port.postMessage(a)}))}subscribe(e){return new Promise(((t,r)=>{let s=this.reqId+1,a=s+1;this.reqId=a;let i=new c(this,e,a);this.expect.set(s,(e=>{this.expect.delete(s),null==e.data.error?t(i):r(e.data)}));let n={_rmx_type:"msg_hub_subscribe",topic:e,reqId:s,subId:a};this.port.postMessage(n)}))}setLocalPubTopic(e){return new Promise(((t,r)=>{let s=this.reqId+1;this.reqId=s,this.expect.set(s,(e=>{this.expect.delete(s),null==e.data.error?t(null):r(e.data)}));let a={_rmx_type:"msg_hub_setLocalPubTopic",topic:e,reqId:s};this.port.postMessage(a)}))}setLocalSubTopic(e){return new Promise(((t,r)=>{let s=this.reqId+1;this.reqId=s,this.expect.set(s,(e=>{this.expect.delete(s),null==e.data.error?t(null):r(e.data)}));let a={_rmx_type:"msg_hub_setLocalSubTopic",topic:e,reqId:s};this.port.postMessage(a)}))}newChannel(){return new Promise(((e,t)=>{let r=this.reqId+1;this.reqId=r,this.expect.set(r,(s=>{if(this.expect.delete(r),null==s.data.error){let t=void 0!==s.ports?s.ports[0]:s.data.port,r=new u(t);e(r)}else t(s.data)}));let s={_rmx_type:"msg_hub_newChannel",reqId:r};this.port.postMessage(s)}))}newJSONMessage(e,r,s){return new t(e,r,s)}newUnparsedJSONMessage(e,t,r){return new s(e,t,r)}newTextMessage(e,t,r){return new a(e,t,r)}newBinaryMessage(e,t,r){return new i(e,t,r)}newLocalMessage(e,t,r){return new n(e,t,r)}newEOF(e,t,r){return new o(e,t,r)}}const h={DEBUG_MESSAGES:256,DEBUG_QUEUES:512,DEBUG_OUTPUT:1024};class d{constructor(e,t){this.config=e.isConfig(),this.sboard=t.isSwitchboard(),this.ffiOverride={},this.mixcore=null,this.reset()}reset(){this.drvCount=0,this.drvRequest=null,this.drvSerial=[-1],this.drvEcho=new Array,this.mixCode=new Map,this.mixCodeName=new Map,this.standalone=!1,this.postponedError=null,this.subscriptions={},this.subNextId=0,this.wasm=null,this.cached_main_module=void 0,this.localFFIs={},this.created=!1,this.wantInitResult=!1,this.mixrt_code=null,void 0!==globalThis.mixrt_code&&null!==globalThis.mixrt_code&&(this.mixrt_code=globalThis.mixrt_code)}isState(){return this}}class m{constructor(){this.vmID="unknown-vmID",this.org="unknown-org",this.workspace="unknown-workspace",this.baseURL=void 0,this.user="unknown-user",this.token="unknown-token",this.outputViaMQTT=!0,this.debugMask=1024,this.machType="WASM",this.quickLoad=!1,this.interceptFFI=!1,this.interceptDynloadFFI=!1,this.mixcore=null}isConfig(){return this}topicBase(){return"/org/"+this.org+"/ws/"+this.workspace+"/vm/"+this.vmID}}class g{constructor(e,t,r){this.config=e.isConfig(),this.chan_driver=t,this.chan_async=r,this.FFIrelease=e=>null,this.wakeup=e=>null,this.reset()}reset(){this.queue=new Map,this.FFIrelease(),this.wakeup(),this.FFICoID=0,this.FFIname="",this.FFIrelease=e=>null,this.wakeup=e=>null}isSwitchboard(){return this}driverRequest(e){this.enqueue("driver",e)}asyncRequest(e){this.enqueue("async",e)}FFICall(e,t){this.enqueue("FFI",(async r=>{this.FFICoID=e,this.FFIname=t;let s=new Promise(((e,t)=>{this.FFIrelease=e}));await s,this.FFICoID=0,this.FFIname="",this.FFIrelease=e=>null}))}FFIReturn(e,t){this.FFIrelease(),this.FFICoID==e?this.enqueueUrgent("FFI",t):this.asyncRequest(t)}enqueue(e,t){let r=this.queue.get(e);void 0===r&&(r=[],this.queue.set(e,r)),r.push(t),this.wakeup()}enqueueUrgent(e,t){let r=this.queue.get(e);void 0===r&&(r=[],this.queue.set(e,r)),r.unshift(t),this.wakeup()}hasTasks(e){let t=this.queue.get(e);return void 0!==t&&t.length>0}async mainLoop(){let e="none";for(this.wakeup=e=>null;;)try{let t=this.findNextQueue(e);for(;"none"==t;){let r=new Promise(((e,t)=>{this.wakeup=e}));await r,this.wakeup=e=>null,t=this.findNextQueue(e)}let r,s=this.queue.get(t);switch(e=t,t){case"driver":r=this.chan_driver;break;case"async":case"FFI":r=this.chan_async}let a=s.shift();await a(r)}catch(e){console.error("mix machine: exception caught by mainLoop: ",e)}}findNextQueue(e){return this.hasTasks("FFI")?"FFI":this.hasTasks(e)?e:this.hasTasks("driver")?"driver":this.hasTasks("async")?"async":"none"}}function f(e,t){let r=e.instance.exports,s=e.call(r.mixrt_copyYGtoIO,t),a=s/4;if(0==s)return;let i=e.call(r.mixrt_getIO);e.call(r.mixrt_relocateOutput,i,a);let n=new Uint8Array(s);return n.set(e.mem8.subarray(i,i+s)),n}function p(e,t){let r=e.instance.exports,s=t.length,a=(s-1)/4+1;e.call(r.mixrt_growIO,a);let i=e.call(r.mixrt_getIO);if(e.mem8.subarray(i,i+s).set(t),!e.call(r.mixrt_relocateInput,i,a)){let t=e.call(r.mixrt_getError);throw new Error("copyInMixValue: cannot relocate value - code "+t)}return i}function b(e,t){let r=e.instance.exports,s=(new TextEncoder).encode(t),a=s.length,i=e.call(r.malloc,a+1);if(0==i)throw new Error("out of memory");return e.mem8.subarray(i,i+a).set(s),e.mem8[i+a]=0,i}function w(e,t){let r=e.instance.exports;e.call(r.free,t)}function _(e,t,r){let s=0;for(;0!=e.mem8[t+s]&&s<r;)s++;let a=new Uint8Array(s);return a.set(e.mem8.subarray(t,t+s)),(new TextDecoder).decode(a)}function y(e,t,r){let s=new Uint8Array(r);return s.set(e.mem8.subarray(t,t+r)),s}function x(e,t,r){let s=e.instance.exports,a=e.call(s.mixrt_initEnvGetEnv);if(0==a)return r;let i=b(e,t);if(0==i)return r;let n=e.call(s.mixrt_mapFindStatic,i,a);if(e.call(s.free,i),0==n)return r;let o=e.call(s.mixrt_getString,n);return 0==o?r:_(e,o,100)}const v=["unset","driver","async","FFI","internal"],E=3,T=8,k=247|1<<E|1<<T;class A{constructor(e,t,r){if(!e instanceof Uint8Array)throw new Error("Token: data must be an Uint8Array");if("number"!=typeof t)throw new Error("Token: enabled_ops must be a number");0==e.length&&(t=k),this.data=e,this.enabled=t,this.extras=r}}function I(e){if("string"!=typeof e)throw new Error("token must be a string");let t=(new TextEncoder).encode(e);return new A(t,1<<E|1<<T,{})}class S{constructor(e,t){if("string"!=typeof e)throw new Error("Case: name must be a string");this.name=e,this.arg=t}}class M{constructor(e){if(!(e instanceof Uint32Array))throw new Error("Opaque: must be a Uint32Array");this.data=e}}class F extends String{constructor(e){super(e),this.tagged=!0}}function D(e){let t="";for(let r=0;r<e.byteLength;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function U(e){let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}function C(e){if("string"!=typeof e)return null;if(!e.startsWith("{"))return null;let t=e.indexOf("}");if(t<0)return null;let r=e.substring(1,t),s=r.indexOf(":");return s>=0&&(r=r.substring(0,s)),r}function R(){return{encode_undefined:()=>({_rmx_type:"{tag}undefined"}),encode_bool:e=>e,encode_null:()=>null,encode_number:e=>{if(Number.isFinite(e))return e;if(Number.isNaN(e))return{_rmx_type:"{tag}nan"};if(e===Number.POSITIVE_INFINITY)return{_rmx_type:"{tag}posinf"};if(e===Number.NEGATIVE_INFINITY)return{_rmx_type:"{tag}neginf"};throw new Error("cannot categorize number: "+e)},encode_string:e=>e,encode_taggedString:e=>{let t=C(e);if(null==t)return e;let r=function(e){if("string"!=typeof e)return"";if(!e.startsWith("{"))return"";let t=e.indexOf("}");if(t<0)return"";let r=e.substring(1,t),s=r.indexOf(":");return s>=0?r.substring(s+1):""}(e);""!=r&&(r=":"+r);let s=function(e){if("string"!=typeof e)return"";if(!e.startsWith("{"))return"";let t=e.indexOf("}");return t<0?"":e.substring(t+1)}(e);return"ref"==t?{_rmx_type:"{tag}case:db.ref",_rmx_value:s}:{_rmx_type:"{tag}"+t+r,_rmx_value:s}},encode_binary:e=>({_rmx_type:"{tag}bin",_rmx_value:D(e)}),encode_opaque:e=>"<opaque>",encode_mapCreate:()=>({}),encode_mapSet:(e,t,r)=>{"_rmx_type"==t&&null!=C(r)?e[t]="{str}"+r:e[t]=r},encode_arrayCreate:()=>[],encode_arrayPush:(e,t)=>e.push(t),encode_case0:e=>({_rmx_type:"{tag}case:"+e}),encode_case1:(e,t)=>({_rmx_type:"{tag}case:"+e,_rmx_value:t}),encode_token:(e,t)=>"<opaque token>"}}function q(){return{encode_undefined:()=>{},encode_bool:e=>e,encode_null:()=>null,encode_number:e=>e,encode_string:e=>e,encode_taggedString:e=>new F(e),encode_binary:e=>e,encode_opaque:e=>new M(e),encode_mapCreate:()=>({}),encode_mapSet:(e,t,r)=>e[t]=r,encode_arrayCreate:()=>[],encode_arrayPush:(e,t)=>e.push(t),encode_case0:e=>new S(e,void 0),encode_case1:(e,t)=>new S(e,t),encode_token:(e,t,r)=>new A(e,t,r)}}function O(e,t,r){function s(r){return e[t+r]}function a(){return s(0)}function i(r,s){return e.subarray(t+r,t+r+s)}function n(t){return O(e,s(t)/4,r)}function o(){let e=i(3,a()-1),t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=t[t.length-1];return t.subarray(0,t.length-r-1)}function l(){let e=o();return(new TextDecoder).decode(e)}let c=255&s(1);switch(c){case 0:return r.encode_undefined();case 1:return r.encode_bool(0!=s(2));case 2:return r.encode_null();case 4:{let e=(u=i(2,2),new DataView(u.buffer,u.byteOffset,u.byteLength).getFloat64(0,!0));return r.encode_number(e)}case 7:return r.encode_mapCreate();case 8:return r.encode_string(l());case 9:return r.encode_taggedString(l());case 10:return r.encode_binary(o());case 12:{let e=a(),t=new Uint32Array(e);return t.set(i(2,e)),r.encode_opaque(t)}case 16:{let e=s(3),t=r.encode_arrayCreate();for(let s=0;s<e;s++){let e=n(4+s);r.encode_arrayPush(t,e)}return t}case 25:{let e=a()/2,t=r.encode_mapCreate();for(let s=0;s<e;s++){let e=n(2*s+2),a=n(2*s+3);r.encode_mapSet(t,e,a)}return t}case 17:{let s=r.encode_mapCreate(),a=[t];for(;a.length>0;){let t=a.shift();if(17==(255&e[t+1])){let i=O(e,e[t+3],r),n=O(e,e[t+4],r);r.encode_mapSet(s,i,n),a.push(e[t+5]),a.push(e[t+6])}}return s}case 26:{let e=n(2),t=n(3);return void 0===t?r.encode_case0(e):r.encode_case1(e,t)}case 28:{let e=s(2),t=n(3),a=n(4);return r.encode_token(e,t,a)}default:return"{unprintable: "+c+"}"}var u}function $(e,t,r){let s=e.instance.exports;switch(e.call(s.mixrt_getTag,t)){case 0:return r.encode_undefined();case 1:return r.encode_bool(0!=e.call(s.mixrt_getBool,t));case 2:return r.encode_null();case 4:return r.encode_number(e.call(s.mixrt_getNumber,t));case 7:return r.encode_mapCreate();case 8:{let a=e.call(s.mixrt_getString,t),i=_(e,a,1e7);return r.encode_string(i)}case 9:{let a=e.call(s.mixrt_getString,t),i=_(e,a,1e7);return r.encode_taggedString(i)}case 10:{let a=e.call(s.mixrt_getBinary,t),i=e.call(s.mixrt_getBinaryLength,t),n=y(e,a,i);return r.encode_binary(n)}case 12:{let s=function(e,t,r){let s=new Uint32Array(r);return s.set(e.mem32.subarray(t>>2,(t>>2)+r)),s}(e,t+8,e.mem32[t>>2]);return r.encode_opaque(s)}case 16:{let a=e.call(s.mixrt_arrayLength,t),i=r.encode_arrayCreate();for(let n=0;n<a;n++){let a=e.call(s.mixrt_arrayGet,t,n,!1),o=$(e,a,r);r.encode_arrayPush(i,o)}return i}case 17:{let a=e.call(s.mixrt_mapHeightLimit),i=e.call(s.malloc,4*a);if(0==i)throw new Error("out of memory");let n=r.encode_mapCreate(),o=e.call(s.mixrt_mapIterateStatic,i,a,t);for(;0!=o;){let t=e.call(s.mixrt_mapCurrentKey,o),a=$(e,t,r),l=e.call(s.mixrt_mapCurrentValue,o),c=$(e,l,r);r.encode_mapSet(n,a,c),o=e.call(s.mixrt_mapNextStatic,i)}return e.call(s.free,i),n}case 26:{let a,i=$(e,e.call(s.mixrt_caseName,t),r);return e.call(s.mixrt_caseHasArg,t)?(a=$(e,e.call(s.mixrt_caseGetArg,t),r),r.encode_case1(i,a)):r.encode_case0(i)}case 28:{let a=e.call(s.mixrt_tokenData,t),i=e.call(s.mixrt_getBinary,a),n=e.call(s.mixrt_getBinaryLength,a),o=y(e,i,n),l=e.call(s.mixrt_tokenEnabledOps,t),c=e.call(s.mixrt_tokenExtras,t),u=f(e,c);return r.encode_token(o,l,u)}default:return"{unprintable}"}}class B{constructor(e){this.data=e}}let G={tag_undefined:!0,tag_null:!0,tag_str:!0,tag_bin:!0,tag_nan:!0,tag_posinf:!0,tag_neginf:!0,tag_handle:!0,tag_tag:!0,tag_ref:!0};function L(){return{decode_type:e=>{switch(typeof e){case"undefined":return"undefined";case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(e instanceof S||function(e){let t=e._rmx_type;return void 0!==t&&"string"==typeof t&&!!t.startsWith("{tag}case:")&&"{tag}case:db.ref"!=t}(e))return"case";if(e instanceof A)return"token";if(e instanceof F)return"taggedString";if(e instanceof Uint8Array)return"binary";if(e instanceof B)return"valueOnly";let t=function(e){let t=e._rmx_type;if(void 0===t||"string"!=typeof t)return null;if(!t.startsWith("{tag}"))return null;if(t=t.substring(5),"case:db.ref"==t)return"ref";let r=t.indexOf(":");return r>=0&&(t=t.substring(0,r)),t}(e);if("string"==typeof t){let e="tag_"+t;if(G[e])return e}return"map";default:throw new Error("Cannot import this type of value: "+typeof e)}},decode_value:(e,t)=>{if(e.startsWith("tag_"))return void 0!==t._rmx_value?t._rmx_value:t.data;switch(e){case"case":if(!(t instanceof S)){let e=t._rmx_type.substring(10),r=t._rmx_value;return new S(e,r)}return t;case"map":let e=t._rmx_type;if(void 0!==e&&e.startsWith("{str}")){e=e.substring(5);let r={};return Object.assign(r,t),r._rmx_type=e,r}return t;default:return t}}}}function N(){return{decode_type:e=>{switch(typeof e){case"undefined":return"undefined";case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":return Array.isArray(e)?"array":null===e?"null":e instanceof S?"case":e instanceof A?"token":e instanceof F?"taggedString":e instanceof M?"opaque":e instanceof Uint8Array?"binary":e instanceof B?"valueOnly":"map";default:throw new Error("Cannot import this type of value: "+typeof e)}},decode_value:(e,t)=>t}}function P(e,t,r){function s(e,t){e.push(255&t,t>>8&255,t>>16&255,t>>24&255)}function a(e,t){e.push(2,0,0,0,4,0,0,0);let r=new DataView(new ArrayBuffer(8));r.setFloat64(0,t,!0),e.push(r.getUint8(0)),e.push(r.getUint8(1)),e.push(r.getUint8(2)),e.push(r.getUint8(3)),e.push(r.getUint8(4)),e.push(r.getUint8(5)),e.push(r.getUint8(6)),e.push(r.getUint8(7))}function i(e,t,r){let a=Math.floor(r.length/4)+2,i=4-r.length%4;s(e,a),s(e,t),s(e,0);for(let t of r)e.push(t);for(let t=0;t<i-1;t++)e.push(0);e.push(i-1),a%2==1&&s(e,4294967295)}function n(e,t,r){i(e,t,(new TextEncoder).encode(r))}function o(e,t){let r=new Array;s(r,e.length),e[t]=r[0],e[t+1]=r[1],e[t+2]=r[2],e[t+3]=r[3]}let l=r.decode_type(t),c=r.decode_value(l,t);switch(l){case"undefined":case"tag_undefined":!function(e){e.push(1,0,0,0,0,0,0,0,1,0,0,0,255,255,255,255)}(e);break;case"null":case"tag_null":!function(e){e.push(0,0,0,0,2,0,0,0)}(e);break;case"boolean":s(e,1),s(e,1),s(e,c?2:0),s(e,4294967295);break;case"number":a(e,c);break;case"tag_str":case"string":n(e,8,c);break;case"tag_bin":i(e,10,U(c));break;case"tag_nan":a(e,Number.NaN);break;case"tag_posinf":a(e,Number.POSITIVE_INFINITY);break;case"tag_neginf":a(e,Number.NEGATIVE_INFINITY);break;case"tag_handle":let u=parseInt(c);s(e,1),s(e,6),s(e,u),s(e,4294967295);break;case"tag_ref":case"taggedString":n(e,9,"{ref}"+c);break;case"binary":i(e,10,c);break;case"opaque":s(e,c.data.length),s(e,12);for(let t=0;t<c.data.length;t++)s(e,c.data[t]);c.data.length%2==1&&s(e,4294967295);break;case"array":{s(e,c.length+2),s(e,528),s(e,0),s(e,c.length);let t=e.length;for(let t=0;t<c.length;t++)s(e,0);c.length%2==1&&s(e,4294967295);for(let s=0;s<c.length;s++)o(e,t+4*s),P(e,c[s],r);break}case"case":{s(e,2),s(e,26);let t=e.length;s(e,0),s(e,0),o(e,t),P(e,c.name,r),o(e,t+4),P(e,c.arg,r);break}case"map":{let t=Symbol.iterator in c?c:Object.entries(c),a=0;for(const e of t)a++;t=Symbol.iterator in c?c:Object.entries(c),s(e,2*a),s(e,25);let i=e.length;for(let t=0;t<2*a;t++)s(e,0);for(const s of t)o(e,i),i+=4,P(e,s[0],r),o(e,i),i+=4,P(e,s[1],r);break}case"token":{let t=c.data,a=c.enabled,i=c.extras||{};s(e,3),s(e,284),s(e,a);let n=e.length;s(e,0);let l=e.length;s(e,0),s(e,4294967295),o(e,n),P(e,t,r),o(e,l),P(e,i,r);break}case"valueOnly":P(e,t.data,N());break;default:throw new Error("cannot import this type: "+l)}}function H(e,t,r){let s=t.decode_type(e),a=t.decode_value(s,e);switch(s){case"undefined":case"tag_undefined":return r.encode_undefined();case"null":case"tag_null":return r.encode_null();case"boolean":return r.encode_bool(1==a);case"number":return r.encode_number(a);case"tag_nan":return r.encode_number(Number.NaN);case"tag_posinf":return r.encode_number(Number.POSITIVE_INFINITY);case"tag_neginf":return r.encode_number(Number.NEGATIVE_INFINITY);case"tag_ref":case"taggedString":let e="{ref}"+a;return r.encode_taggedString(e);case"string":case"tag_str":return r.encode_string(a);case"binary":return r.encode_binary(a);case"tag_bin":return r.encode_binary(U(a));case"array":{let e=r.encode_arrayCreate();for(let s=0;s<a.length;s++)r.encode_arrayPush(e,H(a[s],t,r));return e}case"case":return void 0===a.arg?r.encode_case0(a.name):r.encode_case1(a.name,H(a.arg,t,r));case"map":{let e=r.encode_mapCreate(),s=Symbol.iterator in a?a:Object.entries(a);for(const a of s)e[a[0]]=H(a[1],t,r);return e}case"valueOnly":return H(a.data,N(),r);default:throw new Error("cannot recode this type: "+s)}}class j{constructor(e,t){this.buf=e,this.ptr=t||0}get(e){return this.buf[this.ptr+e]}at(e){let t=this.get(e)/4;return new j(this.buf,t)}tag(){return 255&this.get(1)}slice(){return this.buf.slice(this.ptr,this.ptr+2+this.get(0))}decode(){return O(this.buf,this.ptr,q())}checkTag(e){const t=this.tag();if(e!=t)throw new Error("expected tag "+e+" found "+t);return this}atArrayElt(e){let t=this.arrayLength();if(e>=t)throw new Error("index out of bounds ("+e+" >= "+t+")");return this.at(4+e)}arrayLength(){return this.checkTag(16),this.get(3)}atArrayPath(e){let t=this;for(let r of e)t=t.atArrayElt(r);return t}mapHeader(){return this.checkTag(25),this.get(0)/2}atMapValue(e){let t=this.mapHeader();if(e>=t)throw new Error("index out of bounds ("+e+" >= "+t+")");return this.at(2*e+1)}}function W(e){if(!Array.isArray(e))return!1;for(let t=0;t<e.length;e++)if("string"!=typeof e[t])return!1;return!0}function V(e,t,r){let s,a=e.url;if(void 0===a)throw new Error(r+": config key 'url' must be specified");if("string"!=typeof a)throw new Error(r+": config key 'url' must be a string");try{s=new URL(a)}catch(e){throw new Error(e.message)}if(!t.includes(s.protocol))throw new Error(r+": restricted to https/wss URLs, but got "+s.protocol);s.hash="";let i=e.params;if(void 0!==i){if(!function(e){if("object"!=typeof e)return!1;for(let t in e)if("string"!=typeof e[t])return!1;return!0}(i))throw new Error(r+": config key 'params' must be an object of strings");Object.keys(i).length>0&&(s.search=new URLSearchParams(i).toString())}return s}const Y=new Map,J="cloud-";let z=0;function Q(e){return e.startsWith(J)}function K(e){return"string"==typeof e&&e.startsWith("/cloud/")}function Z(e){return"string"==typeof e&&e.startsWith("$cloud")&&e.indexOf("/")>0}var X=r(811);function ee(e,t){let r=t[0];return new Promise((e=>{setTimeout((function(){e(null)}),1e3*r)}))}function te(e,t){return e.wasm.call(e.mixrt.mixrt_initEnvGetSyncProtocol)>0}function re(e,t){return 0!=e.wasm.call(e.mixrt.mixrt_initEnvGetMQTTEnabled)}function se(e,t){return null}function ae(e,t){return null}async function ie(e,t){let r={logMessages:[{severity:t[0].toString(),text:t[1].toString()}]};await e.publishMessage(r)}class ne extends Error{constructor(e){super(e)}}function oe(e,t,r,s){if("string"==typeof r)return r;if(!(r instanceof A))throw new Error("http.doRequest: config key '"+t+"' must be a token");return(new TextDecoder).decode(r.data)}function le(e,t){try{if(1!=t.length||"object"!=typeof t[0])throw new Error("http.doRequest: argument must be an object");let e,r=t[0],s={method:"GET",headers:new Headers};"string"==typeof r.method&&(s.method=r.method);try{let t=["https:","remix:"];globalThis.state.config.allowInsecureHttp&&t.push("http:"),e=V(r,t,"http.doRequest")}catch(e){throw console.error("Exception: ",e),new ne(e.message)}let a=r.body;if(void 0!==a){if("string"!=typeof a&&!(a instanceof Uint8Array))throw new Error("http.doRequest: config key 'body' must be a string");s.body=a}let i=r.oauthToken;if(void 0!==i){let t=oe(0,"oauthToken",i,e.hostname);""!=t&&(s.headers.set("Authorization","Bearer "+t),s.credentials="same-origin")}let n=r.basicAuth;if(void 0!==n){if("object"!=typeof n)throw new Error("http.doRequest: config key 'basicAuth' must be an object");let t=n.username;if("string"!=typeof t)throw new Error("http.doRequest: config key 'basicAuth.username' must be a string");let r=oe(0,"basicAuth.password",n.password,e.hostname),a=btoa(encodeURIComponent(t+":"+r).replace(/%([0-9A-F]{2})/g,(function(e,t){return String.fromCharCode("0x"+t)})));s.headers.set("Authorization","Basic "+a),s.credentials="include"}let o=r.headers;if("object"==typeof o)for(let e in o){let t=o[e];if("string"!=typeof t)throw new Error("http.doRequest: bad header in config object: "+e);s.headers.set(e,t)}let l=new Request(e,s),c=!0!==r.returnBinaryResponseBody,u=r.mediaTypes||{"*":new S("http.textMode",void 0)};if("object"!=typeof u)throw new Error("http.doRequest: bad mediaTypes setting in config object");let h=e=>{let t={};e.headers.forEach(((e,r)=>{var s;t[(s=r,s.split("-").map((e=>{let t=e.toLowerCase();return""!=t&&(t=e.substring(0,1).toUpperCase()+e.substring(1)),t})).join("-"))]=e}));let r=e.headers.get("content-type"),s="unset",a=!1;null==r&&(r="text/plain");let i=X.parse(r),n=i.type,o=i.type.indexOf("/");if(o>=0&&(n=i.type.substring(0,o)),c){let e=u[i.type];if(void 0===e&&(e=u[n+"/*"],void 0===e&&(e=u["*"],void 0===e&&(e=new S("http.binaryMode",void 0)))),!(e instanceof S))throw new Error("http.doRequest: bad mediaTypes setting in config object");switch(e.name){case"http.textMode":break;case"http.binaryMode":c=!1;break;default:throw new Error("http.doRequest: bad mediaTypes setting in config object")}}if(c){s=i.parameters.charset,a=void 0!==s;let e=a&&function(e){try{return new TextDecoder(e),!0}catch{return!1}}(s);e||(s="iso-8859-1"),a&&(t["X-Received-Content-Type"]=r,i.parameters.charset="utf-8",r=X.format(i),t["Content-Type"]=r)}return e.arrayBuffer().then((r=>{let i;if(c)if(a)i=new TextDecoder(s,{fatal:!1}).decode(r);else try{i=new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{i=new TextDecoder("iso-8859-1",{fatal:!1}).decode(r)}else i=new Uint8Array(r);return{headers:t,body:i,status:e.status}}))};return fetch(l).then((t=>h(t).then((t=>({status:t.status,headers:t.headers,requested_url:e.toString(),body:t.body}))))).catch((e=>(console.error("Exception",e),{error:e.message})))}catch(e){if(e instanceof ne)return console.error("Exception",e),{error:e.message};throw e}}function ce(e,t,r){if("string"==typeof r)return(new TextEncoder).encode(r);if(r instanceof Uint8Array)return r;if(r instanceof A)return r.data;throw new Error(t+": parameter is neither string nor binary nor token")}function ue(e){if(!e.startsWith("-----BEGIN PRIVATE KEY-----"))throw new Error(function_name+": RSA key must be in PKCS#8 PEM format");const t=e.substring(27,e.length-25),r=atob(t.replaceAll(/\s/g,"")),s=new ArrayBuffer(r.length),a=new Uint8Array(s);for(let e=0,t=r.length;e<t;e++)a[e]=r.charCodeAt(e);return s}function he(e,t){if(e.length!=t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function de(e,t){if(void 0===t[0])return;let r=ce(0,"$crypto_SHA1Sum",t[0]);return crypto.subtle.digest("SHA-1",r.buffer).then((e=>new Uint8Array(e)))}function me(e,t){if(void 0===t[0])return;let r=ce(0,"$crypto_SHA256Sum",t[0]);return crypto.subtle.digest("SHA-256",r.buffer).then((e=>new Uint8Array(e)))}function ge(e,t){if(void 0===t[0]||void 0===t[1])return;let r=ce(0,"$crypto_HMACSHA1Sign",t[0]),s=ce(0,"$crypto_HMACSHA1Sign",t[1]);return crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-1"},!1,["sign"]).then((e=>crypto.subtle.sign("HMAC",e,s))).then((e=>new Uint8Array(e)))}function fe(e,t){if(void 0===t[0]||void 0===t[1])return;let r=ce(0,"$crypto_HMACSHA1Verify",t[0]),s=ce(0,"$crypto_HMACSHA1Verify",t[1]),a=ce(0,"$crypto_HMACSHA1Verify",t[2]);return crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-1"},!1,["sign"]).then((e=>crypto.subtle.sign("HMAC",e,s))).then((e=>he(a,new Uint8Array(e))))}function pe(e,t){if(void 0===t[0]||void 0===t[1])return;let r=ce(0,"$crypto_HMACSHA256Sign",t[0]),s=ce(0,"$crypto_HMACSHA256Sign",t[1]);return crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},!1,["sign"]).then((e=>crypto.subtle.sign("HMAC",e,s))).then((e=>new Uint8Array(e)))}function be(e,t){if(void 0===t[0]||void 0===t[1])return;let r=ce(0,"$crypto_HMACSHA256Verify",t[0]),s=ce(0,"$crypto_HMACSHA256Verify",t[1]),a=ce(0,"$crypto_HMACSHA256Verify",t[2]);return crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},!1,["sign"]).then((e=>crypto.subtle.sign("HMAC",e,s))).then((e=>he(a,new Uint8Array(e))))}function we(e,t){if(void 0===t[0]||void 0===t[1])return;let r=function(e,t,r){var s="";if("string"==typeof r)s=r;else if(r instanceof Uint8Array)s=(new TextDecoder).decode(r);else{if(!(r instanceof A))throw new Error("$crypto_RSASHA256Sign: parameter is neither string nor binary nor token");s=(new TextDecoder).decode(r.data)}return ue(s)}(0,0,t[0]),s=ce(0,"$crypto_RSASHA256Sign",t[1]);return crypto.subtle.importKey("pkcs8",r,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["sign"]).then((e=>crypto.subtle.sign("RSASSA-PKCS1-v1_5",e,s))).then((e=>new Uint8Array(e)))}function _e(e,t){if(void 0===t[0]||void 0===t[2])return;let r=new Uint8Array(12);crypto.getRandomValues(r);let s,a=ce(0,"$crypto_AESGCMEncrypt",t[0]);void 0!==t[1]&&null!==t[1]&&(s=ce(0,"$crypto_AESGCMEncrypt",t[1]));let i=ce(0,"$crypto_AESGCMEncrypt",t[2]);return crypto.subtle.importKey("raw",a,"AES-GCM",!1,["encrypt"]).then((e=>crypto.subtle.encrypt({name:"AES-GCM",iv:r,additionalData:s},e,i))).then((e=>{let t=new Uint8Array(e),s=new Uint8Array(e.byteLength+12);return s.set(r),s.set(t,12),new S("ok",s)})).catch((e=>new S("error",e.message)))}function ye(e,t){if(void 0===t[0]||void 0===t[2])return;let r,s=ce(0,"$crypto_AESGCMDecrypt",t[0]);void 0!==t[1]&&null!==t[1]&&(r=ce(0,"$crypto_AESGCMDecrypt",t[1]));let a=ce(0,"$crypto_AESGCMDecrypt",t[2]);if(a.byteLength<12)return new S("error","message too short");let i=new Uint8Array(12);return i.set(a.subarray(0,12)),crypto.subtle.importKey("raw",s,"AES-GCM",!1,["decrypt"]).then((e=>{let t=new Uint8Array(a.byteLength-12);return t.set(a.subarray(12)),crypto.subtle.decrypt({name:"AES-GCM",iv:i,additionalData:r},e,t)})).then((e=>new S("ok",new Uint8Array(e)))).catch((e=>new S("error",e.message)))}function xe(e,t){let r=new Uint8Array(32);return crypto.getRandomValues(r),r}function ve(e){throw new Error("WASM FFI: "+e)}class Ee{constructor(e){this.instance=e,this.functions=[]}static async load(e){let t=await async function(e){let{instance:t}=await WebAssembly.instantiate(e);return void 0!==t.exports._rmx_allocate&&void 0!==t.exports._rmx_deallocate||ve("allocation/deallocation functions unavailable"),t}(e);return new Ee(t)}fun(e){let t=this.instance.exports[e];void 0===t&&ve("function not found: "+e);let r=this.functions.length;return this.functions.push(t),r}call(e,t){(e<0||this.functions.length<=e)&&ve("invalid function");let r=this.functions[e];return function(e,t,r){e.memory.buffer;let s=new Array;P(s,r,N());let a=s.length,i=e._rmx_allocate(s.length+4),n=new Uint32Array(e.memory.buffer,i),o=new Uint8Array(e.memory.buffer,i+4);n[0]=a,o.set(s);let l=t(i),c=new Uint32Array(e.memory.buffer,l),u=c[0],h=O(c.subarray(1,1+u/4),0,q());switch(e._rmx_deallocate(i,s.length+4),e._rmx_deallocate(l,u+4),!h instanceof S&&ve("Wasm call must return a case, actually got a "+h.constructor.name),h.name){case"ok":return h.arg;case"error":ve("Wasm call failed: "+h.arg);default:ve("Wasm call must return a result case, actually got a case "+h.name)}}(this.instance.exports,r,t)}}const Te={wasms:[],load:async function(e,t){let[r]=t,s=await Ee.load(r),a=this.wasms.length;return this.wasms.push(s),a},fun:function(e,t){let[r,s]=t;return(r<0||this.wasms.length<=r)&&ve("invalid instance"),[r,this.wasms[r].fun(s)]},call:function(e,t){let[[r,s],a]=t;(r<0||this.wasms.length<=r)&&ve("invalid instance");let i=this.wasms[r];return void 0===i&&ve("FFI has been shutdown"),i.call(s,a)},shutdown:function(e,t){let[r]=t;(r<0||this.wasms.length<=r)&&ve("invalid instance"),delete this.wasms[r]}};let ke=1,Ae=new Map;class Ie{constructor(e,t,r){let s=ke++;this.id=s,this.kind=e,this.tags=t,this.destroy=r,Ae.set(s,this)}}function Se(e,t){return null}function Me(e,t){return null}function Fe(e,t){let r=t[0];return Ae.forEach((e=>{e.tags.includes(r)&&(e.destroy(e),Ae.delete(e.id))})),null}function De(e,t){return Fe(0,t)}async function Ue(e,t){let[r]=t;return r}function Ce(e,t){return[]}function Re(e){e instanceof Ie&&"websocket"==e.kind&&e.websocket.close()}function qe(e){if(e.incoming.length>0&&null!=e.reader){let t=e.incoming.shift();e.reader(t)}}function Oe(e){if(!(e instanceof M))throw new Error("websocket: bad handle");let t=e.data[0],r=Ae.get(t);if(void 0===r||"websocket"!=r.kind)throw new Error("websocket: bad handle");return r}function $e(e,t){let r=t[0],s=r.resourceTags;if(!W(s))throw new Error("websocket.create: config key 'resourceTags' must be an array of strings");let a=new Ie("websocket",s,Re),i=V(r,["wss:"],"websocket.create"),n=r.subprotocols;if(void 0===n&&(n=[]),!W(n))throw new Error("websocket.create: config key 'subprotocols' must be an array of strings");let o=r.timeout;if(void 0===o&&(o=300),"number"!=typeof o)throw new Error("websocket.create: config key 'timeout' must be a number");let l=r.readTimeout;if(void 0===l&&(l=0),"number"!=typeof l)throw new Error("websocket.create: config key 'readTimeout' must be a number");return a.websocket=new WebSocket(i,n),a.websocket.binaryType="arraybuffer",a.incoming=[],a.reader=null,a.error=void 0,a.rd_timeout=l,a.websocket.onmessage=e=>{a.incoming.push(["message",e]),qe(a)},a.websocket.onerror=e=>{a.incoming.push(["error",e]),a.error=e.message,qe(a)},a.websocket.onclose=e=>{a.incoming.push(["close",e]),qe(a)},new Promise(((e,t)=>{a.websocket.onopen=t=>{e(null)},o>0&&setTimeout((()=>{t(new Error("websocket timeout"))}),1e3*o)})).then((e=>{let t=new Uint32Array(1);return t[0]=a.id,new M(t)}))}function Be(e,t){try{return Oe(t[0]).error}catch(e){return e.message}}function Ge(e,t){let r=Oe(t[0]),s=t[1];if(!(s instanceof S))throw new Error("websocket.write: bad message");switch(s.name){case"websocket.textMsg":case"websocket.binMsg":r.websocket.send(s.arg);break;case"websocket.pingMsg":case"websocket.pongMsg":break;case"websocket.closeMsg":r.websocket.close(s.arg.code,s.arg.text);break;default:throw new Error("websocket.write: bad message")}return null}function Le(e,t){let r=Oe(t[0]);if(null!=r.reader)throw new Error("websocket.read: there is already a reader");return new Promise(((e,t)=>{r.reader=e,qe(r),0==r.incoming.length&&(r.closeEv?e(["close",r.closeEv]):r.error?t(new Error(r.error)):r.rd_timeout>0&&setTimeout((()=>{e(["timeout",null])}),1e3*r.rd_timeout))})).then((e=>{let[t,s]=e;switch(r.reader=null,t){case"message":return"string"==typeof s.data?new S("websocket.textMsg",s.data):new S("websocket.binMsg",new Uint8Array(s.data));case"error":throw new Error(s.message);case"close":let e={code:s.code,text:s.reason};return r.closeEv=s,new S("websocket.closeMsg",e);case"timeout":throw new Error("websocket timeout")}}))}function Ne(e,t){try{let e=Oe(t[0]);return e.error="closed",e.destroy(e),Ae.delete(e.id),null}catch{}return null}function Pe(e,t){if("string"!=typeof t)throw new Error("topic not a string");if(""==t||"/"!=t.at(0)&&"$"!=t.at(0))throw new Error("bad topic string: "+t);if("/"==t.at(0))return t;let r=t.indexOf("/");if(r<0)throw new Error("bad topic string: "+t);let s=t.substring(0,r),a=t.substring(r),i="/org/"+e.state.config.org+"/ws/"+e.state.config.workspace,n=i+"/app/"+x(e.wasm,"app","__empty__"),o=e.state.config.user,l=n+"/user/"+o,c=n+"/session/default",u=i+"/user/"+o;switch(s){case"$workspacePrefix":return i+a;case"$workspace":return i+"/shared/application"+a;case"$appPrefix":return n+a;case"$app":return n+"/shared/application"+a;case"$userPrefix":return l+a;case"$user":return l+"/application"+a;case"$sessionPrefix":return c+a;case"$session":return c+"/application"+a;case"$wsUserPrefix":return u+a;case"$wsUser":return u+"/application"+a;default:throw new Error("bad topic string: "+t)}}function He(e,t){return void 0!==globalThis.hub}function je(e,t){return void 0!==globalThis.hub}async function We(e,t){let r=t[0],s=t[1],a=!!t[2],i=t[3];if(K(r)||Z(r))throw new Error("$mqtt_publish: cannot publish to cloud (only a cloud agent can)");let n=globalThis.hub;if(void 0===n)throw new Error("$mqtt_publish: no broker available");let o=Pe(e,r);if("string"!=typeof s)throw new Error("$mqtt_publish: rmxType must be a string");let l,c="app/"+x(e.wasm,"app","__empty__");return i instanceof Uint8Array?l=n.newBinaryMessage(s,c,i):"string"==typeof i?l=n.newTextMessage(s,c,i):(i=H(i,N(),R()),l=n.newJSONMessage(s,c,i)),await n.publish(o,l,a),null}async function Ve(e,t){let r=t[0];if(K(r)||Z(r))throw new Error("$mqtt_get: cloud topics unsupported");let s=Pe(e,r),a=globalThis.hub;if(void 0===a)throw new Error("$mqtt_get: no broker available");let i=await a.get(s);if(void 0===i)return;let n=H(i.payload,L(),q());return{topic:i.topic,payload:n,retained:i.retained,_rmx_type:i.header._rmx_type,_rmx_encoding:i.header._rmx_encoding,_rmx_sender:i.header._rmx_sender}}async function Ye(e,t){let r=t[0];if(K(r)){let t=e.state.config.token;return await async function(e,t){let r=J+z++,s=await async function(e,t){let r=e.split("/"),[s,a,i]=r.slice(0,3);if(""!=s||"cloud"!=a)throw new Error("invalid cloud topic");let n=`https://${i}/subscribe${e}`,o={};t&&(o.Authorization=`Bearer ${t}`);let l=await fetch(n,{headers:o});if(!l.ok)throw new Error("failure to subscribe to cloud topic");let c=l.body.getReader();return{response:l,reader:c,topic:e}}(e,t);return Y.set(r,s),r}(r,t)}if(Z(r))throw new Error("$mqtt_subscribe: cloud topic path must be absolute");let s=globalThis.hub;if(void 0===s)throw new Error("$mqtt_subscribe: no broker available");let a=Pe(e,r),i="sub"+e.state.subNextId++,n=await s.subscribe(a);return e.state.subscriptions[i]=n,i}async function Je(e,t){let r=t[0];if(Q(r))return await async function(e){let t=Y.get(e);if(void 0===t)throw new Error("invalid cloud subscription");return await async function(e){try{for(;;){let{value:t,done:r}=await e.reader.read();r&&(t={_rmx_type:"{tag}undefined"});let s=(new TextDecoder).decode(t);if(s.startsWith(":")){let t=s.slice(1);"\n"!==t&&console.log(`cloud subscription message: ${t}`,e.topic)}else if(s.startsWith("data:")){let t=s.slice(5);return{payload:H(JSON.parse(t),L(),q()),topic:e.topic,retained:!1,_rmx_type:"msg_cloud_publish",_rmx_encoding:"json",_rmx_sender:"cloud-hub"}}}}catch(e){return void console.error("could not read next cloud subscription message",e)}}(t)}(r);if(void 0===globalThis.hub)throw new Error("$mqtt_subNext: no broker available");let s=e.state.subscriptions[r];if(void 0===s)return;let a=await s.next();if(void 0===a||a.eof)return;let i=H(a.payload,L(),q());return{topic:a.topic,payload:i,retained:a.retained,_rmx_type:a.header._rmx_type,_rmx_encoding:a.header._rmx_encoding,_rmx_sender:a.header._rmx_sender}}async function ze(e,t){let r=t[0];if(Q(r))return await async function(e){let t=Y.get(e);if(void 0===t)throw new Error("invalid cloud subscription");Y.delete(e),function(e){e.reader.cancel()}(t)}(r);if(void 0===globalThis.hub)throw new Error("$mqtt_unsubscribe: no broker available");let s=e.state.subscriptions[r];void 0!==s&&(await s.unsubscribe(),delete e.state.subscriptions[r])}function Qe(e,t){let r=t[0];return!("string"!=typeof r||r.startsWith("/")||r.includes("//")||r.endsWith("/")||r.includes("+")||r.includes("#"))}function Ke(e,t){return!0}function Ze(e,t){throw new Error("$mqtt_mountOrg: not implemented")}function Xe(){return globalThis.performance?performance.now():Date.now()}class et{constructor(){this.inst=null,this.memory=null,this.stdout=new Array,this.stderr=new Array,this.imp_wasi_snapshot_preview1={fd_write:this.fd_write.bind(this),fd_close:this.fd_close.bind(this),fd_seek:this.fd_seek.bind(this),fd_fdstat_get:this.fd_fdstat_get.bind(this),environ_sizes_get:this.environ_sizes_get.bind(this),environ_get:this.environ_get.bind(this),random_get:this.random_get.bind(this),proc_exit:this.proc_exit.bind(this),clock_time_get:this.clock_time_get.bind(this),poll_oneoff:this.poll_oneoff.bind(this)},this.wasiImport=this.imp_wasi_snapshot_preview1}update(){this.memory=this.inst.exports.memory,this.mem8=new Uint8Array(this.memory.buffer),this.mem32=new Uint32Array(this.memory.buffer)}fd_seek(e,t,r,s,a){this.update(),this.abort("unexpected fd_seek call")}clock_time_get(e,t,r){const s=new DataView(this.memory.buffer);if(0===e)s.setBigUint64(r,1000000n*BigInt((new Date).getTime()),!0);else if(1==e){let e;try{e=BigInt(Math.round(1e6*performance.now()))}catch(t){e=0n}s.setBigUint64(r,e,!0)}else s.setBigUint64(r,0n,!0);return 0}poll_oneoff(e,t,r){this.update(),this.abort("unexpected poll_oneoff call")}fd_write(e,t,r,s){let a,i;switch(this.update(),e){case 1:case 2:a=this.stdout,i=console.debug;break;default:return 0}let n=0;for(let e=0;e<r;e++){let r=this.mem32[t+8*e>>2],s=this.mem32[t+(8*e+4)>>2];for(let e=0;e<s;e++){let t=this.mem8[r+e];if(t>=32)a.push(t);else if(10==t){let e=new Uint8Array(a);console.log("WASM: %s",this.utf8array_to_string(e,0,a.length)),a.length=0}}n+=s}return this.mem32[s>>2]=n,0}utf8array_to_string(e,t,r){let s=t+r,a=t;for(;e[a]&&a<s;)a++;return(new TextDecoder).decode(e.subarray(t,a))}fd_close(e){return this.update(),0}fd_fdstat_get(e,t){this.update(),this.abort("unexpected fd_fdstat_get call")}environ_sizes_get(e,t){return this.update(),this.mem32[e>>2]=0,0}environ_get(e,t){return this.update(),0}random_get(e,t){this.update();let r=this.mem8.subarray(e,e+t),s=new Uint8Array(t);return globalThis.ThisIsNode||crypto.getRandomValues(s),r.set(s),0}proc_exit(e){this.update(),console.log("exit("+e+")")}abort(e){let t=(new Error).stack||"(no stack trace)";throw console.error("WASM ABORT: %s at %s",e,t),new WebAssembly.RuntimeError(e)}}class tt{constructor(e){this.main=e.mixrt_code,this.state=e.isState(),this.imp_env={},this.imp_mixrt_host={perfnow:Xe},this.mixModInstances=new Map}update(){this.mem8=new Uint8Array(this.memory.buffer),this.mem32=new Uint32Array(this.memory.buffer)}async compile(){if(void 0===this.state.cached_main_module){if(this.main instanceof WebAssembly.Module)this.main_module=this.main;else if(this.main instanceof Uint8Array)this.main_module=await WebAssembly.compile(this.main);else if(this.main instanceof URL){let e=fetch(this.main);this.main_module=await WebAssembly.compileStreaming(e)}else if("string"==typeof this.main)if(this.main.startsWith("http:")||this.main.startsWith("https:")||this.main.startsWith("data:")){let e=fetch(this.main);this.main_module=await WebAssembly.compileStreaming(e)}else{let e=function(e){let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}(this.main);this.main_module=await WebAssembly.compile(e)}else{let e=await this.main,t=await e.arrayBuffer();this.main_module=await WebAssembly.compile(t)}this.state.cached_main_module=this.main_module}else this.main_module=this.state.cached_main_module}async instantiate(){this.wasi=new et;let e={env:this.imp_env,wasi_snapshot_preview1:this.wasi.imp_wasi_snapshot_preview1,wasi_shim:{clock_time_get:this.clock_time_get(this)},mixrt_host:this.imp_mixrt_host};this.instance=await WebAssembly.instantiate(this.main_module,e),this.wasi.inst=this.instance,this.memory=this.instance.exports.memory,this.update(),this.instance.exports._initialize(),this.table=this.instance.exports.__indirect_function_table,this.seedRNG(),this.setDebugFlags()}async mixAddCode(e,t){let r=WebAssembly.Module.customSections(t,"mix_grooveboxBuildMin");if(r.length>0){let e=new Int32Array(r[0])[0];if(e>parseInt("2824"))throw new Error("This version of GrooveBox is too old: required build: "+e+", but this is build: 2824")}let s=WebAssembly.Module.customSections(t,"mix_constsLength")[0],a=new Int32Array(s)[0],i=WebAssembly.Module.customSections(t,"mix_tableLength")[0],n=new Int32Array(i)[0],o=this.instance.exports.malloc(a),l=this.table.length;this.table.grow(n);let c=WebAssembly.Module.imports(t),u={table:this.table,memory:this.memory,mix_consts:o,tableBase:l},h={};for(let e=0;e<c.length;e++){let t=c[e];switch(t.module){case"env":break;case"mixrt":if("function"==t.kind){let e=this.instance.exports[t.name];if(void 0===e)throw new Error("missing mixrt function: "+t.name);h[t.name]=e}break;default:throw new Error("unsupported import: "+t.module)}}let d={env:u,mixrt:h},m=await WebAssembly.instantiate(t,d);this.mixModInstances.set(e,m),null!=m.exports.mix_initAdd&&m.exports.mix_initAdd()}async mixLinkCode(e){let t=this.mixModInstances.get(e);null!=t&&(null!=t.exports.mix_initLink?t.exports.mix_initLink():t.exports.mix_init())}seedRNG(){this.instance.exports.srandom(2147483647*Math.random())}setDebugFlags(){this.instance.exports.mixrt_setDebugFlags(0)}setTempRet0(e){return t=>{e.tempRet0=t}}clock_time_get(e){return(t,r,s,a)=>{if(e.update(),0!=t)return 28;let i=Date.now(),n=1000000n*BigInt(i);return e.mem32[a>>2]=Number(0xffffffffn&n),e.mem32[1+(a>>2)]=Number(n>>32n&0xffffffffn),0}}wasm_abort(e){return()=>{e.update(),e.abort("Aborting WASM execution")}}call(e,...t){if(void 0===this)throw Error("FATAL: 'this' is undefined");try{let r=e.apply(void 0,t);return this.update(),r}catch(e){let t=e.stack||"(no stack trace)";throw console.error("WASM EXCEPTION: %s at %s",e.message,t),this.update(),e}}abort(e){let t=(new Error).stack||"(no stack trace)";throw console.error("WASM ABORT: %s at %s",e,t),new WebAssembly.RuntimeError(e)}}class rt{constructor(e,t,r){this.secBuf=e,this.sectionsData=t,this.literals=r}toBytes(){let e=new Array;return P(e,[this.secBuf,[null,this.sectionsData],null,null,null,this.literals],N()),new Uint8Array(e)}}function st(e){return e.atArrayElt(2)}function at(e){if(2==e.tag())return null;let t=e.atArrayElt(0).checkTag(10).decode(),r=e.atArrayPath([1,1]).checkTag(10).decode(),s=e.atArrayElt(5).checkTag(16).decode();return new rt(t,r,s)}class it{constructor(){this.instID=void 0,this.codeID=void 0,this.timeout=void 0,this.which=void 0,this.entryID=void 0,this.coroutine=void 0,this.errorCode=void 0,this.errorProxy=void 0,this.withResult=void 0,this.reference=void 0,this.tag=void 0,this.modname=void 0,this.name=void 0,this.location=void 0,this.args=void 0,this.result=void 0,this.message=void 0,this.backtrace=void 0,this.fgBusy=void 0,this.fgBlocked=void 0,this.serial=void 0,this.time=void 0,this.initFlag=0,this.apps=[],this.override=void 0,this.token=void 0,this.privileged=void 0}getInstID(){return this.instID}setInstID(e){this.instID=e}getCodeID(){return this.codeID}setCodeID(e){this.codeID=e}getTimeout(){return this.timeout}setTimeout(e){this.timeout=e}getWhich(){return this.which}setWhich(e){this.which=e}getEntryID(){return this.entryID}setEntryID(e){this.entryID=e}getCoroutine(){return this.coroutine}setCoroutine(e){this.coroutine=e}getErrorCode(){return this.errorCode}setErrorCode(e){this.errorCode=e}getErrorProxy(){return this.errorProxy}setErrorProxy(e){this.errorProxy=e}getWithResult(){return this.withResult}setWithResult(e){this.withResult=e}getReference(){return this.reference}setReference(e){this.reference=e}getTag(){return this.tag}setTag(e){this.tag=e}getModname(){return this.modname}setModname(e){this.modname=e}getName(){return this.name}setName(e){this.name=e}getLocation(){return this.location}setLocation(e){this.location=e}setLocationTriple(e,t,r){let s=e+"/"+t+"/"+r;this.setLocation(s)}getArgs(){return this.args}setArgs(e){this.args=e}getResult(){return this.result}setResult(e){this.result=e}getMessage(){return this.message}setMessage(e){this.message=e}getBacktrace(){return this.backtrace}setBacktrace(e){this.backtrace=e}getFgBusy(){return this.fgBusy}setFgBusy(e){this.fgBusy=e}getFgBlocked(){return this.fgBlocked}setFgBlocked(e){this.fgBlocked=e}getSerial(){return this.serial}setSerial(e){this.serial=e}getTime(){return this.time}setTime(e){this.time=e}getInitFlag(){return this.initFlag}setInitFlag(e){this.initFlag=e}getApps(){return this.apps}setApps(e){this.apps=e}getOverride(){return this.override}setOverride(e){this.override=e}getToken(){return this.token}setToken(e){this.token=e}getPrivileged(){return this.privileged}setPrivileged(e){this.privileged=e}encode(e){let t={};t.msgType=e,this.encodeInstID(t),this.encodeArgs(t),this.encodeResult(t),this.encodeName(t),this.encodeLocation(t),this.encodeErrorCode(t),this.encodeMessage(t),this.encodeBacktrace(t),this.encodeCoroutine(t),this.encodeErrorProxy(t);let r=new Array;return P(r,t,N()),new Uint8Array(r)}encodeInstID(e){void 0!==this.instID&&(e.instID=this.instID)}encodeArgs(e){void 0!==this.args&&(e.args=new Uint8Array(this.args.buffer))}encodeResult(e){void 0!==this.result&&(e.result=new Uint8Array(this.result.buffer))}encodeName(e){void 0!==this.name&&(e.name=this.name)}encodeLocation(e){void 0!==this.location&&(e.location=this.location)}encodeErrorCode(e){void 0!==this.errorCode&&(e.errorCode=this.errorCode)}encodeMessage(e){void 0!==this.message&&(e.message=this.message)}encodeBacktrace(e){void 0!==this.backtrace&&(e.backtrace=this.backtrace)}encodeCoroutine(e){void 0!==this.coroutine&&(e.coroutine=this.coroutine)}encodeErrorProxy(e){void 0!==this.errorProxy&&(e.errorProxy=this.errorProxy)}decode(e){let t=O(new Uint32Array(e.buffer),0,q());return void 0!==t.instID&&(this.instID=t.instID),void 0!==t.args&&(this.args=t.args),void 0!==t.result&&(this.result=t.result),void 0!==t.name&&(this.name=t.name),void 0!==t.location&&(this.location=t.location),void 0!==t.errorCode&&(this.errorCode=t.errorCode),void 0!==t.message&&(this.message=t.message),void 0!==t.backtrace&&(this.backtrace=t.backtrace),void 0!==t.coroutine&&(this.coroutine=t.coroutine),void 0!==t.errorProxy&&(this.errorProxy=t.errorProxy),t.msgType}}class nt{constructor(e,t,r){this.msgType=e,this.params=new it,this.queue=t,this.counter=0,this.state=r.isState()}serializable(){return!1}encode(e){if(!this.serializable())throw new Error("cannot serialize this message type");let t=this.params.encode(this.msgType);return new globalThis.BinaryMessage(e,"vm",t)}async run(e,t,r){let s=this.state.wasm,a=s.instance.exports;for(;;){switch(this.counter++,s.call(a.mixrt_runYG),s.call(a.mixrt_getState)){case 2:this.state.wantInitResult&&this.publishInitResult(e),s.call(a.mixrt_reqRunning);continue;case 5:if(0==s.call(a.mixrt_areFGCoroutinesBusy)&&this.state.config.outputViaMQTT){for(let t of this.state.drvEcho)await this.publishEcho(e,t);this.state.drvEcho=new Array}return;case 4:s.call(a.mixrt_reqRunning);continue;case 6:{let i=s.call(a.mixrt_getBuiltin),n=_(s,i,255);if(this.state.config.outputViaMQTT&&"$outputWithVersion"==n){await this.publishOutput(e),s.call(a.mixrt_reqReturn,s.call(a.mixrt_getCoroutine));let t=new Array;P(t,null,N()),p(s,t);continue}if(this.state.config.outputViaMQTT&&"$outputError"==n){await this.publishOutputError(e),s.call(a.mixrt_reqReturn,s.call(a.mixrt_getCoroutine));let t=new Array;P(t,null,N()),p(s,t);continue}if("$ffi_available"==n){let e=f(s,s.call(a.mixrt_getResult)),[t]=O(new Uint32Array(e.buffer),0,q()),i=Boolean("$ffi_available"==t||this.state.config.localFFIs[t]||this.state.mixcore.handlesFFI(t)||r.get(t)),n=new Array;P(n,i,N()),p(s,n),s.call(a.mixrt_reqReturn,s.call(a.mixrt_getCoroutine));continue}const o=this.state.config.localFFIs[n];if(void 0!==o)return void await this.runLocalFFI(e,t,n,o);if(this.state.mixcore.handlesFFI(n)){await this.runMixcoreFFI(n);continue}let l=r.get(n);if(void 0!==l){this.overriddenFFI(e,t,r,l,n);continue}if(this.state.standalone&&!this.state.config.interceptFFI){let e=new Error("FFI unsupported by this VM: "+n),t=s.call(a.mixrt_getCoroutine);this.ffiabort(t,e);continue}let c=new yt("FFI",this.state);return c.params.setInstID(0),c.params.setCoroutine(s.call(a.mixrt_getCoroutine)),c.params.setName(n),this.setParamsToCurrentLocation(c.params),c.params.setArgs(f(s,s.call(a.mixrt_getResult))),await e.fficall(c)}case 10:{let e=s.call(a.mixrt_getError);void 0===e&&(e=99);let t=_(s,s.call(a.mixrt_getErrorMessage),65535),r=s.call(a.mixrt_getCoroutine);console.error("Mix panic: ",e,t),console.error("Coroutine: ",r);let i=s.call(a.mixrt_locUnitID),n=_(s,i,255),o=s.call(a.mixrt_locUnitPC),l=s.call(a.mixrt_locSecInstr);console.error("Location: ",n," PC ",o," Instr ",l);let c=s.call(a.mixrt_co_backtrace,r),u=_(s,c,65535);console.error("Backtrace: ",u),s.call(a.free,c),s.call(a.mixrt_reqRunning);continue}case 11:console.error("Mix timeout"),s.call(a.mixrt_reqRunning);continue}throw new Error("Unexpected state")}}async runMixcoreFFI(e){let t=this.state.wasm,r=t.instance.exports,s=t.call(r.mixrt_getCoroutine),a=t.call(r.mixrt_getResult),i=f(t,a);try{let a=await this.state.mixcore.dispatchFFI(s,e,i);p(t,Array.from(a)),t.call(r.mixrt_reqReturn,s)}catch(e){this.ffiabort(s,e)}}setParamsToCurrentLocation(e){let t=this.state.wasm,r=t.instance.exports,s=t.call(r.mixrt_locUnitID),a=_(t,s,255),i=t.call(r.mixrt_locUnitPC),n=t.call(r.mixrt_locSecInstr);e.setLocationTriple(a,i,n)}async publishOutput(e){let t=this.state.wasm,r=t.instance.exports;try{let s=t.call(r.mixrt_getResult),a=t.call(r.mixrt_arrayGet,s,0,1);if(0==a)throw new Error("bad result");let i=t.call(r.mixrt_getString,a);if(0==i)throw new Error("bad result");let n=_(t,i,255),o=t.call(r.mixrt_arrayGet,s,1,1);if(0==o)throw new Error("bad result");let l=t.call(r.mixrt_getString,o);if(0==l)throw new Error("bad result");let c=_(t,l,255),u=t.call(r.mixrt_arrayGet,s,2,1),h=t.call(r.mixrt_stringFormatEscJSONYG,u),d='{"_rmx_type":"{tag}undefined"}';if(t.call(r.mixrt_isUndefined,h)||(d=$(t,h,R())),"string"!=typeof d)throw console.debug("bad:",d),new Error("expected string but got "+typeof d);let m='[{"name":'+JSON.stringify(n)+',"version":'+JSON.stringify(c)+',"value":'+d+"}]";await this.publishCellMessages(e,m)}catch(e){console.error("output error",e)}}async publishOutputError(e){let t=this.state.wasm,r=t.instance.exports;try{let s=t.call(r.mixrt_getResult),a=t.call(r.mixrt_arrayGet,s,0,1),i={errors:$(t,a,R())};await this.publishMessage(e,i)}catch(e){console.error("output error",e)}}async publishInitResult(e){let t=this.state.wasm,r=t.instance.exports;try{let s=t.call(r.mixrt_getResult),a={cellMessages:[{name:"$initResult",version:"",value:$(t,s,R())}]};await this.publishMessage(e,a)}catch(e){console.error("output error",e)}}async publishEcho(e,t){let r=this.state.wasm,s=r.instance.exports,a=r.call(s.mixrt_initEnvGetSession),i=(0==a||_(r,a,255),{_rmx_echo:t});await this.publishMessage(e,i)}async publishMessage(e,t){let r=this.state.wasm,s=r.instance.exports,a=r.call(s.mixrt_initEnvGetSession),i={_rmx_type:"msg_response",_rmx_version:"0.0",session:0==a?"":_(r,a,255),machine:this.state.config.vmID,org:this.state.config.org,workspace:this.state.config.workspace,cellMessages:[],logMessages:[]};for(let e in t)i[e]=t[e];this.state.config.debugMask&h.DEBUG_OUTPUT&&console.debug("Output",JSON.stringify(i)),await e.output(i)}async publishCellMessages(e,t){let r=this.state.wasm,s=r.instance.exports,a=r.call(s.mixrt_initEnvGetSession),i=0==a?"":_(r,a,255),n='{"_rmx_type":"msg_response","_rmx_version":"0.0","session":'+JSON.stringify(i)+',"machine":'+JSON.stringify(this.state.config.vmID)+',"org":'+JSON.stringify(this.state.config.org)+',"workspace":'+JSON.stringify(this.state.config.workspace)+',"logMessages":[],"cellMessages":'+t+"}";this.state.config.debugMask&h.DEBUG_OUTPUT&&console.debug("Output",n);let o=new globalThis.UnparsedJSONMessage("msg_response","vm",n);await e.output(o)}ffireturn(e,t,r){const s=this.state.localFFIs[e]||{};delete this.state.localFFIs[e];let a=this.state.wasm,i=a.instance.exports;var n;a.call(i.mixrt_reqReturn,e),s.isRaw?n=t:P(n=new Array,t,s.useJsonDecoder?L():r),p(a,n)}ffiabort(e,t){delete this.state.localFFIs[e];let r=this.state.wasm,s=r.instance.exports;console.error("FFI error: ",t),t.stack&&console.error("FFI backtrace: ",t.stack);let a=b(r,t.message);r.call(s.mixrt_reqRunning),r.call(s.mixrt_setErrorMessage,3,a),r.call(s.free,a),r.call(s.mixrt_reqPanicCoroutine,e,0),r.call(s.mixrt_abortCoroutinePrimaryYG,e)}async runLocalFFI(e,t,r,s){let a=this.state.wasm,i=a.instance.exports,n=a.call(i.mixrt_getCoroutine),o=a.call(i.mixrt_getResult);this.state.localFFIs[n]={name:r,...s};var l=s.isRaw?f(a,o):$(a,o,{encode_undefined:()=>{},encode_bool:e=>e,encode_null:()=>null,encode_number:e=>e,encode_string:e=>e,encode_taggedString:e=>e,encode_binary:e=>e,encode_opaque:e=>new Map([["_rmx_type","opaque"],["data",e]]),encode_mapCreate:()=>({}),encode_mapSet:(e,t,r)=>e[t]=r,encode_arrayCreate:()=>[],encode_arrayPush:(e,t)=>e.push(t),encode_case0:e=>new Map([["_rmx_type","case"],["name",e],["arg",void 0]]),encode_case1:(e,t)=>new Map([["_rmx_type","case"],["name",e],["arg",t]]),encode_token:(e,t,r)=>new Map([["_rmx_type","token"],["data",e],["enabled",t],["extras",r]])});await e.fficall_local(r,n,l)}async overriddenFFI(e,t,r,s,a){let i=this.state.wasm,n=i.instance.exports,o=this.state.sboard,l=this,c=i.call(n.mixrt_getCoroutine),u={wasm:i,mixrt:n,state:this.state,coroutine:c,publishMessage:async t=>{await l.publishMessage(e,t)}},h=i.call(n.mixrt_getResult),d=$(i,h,q());try{let e=s(u,d);e instanceof Promise?(e.then((e=>{o.FFIReturn(c,(async function(s){l.ffireturn(c,e,N()),await l.run(s,t,r)}))}),(e=>{o.FFIReturn(c,(async function(s){l.ffiabort(c,e),await l.run(s,t,r)}))})),i.call(n.mixrt_reqRunning)):l.ffireturn(c,e,N())}catch(e){l.ffiabort(c,e)}}}class ot extends nt{constructor(e,t){if("driver"!=e)throw new Error("DrvCreate: only permitted in queue 'driver'");super(257,e,t)}async exec(e,t){if(0!==this.params.instID)throw new Error("DrvCreate: only one instance supported");let r=new tt(this.state);this.state.wasm=r,await r.compile(),await r.instantiate(),r.call(this.state.wasm.instance.exports.mixrt_setDebugFlags,this.state.config.debugMask),console.log("mix machine: Initial debug mask: ",this.state.config.debugMask),console.debug("Debug levels (call MixSetMask to change):"),console.debug("DEBUG_MEMORY 1"),console.debug("DEBUG_SCHEDULER 2"),console.debug("DEBUG_STATE 4"),console.debug("DEBUG_STACK 8"),console.debug("DEBUG_LOOP 16"),console.debug("DEBUG_MEMORY_OG 32"),console.debug("DEBUG_GC 64"),console.debug("DEBUG_MESSAGES 256"),console.debug("DEBUG_QUEUES 512"),console.debug("DEBUG_OUTPUT 1024");let s=r.instance.exports;r.call(s.mixrt_mem_init),null!=this.params.timeout&&(s.mixrt_setTimeoutForInteraction?r.call(s.mixrt_setTimeoutForInteraction,this.params.timeout):r.call(s.mixrt_setTimeoutForCycle,this.params.timeout)),this.state.created=!0}}class lt extends nt{constructor(e,t){if("driver"!=e)throw new Error("DrvSendCode: only permitted in queue 'driver'");super(513,e,t)}async exec(e,t){let r,s,a=this.state.wasm,i=a.instance.exports;if(void 0===this.params.codeID)throw new Error("DrvSendCode: missing codeID param");if(void 0===this.params.reference)throw new Error("DrvSendCode: missing reference param");if(this.params.reference.startsWith("file:")){let e=this.params.reference.slice(5);r=fs.readFileSync(e),fs.existsSync(e+".dbg")&&(s=fs.readFileSync(e+".dbg"))}else if(this.params.reference.startsWith("data:"))if(globalThis.parseDataURL)r=globalThis.parseDataURL(this.params.reference).body;else{let e=await fetch(this.params.reference);if(!e.ok)throw console.error("Invalid data URL"),new Error("Bad data URL");r=await e.arrayBuffer()}else if(this.params.reference.startsWith("topic:/")){let e=new URL(this.params.reference);r=(await globalThis.hub.get(e.pathname)).payload,this.params.reference.endsWith(".autodel")&&await globalThis.hub.set(e.pathname,globalThis.hub.newBinaryMessage("binary","driver",new Uint8Array(0)));let t=await globalThis.hub.get(e.pathname+".dbg");void 0!==t&&(s=t.payload,await globalThis.hub.set(e.pathname+".dbg",globalThis.hub.newBinaryMessage("binary","driver",new Uint8Array(0))))}else{let e=this.state.config.baseURL;e?e.endsWith("/")||(e+="/"):e=void 0;let t,a=new Headers,i=this.params.reference;if(i.includes("%,")){let e=i.indexOf("%,");t=i.substring(e+2),i=i.substring(0,e)}""!=this.state.config.token&&(i+=i.includes("?")?"&":"?",i+="token="+this.state.config.token,void 0!==t&&(t+=t.includes("?")?"&":"?",t+="token="+this.state.config.token));let n=new URL(i,e),o={headers:a,mode:"cors"},l=await fetch(n.toString(),o);if(!l.ok){let e=await l.text();throw console.error("Cannot load URL:",n.toString(),"status:",l.status,"Bad body:",e),new Error("Bad HTTP status: "+l.status)}if(r=await l.arrayBuffer(),void 0!==t&&(n=new URL(t,e),l=await fetch(n.toString(),o),404!=l.status)){if(!l.ok){let e=await l.text();throw console.error("Cannot load URL:",n.toString(),"status:",l.status,"Bad body:",e),new Error("Bad HTTP status: "+l.status)}s=await l.arrayBuffer()}}let n,o=new Uint8Array(r),l=!1;void 0!==s&&(n=new Uint8Array(s));let c=function(e){for(let t=0;t<4;t++)if(e[t]!="\0asm".codePointAt(t))return!1;return!0}(o);if(c){let e=new WebAssembly.Module(o);void 0===s&&(n=WebAssembly.Module.customSections(e,"mix_debug")[0]),this.state.mixCode.set(this.params.codeID,e),this.state.mixCodeName.set(this.params.codeID,this.params.name),await this.state.wasm.mixAddCode(this.params.codeID,e)}else{if(!function(e){try{return"qcode-5"==new j(new Uint32Array(e.buffer)).atArrayPath([0,0]).decode()}catch(e){return!1}}(o))throw new Error("Expected Wasm or QCode-5");{let e=new j(new Uint32Array(o.buffer));if(void 0===s){let t=at(st(e));null!=t&&(n=t.toBytes(),l=!0)}if(function(e){return 2!=e.atArrayElt(1).tag()}(e)){if(void 0===this.params.name)throw new Error("DrvSendCode: missing name param");let e=o.length,t=a.call(i.malloc,e);if(0==t)throw new Error("out of memory");a.mem8.subarray(t,t+e).set(o);let r=b(a,this.params.name),s=this.state.config.quickLoad;if(0==a.call(i.mixrt_interpreterAddCode2,t,t+e,r,r,s)){let e=_(a,a.call(i.mixrt_getErrorMessage),65535);throw new Error(e+" - when loading "+this.params.name)}this.state.mixCode.set(this.params.codeID,"BYTE"),this.state.mixCodeName.set(this.params.codeID,this.params.name)}}}if(void 0!==n){if(!l){let e=at(st(new j(new Uint32Array(n.buffer))));null!=e&&(n=e.toBytes())}await this.state.mixcore.publishDebugObject(this.params.name,n)}for(let e of this.params.apps){if(void 0===this.params.name)throw new Error("DrvSendCode: missing name param");if("$executable-0@x"==this.params.name)continue;let t=b(a,this.params.name),r=b(a,e);if(0==a.call(i.mixrt_libApp,t,r)){let t=_(a,a.call(i.mixrt_getErrorMessage),65535);throw new Error(t+" - when associating library "+this.params.name+" with app "+e)}a.call(i.free,t),a.call(i.free,r)}}}class ct extends nt{constructor(e,t){if("driver"!=e)throw new Error("DrvLinkCode: only permitted in queue 'driver'");super(515,e,t)}async exec(e,t){let r=this.state.wasm,s=r.instance.exports;if(0!==this.params.instID)throw new Error("DrvLinkCode: only one instance supported");if(void 0===this.params.codeID)throw new Error("DrvLinkCode: missing codeID param");let a=this.state.mixCode.get(this.params.codeID);if(void 0===a)throw new Error("DrvLinkCode: unknown code reference");let i=this.state.mixCodeName.get(this.params.codeID),n=b(r,i),o=0;if("BYTE"==a){if(null!=s.mixrt_interpreterLinkUnitYG){if(!r.call(s.mixrt_interpreterLinkUnitYG,n)){let e=_(r,r.call(s.mixrt_getErrorMessage),65535);throw new Error(e+" - when linking "+i)}o=1}else if(!r.call(s.mixrt_interpreterLinkCodeYG)){let e=_(r,r.call(s.mixrt_getErrorMessage),65535);throw new Error(e)}}else await r.mixLinkCode(this.params.codeID),o=1;if(null!=this.params.override&&null!=this.params.override.ondemand){let e=new Array;P(e,this.params.override.ondemand,L());let t=p(r,e),a=r.call(s.mixrt_copyIOtoYG,t,t,t+e.length);if(0==a)throw new Error("cannot create value");if(0==r.call(s.mixrt_setOnDemandOverrideFromValue,a)){let e=_(r,r.call(s.mixrt_getErrorMessage),65535);throw new Error(e+" - when injecting override")}}if(this.params.initFlag){let e=s.mixrt_setInitLibraryRecursively;if(!o||null==e)throw new Error("This version of mixrt doesn't support dynamic loading");if(!r.call(e,n)){let e=_(r,r.call(s.mixrt_getErrorMessage),65535);throw new Error(e)}}w(r,n)}}class ut extends nt{constructor(e,t){if("driver"!=e)throw new Error("DrvToInit: only permitted in queue 'driver'");super(769,e,t),this.wantResult=!1}async exec(e,t,r){let s=this.state.wasm,a=s.instance.exports,i=s.call(a.mixrt_getState);if(0!==i&&2!==i&&4!==i&&5!==i)throw new Error("state mismatch after ToInit: "+i);if(s.call(a.mixrt_reqInit),function(e,t){let r=v.findIndex((e=>e==t)),s=e.instance.exports;e.call(s.mixrt_setReqQueue,r)}(s,this.queue),this.state.wantInitResult=this.wantResult,void 0!==this.params.serial&&(t[0]=this.params.serial),void 0!==this.params.args){let e=this.params.args,t=p(s,e),i=s.call(a.mixrt_copyIOtoYG,t,t,t+e.length);if(0==i)throw new Error("cannot create value");s.call(a.mixrt_initEnvExtract,i),s.call(a.mixrt_ffiArgChecksInstall),this.state.standalone=s.call(a.mixrt_initEnvStandalone),this.state.standalone&&((n=r).set("$flush",Se),n.set("$loadHook",Me),n.set("$destroyHook",Fe),n.set("$freeResources",De),n.set("$decodeError",Ue),n.set("get_backtrace",Ce),n.set("$websocket_create",$e),n.set("$websocket_write",Ge),n.set("$websocket_read",Le),n.set("$websocket_close",Ne),n.set("$websocket_error",Be),n.set("$mqtt_available",He),n.set("$mqtt_brokerAvailable",je),n.set("$mqtt_publish",We),n.set("$mqtt_subscribe",Ye),n.set("$mqtt_subNext",Je),n.set("$mqtt_get",Ve),n.set("$mqtt_unsubscribe",ze),n.set("$mqtt_isLegalSubTopic",Qe),n.set("$mqtt_haveExternalSubscribers",Ke),n.set("$mqtt_mountOrg",Ze),s.call(a.mixrt_ffiArgChecksInstallStandalone),this.state.config.interceptDynloadFFI||(s.call(a.mixrt_enableResolveLibrary),s.call(a.mixrt_enableLoadLibrary)))}var n;await this.run(e,t,r)}}class ht extends nt{constructor(e,t){if("driver"!=e&&"async"!=e)throw new Error("DrvToEnter: only permitted in queues 'driver' and 'async'");super(770,e,t)}async exec(e,t,r){if(void 0===this.params.tag)throw new Error("DrvToEnter: missing param: tag");if(void 0===this.params.modname)throw new Error("DrvToEnter: missing param: modname");if(void 0===this.params.entryID)throw new Error("DrvToEnter: missing param: entryID");if(void 0===this.params.args)throw new Error("DrvToEnter: missing args");let s=this.state.wasm,a=s.instance.exports;if(this.params.token){if(!this.params.privileged)throw new Error("attempt to use setToken with an unprivileged request");await async function(e,t,r){let s;try{s=function(e){var t=e.split(".")[1].replace(/-/g,"+").replace(/_/g,"/");let r=atob(t).split("").map((e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)));var s=decodeURIComponent(r.join(""));return JSON.parse(s)}(r)}catch(e){console.log("unable to parse token as JWT",e),s={}}let a={token:I(r),userPseudonym:s.sub?await ft(s.sub):"",user:s.email??"",userID:s.sub??"",userIsVerified:s.email_verified??!1,userIsAnonymous:s.anon??!1};for(let[r,s]of Object.entries(a))dt(e,t,r,s)}(s,a,this.params.token)}let i=b(s,this.params.tag),n=b(s,this.params.modname),o=s.call(a.mixrt_findEntry,i,n);if(w(s,i),w(s,n),0==o)throw new Error("DrvToEnter: cannot find entry, tag="+this.params.tag+" modname="+this.params.modname);var l;s.call(a.mixrt_reqEntry,o,this.params.entryID,(l=this.queue,v.findIndex((e=>e==l))),this.params.withResult?1:0),p(s,this.params.args),void 0!==this.params.serial&&(t[0]=this.params.serial),await this.run(e,t,r)}}function dt(e,t,r,s){let a=new Array;P(a,[r,s],L());let i=p(e,a),n=e.call(t.mixrt_copyIOtoYG,i,i,i+a.length),o=e.call(t.mixrt_arrayGet,n,0,!1),l=e.call(t.mixrt_arrayGet,n,1,!1);if(!e.call(t.mixrt_envUpdateYG,o,l)){let r=e.call(t.mixrt_getError),s=e.call(t.mixrt_getErrorMessage),a=null;throw s&&(a=_(e,s,20480)),new Error(`could not update env: ${a} (${r})`)}}function mt(e){const t=Array.from(e,(e=>String.fromCodePoint(e)));return btoa(t.join(""))}let gt=function(){const e=new Uint8Array(24);return globalThis.crypto.getRandomValues(e),mt(e)}();async function ft(e){let t=e+gt,r=(new TextEncoder).encode(t),s=await crypto.subtle.digest("SHA-256",r);return mt(new Uint8Array(s))}class pt extends nt{constructor(e,t){if("FFI"!=e)throw new Error("DrvReturn: only permitted in queue 'FFI'");super(771,e,t)}serializable(){return!0}async exec(e,t,r){let s=this.state.wasm,a=s.instance.exports;if(void 0===this.params.coroutine)throw new Error("DrvReturn: missing param: coroutine");if(void 0===this.params.result)throw new Error("DrvReturn: missing param: result");s.call(a.mixrt_reqReturn,this.params.coroutine),p(s,this.params.result),await this.run(e,t,r)}}class bt extends nt{constructor(e,t){if("FFI"!=e)throw new Error("DrvAbort: only permitted in queue 'FFI'");super(773,e,t)}serializable(){return!0}async exec(e,t,r){let s=this.state.wasm,a=s.instance.exports;if(void 0===this.params.coroutine)throw new Error("DrvAbort: missing param: coroutine");if(!s.call(a.mixrt_co_exists,this.params.coroutine))throw new Error("DrvAbort: no such coroutine: "+this.params.coroutine);let i=this.params.message;void 0===i&&(i="<no message provided>");let n=b(s,i);s.call(a.mixrt_reqRunning),void 0!==this.params.errorProxy?s.call(a.mixrt_setErrorMessageAndProxy,this.params.errorProxy,n):s.call(a.mixrt_setErrorMessage,3,n),s.call(a.free,n),s.call(a.mixrt_reqPanicCoroutine,this.params.coroutine,0),s.call(a.mixrt_abortCoroutinePrimaryYG,this.params.coroutine),await this.run(e,t,r)}}class wt extends nt{constructor(e,t){if("FFI"!=e)throw new Error("DrvLater: only permitted in queue 'FFI'");super(777,e,t)}serializable(){return!0}async exec(e,t,r){let s=this.state.wasm,a=s.instance.exports;s.call(a.mixrt_reqRunning),await this.run(e,t,r)}}class _t extends nt{constructor(e,t){super(777,e,t)}async exec(e,t,r){let s=this.state.wasm,a=s.instance.exports;s.call(a.mixrt_reqRunning),await this.run(e,t,r)}}class yt extends nt{constructor(e,t){super(1030,e,t)}serializable(){return!0}}const xt=["$destroyHook","$hideHook","$isSyncEnabled","$loadHook","$flush","$showHook","$log","get_env","$outputError","$outputWithVersion","$co_sleep","$decodeError"];function vt(e,t){return"CORE"==t?xt.includes(e):"*"===t.slice(-1)?e.startsWith(t.slice(0,-1)):e===t}class Et{static async create(e){e=e??{};let t=new Et;switch(t.mixcore=null,t.ffiNames=[],t.publishDebugObjects=e.publishDebugObjects,e.kind){case"webkit":t.mixcore=new Tt;break;case"tauri":{let{dbDir:r,dbName:s,dbUser:a}=e;t.mixcore=await kt.create(r,s,a);break}case"service-worker":{let{mixcoreId:r,baseURL:s}=e;t.mixcore=new At(r,s??"");break}}if(t.mixcore){let{enableFFIs:i,disableFFIs:n}=e,o=await t.mixcore.ffiNames();t.ffiNames=(r=o,a=n,void 0!==(s=i)&&(r=r.filter((e=>s.some((t=>vt(e,t)))))),void 0!==a&&(r=r.filter((e=>!a.some((t=>vt(e,t)))))),r)}var r,s,a;return console.log("Mixcore (worker)",t.mixcore,t.ffiNames),t}handlesFFI(e){return this.ffiNames.includes(e)}dispatchFFI(e,t,r){return this.mixcore.ffiDispatch(e,t,r)}async publishDebugObject(e,t){if(this.publishDebugObjects){let r=globalThis.hub,s=globalThis.state.config.vmID,a={id:e,code:t},i=r.newLocalMessage("msg_register_debug_object","vm",a);await r.publish(`/debug-objects/${s}`,i,!1)}}}class Tt{async handler(e,t){return await window.webkit.messageHandlers[e].postMessage(t)}async ffiNames(){return await this.handler("mixcore_ffi_names",{})}async ffiDispatch(e,t,r){return await this.handler("mixcore_ffi_dispatch",{co:e,name:t,argsBuf:r})}}class kt{static async create(e,t,r){let s={user:r};return await window.__TAURI__.invoke("mixcore_setup",{env:s,dbDir:e,dbName:t,username:r}),new kt}async ffiNames(){return await window.__TAURI__.invoke("mixcore_ffi_names")}async ffiDispatch(e,t,r){console.log("MixcoreTauri.ffiDispatch",t,r);try{let s=Array.from(new Uint8Array(r.buffer)),a=await window.__TAURI__.invoke("mixcore_ffi_dispatch",{co:e,name:t,argsBuf:s});if(a.Sync){if(a.Sync.Ok)return new Uint8Array(a.Sync.Ok);if(a.Sync.Err)throw new Error(`FFI execution error: ${a.Sync.Err}`)}throw new Error(`unexpected FFI dispatch result ${a}`)}catch(e){throw e}}}class At{constructor(e,t){this.mixcoreId=e,this.baseURL=t}async ffiNames(){let e=new URL(`${this.baseURL}/mixcore/ffi-names`,globalThis.location.origin),t=await fetch(e);return await t.json()}async ffiDispatch(e,t,r){let s=new URL(`${this.baseURL}/mixcore/ffi-dispatch`,globalThis.location.origin);s.searchParams.set("mixcore",this.mixcoreId),s.searchParams.set("co",e),s.searchParams.set("name",t);let a={method:"POST",body:r},i=await fetch(s,a);if(!i.ok)throw new Error(await i.text());return new Uint8Array(await i.arrayBuffer())}}async function It(){let e=globalThis.state.config,t=globalThis.hub,r=await t.subscribe(e.topicBase()+"/FFIReturn");await async function(e,t){(async function(e,t){for(;;){let t=await e.next();await Ft(t)}})(e).catch((e=>console.log("Error",e)))}(r);let s=await t.subscribe(e.topicBase()+"/initiate");if(await async function(e){(async function(e){for(;;){let t=await e.next();await Mt(t)}})(e).catch((e=>console.log("Error",e)))}(s),e.localFFIs){let e=globalThis.state.config.vmID;await t.setLocalPubTopic("/local/"+e),await t.setLocalSubTopic("/local/"+e);let r=await t.subscribe("/local/"+e+"/ffi/return");await async function(e){(async function(e){for(;;){let t=await e.next();await Dt(t)}})(e).catch((e=>console.log("Error",e)))}(r)}let a=globalThis.state.config.vmID;await t.setLocalPubTopic(`/debug-objects/${a}`),state.sboard.mainLoop(),t.setLocalPubTopic("/local/test"),t.setLocalSubTopic("/local/test"),await async function(){let e=globalThis.state.config,t=globalThis.hub,r=e.topicBase()+"/announce",s={_rmx_type:"msg_vm_register",id:e.vmID,variant:e.machType,version:0},a=new globalThis.JSONMessage("msg_vm_register","vm",s);await t.publish(r,a,!0)}()}function St(e,t){let r=t._rmx_echo;if(void 0!==t&&"string"==typeof r){globalThis.state.drvEcho.push(r);let s=t.timeout;"number"==typeof s&&s>0&&setTimeout((()=>{globalThis.state.drvEcho=globalThis.state.drvEcho.filter((e=>e!=r));let s={_rmx_type:"msg_response",_rmx_version:"0.0",_rmx_echo:r,session:t.session,machine:globalThis.state.config.vmID,org:globalThis.state.config.org,workspace:globalThis.state.config.workspace,cellMessages:[],logMessages:[],errors:{code:"",message:"execution timed out"}};e.output(s)}),1e3*s)}}async function Mt(e){let t=e.payload?._rmx_type;if(t&&e.rmxType!==t)throw new Error(`message envelope type (${e.rmxType}) differs from payload type (${t})`);try{switch(e.rmxType){case"msg_vm_configure":await async function(e){let t=e.payload;if(globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Received message:",t),"object"!=typeof t)throw new Error("bad msg_vm_configure message");t.reset&&(globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Resetting machine on request"),globalThis.state.sboard.reset(),globalThis.state.reset());let r=t.code||[];if(!Array.isArray(r))throw new Error("bad msg_vm_configure message: 'code' not an array");let s=t.config,a=t.load,i=t.override,n=[],o=t._rmx_echo;if(void 0!==t&&"string"==typeof o&&globalThis.state.drvEcho.push(o),!globalThis.state.created){let e=new ot("driver",globalThis.state);e.params.setInstID(0),n.push(e)}for(let e of r){let t=new lt("driver",globalThis.state),r=t.params,s=e.codeID;if("number"!=typeof s)throw new Error("bad msg_vm_configure message: 'code[].codeID' not a number");let a=e.reference;if("string"!=typeof a)throw new Error("bad msg_vm_configure message: 'code[].reference' not a string");let i=e.name||"";if("string"!=typeof i)throw new Error("bad msg_vm_configure message: 'code[].name' not a string");let o=e.apps||[];if(!Array.isArray(o))throw new Error("bad msg_vm_configure message: 'code[].apps' not an array");r.setInstID(0),r.setCodeID(s),r.setReference(a),r.setName(i),r.setApps(o),n.push(t)}let l=!0;for(let e of r){let t=new ct("driver",globalThis.state),r=t.params,s=e.codeID,a=e.initFlag||!1;r.setInstID(0),r.setCodeID(s),r.setInitFlag(a),l&&null!=i&&r.setOverride(i),n.push(t),l=!1}if(void 0!==s){s.standalone&&(s.isMQTTEnabled=!0),void 0!==s.env&&void 0!==s.env.token&&(s.env.token=I(s.env.token));let e=new ut("driver",globalThis.state),r=e.params;r.setInstID(0);let a=new Array;P(a,s,L()),r.setArgs(a),e.wantResult=!!t.wantResult,n.push(e)}else{let e=new ut("driver",globalThis.state);e.params.setInstID(0),e.wantResult=!!t.wantResult,n.push(e)}for(let e of n)globalThis.state.sboard.enqueue("driver",(async function(t){try{globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Driver request from msg_vm_configure",e),await e.exec(t,globalThis.state.drvSerial,globalThis.state.ffiOverride)}catch(e){console.error("Exception",e)}}));if(void 0!==a){if("object"!=typeof a)throw new Error("bad msg_vm_configure message: 'load' not an object");let e=a.screen;if("string"!=typeof e)throw new Error("bad msg_vm_configure message: 'load.screen' not a string");let r=a.params;if(!Array.isArray(r))throw new Error("bad msg_vm_configure message: 'load.params' not an array");let s=new ht("driver",globalThis.state),i=s.params;i.setTag("load"),i.setModname(""),i.setEntryID(0);let n=new Array;a.paramsEscEnabled?L():N(),P(n,[e,r],N()),i.setArgs(n),globalThis.state.sboard.enqueue("driver",(async function(e){globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Driver request from msg_vm_configure",s),St(e,t),await s.exec(e,globalThis.state.drvSerial,globalThis.state.ffiOverride)}))}globalThis.state.sboard.driverRequest((async function(e){}))}(e);break;case"msg_session_poll":{let t=e.payload;globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Received message:",t);let r=new _t("async",globalThis.state);globalThis.state.sboard.asyncRequest((async function(e){globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Driver request",r),St(e,t),await r.exec(e,globalThis.state.drvSerial,globalThis.state.ffiOverride)}));break}case"msg_view_invoke":case"msg_view_invokePrivilegedAction":{let t=e.payload;if(globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Received message:",t),"object"!=typeof t)throw new Error("bad msg_view_invoke message");let r=t.name;if("string"!=typeof r)throw new Error("bad msg_view_invoke message: name");let s=t.env,a=t.arg;void 0===a&&(a=null);let i=t.nextActions;if(void 0===i&&(i=[]),!Array.isArray(i))throw new Error("bad msg_view_invoke message: nextActions");let n=t.options;if(void 0===n&&(n={}),"object"!=typeof n)throw new Error("bad msg_view_invoke message: options");let o=new ht("async",globalThis.state),l=o.params;l.setTag("invoke3"),l.setModname(""),l.setEntryID(0),l.setToken(t.setToken),"msg_view_invokePrivilegedAction"===e.rmxType&&l.setPrivileged(!0);let c=[new B(r),new B(s),t.argEscEnabled?a:new B(a),i,new B(n)],u=L(),d=new Array;P(d,c,u),l.setArgs(d),globalThis.state.sboard.asyncRequest((async function(e){St(e,t),globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Async request",o),await o.exec(e,globalThis.state.drvSerial,globalThis.state.ffiOverride)}));break}case"msg_view_input":{let t=e.payload;if(globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Received message:",t),"object"!=typeof t)throw new Error("bad msg_view_input message");let r=t.name;if("string"!=typeof r)throw new Error("bad msg_view_input message: name");let s=t.value,a=new ht("async",globalThis.state),i=a.params;i.setTag("input"),i.setModname(""),i.setEntryID(0);let n=new Array,o=t.valueEscEnabled?L():N();P(n,[new B(r),s],o),i.setArgs(n),globalThis.state.sboard.asyncRequest((async function(e){St(e,t),globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Async request",a),await a.exec(e,globalThis.state.drvSerial,globalThis.state.ffiOverride)}));break}case"msg_view_load":{let t=e.payload;if(globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Received message:",t),"object"!=typeof t)throw new Error("bad msg_view_load message");let r=t.module;if("string"!=typeof r)throw new Error("bad msg_view_load message: module");let s=t.args;if(void 0===s&&(s=[]),!Array.isArray(s))throw new Error("bad msg_view_load message: args");let a=new ht("async",globalThis.state),i=a.params;i.setTag("load"),i.setModname(""),i.setEntryID(0);let n=new Array,o=t.argsEscEnabled?L():N();P(n,[new B(r),s],o),i.setArgs(n),globalThis.state.sboard.asyncRequest((async function(e){St(e,t),globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Async request",a),await a.exec(e,globalThis.state.drvSerial,globalThis.state.ffiOverride)}));break}case"msg_view_push":{let t=e.payload;if(globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Received message:",t),"object"!=typeof t)throw new Error("bad msg_view_push message");let r=t.module;if("string"!=typeof r)throw new Error("bad msg_view_push message: module");let s=t.args;if(void 0===s&&(s=[]),!Array.isArray(s))throw new Error("bad msg_view_push message: args");let a=new ht("async",globalThis.state),i=a.params;i.setTag("push"),i.setModname(""),i.setEntryID(0);let n=new Array,o=t.argsEscEnabled?L():N();P(n,[new B(r),s],o),i.setArgs(n),globalThis.state.sboard.asyncRequest((async function(e){St(e,t),globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Async request",a),await a.exec(e,globalThis.state.drvSerial,globalThis.state.ffiOverride)}));break}case"msg_view_pop":{let t=e.payload;if(globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Received message:",t),"object"!=typeof t)throw new Error("bad msg_view_pop message");let r=new ht("async",globalThis.state),s=r.params;s.setTag("pop"),s.setModname(""),s.setEntryID(0);let a=new Array;P(a,[],N()),s.setArgs(a),globalThis.state.sboard.asyncRequest((async function(e){St(e,t),globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Async request",r),await r.exec(e,globalThis.state.drvSerial,globalThis.state.ffiOverride)}));break}case"msg_view_reset":{let t=e.payload;if(globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Received message:",t),"object"!=typeof t)throw new Error("bad msg_view_reset message");let r=new ht("async",globalThis.state),s=r.params;s.setTag("reset"),s.setModname(""),s.setEntryID(0);let a=new Array;P(a,[],N()),s.setArgs(a),globalThis.state.sboard.asyncRequest((async function(e){St(e,t),globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Async request",r),await r.exec(e,globalThis.state.drvSerial,globalThis.state.ffiOverride)}));break}case"msg_view_refresh":{let t=e.payload;if(globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Received message:",t),"object"!=typeof t)throw new Error("bad msg_view_refresh message");let r=new ht("async",globalThis.state),s=r.params;s.setTag("refresh"),s.setModname(""),s.setEntryID(0);let a=new Array;P(a,[],N()),s.setArgs(a),globalThis.state.sboard.asyncRequest((async function(e){St(e,t),globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Async request",r),await r.exec(e,globalThis.state.drvSerial,globalThis.state.ffiOverride)}));break}case"msg_introspect_spreadsheet":{let t=e.payload;if(globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Received message:",t),"object"!=typeof t)throw new Error("bad msg_introspect_spreadsheet message");let r=t.filter,s=new ht("async",globalThis.state),a=s.params;a.setTag("spreadsheet_out"),a.setModname(""),a.setEntryID(0);let i=new Array;P(i,[r],N()),a.setArgs(i),globalThis.state.sboard.asyncRequest((async function(e){St(e,t),globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Async request",s),await s.exec(e,globalThis.state.drvSerial,globalThis.state.ffiOverride)}));break}case"msg_introspect_debug":{let t=e.payload;if(globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Received message:",t),"object"!=typeof t)throw new Error("bad msg_introspect_debug message");let r=t.command,s=new ht("async",globalThis.state),a=s.params;a.setTag("debugCommand_out"),a.setModname(""),a.setEntryID(0);let i=new Array;P(i,[r],N()),a.setArgs(i),globalThis.state.sboard.asyncRequest((async function(e){St(e,t),globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Async request",s),await s.exec(e,globalThis.state.drvSerial,globalThis.state.ffiOverride)}));break}}}catch(e){console.error(e)}}async function Ft(e,t){if("msg_mixFFI"==e.rmxType){if("binary"!=e.header._rmx_encoding)throw new Error("bad _rmx_encoding of msg_mixFFI message");let t=function(e,t,r,s){if("msg_mixDriver"!==e.rmxType&&"msg_mixFFI"!==e.rmxType)throw new Error("Driver: got message with bad _rmx_type");let a,i=new it,n=i.decode(e.payload);switch(n){case 771:a=new pt(t,r);break;case 773:a=new bt(t,r);break;case 777:a=new wt(t,r);break;case 1030:a=new yt(t,r);break;default:throw new Error("Driver: unknown/unsupported message type: "+n)}return a.params=i,a}(e,"FFI",globalThis.state),r=t.params.getCoroutine();globalThis.state.sboard.FFIReturn(r,(async function(e){globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("FFI return",t),await t.exec(e,globalThis.state.drvSerial,globalThis.state.ffiOverride)}))}}async function Dt(e){let t=globalThis.state.config.vmID,r=e.payload.call_id;switch(e.rmxType){case"msg_ffi_return":globalThis.state.sboard.FFIReturn(r,(async function(t){let s=new nt("local","FFI",globalThis.state);s.ffireturn(r,e.payload.value,{decode_type:e=>{switch(typeof e){case"undefined":return"undefined";case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":return Array.isArray(e)?"array":null===e?"null":e instanceof Map?e.get("_rmx_type"):e instanceof Uint8Array?"binary":"map";default:throw new Error("Cannot import this type of value: "+typeof e)}},decode_value:(e,t)=>{switch(e){case"case":return{name:t.get("name"),arg:t.get("arg")};case"token":return{data:t.get("data"),enabled:t.get("enabled"),extras:t.get("extras")};case"opaque":return{data:t.get("data")};default:return t}}}),await s.run(t,globalThis.state.drvSerial,globalThis.state.ffiOverride)}));break;case"msg_ffi_error":globalThis.state.sboard.FFIReturn(r,(async function(t){let s=new nt("local","FFI",globalThis.state),a={message:e.payload.message,stack:e.payload.stack};s.ffiabort(r,a),await s.run(t,globalThis.state.drvSerial,globalThis.state.ffiOverride)}));break;case"msg_ffi_later":globalThis.state.sboard.FFIReturn(r,(async function(e){let t=globalThis.state.wasm,r=t.instance.exports;t.call(r.mixrt_reqRunning);let s=new nt("local","FFI",globalThis.state);await s.run(e,globalThis.state.drvSerial,globalThis.state.ffiOverride)}));break;default:console.log("unexpected rmxType on /local/"+t+"/ffi/return: "+e.rmxType)}}async function Ut(e){if(!e instanceof yt)throw new Error("trying to send the wrong message on drvFFICall topic");let t=globalThis.state.config,r=globalThis.hub;globalThis.state.sboard.FFICall(e.params.getCoroutine(),e.params.getName());let s=t.topicBase()+"/FFICall";globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("FFI call",e);let a=e.encode("msg_mixFFI");await r.publish(s,a,!1)}async function Ct(e,t,r){globalThis.state.sboard.FFICall(t,e);let s=globalThis.hub,a={name:e,call_id:t,args:r},i=s.newLocalMessage("msg_ffi_call","vm",a),n=globalThis.state.config.vmID;await s.publish("/local/"+n+"/ffi/call",i,!1)}async function Rt(e){let t,r=globalThis.state.config,s=globalThis.hub,a=r.topicBase()+"/output";t="object"==typeof e&&"function"==typeof e.publish?e:new globalThis.JSONMessage("msg_response","vm",e),await s.publish(a,t,!1)}!function(){if(console.log("GROOVEBOX_BUILD (machine-wasm)","2824"),function(){let e=new Uint32Array(1);e[0]=305419896;let t=new Uint8Array(e.buffer);return 120==t[0]&&86==t[1]&&52==t[2]&&18==t[3]}()){try{r.g.process&&(r.g.process.stdout._handle&&r.g.process.stdout._handle.setBlocking(!0),r.g.process.stderr._handle&&r.g.process.stderr._handle.setBlocking(!0))}catch{console.log("setting up stdout/err failed")}console.log("mix machine: worker started")}else console.error("refusing to start up Mix Machine on a big-endian platform")}(),globalThis.Channel=u,globalThis.JSONMessage=t,globalThis.UnparsedJSONMessage=s,globalThis.BinaryMessage=i,globalThis.TextMessage=a,globalThis.EOF=o,onmessage=function(e){let t=e.data;switch(t._rmx_type){case"msg_vm_configure":!async function(e){let t=new m;t.vmID=e.vmID,t.org=e.org,t.workspace=e.workspace,t.workerURL=e.workerURL,t.baseURL=e.baseURL,t.user=e.user,t.token=e.token,t.debugMask=e.debugMask,t.machType=void 0!==e.machType?e.machType:"WASM",t.localFFIs=e.localFFIs?e.localFFIs:{},t.allowInsecureHttp=e.allowInsecureHttp,t.outputViaMQTT=e.outputViaMQTT,t.interceptFFI=e.interceptFFI,t.interceptDynloadFFI=e.interceptDynloadFFI;let r=new globalThis.Channel(e.hub);globalThis.hub=r;let s=new g(t,{fficall:Ut,fficall_local:Ct,output:Rt},{fficall:Ut,fficall_local:Ct,output:Rt}),a=new d(t,s);a.ffiOverride=function(){let e=new Map;return e.set("$co_sleep",ee),e.set("$isSyncEnabled",te),e.set("$mqtt_available",re),e.set("$showHook",se),e.set("$hideHook",ae),e.set("$log",ie),e.set("$http_do",le),e.set("$http_do_client",le),e.set("$crypto_SHA1Sum",de),e.set("$crypto_SHA256Sum",me),e.set("$crypto_HMACSHA1Sign",ge),e.set("$crypto_HMACSHA1Verify",fe),e.set("$crypto_HMACSHA256Sign",pe),e.set("$crypto_HMACSHA256Verify",be),e.set("$crypto_RSASHA256Sign",we),e.set("$crypto_AESGCMEncrypt",_e),e.set("$crypto_AESGCMDecrypt",ye),e.set("$crypto_randomKey32",xe),e.set("$wasm_load",Te.load.bind(Te)),e.set("$wasm_fun",Te.fun.bind(Te)),e.set("$wasm_call",Te.call.bind(Te)),e.set("$wasm_shutdown",Te.shutdown.bind(Te)),e}(),e.mixrtCode&&(a.mixrt_code=e.mixrtCode),a.mixcore=await Et.create(e.mixcore),globalThis.state=a;try{await It()}catch(e){console.log("Error",e)}}(t);break;case"msg_vm_logStatus":console.log("mix machine: still here");break;case"msg_vm_logMask":r=t.mask,globalThis.state&&(console.log("mix machine: Setting debug mask to: ",r),globalThis.state.config.debugMask=r,globalThis.state.wasm&&globalThis.state.wasm.call(globalThis.state.wasm.instance.exports.mixrt_setDebugFlags,r));break;default:console.error("mix machine: unknown message type: "+t._rmx_type)}var r}})()})();
2
+ (()=>{"use strict";var e={811:(e,t)=>{var r=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,s=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,a=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,i=/\\([\u000b\u0020-\u00ff])/g,n=/([\\"])/g,o=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;function l(e){var t=String(e);if(a.test(t))return t;if(t.length>0&&!s.test(t))throw new TypeError("invalid parameter value");return'"'+t.replace(n,"\\$1")+'"'}function c(e){this.parameters=Object.create(null),this.type=e}t.format=function(e){if(!e||"object"!=typeof e)throw new TypeError("argument obj is required");var t=e.parameters,r=e.type;if(!r||!o.test(r))throw new TypeError("invalid type");var s=r;if(t&&"object"==typeof t)for(var i,n=Object.keys(t).sort(),c=0;c<n.length;c++){if(i=n[c],!a.test(i))throw new TypeError("invalid parameter name");s+="; "+i+"="+l(t[i])}return s},t.parse=function(e){if(!e)throw new TypeError("argument string is required");var t="object"==typeof e?function(e){var t;if("function"==typeof e.getHeader?t=e.getHeader("content-type"):"object"==typeof e.headers&&(t=e.headers&&e.headers["content-type"]),"string"!=typeof t)throw new TypeError("content-type header is missing from object");return t}(e):e;if("string"!=typeof t)throw new TypeError("argument string is required to be a string");var s=t.indexOf(";"),a=-1!==s?t.slice(0,s).trim():t.trim();if(!o.test(a))throw new TypeError("invalid media type");var n=new c(a.toLowerCase());if(-1!==s){var l,u,h;for(r.lastIndex=s;u=r.exec(t);){if(u.index!==s)throw new TypeError("invalid parameter format");s+=u[0].length,l=u[1].toLowerCase(),34===(h=u[2]).charCodeAt(0)&&-1!==(h=h.slice(1,-1)).indexOf("\\")&&(h=h.replace(i,"$1")),n.parameters[l]=h}if(s!==t.length)throw new TypeError("invalid parameter format")}return n}}},t={};function r(s){var a=t[s];if(void 0!==a)return a.exports;var i=t[s]={exports:{}};return e[s](i,i.exports,r),i.exports}r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),(()=>{let e=function(e){};globalThis.ThisIsNode;class t{constructor(e,t,r){this.rmxType=e,this.sender=t,this.payload="string"==typeof r?JSON.parse(r):r,this.eof=!1,this.localOnly=!1,this.header={_rmx_type:e,_rmx_encoding:"json",_rmx_sender:t},this.topic="",this.retained=!1}received(e,t){return this.topic=e,this.retained=t,this}publish(e,t,r){return this.topic=t,this.retained=r,{_rmx_type:"msg_hub_publish",header:this.header,reqId:e,topic:t,payload:JSON.stringify(this.payload),retained:r,localOnly:!1}}}class s{constructor(e,t,r){if("string"!=typeof r)throw new Error("payload must be string");this.rmxType=e,this.sender=t,this.payload=r,this.eof=!1,this.localOnly=!1,this.header={_rmx_type:e,_rmx_encoding:"json",_rmx_sender:t},this.topic="",this.retained=!1}received(e,t){return this.topic=e,this.retained=t,this}publish(e,t,r){return this.topic=t,this.retained=r,{_rmx_type:"msg_hub_publish",header:this.header,reqId:e,topic:t,payload:this.payload,retained:r,localOnly:!1}}}class a{constructor(e,t,r){this.rmxType=e,this.sender=t,this.payload=r,this.eof=!1,this.localOnly=!1,this.header={_rmx_type:e,_rmx_encoding:"text",_rmx_sender:t},this.topic="",this.retained=!1}received(e,t){return this.topic=e,this.retained=t,this}publish(e,t,r){return this.topic=t,this.retained=r,{_rmx_type:"msg_hub_publish",header:this.header,reqId:e,topic:t,payload:this.payload,retained:r,localOnly:!1}}}class i{constructor(e,t,r){this.rmxType=e,this.sender=t,this.payload=r,this.eof=!1,this.localOnly=!1,this.header={_rmx_type:e,_rmx_encoding:"binary",_rmx_sender:t},this.topic="",this.retained=!1}received(e,t){return this.topic=e,this.retained=t,this}publish(e,t,r){return this.topic=t,this.retained=r,{_rmx_type:"msg_hub_publish",header:this.header,reqId:e,topic:t,payload:this.payload,retained:r,localOnly:!1}}}class n{constructor(e,t,r){this.rmxType=e,this.sender=t,this.payload=r,this.eof=!1,this.localOnly=!0,this.header={_rmx_type:e,_rmx_encoding:"local",_rmx_sender:t},this.topic="",this.retained=!1}received(e,t){return this.topic=e,this.retained=t,this}publish(e,t,r){return this.topic=t,this.retained=r,{_rmx_type:"msg_hub_publish",header:this.header,reqId:e,topic:t,payload:this.payload,retained:r,localOnly:!0}}}class o{constructor(){this.rmxType="",this.sender="",this.payload=null,this.eof=!0,this.localOnly=!1,this.header={_rmx_type:"",_rmx_encoding:"eof",_rmx_sender:""},this.topic="",this.retained=!1}}function l(e){if(e.eof)return new o;switch(e.header._rmx_encoding){case"text":return new a(e.header._rmx_type,e.header._rmx_sender,e.payload).received(e.topic,e.retained);case"json":return new t(e.header._rmx_type,e.header._rmx_sender,e.payload).received(e.topic,e.retained);case"binary":return new i(e.header._rmx_type,e.header._rmx_sender,e.payload).received(e.topic,e.retained);case"local":return new n(e.header._rmx_type,e.header._rmx_sender,e.payload).received(e.topic,e.retained);default:throw new Error("bad _rmx_encoding: "+e.header._rmx_encoding)}}class c{constructor(e,t,r){this.channel=e,this.topic=t,this.subId=r,this.buffer=new Array,this.eof=!1,this.notify=()=>null,e.expect.set(r,(e=>{null!=e.data.error?console.warn("got an unexpected error message: "+e.data.error):(this.buffer.push(l(e.data)),this.eof=this.eof||e.data.eof,this.notify())}))}next(){return new Promise(((e,t)=>{this.buffer.length>0?e(this.buffer.shift()):this.notify=()=>{this.notify=()=>null,this.buffer.length>0&&e(this.buffer.shift())}}))}unsubscribe(){return new Promise(((e,t)=>{let r=this.channel.reqId+1;this.channel.reqId=r,this.channel.expect.set(r,(s=>{this.channel.expect.delete(r),null==s.data.error?e(s.data):t(s.data)}));let s={_rmx_type:"msg_hub_unsubscribe",topic:this.topic,reqId:r,subId:this.subId};this.channel.port.postMessage(s)}))}}class u{constructor(e){this.port=e,this.expect=new Map,this.reqId=0,this.port.onmessage=e=>{try{let t=this.expect.get(e.data.reqId);e.eof&&this.expect.delete(e.data.reqId),t(e)}catch(e){console.error("Exception when receiving a message in hub-client: ",e)}}}publish(e,t,r){return new Promise(((s,a)=>{let i=this.reqId+1;this.reqId=i,this.expect.set(i,(e=>{this.expect.delete(i),null==e.data.error?s(null):a(e.data)}));let n=t.publish(i,e,r);this.port.postMessage(n)}))}send(e,t){return this.publish(e,t,!1)}set(e,t){return this.publish(e,t,!0)}get(e){return new Promise(((t,r)=>{let s=this.reqId+1;this.reqId=s,this.expect.set(s,(e=>{this.expect.delete(s),null==e.data.error?void 0!==e.data.payload?t(l(e.data.payload)):t(void 0):r(e.data)}));let a={_rmx_type:"msg_hub_get",header:{_rmx_type:"msg_hub_get",_rmx_encoding:"json",_rmx_sender:this.sender},reqId:s,topic:e,payload:"null",retained:!1,localOnly:!0};this.port.postMessage(a)}))}subscribe(e){return new Promise(((t,r)=>{let s=this.reqId+1,a=s+1;this.reqId=a;let i=new c(this,e,a);this.expect.set(s,(e=>{this.expect.delete(s),null==e.data.error?t(i):r(e.data)}));let n={_rmx_type:"msg_hub_subscribe",topic:e,reqId:s,subId:a};this.port.postMessage(n)}))}setLocalPubTopic(e){return new Promise(((t,r)=>{let s=this.reqId+1;this.reqId=s,this.expect.set(s,(e=>{this.expect.delete(s),null==e.data.error?t(null):r(e.data)}));let a={_rmx_type:"msg_hub_setLocalPubTopic",topic:e,reqId:s};this.port.postMessage(a)}))}setLocalSubTopic(e){return new Promise(((t,r)=>{let s=this.reqId+1;this.reqId=s,this.expect.set(s,(e=>{this.expect.delete(s),null==e.data.error?t(null):r(e.data)}));let a={_rmx_type:"msg_hub_setLocalSubTopic",topic:e,reqId:s};this.port.postMessage(a)}))}newChannel(){return new Promise(((e,t)=>{let r=this.reqId+1;this.reqId=r,this.expect.set(r,(s=>{if(this.expect.delete(r),null==s.data.error){let t=void 0!==s.ports?s.ports[0]:s.data.port,r=new u(t);e(r)}else t(s.data)}));let s={_rmx_type:"msg_hub_newChannel",reqId:r};this.port.postMessage(s)}))}newJSONMessage(e,r,s){return new t(e,r,s)}newUnparsedJSONMessage(e,t,r){return new s(e,t,r)}newTextMessage(e,t,r){return new a(e,t,r)}newBinaryMessage(e,t,r){return new i(e,t,r)}newLocalMessage(e,t,r){return new n(e,t,r)}newEOF(e,t,r){return new o(e,t,r)}}const h={DEBUG_MESSAGES:256,DEBUG_QUEUES:512,DEBUG_OUTPUT:1024};class d{constructor(e,t){this.config=e.isConfig(),this.sboard=t.isSwitchboard(),this.ffiOverride={},this.mixcore=null,this.reset()}reset(){this.drvCount=0,this.drvRequest=null,this.drvSerial=[-1],this.drvEcho=new Array,this.mixCode=new Map,this.mixCodeName=new Map,this.standalone=!1,this.postponedError=null,this.subscriptions={},this.subNextId=0,this.wasm=null,this.cached_main_module=void 0,this.localFFIs={},this.created=!1,this.wantInitResult=!1,this.mixrt_code=null,void 0!==globalThis.mixrt_code&&null!==globalThis.mixrt_code&&(this.mixrt_code=globalThis.mixrt_code)}isState(){return this}}class m{constructor(){this.vmID="unknown-vmID",this.org="unknown-org",this.workspace="unknown-workspace",this.baseURL=void 0,this.user="unknown-user",this.token="unknown-token",this.outputViaMQTT=!0,this.debugMask=1024,this.machType="WASM",this.quickLoad=!1,this.interceptFFI=!1,this.interceptDynloadFFI=!1,this.mixcore=null}isConfig(){return this}topicBase(){return"/org/"+this.org+"/ws/"+this.workspace+"/vm/"+this.vmID}}class g{constructor(e,t,r){this.config=e.isConfig(),this.chan_driver=t,this.chan_async=r,this.FFIrelease=e=>null,this.wakeup=e=>null,this.reset()}reset(){this.queue=new Map,this.FFIrelease(),this.wakeup(),this.FFICoID=0,this.FFIname="",this.FFIrelease=e=>null,this.wakeup=e=>null}isSwitchboard(){return this}driverRequest(e){this.enqueue("driver",e)}asyncRequest(e){this.enqueue("async",e)}FFICall(e,t){this.enqueue("FFI",(async r=>{this.FFICoID=e,this.FFIname=t;let s=new Promise(((e,t)=>{this.FFIrelease=e}));await s,this.FFICoID=0,this.FFIname="",this.FFIrelease=e=>null}))}FFIReturn(e,t){this.FFIrelease(),this.FFICoID==e?this.enqueueUrgent("FFI",t):this.asyncRequest(t)}enqueue(e,t){let r=this.queue.get(e);void 0===r&&(r=[],this.queue.set(e,r)),r.push(t),this.wakeup()}enqueueUrgent(e,t){let r=this.queue.get(e);void 0===r&&(r=[],this.queue.set(e,r)),r.unshift(t),this.wakeup()}hasTasks(e){let t=this.queue.get(e);return void 0!==t&&t.length>0}async mainLoop(){let e="none";for(this.wakeup=e=>null;;)try{let t=this.findNextQueue(e);for(;"none"==t;){let r=new Promise(((e,t)=>{this.wakeup=e}));await r,this.wakeup=e=>null,t=this.findNextQueue(e)}let r,s=this.queue.get(t);switch(e=t,t){case"driver":r=this.chan_driver;break;case"async":case"FFI":r=this.chan_async}let a=s.shift();await a(r)}catch(e){console.error("mix machine: exception caught by mainLoop: ",e)}}findNextQueue(e){return this.hasTasks("FFI")?"FFI":this.hasTasks(e)?e:this.hasTasks("driver")?"driver":this.hasTasks("async")?"async":"none"}}function f(e,t){let r=e.instance.exports,s=e.call(r.mixrt_copyYGtoIO,t),a=s/4;if(0==s)return;let i=e.call(r.mixrt_getIO);e.call(r.mixrt_relocateOutput,i,a);let n=new Uint8Array(s);return n.set(e.mem8.subarray(i,i+s)),n}function p(e,t){let r=e.instance.exports,s=t.length,a=(s-1)/4+1;e.call(r.mixrt_growIO,a);let i=e.call(r.mixrt_getIO);if(e.mem8.subarray(i,i+s).set(t),!e.call(r.mixrt_relocateInput,i,a)){let t=e.call(r.mixrt_getError);throw new Error("copyInMixValue: cannot relocate value - code "+t)}return i}function b(e,t){let r=e.instance.exports,s=(new TextEncoder).encode(t),a=s.length,i=e.call(r.malloc,a+1);if(0==i)throw new Error("out of memory");return e.mem8.subarray(i,i+a).set(s),e.mem8[i+a]=0,i}function w(e,t){let r=e.instance.exports;e.call(r.free,t)}function _(e,t,r){let s=0;for(;0!=e.mem8[t+s]&&s<r;)s++;let a=new Uint8Array(s);return a.set(e.mem8.subarray(t,t+s)),(new TextDecoder).decode(a)}function y(e,t,r){let s=new Uint8Array(r);return s.set(e.mem8.subarray(t,t+r)),s}function x(e,t,r){let s=e.instance.exports,a=e.call(s.mixrt_initEnvGetEnv);if(0==a)return r;let i=b(e,t);if(0==i)return r;let n=e.call(s.mixrt_mapFindStatic,i,a);if(e.call(s.free,i),0==n)return r;let o=e.call(s.mixrt_getString,n);return 0==o?r:_(e,o,100)}const v=["unset","driver","async","FFI","internal"],E=3,T=8,k=247|1<<E|1<<T;class A{constructor(e,t,r){if(!e instanceof Uint8Array)throw new Error("Token: data must be an Uint8Array");if("number"!=typeof t)throw new Error("Token: enabled_ops must be a number");0==e.length&&(t=k),this.data=e,this.enabled=t,this.extras=r}}function I(e){if("string"!=typeof e)throw new Error("token must be a string");let t=(new TextEncoder).encode(e);return new A(t,1<<E|1<<T,{})}class S{constructor(e,t){if("string"!=typeof e)throw new Error("Case: name must be a string");this.name=e,this.arg=t}}class M{constructor(e){if(!(e instanceof Uint32Array))throw new Error("Opaque: must be a Uint32Array");this.data=e}}class F extends String{constructor(e){super(e),this.tagged=!0}}function D(e){let t="";for(let r=0;r<e.byteLength;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function U(e){let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}function C(e){if("string"!=typeof e)return null;if(!e.startsWith("{"))return null;let t=e.indexOf("}");if(t<0)return null;let r=e.substring(1,t),s=r.indexOf(":");return s>=0&&(r=r.substring(0,s)),r}function R(){return{encode_undefined:()=>({_rmx_type:"{tag}undefined"}),encode_bool:e=>e,encode_null:()=>null,encode_number:e=>{if(Number.isFinite(e))return e;if(Number.isNaN(e))return{_rmx_type:"{tag}nan"};if(e===Number.POSITIVE_INFINITY)return{_rmx_type:"{tag}posinf"};if(e===Number.NEGATIVE_INFINITY)return{_rmx_type:"{tag}neginf"};throw new Error("cannot categorize number: "+e)},encode_string:e=>e,encode_taggedString:e=>{let t=C(e);if(null==t)return e;let r=function(e){if("string"!=typeof e)return"";if(!e.startsWith("{"))return"";let t=e.indexOf("}");if(t<0)return"";let r=e.substring(1,t),s=r.indexOf(":");return s>=0?r.substring(s+1):""}(e);""!=r&&(r=":"+r);let s=function(e){if("string"!=typeof e)return"";if(!e.startsWith("{"))return"";let t=e.indexOf("}");return t<0?"":e.substring(t+1)}(e);return"ref"==t?{_rmx_type:"{tag}case:db.ref",_rmx_value:s}:{_rmx_type:"{tag}"+t+r,_rmx_value:s}},encode_binary:e=>({_rmx_type:"{tag}bin",_rmx_value:D(e)}),encode_opaque:e=>"<opaque>",encode_mapCreate:()=>({}),encode_mapSet:(e,t,r)=>{"_rmx_type"==t&&null!=C(r)?e[t]="{str}"+r:e[t]=r},encode_arrayCreate:()=>[],encode_arrayPush:(e,t)=>e.push(t),encode_case0:e=>({_rmx_type:"{tag}case:"+e}),encode_case1:(e,t)=>({_rmx_type:"{tag}case:"+e,_rmx_value:t}),encode_token:(e,t)=>"<opaque token>"}}function q(){return{encode_undefined:()=>{},encode_bool:e=>e,encode_null:()=>null,encode_number:e=>e,encode_string:e=>e,encode_taggedString:e=>new F(e),encode_binary:e=>e,encode_opaque:e=>new M(e),encode_mapCreate:()=>({}),encode_mapSet:(e,t,r)=>e[t]=r,encode_arrayCreate:()=>[],encode_arrayPush:(e,t)=>e.push(t),encode_case0:e=>new S(e,void 0),encode_case1:(e,t)=>new S(e,t),encode_token:(e,t,r)=>new A(e,t,r)}}function O(e,t,r){function s(r){return e[t+r]}function a(){return s(0)}function i(r,s){return e.subarray(t+r,t+r+s)}function n(t){return O(e,s(t)/4,r)}function o(){let e=i(3,a()-1),t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=t[t.length-1];return t.subarray(0,t.length-r-1)}function l(){let e=o();return(new TextDecoder).decode(e)}let c=255&s(1);switch(c){case 0:return r.encode_undefined();case 1:return r.encode_bool(0!=s(2));case 2:return r.encode_null();case 4:{let e=(u=i(2,2),new DataView(u.buffer,u.byteOffset,u.byteLength).getFloat64(0,!0));return r.encode_number(e)}case 7:return r.encode_mapCreate();case 8:return r.encode_string(l());case 9:return r.encode_taggedString(l());case 10:return r.encode_binary(o());case 12:{let e=a(),t=new Uint32Array(e);return t.set(i(2,e)),r.encode_opaque(t)}case 16:{let e=s(3),t=r.encode_arrayCreate();for(let s=0;s<e;s++){let e=n(4+s);r.encode_arrayPush(t,e)}return t}case 25:{let e=a()/2,t=r.encode_mapCreate();for(let s=0;s<e;s++){let e=n(2*s+2),a=n(2*s+3);r.encode_mapSet(t,e,a)}return t}case 17:{let s=r.encode_mapCreate(),a=[t];for(;a.length>0;){let t=a.shift();if(17==(255&e[t+1])){let i=O(e,e[t+3],r),n=O(e,e[t+4],r);r.encode_mapSet(s,i,n),a.push(e[t+5]),a.push(e[t+6])}}return s}case 26:{let e=n(2),t=n(3);return void 0===t?r.encode_case0(e):r.encode_case1(e,t)}case 28:{let e=s(2),t=n(3),a=n(4);return r.encode_token(e,t,a)}default:return"{unprintable: "+c+"}"}var u}function $(e,t,r){let s=e.instance.exports;switch(e.call(s.mixrt_getTag,t)){case 0:return r.encode_undefined();case 1:return r.encode_bool(0!=e.call(s.mixrt_getBool,t));case 2:return r.encode_null();case 4:return r.encode_number(e.call(s.mixrt_getNumber,t));case 7:return r.encode_mapCreate();case 8:{let a=e.call(s.mixrt_getString,t),i=_(e,a,1e7);return r.encode_string(i)}case 9:{let a=e.call(s.mixrt_getString,t),i=_(e,a,1e7);return r.encode_taggedString(i)}case 10:{let a=e.call(s.mixrt_getBinary,t),i=e.call(s.mixrt_getBinaryLength,t),n=y(e,a,i);return r.encode_binary(n)}case 12:{let s=function(e,t,r){let s=new Uint32Array(r);return s.set(e.mem32.subarray(t>>2,(t>>2)+r)),s}(e,t+8,e.mem32[t>>2]);return r.encode_opaque(s)}case 16:{let a=e.call(s.mixrt_arrayLength,t),i=r.encode_arrayCreate();for(let n=0;n<a;n++){let a=e.call(s.mixrt_arrayGet,t,n,!1),o=$(e,a,r);r.encode_arrayPush(i,o)}return i}case 17:{let a=e.call(s.mixrt_mapHeightLimit),i=e.call(s.malloc,4*a);if(0==i)throw new Error("out of memory");let n=r.encode_mapCreate(),o=e.call(s.mixrt_mapIterateStatic,i,a,t);for(;0!=o;){let t=e.call(s.mixrt_mapCurrentKey,o),a=$(e,t,r),l=e.call(s.mixrt_mapCurrentValue,o),c=$(e,l,r);r.encode_mapSet(n,a,c),o=e.call(s.mixrt_mapNextStatic,i)}return e.call(s.free,i),n}case 26:{let a,i=$(e,e.call(s.mixrt_caseName,t),r);return e.call(s.mixrt_caseHasArg,t)?(a=$(e,e.call(s.mixrt_caseGetArg,t),r),r.encode_case1(i,a)):r.encode_case0(i)}case 28:{let a=e.call(s.mixrt_tokenData,t),i=e.call(s.mixrt_getBinary,a),n=e.call(s.mixrt_getBinaryLength,a),o=y(e,i,n),l=e.call(s.mixrt_tokenEnabledOps,t),c=e.call(s.mixrt_tokenExtras,t),u=f(e,c);return r.encode_token(o,l,u)}default:return"{unprintable}"}}class B{constructor(e){this.data=e}}let G={tag_undefined:!0,tag_null:!0,tag_str:!0,tag_bin:!0,tag_nan:!0,tag_posinf:!0,tag_neginf:!0,tag_handle:!0,tag_tag:!0,tag_ref:!0};function L(){return{decode_type:e=>{switch(typeof e){case"undefined":return"undefined";case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(e instanceof S||function(e){let t=e._rmx_type;return void 0!==t&&"string"==typeof t&&!!t.startsWith("{tag}case:")&&"{tag}case:db.ref"!=t}(e))return"case";if(e instanceof A)return"token";if(e instanceof F)return"taggedString";if(e instanceof Uint8Array)return"binary";if(e instanceof B)return"valueOnly";let t=function(e){let t=e._rmx_type;if(void 0===t||"string"!=typeof t)return null;if(!t.startsWith("{tag}"))return null;if(t=t.substring(5),"case:db.ref"==t)return"ref";let r=t.indexOf(":");return r>=0&&(t=t.substring(0,r)),t}(e);if("string"==typeof t){let e="tag_"+t;if(G[e])return e}return"map";default:throw new Error("Cannot import this type of value: "+typeof e)}},decode_value:(e,t)=>{if(e.startsWith("tag_"))return void 0!==t._rmx_value?t._rmx_value:t.data;switch(e){case"case":if(!(t instanceof S)){let e=t._rmx_type.substring(10),r=t._rmx_value;return new S(e,r)}return t;case"map":let e=t._rmx_type;if(void 0!==e&&e.startsWith("{str}")){e=e.substring(5);let r={};return Object.assign(r,t),r._rmx_type=e,r}return t;default:return t}}}}function N(){return{decode_type:e=>{switch(typeof e){case"undefined":return"undefined";case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":return Array.isArray(e)?"array":null===e?"null":e instanceof S?"case":e instanceof A?"token":e instanceof F?"taggedString":e instanceof M?"opaque":e instanceof Uint8Array?"binary":e instanceof B?"valueOnly":"map";default:throw new Error("Cannot import this type of value: "+typeof e)}},decode_value:(e,t)=>t}}function P(e,t,r){function s(e,t){e.push(255&t,t>>8&255,t>>16&255,t>>24&255)}function a(e,t){e.push(2,0,0,0,4,0,0,0);let r=new DataView(new ArrayBuffer(8));r.setFloat64(0,t,!0),e.push(r.getUint8(0)),e.push(r.getUint8(1)),e.push(r.getUint8(2)),e.push(r.getUint8(3)),e.push(r.getUint8(4)),e.push(r.getUint8(5)),e.push(r.getUint8(6)),e.push(r.getUint8(7))}function i(e,t,r){let a=Math.floor(r.length/4)+2,i=4-r.length%4;s(e,a),s(e,t),s(e,0);for(let t of r)e.push(t);for(let t=0;t<i-1;t++)e.push(0);e.push(i-1),a%2==1&&s(e,4294967295)}function n(e,t,r){i(e,t,(new TextEncoder).encode(r))}function o(e,t){let r=new Array;s(r,e.length),e[t]=r[0],e[t+1]=r[1],e[t+2]=r[2],e[t+3]=r[3]}let l=r.decode_type(t),c=r.decode_value(l,t);switch(l){case"undefined":case"tag_undefined":!function(e){e.push(1,0,0,0,0,0,0,0,1,0,0,0,255,255,255,255)}(e);break;case"null":case"tag_null":!function(e){e.push(0,0,0,0,2,0,0,0)}(e);break;case"boolean":s(e,1),s(e,1),s(e,c?2:0),s(e,4294967295);break;case"number":a(e,c);break;case"tag_str":case"string":n(e,8,c);break;case"tag_bin":i(e,10,U(c));break;case"tag_nan":a(e,Number.NaN);break;case"tag_posinf":a(e,Number.POSITIVE_INFINITY);break;case"tag_neginf":a(e,Number.NEGATIVE_INFINITY);break;case"tag_handle":let u=parseInt(c);s(e,1),s(e,6),s(e,u),s(e,4294967295);break;case"tag_ref":case"taggedString":n(e,9,"{ref}"+c);break;case"binary":i(e,10,c);break;case"opaque":s(e,c.data.length),s(e,12);for(let t=0;t<c.data.length;t++)s(e,c.data[t]);c.data.length%2==1&&s(e,4294967295);break;case"array":{s(e,c.length+2),s(e,528),s(e,0),s(e,c.length);let t=e.length;for(let t=0;t<c.length;t++)s(e,0);c.length%2==1&&s(e,4294967295);for(let s=0;s<c.length;s++)o(e,t+4*s),P(e,c[s],r);break}case"case":{s(e,2),s(e,26);let t=e.length;s(e,0),s(e,0),o(e,t),P(e,c.name,r),o(e,t+4),P(e,c.arg,r);break}case"map":{let t=Symbol.iterator in c?c:Object.entries(c),a=0;for(const e of t)a++;t=Symbol.iterator in c?c:Object.entries(c),s(e,2*a),s(e,25);let i=e.length;for(let t=0;t<2*a;t++)s(e,0);for(const s of t)o(e,i),i+=4,P(e,s[0],r),o(e,i),i+=4,P(e,s[1],r);break}case"token":{let t=c.data,a=c.enabled,i=c.extras||{};s(e,3),s(e,284),s(e,a);let n=e.length;s(e,0);let l=e.length;s(e,0),s(e,4294967295),o(e,n),P(e,t,r),o(e,l),P(e,i,r);break}case"valueOnly":P(e,t.data,N());break;default:throw new Error("cannot import this type: "+l)}}function H(e,t,r){let s=t.decode_type(e),a=t.decode_value(s,e);switch(s){case"undefined":case"tag_undefined":return r.encode_undefined();case"null":case"tag_null":return r.encode_null();case"boolean":return r.encode_bool(1==a);case"number":return r.encode_number(a);case"tag_nan":return r.encode_number(Number.NaN);case"tag_posinf":return r.encode_number(Number.POSITIVE_INFINITY);case"tag_neginf":return r.encode_number(Number.NEGATIVE_INFINITY);case"tag_ref":case"taggedString":let e="{ref}"+a;return r.encode_taggedString(e);case"string":case"tag_str":return r.encode_string(a);case"binary":return r.encode_binary(a);case"tag_bin":return r.encode_binary(U(a));case"array":{let e=r.encode_arrayCreate();for(let s=0;s<a.length;s++)r.encode_arrayPush(e,H(a[s],t,r));return e}case"case":return void 0===a.arg?r.encode_case0(a.name):r.encode_case1(a.name,H(a.arg,t,r));case"map":{let e=r.encode_mapCreate(),s=Symbol.iterator in a?a:Object.entries(a);for(const a of s)e[a[0]]=H(a[1],t,r);return e}case"valueOnly":return H(a.data,N(),r);default:throw new Error("cannot recode this type: "+s)}}class j{constructor(e,t){this.buf=e,this.ptr=t||0}get(e){return this.buf[this.ptr+e]}at(e){let t=this.get(e)/4;return new j(this.buf,t)}tag(){return 255&this.get(1)}slice(){return this.buf.slice(this.ptr,this.ptr+2+this.get(0))}decode(){return O(this.buf,this.ptr,q())}checkTag(e){const t=this.tag();if(e!=t)throw new Error("expected tag "+e+" found "+t);return this}atArrayElt(e){let t=this.arrayLength();if(e>=t)throw new Error("index out of bounds ("+e+" >= "+t+")");return this.at(4+e)}arrayLength(){return this.checkTag(16),this.get(3)}atArrayPath(e){let t=this;for(let r of e)t=t.atArrayElt(r);return t}mapHeader(){return this.checkTag(25),this.get(0)/2}atMapValue(e){let t=this.mapHeader();if(e>=t)throw new Error("index out of bounds ("+e+" >= "+t+")");return this.at(2*e+1)}}function W(e){if(!Array.isArray(e))return!1;for(let t=0;t<e.length;e++)if("string"!=typeof e[t])return!1;return!0}function V(e,t,r){let s,a=e.url;if(void 0===a)throw new Error(r+": config key 'url' must be specified");if("string"!=typeof a)throw new Error(r+": config key 'url' must be a string");try{s=new URL(a)}catch(e){throw new Error(e.message)}if(!t.includes(s.protocol))throw new Error(r+": restricted to https/wss URLs, but got "+s.protocol);s.hash="";let i=e.params;if(void 0!==i){if(!function(e){if("object"!=typeof e)return!1;for(let t in e)if("string"!=typeof e[t])return!1;return!0}(i))throw new Error(r+": config key 'params' must be an object of strings");Object.keys(i).length>0&&(s.search=new URLSearchParams(i).toString())}return s}const Y=new Map,J="cloud-";let z=0;function Q(e){return e.startsWith(J)}function K(e){return"string"==typeof e&&e.startsWith("/cloud/")}function Z(e){return"string"==typeof e&&e.startsWith("$cloud")&&e.indexOf("/")>0}var X=r(811);function ee(e,t){let r=t[0];return new Promise((e=>{setTimeout((function(){e(null)}),1e3*r)}))}function te(e,t){return e.wasm.call(e.mixrt.mixrt_initEnvGetSyncProtocol)>0}function re(e,t){return 0!=e.wasm.call(e.mixrt.mixrt_initEnvGetMQTTEnabled)}function se(e,t){return null}function ae(e,t){return null}async function ie(e,t){let r={logMessages:[{severity:t[0].toString(),text:t[1].toString()}]};await e.publishMessage(r)}class ne extends Error{constructor(e){super(e)}}function oe(e,t,r,s){if("string"==typeof r)return r;if(!(r instanceof A))throw new Error("http.doRequest: config key '"+t+"' must be a token");return(new TextDecoder).decode(r.data)}function le(e,t){try{if(1!=t.length||"object"!=typeof t[0])throw new Error("http.doRequest: argument must be an object");let e,r=t[0],s={method:"GET",headers:new Headers};"string"==typeof r.method&&(s.method=r.method);try{let t=["https:","remix:"];globalThis.state.config.allowInsecureHttp&&t.push("http:"),e=V(r,t,"http.doRequest")}catch(e){throw console.error("Exception: ",e),new ne(e.message)}let a=r.body;if(void 0!==a){if("string"!=typeof a&&!(a instanceof Uint8Array))throw new Error("http.doRequest: config key 'body' must be a string");s.body=a}let i=r.oauthToken;if(void 0!==i){let t=oe(0,"oauthToken",i,e.hostname);""!=t&&(s.headers.set("Authorization","Bearer "+t),s.credentials="same-origin")}let n=r.basicAuth;if(void 0!==n){if("object"!=typeof n)throw new Error("http.doRequest: config key 'basicAuth' must be an object");let t=n.username;if("string"!=typeof t)throw new Error("http.doRequest: config key 'basicAuth.username' must be a string");let r=oe(0,"basicAuth.password",n.password,e.hostname),a=btoa(encodeURIComponent(t+":"+r).replace(/%([0-9A-F]{2})/g,(function(e,t){return String.fromCharCode("0x"+t)})));s.headers.set("Authorization","Basic "+a),s.credentials="include"}let o=r.headers;if("object"==typeof o)for(let e in o){let t=o[e];if("string"!=typeof t)throw new Error("http.doRequest: bad header in config object: "+e);s.headers.set(e,t)}let l=new Request(e,s),c=!0!==r.returnBinaryResponseBody,u=r.mediaTypes||{"*":new S("http.textMode",void 0)};if("object"!=typeof u)throw new Error("http.doRequest: bad mediaTypes setting in config object");let h=e=>{let t={};e.headers.forEach(((e,r)=>{var s;t[(s=r,s.split("-").map((e=>{let t=e.toLowerCase();return""!=t&&(t=e.substring(0,1).toUpperCase()+e.substring(1)),t})).join("-"))]=e}));let r=e.headers.get("content-type"),s="unset",a=!1;null==r&&(r="text/plain");let i=X.parse(r),n=i.type,o=i.type.indexOf("/");if(o>=0&&(n=i.type.substring(0,o)),c){let e=u[i.type];if(void 0===e&&(e=u[n+"/*"],void 0===e&&(e=u["*"],void 0===e&&(e=new S("http.binaryMode",void 0)))),!(e instanceof S))throw new Error("http.doRequest: bad mediaTypes setting in config object");switch(e.name){case"http.textMode":break;case"http.binaryMode":c=!1;break;default:throw new Error("http.doRequest: bad mediaTypes setting in config object")}}if(c){s=i.parameters.charset,a=void 0!==s;let e=a&&function(e){try{return new TextDecoder(e),!0}catch{return!1}}(s);e||(s="iso-8859-1"),a&&(t["X-Received-Content-Type"]=r,i.parameters.charset="utf-8",r=X.format(i),t["Content-Type"]=r)}return e.arrayBuffer().then((r=>{let i;if(c)if(a)i=new TextDecoder(s,{fatal:!1}).decode(r);else try{i=new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{i=new TextDecoder("iso-8859-1",{fatal:!1}).decode(r)}else i=new Uint8Array(r);return{headers:t,body:i,status:e.status}}))};return fetch(l).then((t=>h(t).then((t=>({status:t.status,headers:t.headers,requested_url:e.toString(),body:t.body}))))).catch((e=>(console.error("Exception",e),{error:e.message})))}catch(e){if(e instanceof ne)return console.error("Exception",e),{error:e.message};throw e}}function ce(e,t,r){if("string"==typeof r)return(new TextEncoder).encode(r);if(r instanceof Uint8Array)return r;if(r instanceof A)return r.data;throw new Error(t+": parameter is neither string nor binary nor token")}function ue(e){if(!e.startsWith("-----BEGIN PRIVATE KEY-----"))throw new Error(function_name+": RSA key must be in PKCS#8 PEM format");const t=e.substring(27,e.length-25),r=atob(t.replaceAll(/\s/g,"")),s=new ArrayBuffer(r.length),a=new Uint8Array(s);for(let e=0,t=r.length;e<t;e++)a[e]=r.charCodeAt(e);return s}function he(e,t){if(e.length!=t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function de(e,t){if(void 0===t[0])return;let r=ce(0,"$crypto_SHA1Sum",t[0]);return crypto.subtle.digest("SHA-1",r.buffer).then((e=>new Uint8Array(e)))}function me(e,t){if(void 0===t[0])return;let r=ce(0,"$crypto_SHA256Sum",t[0]);return crypto.subtle.digest("SHA-256",r.buffer).then((e=>new Uint8Array(e)))}function ge(e,t){if(void 0===t[0]||void 0===t[1])return;let r=ce(0,"$crypto_HMACSHA1Sign",t[0]),s=ce(0,"$crypto_HMACSHA1Sign",t[1]);return crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-1"},!1,["sign"]).then((e=>crypto.subtle.sign("HMAC",e,s))).then((e=>new Uint8Array(e)))}function fe(e,t){if(void 0===t[0]||void 0===t[1])return;let r=ce(0,"$crypto_HMACSHA1Verify",t[0]),s=ce(0,"$crypto_HMACSHA1Verify",t[1]),a=ce(0,"$crypto_HMACSHA1Verify",t[2]);return crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-1"},!1,["sign"]).then((e=>crypto.subtle.sign("HMAC",e,s))).then((e=>he(a,new Uint8Array(e))))}function pe(e,t){if(void 0===t[0]||void 0===t[1])return;let r=ce(0,"$crypto_HMACSHA256Sign",t[0]),s=ce(0,"$crypto_HMACSHA256Sign",t[1]);return crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},!1,["sign"]).then((e=>crypto.subtle.sign("HMAC",e,s))).then((e=>new Uint8Array(e)))}function be(e,t){if(void 0===t[0]||void 0===t[1])return;let r=ce(0,"$crypto_HMACSHA256Verify",t[0]),s=ce(0,"$crypto_HMACSHA256Verify",t[1]),a=ce(0,"$crypto_HMACSHA256Verify",t[2]);return crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},!1,["sign"]).then((e=>crypto.subtle.sign("HMAC",e,s))).then((e=>he(a,new Uint8Array(e))))}function we(e,t){if(void 0===t[0]||void 0===t[1])return;let r=function(e,t,r){var s="";if("string"==typeof r)s=r;else if(r instanceof Uint8Array)s=(new TextDecoder).decode(r);else{if(!(r instanceof A))throw new Error("$crypto_RSASHA256Sign: parameter is neither string nor binary nor token");s=(new TextDecoder).decode(r.data)}return ue(s)}(0,0,t[0]),s=ce(0,"$crypto_RSASHA256Sign",t[1]);return crypto.subtle.importKey("pkcs8",r,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["sign"]).then((e=>crypto.subtle.sign("RSASSA-PKCS1-v1_5",e,s))).then((e=>new Uint8Array(e)))}function _e(e,t){if(void 0===t[0]||void 0===t[2])return;let r=new Uint8Array(12);crypto.getRandomValues(r);let s,a=ce(0,"$crypto_AESGCMEncrypt",t[0]);void 0!==t[1]&&null!==t[1]&&(s=ce(0,"$crypto_AESGCMEncrypt",t[1]));let i=ce(0,"$crypto_AESGCMEncrypt",t[2]);return crypto.subtle.importKey("raw",a,"AES-GCM",!1,["encrypt"]).then((e=>crypto.subtle.encrypt({name:"AES-GCM",iv:r,additionalData:s},e,i))).then((e=>{let t=new Uint8Array(e),s=new Uint8Array(e.byteLength+12);return s.set(r),s.set(t,12),new S("ok",s)})).catch((e=>new S("error",e.message)))}function ye(e,t){if(void 0===t[0]||void 0===t[2])return;let r,s=ce(0,"$crypto_AESGCMDecrypt",t[0]);void 0!==t[1]&&null!==t[1]&&(r=ce(0,"$crypto_AESGCMDecrypt",t[1]));let a=ce(0,"$crypto_AESGCMDecrypt",t[2]);if(a.byteLength<12)return new S("error","message too short");let i=new Uint8Array(12);return i.set(a.subarray(0,12)),crypto.subtle.importKey("raw",s,"AES-GCM",!1,["decrypt"]).then((e=>{let t=new Uint8Array(a.byteLength-12);return t.set(a.subarray(12)),crypto.subtle.decrypt({name:"AES-GCM",iv:i,additionalData:r},e,t)})).then((e=>new S("ok",new Uint8Array(e)))).catch((e=>new S("error",e.message)))}function xe(e,t){let r=new Uint8Array(32);return crypto.getRandomValues(r),r}function ve(e){throw new Error("WASM FFI: "+e)}class Ee{constructor(e){this.instance=e,this.functions=[]}static async load(e){let t=await async function(e){let{instance:t}=await WebAssembly.instantiate(e);return void 0!==t.exports._rmx_allocate&&void 0!==t.exports._rmx_deallocate||ve("allocation/deallocation functions unavailable"),t}(e);return new Ee(t)}fun(e){let t=this.instance.exports[e];void 0===t&&ve("function not found: "+e);let r=this.functions.length;return this.functions.push(t),r}call(e,t){(e<0||this.functions.length<=e)&&ve("invalid function");let r=this.functions[e];return function(e,t,r){e.memory.buffer;let s=new Array;P(s,r,N());let a=s.length,i=e._rmx_allocate(s.length+4),n=new Uint32Array(e.memory.buffer,i),o=new Uint8Array(e.memory.buffer,i+4);n[0]=a,o.set(s);let l=t(i),c=new Uint32Array(e.memory.buffer,l),u=c[0],h=O(c.subarray(1,1+u/4),0,q());switch(e._rmx_deallocate(i,s.length+4),e._rmx_deallocate(l,u+4),!h instanceof S&&ve("Wasm call must return a case, actually got a "+h.constructor.name),h.name){case"ok":return h.arg;case"error":ve("Wasm call failed: "+h.arg);default:ve("Wasm call must return a result case, actually got a case "+h.name)}}(this.instance.exports,r,t)}}const Te={wasms:[],load:async function(e,t){let[r]=t,s=await Ee.load(r),a=this.wasms.length;return this.wasms.push(s),a},fun:function(e,t){let[r,s]=t;return(r<0||this.wasms.length<=r)&&ve("invalid instance"),[r,this.wasms[r].fun(s)]},call:function(e,t){let[[r,s],a]=t;(r<0||this.wasms.length<=r)&&ve("invalid instance");let i=this.wasms[r];return void 0===i&&ve("FFI has been shutdown"),i.call(s,a)},shutdown:function(e,t){let[r]=t;(r<0||this.wasms.length<=r)&&ve("invalid instance"),delete this.wasms[r]}};let ke=1,Ae=new Map;class Ie{constructor(e,t,r){let s=ke++;this.id=s,this.kind=e,this.tags=t,this.destroy=r,Ae.set(s,this)}}function Se(e,t){return null}function Me(e,t){return null}function Fe(e,t){let r=t[0];return Ae.forEach((e=>{e.tags.includes(r)&&(e.destroy(e),Ae.delete(e.id))})),null}function De(e,t){return Fe(0,t)}async function Ue(e,t){let[r]=t;return r}function Ce(e,t){return[]}function Re(e){e instanceof Ie&&"websocket"==e.kind&&e.websocket.close()}function qe(e){if(e.incoming.length>0&&null!=e.reader){let t=e.incoming.shift();e.reader(t)}}function Oe(e){if(!(e instanceof M))throw new Error("websocket: bad handle");let t=e.data[0],r=Ae.get(t);if(void 0===r||"websocket"!=r.kind)throw new Error("websocket: bad handle");return r}function $e(e,t){let r=t[0],s=r.resourceTags;if(!W(s))throw new Error("websocket.create: config key 'resourceTags' must be an array of strings");let a=new Ie("websocket",s,Re),i=V(r,["wss:"],"websocket.create"),n=r.subprotocols;if(void 0===n&&(n=[]),!W(n))throw new Error("websocket.create: config key 'subprotocols' must be an array of strings");let o=r.timeout;if(void 0===o&&(o=300),"number"!=typeof o)throw new Error("websocket.create: config key 'timeout' must be a number");let l=r.readTimeout;if(void 0===l&&(l=0),"number"!=typeof l)throw new Error("websocket.create: config key 'readTimeout' must be a number");return a.websocket=new WebSocket(i,n),a.websocket.binaryType="arraybuffer",a.incoming=[],a.reader=null,a.error=void 0,a.rd_timeout=l,a.websocket.onmessage=e=>{a.incoming.push(["message",e]),qe(a)},a.websocket.onerror=e=>{a.incoming.push(["error",e]),a.error=e.message,qe(a)},a.websocket.onclose=e=>{a.incoming.push(["close",e]),qe(a)},new Promise(((e,t)=>{a.websocket.onopen=t=>{e(null)},o>0&&setTimeout((()=>{t(new Error("websocket timeout"))}),1e3*o)})).then((e=>{let t=new Uint32Array(1);return t[0]=a.id,new M(t)}))}function Be(e,t){try{return Oe(t[0]).error}catch(e){return e.message}}function Ge(e,t){let r=Oe(t[0]),s=t[1];if(!(s instanceof S))throw new Error("websocket.write: bad message");switch(s.name){case"websocket.textMsg":case"websocket.binMsg":r.websocket.send(s.arg);break;case"websocket.pingMsg":case"websocket.pongMsg":break;case"websocket.closeMsg":r.websocket.close(s.arg.code,s.arg.text);break;default:throw new Error("websocket.write: bad message")}return null}function Le(e,t){let r=Oe(t[0]);if(null!=r.reader)throw new Error("websocket.read: there is already a reader");return new Promise(((e,t)=>{r.reader=e,qe(r),0==r.incoming.length&&(r.closeEv?e(["close",r.closeEv]):r.error?t(new Error(r.error)):r.rd_timeout>0&&setTimeout((()=>{e(["timeout",null])}),1e3*r.rd_timeout))})).then((e=>{let[t,s]=e;switch(r.reader=null,t){case"message":return"string"==typeof s.data?new S("websocket.textMsg",s.data):new S("websocket.binMsg",new Uint8Array(s.data));case"error":throw new Error(s.message);case"close":let e={code:s.code,text:s.reason};return r.closeEv=s,new S("websocket.closeMsg",e);case"timeout":throw new Error("websocket timeout")}}))}function Ne(e,t){try{let e=Oe(t[0]);return e.error="closed",e.destroy(e),Ae.delete(e.id),null}catch{}return null}function Pe(e,t){if("string"!=typeof t)throw new Error("topic not a string");if(""==t||"/"!=t.at(0)&&"$"!=t.at(0))throw new Error("bad topic string: "+t);if("/"==t.at(0))return t;let r=t.indexOf("/");if(r<0)throw new Error("bad topic string: "+t);let s=t.substring(0,r),a=t.substring(r),i="/org/"+e.state.config.org+"/ws/"+e.state.config.workspace,n=i+"/app/"+x(e.wasm,"app","__empty__"),o=e.state.config.user,l=n+"/user/"+o,c=n+"/session/default",u=i+"/user/"+o;switch(s){case"$workspacePrefix":return i+a;case"$workspace":return i+"/shared/application"+a;case"$appPrefix":return n+a;case"$app":return n+"/shared/application"+a;case"$userPrefix":return l+a;case"$user":return l+"/application"+a;case"$sessionPrefix":return c+a;case"$session":return c+"/application"+a;case"$wsUserPrefix":return u+a;case"$wsUser":return u+"/application"+a;default:throw new Error("bad topic string: "+t)}}function He(e,t){return void 0!==globalThis.hub}function je(e,t){return void 0!==globalThis.hub}async function We(e,t){let r=t[0],s=t[1],a=!!t[2],i=t[3];if(K(r)||Z(r))throw new Error("$mqtt_publish: cannot publish to cloud (only a cloud agent can)");let n=globalThis.hub;if(void 0===n)throw new Error("$mqtt_publish: no broker available");let o=Pe(e,r);if("string"!=typeof s)throw new Error("$mqtt_publish: rmxType must be a string");let l,c="app/"+x(e.wasm,"app","__empty__");return i instanceof Uint8Array?l=n.newBinaryMessage(s,c,i):"string"==typeof i?l=n.newTextMessage(s,c,i):(i=H(i,N(),R()),l=n.newJSONMessage(s,c,i)),await n.publish(o,l,a),null}async function Ve(e,t){let r=t[0];if(K(r)||Z(r))throw new Error("$mqtt_get: cloud topics unsupported");let s=Pe(e,r),a=globalThis.hub;if(void 0===a)throw new Error("$mqtt_get: no broker available");let i=await a.get(s);if(void 0===i)return;let n=H(i.payload,L(),q());return{topic:i.topic,payload:n,retained:i.retained,_rmx_type:i.header._rmx_type,_rmx_encoding:i.header._rmx_encoding,_rmx_sender:i.header._rmx_sender}}async function Ye(e,t){let r=t[0];if(K(r)){let t=e.state.config.token;return await async function(e,t){let r=J+z++,s=await async function(e,t){let r=e.split("/"),[s,a,i]=r.slice(0,3);if(""!=s||"cloud"!=a)throw new Error("invalid cloud topic");let n=`https://${i}/subscribe${e}`,o={};t&&(o.Authorization=`Bearer ${t}`);let l=await fetch(n,{headers:o});if(!l.ok)throw new Error("failure to subscribe to cloud topic");let c=l.body.getReader();return{response:l,reader:c,topic:e}}(e,t);return Y.set(r,s),r}(r,t)}if(Z(r))throw new Error("$mqtt_subscribe: cloud topic path must be absolute");let s=globalThis.hub;if(void 0===s)throw new Error("$mqtt_subscribe: no broker available");let a=Pe(e,r),i="sub"+e.state.subNextId++,n=await s.subscribe(a);return e.state.subscriptions[i]=n,i}async function Je(e,t){let r=t[0];if(Q(r))return await async function(e){let t=Y.get(e);if(void 0===t)throw new Error("invalid cloud subscription");return await async function(e){try{for(;;){let{value:t,done:r}=await e.reader.read();r&&(t={_rmx_type:"{tag}undefined"});let s=(new TextDecoder).decode(t);if(s.startsWith(":")){let t=s.slice(1);"\n"!==t&&console.log(`cloud subscription message: ${t}`,e.topic)}else if(s.startsWith("data:")){let t=s.slice(5);return{payload:H(JSON.parse(t),L(),q()),topic:e.topic,retained:!1,_rmx_type:"msg_cloud_publish",_rmx_encoding:"json",_rmx_sender:"cloud-hub"}}}}catch(e){return void console.error("could not read next cloud subscription message",e)}}(t)}(r);if(void 0===globalThis.hub)throw new Error("$mqtt_subNext: no broker available");let s=e.state.subscriptions[r];if(void 0===s)return;let a=await s.next();if(void 0===a||a.eof)return;let i=H(a.payload,L(),q());return{topic:a.topic,payload:i,retained:a.retained,_rmx_type:a.header._rmx_type,_rmx_encoding:a.header._rmx_encoding,_rmx_sender:a.header._rmx_sender}}async function ze(e,t){let r=t[0];if(Q(r))return await async function(e){let t=Y.get(e);if(void 0===t)throw new Error("invalid cloud subscription");Y.delete(e),function(e){e.reader.cancel()}(t)}(r);if(void 0===globalThis.hub)throw new Error("$mqtt_unsubscribe: no broker available");let s=e.state.subscriptions[r];void 0!==s&&(await s.unsubscribe(),delete e.state.subscriptions[r])}function Qe(e,t){let r=t[0];return!("string"!=typeof r||r.startsWith("/")||r.includes("//")||r.endsWith("/")||r.includes("+")||r.includes("#"))}function Ke(e,t){return!0}function Ze(e,t){throw new Error("$mqtt_mountOrg: not implemented")}function Xe(){return globalThis.performance?performance.now():Date.now()}class et{constructor(){this.inst=null,this.memory=null,this.stdout=new Array,this.stderr=new Array,this.imp_wasi_snapshot_preview1={fd_write:this.fd_write.bind(this),fd_close:this.fd_close.bind(this),fd_seek:this.fd_seek.bind(this),fd_fdstat_get:this.fd_fdstat_get.bind(this),environ_sizes_get:this.environ_sizes_get.bind(this),environ_get:this.environ_get.bind(this),random_get:this.random_get.bind(this),proc_exit:this.proc_exit.bind(this),clock_time_get:this.clock_time_get.bind(this),poll_oneoff:this.poll_oneoff.bind(this)},this.wasiImport=this.imp_wasi_snapshot_preview1}update(){this.memory=this.inst.exports.memory,this.mem8=new Uint8Array(this.memory.buffer),this.mem32=new Uint32Array(this.memory.buffer)}fd_seek(e,t,r,s,a){this.update(),this.abort("unexpected fd_seek call")}clock_time_get(e,t,r){const s=new DataView(this.memory.buffer);if(0===e)s.setBigUint64(r,1000000n*BigInt((new Date).getTime()),!0);else if(1==e){let e;try{e=BigInt(Math.round(1e6*performance.now()))}catch(t){e=0n}s.setBigUint64(r,e,!0)}else s.setBigUint64(r,0n,!0);return 0}poll_oneoff(e,t,r){this.update(),this.abort("unexpected poll_oneoff call")}fd_write(e,t,r,s){let a,i;switch(this.update(),e){case 1:case 2:a=this.stdout,i=console.debug;break;default:return 0}let n=0;for(let e=0;e<r;e++){let r=this.mem32[t+8*e>>2],s=this.mem32[t+(8*e+4)>>2];for(let e=0;e<s;e++){let t=this.mem8[r+e];if(t>=32)a.push(t);else if(10==t){let e=new Uint8Array(a);console.log("WASM: %s",this.utf8array_to_string(e,0,a.length)),a.length=0}}n+=s}return this.mem32[s>>2]=n,0}utf8array_to_string(e,t,r){let s=t+r,a=t;for(;e[a]&&a<s;)a++;return(new TextDecoder).decode(e.subarray(t,a))}fd_close(e){return this.update(),0}fd_fdstat_get(e,t){this.update(),this.abort("unexpected fd_fdstat_get call")}environ_sizes_get(e,t){return this.update(),this.mem32[e>>2]=0,0}environ_get(e,t){return this.update(),0}random_get(e,t){this.update();let r=this.mem8.subarray(e,e+t),s=new Uint8Array(t);return globalThis.ThisIsNode||crypto.getRandomValues(s),r.set(s),0}proc_exit(e){this.update(),console.log("exit("+e+")")}abort(e){let t=(new Error).stack||"(no stack trace)";throw console.error("WASM ABORT: %s at %s",e,t),new WebAssembly.RuntimeError(e)}}class tt{constructor(e){this.main=e.mixrt_code,this.state=e.isState(),this.imp_env={},this.imp_mixrt_host={perfnow:Xe},this.mixModInstances=new Map}update(){this.mem8=new Uint8Array(this.memory.buffer),this.mem32=new Uint32Array(this.memory.buffer)}async compile(){if(void 0===this.state.cached_main_module){if(this.main instanceof WebAssembly.Module)this.main_module=this.main;else if(this.main instanceof Uint8Array)this.main_module=await WebAssembly.compile(this.main);else if(this.main instanceof URL){let e=fetch(this.main);this.main_module=await WebAssembly.compileStreaming(e)}else if("string"==typeof this.main)if(this.main.startsWith("http:")||this.main.startsWith("https:")||this.main.startsWith("data:")){let e=fetch(this.main);this.main_module=await WebAssembly.compileStreaming(e)}else{let e=function(e){let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}(this.main);this.main_module=await WebAssembly.compile(e)}else{let e=await this.main,t=await e.arrayBuffer();this.main_module=await WebAssembly.compile(t)}this.state.cached_main_module=this.main_module}else this.main_module=this.state.cached_main_module}async instantiate(){this.wasi=new et;let e={env:this.imp_env,wasi_snapshot_preview1:this.wasi.imp_wasi_snapshot_preview1,wasi_shim:{clock_time_get:this.clock_time_get(this)},mixrt_host:this.imp_mixrt_host};this.instance=await WebAssembly.instantiate(this.main_module,e),this.wasi.inst=this.instance,this.memory=this.instance.exports.memory,this.update(),this.instance.exports._initialize(),this.table=this.instance.exports.__indirect_function_table,this.seedRNG(),this.setDebugFlags()}async mixAddCode(e,t){let r=WebAssembly.Module.customSections(t,"mix_grooveboxBuildMin");if(r.length>0){let e=new Int32Array(r[0])[0];if(e>parseInt("2827"))throw new Error("This version of GrooveBox is too old: required build: "+e+", but this is build: 2827")}let s=WebAssembly.Module.customSections(t,"mix_constsLength")[0],a=new Int32Array(s)[0],i=WebAssembly.Module.customSections(t,"mix_tableLength")[0],n=new Int32Array(i)[0],o=this.instance.exports.malloc(a),l=this.table.length;this.table.grow(n);let c=WebAssembly.Module.imports(t),u={table:this.table,memory:this.memory,mix_consts:o,tableBase:l},h={};for(let e=0;e<c.length;e++){let t=c[e];switch(t.module){case"env":break;case"mixrt":if("function"==t.kind){let e=this.instance.exports[t.name];if(void 0===e)throw new Error("missing mixrt function: "+t.name);h[t.name]=e}break;default:throw new Error("unsupported import: "+t.module)}}let d={env:u,mixrt:h},m=await WebAssembly.instantiate(t,d);this.mixModInstances.set(e,m),null!=m.exports.mix_initAdd&&m.exports.mix_initAdd()}async mixLinkCode(e){let t=this.mixModInstances.get(e);null!=t&&(null!=t.exports.mix_initLink?t.exports.mix_initLink():t.exports.mix_init())}seedRNG(){this.instance.exports.srandom(2147483647*Math.random())}setDebugFlags(){this.instance.exports.mixrt_setDebugFlags(0)}setTempRet0(e){return t=>{e.tempRet0=t}}clock_time_get(e){return(t,r,s,a)=>{if(e.update(),0!=t)return 28;let i=Date.now(),n=1000000n*BigInt(i);return e.mem32[a>>2]=Number(0xffffffffn&n),e.mem32[1+(a>>2)]=Number(n>>32n&0xffffffffn),0}}wasm_abort(e){return()=>{e.update(),e.abort("Aborting WASM execution")}}call(e,...t){if(void 0===this)throw Error("FATAL: 'this' is undefined");try{let r=e.apply(void 0,t);return this.update(),r}catch(e){let t=e.stack||"(no stack trace)";throw console.error("WASM EXCEPTION: %s at %s",e.message,t),this.update(),e}}abort(e){let t=(new Error).stack||"(no stack trace)";throw console.error("WASM ABORT: %s at %s",e,t),new WebAssembly.RuntimeError(e)}}class rt{constructor(e,t,r){this.secBuf=e,this.sectionsData=t,this.literals=r}toBytes(){let e=new Array;return P(e,[this.secBuf,[null,this.sectionsData],null,null,null,this.literals],N()),new Uint8Array(e)}}function st(e){return e.atArrayElt(2)}function at(e){if(2==e.tag())return null;let t=e.atArrayElt(0).checkTag(10).decode(),r=e.atArrayPath([1,1]).checkTag(10).decode(),s=e.atArrayElt(5).checkTag(16).decode();return new rt(t,r,s)}class it{constructor(){this.instID=void 0,this.codeID=void 0,this.timeout=void 0,this.which=void 0,this.entryID=void 0,this.coroutine=void 0,this.errorCode=void 0,this.errorProxy=void 0,this.withResult=void 0,this.reference=void 0,this.tag=void 0,this.modname=void 0,this.name=void 0,this.location=void 0,this.args=void 0,this.result=void 0,this.message=void 0,this.backtrace=void 0,this.fgBusy=void 0,this.fgBlocked=void 0,this.serial=void 0,this.time=void 0,this.initFlag=0,this.apps=[],this.override=void 0,this.token=void 0,this.privileged=void 0}getInstID(){return this.instID}setInstID(e){this.instID=e}getCodeID(){return this.codeID}setCodeID(e){this.codeID=e}getTimeout(){return this.timeout}setTimeout(e){this.timeout=e}getWhich(){return this.which}setWhich(e){this.which=e}getEntryID(){return this.entryID}setEntryID(e){this.entryID=e}getCoroutine(){return this.coroutine}setCoroutine(e){this.coroutine=e}getErrorCode(){return this.errorCode}setErrorCode(e){this.errorCode=e}getErrorProxy(){return this.errorProxy}setErrorProxy(e){this.errorProxy=e}getWithResult(){return this.withResult}setWithResult(e){this.withResult=e}getReference(){return this.reference}setReference(e){this.reference=e}getTag(){return this.tag}setTag(e){this.tag=e}getModname(){return this.modname}setModname(e){this.modname=e}getName(){return this.name}setName(e){this.name=e}getLocation(){return this.location}setLocation(e){this.location=e}setLocationTriple(e,t,r){let s=e+"/"+t+"/"+r;this.setLocation(s)}getArgs(){return this.args}setArgs(e){this.args=e}getResult(){return this.result}setResult(e){this.result=e}getMessage(){return this.message}setMessage(e){this.message=e}getBacktrace(){return this.backtrace}setBacktrace(e){this.backtrace=e}getFgBusy(){return this.fgBusy}setFgBusy(e){this.fgBusy=e}getFgBlocked(){return this.fgBlocked}setFgBlocked(e){this.fgBlocked=e}getSerial(){return this.serial}setSerial(e){this.serial=e}getTime(){return this.time}setTime(e){this.time=e}getInitFlag(){return this.initFlag}setInitFlag(e){this.initFlag=e}getApps(){return this.apps}setApps(e){this.apps=e}getOverride(){return this.override}setOverride(e){this.override=e}getToken(){return this.token}setToken(e){this.token=e}getPrivileged(){return this.privileged}setPrivileged(e){this.privileged=e}encode(e){let t={};t.msgType=e,this.encodeInstID(t),this.encodeArgs(t),this.encodeResult(t),this.encodeName(t),this.encodeLocation(t),this.encodeErrorCode(t),this.encodeMessage(t),this.encodeBacktrace(t),this.encodeCoroutine(t),this.encodeErrorProxy(t);let r=new Array;return P(r,t,N()),new Uint8Array(r)}encodeInstID(e){void 0!==this.instID&&(e.instID=this.instID)}encodeArgs(e){void 0!==this.args&&(e.args=new Uint8Array(this.args.buffer))}encodeResult(e){void 0!==this.result&&(e.result=new Uint8Array(this.result.buffer))}encodeName(e){void 0!==this.name&&(e.name=this.name)}encodeLocation(e){void 0!==this.location&&(e.location=this.location)}encodeErrorCode(e){void 0!==this.errorCode&&(e.errorCode=this.errorCode)}encodeMessage(e){void 0!==this.message&&(e.message=this.message)}encodeBacktrace(e){void 0!==this.backtrace&&(e.backtrace=this.backtrace)}encodeCoroutine(e){void 0!==this.coroutine&&(e.coroutine=this.coroutine)}encodeErrorProxy(e){void 0!==this.errorProxy&&(e.errorProxy=this.errorProxy)}decode(e){let t=O(new Uint32Array(e.buffer),0,q());return void 0!==t.instID&&(this.instID=t.instID),void 0!==t.args&&(this.args=t.args),void 0!==t.result&&(this.result=t.result),void 0!==t.name&&(this.name=t.name),void 0!==t.location&&(this.location=t.location),void 0!==t.errorCode&&(this.errorCode=t.errorCode),void 0!==t.message&&(this.message=t.message),void 0!==t.backtrace&&(this.backtrace=t.backtrace),void 0!==t.coroutine&&(this.coroutine=t.coroutine),void 0!==t.errorProxy&&(this.errorProxy=t.errorProxy),t.msgType}}class nt{constructor(e,t,r){this.msgType=e,this.params=new it,this.queue=t,this.counter=0,this.state=r.isState()}serializable(){return!1}encode(e){if(!this.serializable())throw new Error("cannot serialize this message type");let t=this.params.encode(this.msgType);return new globalThis.BinaryMessage(e,"vm",t)}async run(e,t,r){let s=this.state.wasm,a=s.instance.exports;for(;;){switch(this.counter++,s.call(a.mixrt_runYG),s.call(a.mixrt_getState)){case 2:this.state.wantInitResult&&this.publishInitResult(e),s.call(a.mixrt_reqRunning);continue;case 5:if(0==s.call(a.mixrt_areFGCoroutinesBusy)&&this.state.config.outputViaMQTT){for(let t of this.state.drvEcho)await this.publishEcho(e,t);this.state.drvEcho=new Array}return;case 4:s.call(a.mixrt_reqRunning);continue;case 6:{let i=s.call(a.mixrt_getBuiltin),n=_(s,i,255);if(this.state.config.outputViaMQTT&&"$outputWithVersion"==n){await this.publishOutput(e),s.call(a.mixrt_reqReturn,s.call(a.mixrt_getCoroutine));let t=new Array;P(t,null,N()),p(s,t);continue}if(this.state.config.outputViaMQTT&&"$outputError"==n){await this.publishOutputError(e),s.call(a.mixrt_reqReturn,s.call(a.mixrt_getCoroutine));let t=new Array;P(t,null,N()),p(s,t);continue}if("$ffi_available"==n){let e=f(s,s.call(a.mixrt_getResult)),[t]=O(new Uint32Array(e.buffer),0,q()),i=Boolean("$ffi_available"==t||this.state.config.localFFIs[t]||this.state.mixcore.handlesFFI(t)||r.get(t)),n=new Array;P(n,i,N()),p(s,n),s.call(a.mixrt_reqReturn,s.call(a.mixrt_getCoroutine));continue}const o=this.state.config.localFFIs[n];if(void 0!==o)return void await this.runLocalFFI(e,t,n,o);if(this.state.mixcore.handlesFFI(n)){await this.runMixcoreFFI(n);continue}let l=r.get(n);if(void 0!==l){this.overriddenFFI(e,t,r,l,n);continue}if(this.state.standalone&&!this.state.config.interceptFFI){let e=new Error("FFI unsupported by this VM: "+n),t=s.call(a.mixrt_getCoroutine);this.ffiabort(t,e);continue}let c=new yt("FFI",this.state);return c.params.setInstID(0),c.params.setCoroutine(s.call(a.mixrt_getCoroutine)),c.params.setName(n),this.setParamsToCurrentLocation(c.params),c.params.setArgs(f(s,s.call(a.mixrt_getResult))),await e.fficall(c)}case 10:{let e=s.call(a.mixrt_getError);void 0===e&&(e=99);let t=_(s,s.call(a.mixrt_getErrorMessage),65535),r=s.call(a.mixrt_getCoroutine);console.error("Mix panic: ",e,t),console.error("Coroutine: ",r);let i=s.call(a.mixrt_locUnitID),n=_(s,i,255),o=s.call(a.mixrt_locUnitPC),l=s.call(a.mixrt_locSecInstr);console.error("Location: ",n," PC ",o," Instr ",l);let c=s.call(a.mixrt_co_backtrace,r),u=_(s,c,65535);console.error("Backtrace: ",u),s.call(a.free,c),s.call(a.mixrt_reqRunning);continue}case 11:console.error("Mix timeout"),s.call(a.mixrt_reqRunning);continue}throw new Error("Unexpected state")}}async runMixcoreFFI(e){let t=this.state.wasm,r=t.instance.exports,s=t.call(r.mixrt_getCoroutine),a=t.call(r.mixrt_getResult),i=f(t,a);try{let a=await this.state.mixcore.dispatchFFI(s,e,i);p(t,Array.from(a)),t.call(r.mixrt_reqReturn,s)}catch(e){this.ffiabort(s,e)}}setParamsToCurrentLocation(e){let t=this.state.wasm,r=t.instance.exports,s=t.call(r.mixrt_locUnitID),a=_(t,s,255),i=t.call(r.mixrt_locUnitPC),n=t.call(r.mixrt_locSecInstr);e.setLocationTriple(a,i,n)}async publishOutput(e){let t=this.state.wasm,r=t.instance.exports;try{let s=t.call(r.mixrt_getResult),a=t.call(r.mixrt_arrayGet,s,0,1);if(0==a)throw new Error("bad result");let i=t.call(r.mixrt_getString,a);if(0==i)throw new Error("bad result");let n=_(t,i,255),o=t.call(r.mixrt_arrayGet,s,1,1);if(0==o)throw new Error("bad result");let l=t.call(r.mixrt_getString,o);if(0==l)throw new Error("bad result");let c=_(t,l,255),u=t.call(r.mixrt_arrayGet,s,2,1),h=t.call(r.mixrt_stringFormatEscJSONYG,u),d='{"_rmx_type":"{tag}undefined"}';if(t.call(r.mixrt_isUndefined,h)||(d=$(t,h,R())),"string"!=typeof d)throw console.debug("bad:",d),new Error("expected string but got "+typeof d);let m='[{"name":'+JSON.stringify(n)+',"version":'+JSON.stringify(c)+',"value":'+d+"}]";await this.publishCellMessages(e,m)}catch(e){console.error("output error",e)}}async publishOutputError(e){let t=this.state.wasm,r=t.instance.exports;try{let s=t.call(r.mixrt_getResult),a=t.call(r.mixrt_arrayGet,s,0,1),i={errors:$(t,a,R())};await this.publishMessage(e,i)}catch(e){console.error("output error",e)}}async publishInitResult(e){let t=this.state.wasm,r=t.instance.exports;try{let s=t.call(r.mixrt_getResult),a={cellMessages:[{name:"$initResult",version:"",value:$(t,s,R())}]};await this.publishMessage(e,a)}catch(e){console.error("output error",e)}}async publishEcho(e,t){let r=this.state.wasm,s=r.instance.exports,a=r.call(s.mixrt_initEnvGetSession),i=(0==a||_(r,a,255),{_rmx_echo:t});await this.publishMessage(e,i)}async publishMessage(e,t){let r=this.state.wasm,s=r.instance.exports,a=r.call(s.mixrt_initEnvGetSession),i={_rmx_type:"msg_response",_rmx_version:"0.0",session:0==a?"":_(r,a,255),machine:this.state.config.vmID,org:this.state.config.org,workspace:this.state.config.workspace,cellMessages:[],logMessages:[]};for(let e in t)i[e]=t[e];this.state.config.debugMask&h.DEBUG_OUTPUT&&console.debug("Output",JSON.stringify(i)),await e.output(i)}async publishCellMessages(e,t){let r=this.state.wasm,s=r.instance.exports,a=r.call(s.mixrt_initEnvGetSession),i=0==a?"":_(r,a,255),n='{"_rmx_type":"msg_response","_rmx_version":"0.0","session":'+JSON.stringify(i)+',"machine":'+JSON.stringify(this.state.config.vmID)+',"org":'+JSON.stringify(this.state.config.org)+',"workspace":'+JSON.stringify(this.state.config.workspace)+',"logMessages":[],"cellMessages":'+t+"}";this.state.config.debugMask&h.DEBUG_OUTPUT&&console.debug("Output",n);let o=new globalThis.UnparsedJSONMessage("msg_response","vm",n);await e.output(o)}ffireturn(e,t,r){const s=this.state.localFFIs[e]||{};delete this.state.localFFIs[e];let a=this.state.wasm,i=a.instance.exports;var n;a.call(i.mixrt_reqReturn,e),s.isRaw?n=t:P(n=new Array,t,s.useJsonDecoder?L():r),p(a,n)}ffiabort(e,t){delete this.state.localFFIs[e];let r=this.state.wasm,s=r.instance.exports;console.error("FFI error: ",t),t.stack&&console.error("FFI backtrace: ",t.stack);let a=b(r,t.message);r.call(s.mixrt_reqRunning),r.call(s.mixrt_setErrorMessage,3,a),r.call(s.free,a),r.call(s.mixrt_reqPanicCoroutine,e,0),r.call(s.mixrt_abortCoroutinePrimaryYG,e)}async runLocalFFI(e,t,r,s){let a=this.state.wasm,i=a.instance.exports,n=a.call(i.mixrt_getCoroutine),o=a.call(i.mixrt_getResult);this.state.localFFIs[n]={name:r,...s};var l=s.isRaw?f(a,o):$(a,o,{encode_undefined:()=>{},encode_bool:e=>e,encode_null:()=>null,encode_number:e=>e,encode_string:e=>e,encode_taggedString:e=>e,encode_binary:e=>e,encode_opaque:e=>new Map([["_rmx_type","opaque"],["data",e]]),encode_mapCreate:()=>({}),encode_mapSet:(e,t,r)=>e[t]=r,encode_arrayCreate:()=>[],encode_arrayPush:(e,t)=>e.push(t),encode_case0:e=>new Map([["_rmx_type","case"],["name",e],["arg",void 0]]),encode_case1:(e,t)=>new Map([["_rmx_type","case"],["name",e],["arg",t]]),encode_token:(e,t,r)=>new Map([["_rmx_type","token"],["data",e],["enabled",t],["extras",r]])});await e.fficall_local(r,n,l)}async overriddenFFI(e,t,r,s,a){let i=this.state.wasm,n=i.instance.exports,o=this.state.sboard,l=this,c=i.call(n.mixrt_getCoroutine),u={wasm:i,mixrt:n,state:this.state,coroutine:c,publishMessage:async t=>{await l.publishMessage(e,t)}},h=i.call(n.mixrt_getResult),d=$(i,h,q());try{let e=s(u,d);e instanceof Promise?(e.then((e=>{o.FFIReturn(c,(async function(s){l.ffireturn(c,e,N()),await l.run(s,t,r)}))}),(e=>{o.FFIReturn(c,(async function(s){l.ffiabort(c,e),await l.run(s,t,r)}))})),i.call(n.mixrt_reqRunning)):l.ffireturn(c,e,N())}catch(e){l.ffiabort(c,e)}}}class ot extends nt{constructor(e,t){if("driver"!=e)throw new Error("DrvCreate: only permitted in queue 'driver'");super(257,e,t)}async exec(e,t){if(0!==this.params.instID)throw new Error("DrvCreate: only one instance supported");let r=new tt(this.state);this.state.wasm=r,await r.compile(),await r.instantiate(),r.call(this.state.wasm.instance.exports.mixrt_setDebugFlags,this.state.config.debugMask),console.log("mix machine: Initial debug mask: ",this.state.config.debugMask),console.debug("Debug levels (call MixSetMask to change):"),console.debug("DEBUG_MEMORY 1"),console.debug("DEBUG_SCHEDULER 2"),console.debug("DEBUG_STATE 4"),console.debug("DEBUG_STACK 8"),console.debug("DEBUG_LOOP 16"),console.debug("DEBUG_MEMORY_OG 32"),console.debug("DEBUG_GC 64"),console.debug("DEBUG_MESSAGES 256"),console.debug("DEBUG_QUEUES 512"),console.debug("DEBUG_OUTPUT 1024");let s=r.instance.exports;r.call(s.mixrt_mem_init),null!=this.params.timeout&&(s.mixrt_setTimeoutForInteraction?r.call(s.mixrt_setTimeoutForInteraction,this.params.timeout):r.call(s.mixrt_setTimeoutForCycle,this.params.timeout)),this.state.created=!0}}class lt extends nt{constructor(e,t){if("driver"!=e)throw new Error("DrvSendCode: only permitted in queue 'driver'");super(513,e,t)}async exec(e,t){let r,s,a=this.state.wasm,i=a.instance.exports;if(void 0===this.params.codeID)throw new Error("DrvSendCode: missing codeID param");if(void 0===this.params.reference)throw new Error("DrvSendCode: missing reference param");if(this.params.reference.startsWith("file:")){let e=this.params.reference.slice(5);r=fs.readFileSync(e),fs.existsSync(e+".dbg")&&(s=fs.readFileSync(e+".dbg"))}else if(this.params.reference.startsWith("data:"))if(globalThis.parseDataURL)r=globalThis.parseDataURL(this.params.reference).body;else{let e=await fetch(this.params.reference);if(!e.ok)throw console.error("Invalid data URL"),new Error("Bad data URL");r=await e.arrayBuffer()}else if(this.params.reference.startsWith("topic:/")){let e=new URL(this.params.reference);r=(await globalThis.hub.get(e.pathname)).payload,this.params.reference.endsWith(".autodel")&&await globalThis.hub.set(e.pathname,globalThis.hub.newBinaryMessage("binary","driver",new Uint8Array(0)));let t=await globalThis.hub.get(e.pathname+".dbg");void 0!==t&&(s=t.payload,await globalThis.hub.set(e.pathname+".dbg",globalThis.hub.newBinaryMessage("binary","driver",new Uint8Array(0))))}else{let e=this.state.config.baseURL;e?e.endsWith("/")||(e+="/"):e=void 0;let t,a=new Headers,i=this.params.reference;if(i.includes("%,")){let e=i.indexOf("%,");t=i.substring(e+2),i=i.substring(0,e)}""!=this.state.config.token&&(i+=i.includes("?")?"&":"?",i+="token="+this.state.config.token,void 0!==t&&(t+=t.includes("?")?"&":"?",t+="token="+this.state.config.token));let n=new URL(i,e),o={headers:a,mode:"cors"},l=await fetch(n.toString(),o);if(!l.ok){let e=await l.text();throw console.error("Cannot load URL:",n.toString(),"status:",l.status,"Bad body:",e),new Error("Bad HTTP status: "+l.status)}if(r=await l.arrayBuffer(),void 0!==t&&(n=new URL(t,e),l=await fetch(n.toString(),o),404!=l.status)){if(!l.ok){let e=await l.text();throw console.error("Cannot load URL:",n.toString(),"status:",l.status,"Bad body:",e),new Error("Bad HTTP status: "+l.status)}s=await l.arrayBuffer()}}let n,o=new Uint8Array(r),l=!1;void 0!==s&&(n=new Uint8Array(s));let c=function(e){for(let t=0;t<4;t++)if(e[t]!="\0asm".codePointAt(t))return!1;return!0}(o);if(c){let e=new WebAssembly.Module(o);void 0===s&&(n=WebAssembly.Module.customSections(e,"mix_debug")[0]),this.state.mixCode.set(this.params.codeID,e),this.state.mixCodeName.set(this.params.codeID,this.params.name),await this.state.wasm.mixAddCode(this.params.codeID,e)}else{if(!function(e){try{return"qcode-5"==new j(new Uint32Array(e.buffer)).atArrayPath([0,0]).decode()}catch(e){return!1}}(o))throw new Error("Expected Wasm or QCode-5");{let e=new j(new Uint32Array(o.buffer));if(void 0===s){let t=at(st(e));null!=t&&(n=t.toBytes(),l=!0)}if(function(e){return 2!=e.atArrayElt(1).tag()}(e)){if(void 0===this.params.name)throw new Error("DrvSendCode: missing name param");let e=o.length,t=a.call(i.malloc,e);if(0==t)throw new Error("out of memory");a.mem8.subarray(t,t+e).set(o);let r=b(a,this.params.name),s=this.state.config.quickLoad;if(0==a.call(i.mixrt_interpreterAddCode2,t,t+e,r,r,s)){let e=_(a,a.call(i.mixrt_getErrorMessage),65535);throw new Error(e+" - when loading "+this.params.name)}this.state.mixCode.set(this.params.codeID,"BYTE"),this.state.mixCodeName.set(this.params.codeID,this.params.name)}}}if(void 0!==n){if(!l){let e=at(st(new j(new Uint32Array(n.buffer))));null!=e&&(n=e.toBytes())}await this.state.mixcore.publishDebugObject(this.params.name,n)}for(let e of this.params.apps){if(void 0===this.params.name)throw new Error("DrvSendCode: missing name param");if("$executable-0@x"==this.params.name)continue;let t=b(a,this.params.name),r=b(a,e);if(0==a.call(i.mixrt_libApp,t,r)){let t=_(a,a.call(i.mixrt_getErrorMessage),65535);throw new Error(t+" - when associating library "+this.params.name+" with app "+e)}a.call(i.free,t),a.call(i.free,r)}}}class ct extends nt{constructor(e,t){if("driver"!=e)throw new Error("DrvLinkCode: only permitted in queue 'driver'");super(515,e,t)}async exec(e,t){let r=this.state.wasm,s=r.instance.exports;if(0!==this.params.instID)throw new Error("DrvLinkCode: only one instance supported");if(void 0===this.params.codeID)throw new Error("DrvLinkCode: missing codeID param");let a=this.state.mixCode.get(this.params.codeID);if(void 0===a)throw new Error("DrvLinkCode: unknown code reference");let i=this.state.mixCodeName.get(this.params.codeID),n=b(r,i),o=0;if("BYTE"==a){if(null!=s.mixrt_interpreterLinkUnitYG){if(!r.call(s.mixrt_interpreterLinkUnitYG,n)){let e=_(r,r.call(s.mixrt_getErrorMessage),65535);throw new Error(e+" - when linking "+i)}o=1}else if(!r.call(s.mixrt_interpreterLinkCodeYG)){let e=_(r,r.call(s.mixrt_getErrorMessage),65535);throw new Error(e)}}else await r.mixLinkCode(this.params.codeID),o=1;if(null!=this.params.override&&null!=this.params.override.ondemand){let e=new Array;P(e,this.params.override.ondemand,L());let t=p(r,e),a=r.call(s.mixrt_copyIOtoYG,t,t,t+e.length);if(0==a)throw new Error("cannot create value");if(0==r.call(s.mixrt_setOnDemandOverrideFromValue,a)){let e=_(r,r.call(s.mixrt_getErrorMessage),65535);throw new Error(e+" - when injecting override")}}if(this.params.initFlag){let e=s.mixrt_setInitLibraryRecursively;if(!o||null==e)throw new Error("This version of mixrt doesn't support dynamic loading");if(!r.call(e,n)){let e=_(r,r.call(s.mixrt_getErrorMessage),65535);throw new Error(e)}}w(r,n)}}class ut extends nt{constructor(e,t){if("driver"!=e)throw new Error("DrvToInit: only permitted in queue 'driver'");super(769,e,t),this.wantResult=!1}async exec(e,t,r){let s=this.state.wasm,a=s.instance.exports,i=s.call(a.mixrt_getState);if(0!==i&&2!==i&&4!==i&&5!==i)throw new Error("state mismatch after ToInit: "+i);if(s.call(a.mixrt_reqInit),function(e,t){let r=v.findIndex((e=>e==t)),s=e.instance.exports;e.call(s.mixrt_setReqQueue,r)}(s,this.queue),this.state.wantInitResult=this.wantResult,void 0!==this.params.serial&&(t[0]=this.params.serial),void 0!==this.params.args){let e=this.params.args,t=p(s,e),i=s.call(a.mixrt_copyIOtoYG,t,t,t+e.length);if(0==i)throw new Error("cannot create value");s.call(a.mixrt_initEnvExtract,i),s.call(a.mixrt_ffiArgChecksInstall),this.state.standalone=s.call(a.mixrt_initEnvStandalone),this.state.standalone&&((n=r).set("$flush",Se),n.set("$loadHook",Me),n.set("$destroyHook",Fe),n.set("$freeResources",De),n.set("$decodeError",Ue),n.set("get_backtrace",Ce),n.set("$websocket_create",$e),n.set("$websocket_write",Ge),n.set("$websocket_read",Le),n.set("$websocket_close",Ne),n.set("$websocket_error",Be),n.set("$mqtt_available",He),n.set("$mqtt_brokerAvailable",je),n.set("$mqtt_publish",We),n.set("$mqtt_subscribe",Ye),n.set("$mqtt_subNext",Je),n.set("$mqtt_get",Ve),n.set("$mqtt_unsubscribe",ze),n.set("$mqtt_isLegalSubTopic",Qe),n.set("$mqtt_haveExternalSubscribers",Ke),n.set("$mqtt_mountOrg",Ze),s.call(a.mixrt_ffiArgChecksInstallStandalone),this.state.config.interceptDynloadFFI||(s.call(a.mixrt_enableResolveLibrary),s.call(a.mixrt_enableLoadLibrary)))}var n;await this.run(e,t,r)}}class ht extends nt{constructor(e,t){if("driver"!=e&&"async"!=e)throw new Error("DrvToEnter: only permitted in queues 'driver' and 'async'");super(770,e,t)}async exec(e,t,r){if(void 0===this.params.tag)throw new Error("DrvToEnter: missing param: tag");if(void 0===this.params.modname)throw new Error("DrvToEnter: missing param: modname");if(void 0===this.params.entryID)throw new Error("DrvToEnter: missing param: entryID");if(void 0===this.params.args)throw new Error("DrvToEnter: missing args");let s=this.state.wasm,a=s.instance.exports;if(this.params.token){if(!this.params.privileged)throw new Error("attempt to use setToken with an unprivileged request");await async function(e,t,r){let s;try{s=function(e){var t=e.split(".")[1].replace(/-/g,"+").replace(/_/g,"/");let r=atob(t).split("").map((e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)));var s=decodeURIComponent(r.join(""));return JSON.parse(s)}(r)}catch(e){console.log("unable to parse token as JWT",e),s={}}let a={token:I(r),userPseudonym:s.sub?await ft(s.sub):"",user:s.email??"",userID:s.sub??"",userIsVerified:s.email_verified??!1,userIsAnonymous:s.anon??!1};for(let[r,s]of Object.entries(a))dt(e,t,r,s)}(s,a,this.params.token)}let i=b(s,this.params.tag),n=b(s,this.params.modname),o=s.call(a.mixrt_findEntry,i,n);if(w(s,i),w(s,n),0==o)throw new Error("DrvToEnter: cannot find entry, tag="+this.params.tag+" modname="+this.params.modname);var l;s.call(a.mixrt_reqEntry,o,this.params.entryID,(l=this.queue,v.findIndex((e=>e==l))),this.params.withResult?1:0),p(s,this.params.args),void 0!==this.params.serial&&(t[0]=this.params.serial),await this.run(e,t,r)}}function dt(e,t,r,s){let a=new Array;P(a,[r,s],L());let i=p(e,a),n=e.call(t.mixrt_copyIOtoYG,i,i,i+a.length),o=e.call(t.mixrt_arrayGet,n,0,!1),l=e.call(t.mixrt_arrayGet,n,1,!1);if(!e.call(t.mixrt_envUpdateYG,o,l)){let r=e.call(t.mixrt_getError),s=e.call(t.mixrt_getErrorMessage),a=null;throw s&&(a=_(e,s,20480)),new Error(`could not update env: ${a} (${r})`)}}function mt(e){const t=Array.from(e,(e=>String.fromCodePoint(e)));return btoa(t.join(""))}let gt=function(){const e=new Uint8Array(24);return globalThis.crypto.getRandomValues(e),mt(e)}();async function ft(e){let t=e+gt,r=(new TextEncoder).encode(t),s=await crypto.subtle.digest("SHA-256",r);return mt(new Uint8Array(s))}class pt extends nt{constructor(e,t){if("FFI"!=e)throw new Error("DrvReturn: only permitted in queue 'FFI'");super(771,e,t)}serializable(){return!0}async exec(e,t,r){let s=this.state.wasm,a=s.instance.exports;if(void 0===this.params.coroutine)throw new Error("DrvReturn: missing param: coroutine");if(void 0===this.params.result)throw new Error("DrvReturn: missing param: result");s.call(a.mixrt_reqReturn,this.params.coroutine),p(s,this.params.result),await this.run(e,t,r)}}class bt extends nt{constructor(e,t){if("FFI"!=e)throw new Error("DrvAbort: only permitted in queue 'FFI'");super(773,e,t)}serializable(){return!0}async exec(e,t,r){let s=this.state.wasm,a=s.instance.exports;if(void 0===this.params.coroutine)throw new Error("DrvAbort: missing param: coroutine");if(!s.call(a.mixrt_co_exists,this.params.coroutine))throw new Error("DrvAbort: no such coroutine: "+this.params.coroutine);let i=this.params.message;void 0===i&&(i="<no message provided>");let n=b(s,i);s.call(a.mixrt_reqRunning),void 0!==this.params.errorProxy?s.call(a.mixrt_setErrorMessageAndProxy,this.params.errorProxy,n):s.call(a.mixrt_setErrorMessage,3,n),s.call(a.free,n),s.call(a.mixrt_reqPanicCoroutine,this.params.coroutine,0),s.call(a.mixrt_abortCoroutinePrimaryYG,this.params.coroutine),await this.run(e,t,r)}}class wt extends nt{constructor(e,t){if("FFI"!=e)throw new Error("DrvLater: only permitted in queue 'FFI'");super(777,e,t)}serializable(){return!0}async exec(e,t,r){let s=this.state.wasm,a=s.instance.exports;s.call(a.mixrt_reqRunning),await this.run(e,t,r)}}class _t extends nt{constructor(e,t){super(777,e,t)}async exec(e,t,r){let s=this.state.wasm,a=s.instance.exports;s.call(a.mixrt_reqRunning),await this.run(e,t,r)}}class yt extends nt{constructor(e,t){super(1030,e,t)}serializable(){return!0}}const xt=["$destroyHook","$hideHook","$isSyncEnabled","$loadHook","$flush","$showHook","$log","get_env","$outputError","$outputWithVersion","$co_sleep","$decodeError"];function vt(e,t){return"CORE"==t?xt.includes(e):"*"===t.slice(-1)?e.startsWith(t.slice(0,-1)):e===t}class Et{static async create(e){e=e??{};let t=new Et;switch(t.mixcore=null,t.ffiNames=[],t.publishDebugObjects=e.publishDebugObjects,e.kind){case"webkit":t.mixcore=new Tt;break;case"tauri":{let{dbDir:r,dbName:s,dbUser:a}=e;t.mixcore=await kt.create(r,s,a);break}case"service-worker":{let{mixcoreId:r,baseURL:s}=e;t.mixcore=new At(r,s??"");break}}if(t.mixcore){let{enableFFIs:i,disableFFIs:n}=e,o=await t.mixcore.ffiNames();t.ffiNames=(r=o,a=n,void 0!==(s=i)&&(r=r.filter((e=>s.some((t=>vt(e,t)))))),void 0!==a&&(r=r.filter((e=>!a.some((t=>vt(e,t)))))),r)}var r,s,a;return console.log("Mixcore (worker)",t.mixcore,t.ffiNames),t}handlesFFI(e){return this.ffiNames.includes(e)}dispatchFFI(e,t,r){return this.mixcore.ffiDispatch(e,t,r)}async publishDebugObject(e,t){if(this.publishDebugObjects){let r=globalThis.hub,s=globalThis.state.config.vmID,a={id:e,code:t},i=r.newLocalMessage("msg_register_debug_object","vm",a);await r.publish(`/debug-objects/${s}`,i,!1)}}}class Tt{async handler(e,t){return await window.webkit.messageHandlers[e].postMessage(t)}async ffiNames(){return await this.handler("mixcore_ffi_names",{})}async ffiDispatch(e,t,r){return await this.handler("mixcore_ffi_dispatch",{co:e,name:t,argsBuf:r})}}class kt{static async create(e,t,r){let s={user:r};return await window.__TAURI__.invoke("mixcore_setup",{env:s,dbDir:e,dbName:t,username:r}),new kt}async ffiNames(){return await window.__TAURI__.invoke("mixcore_ffi_names")}async ffiDispatch(e,t,r){console.log("MixcoreTauri.ffiDispatch",t,r);try{let s=Array.from(new Uint8Array(r.buffer)),a=await window.__TAURI__.invoke("mixcore_ffi_dispatch",{co:e,name:t,argsBuf:s});if(a.Sync){if(a.Sync.Ok)return new Uint8Array(a.Sync.Ok);if(a.Sync.Err)throw new Error(`FFI execution error: ${a.Sync.Err}`)}throw new Error(`unexpected FFI dispatch result ${a}`)}catch(e){throw e}}}class At{constructor(e,t){this.mixcoreId=e,this.baseURL=t}async ffiNames(){let e=new URL(`${this.baseURL}/mixcore/ffi-names`,globalThis.location.origin),t=await fetch(e);return await t.json()}async ffiDispatch(e,t,r){let s=new URL(`${this.baseURL}/mixcore/ffi-dispatch`,globalThis.location.origin);s.searchParams.set("mixcore",this.mixcoreId),s.searchParams.set("co",e),s.searchParams.set("name",t);let a={method:"POST",body:r},i=await fetch(s,a);if(!i.ok)throw new Error(await i.text());return new Uint8Array(await i.arrayBuffer())}}async function It(){let e=globalThis.state.config,t=globalThis.hub,r=await t.subscribe(e.topicBase()+"/FFIReturn");await async function(e,t){(async function(e,t){for(;;){let t=await e.next();await Ft(t)}})(e).catch((e=>console.log("Error",e)))}(r);let s=await t.subscribe(e.topicBase()+"/initiate");if(await async function(e){(async function(e){for(;;){let t=await e.next();await Mt(t)}})(e).catch((e=>console.log("Error",e)))}(s),e.localFFIs){let e=globalThis.state.config.vmID;await t.setLocalPubTopic("/local/"+e),await t.setLocalSubTopic("/local/"+e);let r=await t.subscribe("/local/"+e+"/ffi/return");await async function(e){(async function(e){for(;;){let t=await e.next();await Dt(t)}})(e).catch((e=>console.log("Error",e)))}(r)}let a=globalThis.state.config.vmID;await t.setLocalPubTopic(`/debug-objects/${a}`),state.sboard.mainLoop(),t.setLocalPubTopic("/local/test"),t.setLocalSubTopic("/local/test"),await async function(){let e=globalThis.state.config,t=globalThis.hub,r=e.topicBase()+"/announce",s={_rmx_type:"msg_vm_register",id:e.vmID,variant:e.machType,version:0},a=new globalThis.JSONMessage("msg_vm_register","vm",s);await t.publish(r,a,!0)}()}function St(e,t){let r=t._rmx_echo;if(void 0!==t&&"string"==typeof r){globalThis.state.drvEcho.push(r);let s=t.timeout;"number"==typeof s&&s>0&&setTimeout((()=>{globalThis.state.drvEcho=globalThis.state.drvEcho.filter((e=>e!=r));let s={_rmx_type:"msg_response",_rmx_version:"0.0",_rmx_echo:r,session:t.session,machine:globalThis.state.config.vmID,org:globalThis.state.config.org,workspace:globalThis.state.config.workspace,cellMessages:[],logMessages:[],errors:{code:"",message:"execution timed out"}};e.output(s)}),1e3*s)}}async function Mt(e){let t=e.payload?._rmx_type;if(t&&e.rmxType!==t)throw new Error(`message envelope type (${e.rmxType}) differs from payload type (${t})`);try{switch(e.rmxType){case"msg_vm_configure":await async function(e){let t=e.payload;if(globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Received message:",t),"object"!=typeof t)throw new Error("bad msg_vm_configure message");t.reset&&(globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Resetting machine on request"),globalThis.state.sboard.reset(),globalThis.state.reset());let r=t.code||[];if(!Array.isArray(r))throw new Error("bad msg_vm_configure message: 'code' not an array");let s=t.config,a=t.load,i=t.override,n=[],o=t._rmx_echo;if(void 0!==t&&"string"==typeof o&&globalThis.state.drvEcho.push(o),!globalThis.state.created){let e=new ot("driver",globalThis.state);e.params.setInstID(0),n.push(e)}for(let e of r){let t=new lt("driver",globalThis.state),r=t.params,s=e.codeID;if("number"!=typeof s)throw new Error("bad msg_vm_configure message: 'code[].codeID' not a number");let a=e.reference;if("string"!=typeof a)throw new Error("bad msg_vm_configure message: 'code[].reference' not a string");let i=e.name||"";if("string"!=typeof i)throw new Error("bad msg_vm_configure message: 'code[].name' not a string");let o=e.apps||[];if(!Array.isArray(o))throw new Error("bad msg_vm_configure message: 'code[].apps' not an array");r.setInstID(0),r.setCodeID(s),r.setReference(a),r.setName(i),r.setApps(o),n.push(t)}let l=!0;for(let e of r){let t=new ct("driver",globalThis.state),r=t.params,s=e.codeID,a=e.initFlag||!1;r.setInstID(0),r.setCodeID(s),r.setInitFlag(a),l&&null!=i&&r.setOverride(i),n.push(t),l=!1}if(void 0!==s){s.standalone&&(s.isMQTTEnabled=!0),void 0!==s.env&&void 0!==s.env.token&&(s.env.token=I(s.env.token));let e=new ut("driver",globalThis.state),r=e.params;r.setInstID(0);let a=new Array;P(a,s,L()),r.setArgs(a),e.wantResult=!!t.wantResult,n.push(e)}else{let e=new ut("driver",globalThis.state);e.params.setInstID(0),e.wantResult=!!t.wantResult,n.push(e)}for(let e of n)globalThis.state.sboard.enqueue("driver",(async function(t){try{globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Driver request from msg_vm_configure",e),await e.exec(t,globalThis.state.drvSerial,globalThis.state.ffiOverride)}catch(e){console.error("Exception",e)}}));if(void 0!==a){if("object"!=typeof a)throw new Error("bad msg_vm_configure message: 'load' not an object");let e=a.screen;if("string"!=typeof e)throw new Error("bad msg_vm_configure message: 'load.screen' not a string");let r=a.params;if(!Array.isArray(r))throw new Error("bad msg_vm_configure message: 'load.params' not an array");let s=new ht("driver",globalThis.state),i=s.params;i.setTag("load"),i.setModname(""),i.setEntryID(0);let n=new Array;a.paramsEscEnabled?L():N(),P(n,[e,r],N()),i.setArgs(n),globalThis.state.sboard.enqueue("driver",(async function(e){globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Driver request from msg_vm_configure",s),St(e,t),await s.exec(e,globalThis.state.drvSerial,globalThis.state.ffiOverride)}))}globalThis.state.sboard.driverRequest((async function(e){}))}(e);break;case"msg_session_poll":{let t=e.payload;globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Received message:",t);let r=new _t("async",globalThis.state);globalThis.state.sboard.asyncRequest((async function(e){globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Driver request",r),St(e,t),await r.exec(e,globalThis.state.drvSerial,globalThis.state.ffiOverride)}));break}case"msg_view_invoke":case"msg_view_invokePrivilegedAction":{let t=e.payload;if(globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Received message:",t),"object"!=typeof t)throw new Error("bad msg_view_invoke message");let r=t.name;if("string"!=typeof r)throw new Error("bad msg_view_invoke message: name");let s=t.env,a=t.arg;void 0===a&&(a=null);let i=t.nextActions;if(void 0===i&&(i=[]),!Array.isArray(i))throw new Error("bad msg_view_invoke message: nextActions");let n=t.options;if(void 0===n&&(n={}),"object"!=typeof n)throw new Error("bad msg_view_invoke message: options");let o=new ht("async",globalThis.state),l=o.params;l.setTag("invoke3"),l.setModname(""),l.setEntryID(0),l.setToken(t.setToken),"msg_view_invokePrivilegedAction"===e.rmxType&&l.setPrivileged(!0);let c=[new B(r),new B(s),t.argEscEnabled?a:new B(a),i,new B(n)],u=L(),d=new Array;P(d,c,u),l.setArgs(d),globalThis.state.sboard.asyncRequest((async function(e){St(e,t),globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Async request",o),await o.exec(e,globalThis.state.drvSerial,globalThis.state.ffiOverride)}));break}case"msg_view_input":{let t=e.payload;if(globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Received message:",t),"object"!=typeof t)throw new Error("bad msg_view_input message");let r=t.name;if("string"!=typeof r)throw new Error("bad msg_view_input message: name");let s=t.value,a=new ht("async",globalThis.state),i=a.params;i.setTag("input"),i.setModname(""),i.setEntryID(0);let n=new Array,o=t.valueEscEnabled?L():N();P(n,[new B(r),s],o),i.setArgs(n),globalThis.state.sboard.asyncRequest((async function(e){St(e,t),globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Async request",a),await a.exec(e,globalThis.state.drvSerial,globalThis.state.ffiOverride)}));break}case"msg_view_load":{let t=e.payload;if(globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Received message:",t),"object"!=typeof t)throw new Error("bad msg_view_load message");let r=t.module;if("string"!=typeof r)throw new Error("bad msg_view_load message: module");let s=t.args;if(void 0===s&&(s=[]),!Array.isArray(s))throw new Error("bad msg_view_load message: args");let a=new ht("async",globalThis.state),i=a.params;i.setTag("load"),i.setModname(""),i.setEntryID(0);let n=new Array,o=t.argsEscEnabled?L():N();P(n,[new B(r),s],o),i.setArgs(n),globalThis.state.sboard.asyncRequest((async function(e){St(e,t),globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Async request",a),await a.exec(e,globalThis.state.drvSerial,globalThis.state.ffiOverride)}));break}case"msg_view_push":{let t=e.payload;if(globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Received message:",t),"object"!=typeof t)throw new Error("bad msg_view_push message");let r=t.module;if("string"!=typeof r)throw new Error("bad msg_view_push message: module");let s=t.args;if(void 0===s&&(s=[]),!Array.isArray(s))throw new Error("bad msg_view_push message: args");let a=new ht("async",globalThis.state),i=a.params;i.setTag("push"),i.setModname(""),i.setEntryID(0);let n=new Array,o=t.argsEscEnabled?L():N();P(n,[new B(r),s],o),i.setArgs(n),globalThis.state.sboard.asyncRequest((async function(e){St(e,t),globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Async request",a),await a.exec(e,globalThis.state.drvSerial,globalThis.state.ffiOverride)}));break}case"msg_view_pop":{let t=e.payload;if(globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Received message:",t),"object"!=typeof t)throw new Error("bad msg_view_pop message");let r=new ht("async",globalThis.state),s=r.params;s.setTag("pop"),s.setModname(""),s.setEntryID(0);let a=new Array;P(a,[],N()),s.setArgs(a),globalThis.state.sboard.asyncRequest((async function(e){St(e,t),globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Async request",r),await r.exec(e,globalThis.state.drvSerial,globalThis.state.ffiOverride)}));break}case"msg_view_reset":{let t=e.payload;if(globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Received message:",t),"object"!=typeof t)throw new Error("bad msg_view_reset message");let r=new ht("async",globalThis.state),s=r.params;s.setTag("reset"),s.setModname(""),s.setEntryID(0);let a=new Array;P(a,[],N()),s.setArgs(a),globalThis.state.sboard.asyncRequest((async function(e){St(e,t),globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Async request",r),await r.exec(e,globalThis.state.drvSerial,globalThis.state.ffiOverride)}));break}case"msg_view_refresh":{let t=e.payload;if(globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Received message:",t),"object"!=typeof t)throw new Error("bad msg_view_refresh message");let r=new ht("async",globalThis.state),s=r.params;s.setTag("refresh"),s.setModname(""),s.setEntryID(0);let a=new Array;P(a,[],N()),s.setArgs(a),globalThis.state.sboard.asyncRequest((async function(e){St(e,t),globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Async request",r),await r.exec(e,globalThis.state.drvSerial,globalThis.state.ffiOverride)}));break}case"msg_introspect_spreadsheet":{let t=e.payload;if(globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Received message:",t),"object"!=typeof t)throw new Error("bad msg_introspect_spreadsheet message");let r=t.filter,s=new ht("async",globalThis.state),a=s.params;a.setTag("spreadsheet_out"),a.setModname(""),a.setEntryID(0);let i=new Array;P(i,[r],N()),a.setArgs(i),globalThis.state.sboard.asyncRequest((async function(e){St(e,t),globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Async request",s),await s.exec(e,globalThis.state.drvSerial,globalThis.state.ffiOverride)}));break}case"msg_introspect_debug":{let t=e.payload;if(globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Received message:",t),"object"!=typeof t)throw new Error("bad msg_introspect_debug message");let r=t.command,s=new ht("async",globalThis.state),a=s.params;a.setTag("debugCommand_out"),a.setModname(""),a.setEntryID(0);let i=new Array;P(i,[r],N()),a.setArgs(i),globalThis.state.sboard.asyncRequest((async function(e){St(e,t),globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("Async request",s),await s.exec(e,globalThis.state.drvSerial,globalThis.state.ffiOverride)}));break}}}catch(e){console.error(e)}}async function Ft(e,t){if("msg_mixFFI"==e.rmxType){if("binary"!=e.header._rmx_encoding)throw new Error("bad _rmx_encoding of msg_mixFFI message");let t=function(e,t,r,s){if("msg_mixDriver"!==e.rmxType&&"msg_mixFFI"!==e.rmxType)throw new Error("Driver: got message with bad _rmx_type");let a,i=new it,n=i.decode(e.payload);switch(n){case 771:a=new pt(t,r);break;case 773:a=new bt(t,r);break;case 777:a=new wt(t,r);break;case 1030:a=new yt(t,r);break;default:throw new Error("Driver: unknown/unsupported message type: "+n)}return a.params=i,a}(e,"FFI",globalThis.state),r=t.params.getCoroutine();globalThis.state.sboard.FFIReturn(r,(async function(e){globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("FFI return",t),await t.exec(e,globalThis.state.drvSerial,globalThis.state.ffiOverride)}))}}async function Dt(e){let t=globalThis.state.config.vmID,r=e.payload.call_id;switch(e.rmxType){case"msg_ffi_return":globalThis.state.sboard.FFIReturn(r,(async function(t){let s=new nt("local","FFI",globalThis.state);s.ffireturn(r,e.payload.value,{decode_type:e=>{switch(typeof e){case"undefined":return"undefined";case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":return Array.isArray(e)?"array":null===e?"null":e instanceof Map?e.get("_rmx_type"):e instanceof Uint8Array?"binary":"map";default:throw new Error("Cannot import this type of value: "+typeof e)}},decode_value:(e,t)=>{switch(e){case"case":return{name:t.get("name"),arg:t.get("arg")};case"token":return{data:t.get("data"),enabled:t.get("enabled"),extras:t.get("extras")};case"opaque":return{data:t.get("data")};default:return t}}}),await s.run(t,globalThis.state.drvSerial,globalThis.state.ffiOverride)}));break;case"msg_ffi_error":globalThis.state.sboard.FFIReturn(r,(async function(t){let s=new nt("local","FFI",globalThis.state),a={message:e.payload.message,stack:e.payload.stack};s.ffiabort(r,a),await s.run(t,globalThis.state.drvSerial,globalThis.state.ffiOverride)}));break;case"msg_ffi_later":globalThis.state.sboard.FFIReturn(r,(async function(e){let t=globalThis.state.wasm,r=t.instance.exports;t.call(r.mixrt_reqRunning);let s=new nt("local","FFI",globalThis.state);await s.run(e,globalThis.state.drvSerial,globalThis.state.ffiOverride)}));break;default:console.log("unexpected rmxType on /local/"+t+"/ffi/return: "+e.rmxType)}}async function Ut(e){if(!e instanceof yt)throw new Error("trying to send the wrong message on drvFFICall topic");let t=globalThis.state.config,r=globalThis.hub;globalThis.state.sboard.FFICall(e.params.getCoroutine(),e.params.getName());let s=t.topicBase()+"/FFICall";globalThis.state.config.debugMask&h.DEBUG_MESSAGES&&console.log("FFI call",e);let a=e.encode("msg_mixFFI");await r.publish(s,a,!1)}async function Ct(e,t,r){globalThis.state.sboard.FFICall(t,e);let s=globalThis.hub,a={name:e,call_id:t,args:r},i=s.newLocalMessage("msg_ffi_call","vm",a),n=globalThis.state.config.vmID;await s.publish("/local/"+n+"/ffi/call",i,!1)}async function Rt(e){let t,r=globalThis.state.config,s=globalThis.hub,a=r.topicBase()+"/output";t="object"==typeof e&&"function"==typeof e.publish?e:new globalThis.JSONMessage("msg_response","vm",e),await s.publish(a,t,!1)}!function(){if(console.log("GROOVEBOX_BUILD (machine-wasm)","2827"),function(){let e=new Uint32Array(1);e[0]=305419896;let t=new Uint8Array(e.buffer);return 120==t[0]&&86==t[1]&&52==t[2]&&18==t[3]}()){try{r.g.process&&(r.g.process.stdout._handle&&r.g.process.stdout._handle.setBlocking(!0),r.g.process.stderr._handle&&r.g.process.stderr._handle.setBlocking(!0))}catch{console.log("setting up stdout/err failed")}console.log("mix machine: worker started")}else console.error("refusing to start up Mix Machine on a big-endian platform")}(),globalThis.Channel=u,globalThis.JSONMessage=t,globalThis.UnparsedJSONMessage=s,globalThis.BinaryMessage=i,globalThis.TextMessage=a,globalThis.EOF=o,onmessage=function(e){let t=e.data;switch(t._rmx_type){case"msg_vm_configure":!async function(e){let t=new m;t.vmID=e.vmID,t.org=e.org,t.workspace=e.workspace,t.workerURL=e.workerURL,t.baseURL=e.baseURL,t.user=e.user,t.token=e.token,t.debugMask=e.debugMask,t.machType=void 0!==e.machType?e.machType:"WASM",t.localFFIs=e.localFFIs?e.localFFIs:{},t.allowInsecureHttp=e.allowInsecureHttp,t.outputViaMQTT=e.outputViaMQTT,t.interceptFFI=e.interceptFFI,t.interceptDynloadFFI=e.interceptDynloadFFI;let r=new globalThis.Channel(e.hub);globalThis.hub=r;let s=new g(t,{fficall:Ut,fficall_local:Ct,output:Rt},{fficall:Ut,fficall_local:Ct,output:Rt}),a=new d(t,s);a.ffiOverride=function(){let e=new Map;return e.set("$co_sleep",ee),e.set("$isSyncEnabled",te),e.set("$mqtt_available",re),e.set("$showHook",se),e.set("$hideHook",ae),e.set("$log",ie),e.set("$http_do",le),e.set("$http_do_client",le),e.set("$crypto_SHA1Sum",de),e.set("$crypto_SHA256Sum",me),e.set("$crypto_HMACSHA1Sign",ge),e.set("$crypto_HMACSHA1Verify",fe),e.set("$crypto_HMACSHA256Sign",pe),e.set("$crypto_HMACSHA256Verify",be),e.set("$crypto_RSASHA256Sign",we),e.set("$crypto_AESGCMEncrypt",_e),e.set("$crypto_AESGCMDecrypt",ye),e.set("$crypto_randomKey32",xe),e.set("$wasm_load",Te.load.bind(Te)),e.set("$wasm_fun",Te.fun.bind(Te)),e.set("$wasm_call",Te.call.bind(Te)),e.set("$wasm_shutdown",Te.shutdown.bind(Te)),e}(),e.mixrtCode&&(a.mixrt_code=e.mixrtCode),a.mixcore=await Et.create(e.mixcore),globalThis.state=a;try{await It()}catch(e){console.log("Error",e)}}(t);break;case"msg_vm_logStatus":console.log("mix machine: still here");break;case"msg_vm_logMask":r=t.mask,globalThis.state&&(console.log("mix machine: Setting debug mask to: ",r),globalThis.state.config.debugMask=r,globalThis.state.wasm&&globalThis.state.wasm.call(globalThis.state.wasm.instance.exports.mixrt_setDebugFlags,r));break;default:console.error("mix machine: unknown message type: "+t._rmx_type)}var r}})()})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@remix_labs/machine-starter",
3
- "version": "2.2598.0-dev",
3
+ "version": "2.2601.0-dev",
4
4
  "description": "start the groove",
5
5
  "main": "node.js",
6
6
  "browser": "index.js",
@@ -11,7 +11,7 @@
11
11
  "author": "Remixlabs staff",
12
12
  "license": "ISC",
13
13
  "dependencies": {
14
- "@remix_labs/hub-client": "2.2598.0-dev",
14
+ "@remix_labs/hub-client": "2.2601.0-dev",
15
15
  "nanoid": "^5.0.2",
16
16
  "web-worker": "^1.2.0"
17
17
  },