@kemu-io/edge-runtime 0.1.11 → 0.1.13
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.
- package/package.json +1 -1
- package/runner.d.ts +11 -4
- package/runner.js +2 -2
package/runner.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{config as e}from"dotenv";import{readFile as t,access as n}from"node:fs/promises";import{nanoid as r}from"nanoid";import s from"jsonp";import i from"crypto-js";import o from"util";import a from"emittery";import"axios";import c from"jszip";import{satisfies as l}from"compare-versions";import u from"debug";import d,{join as p,dirname as h,resolve as f}from"path";import"node-ipc";import{mkdir as g,readFile as m,access as v,constants as y,readdir as b,rm as S}from"fs/promises";import w from"minimist";import I from"tty";import _,{homedir as $}from"os";import C,{createHash as k}from"crypto";import E from"net";import x from"tls";import A,{promises as N}from"fs";import O from"dgram";import L from"stream";import P from"zlib";import T from"buffer";import B from"events";import j from"https";import D from"http";import U,{fileURLToPath as M}from"url";import F from"node:os";import{spawn as R}from"child_process";import{join as W,resolve as G,dirname as V}from"node:path";import{ImageData as H,loadImage as z,createCanvas as q}from"@napi-rs/canvas";var K;!function(e){e.STARTING="STARTING",e.PENDING="PENDING",e.RUNNING="RUNNING",e.PAUSED="PAUSED",e.DRAINING="DRAINING",e.STOPPED="STOPPED",e.ERROR="ERROR"}(K=K||(K={}));const J={};let Y=0,X="";const Z=e=>J[e]?J[e]:null,Q=(e,t)=>{const n=Z(e);if(!n)return n;return n.blocks[t]||null},ee=(e,t,n)=>{const r=Q(e,t);if(!r)return r;return r.gates[n]},te=(e,t)=>{let n=r(4);for(;J[n];)n=r(4);const s=(i=e,JSON.parse(JSON.stringify(i)));var i;return s.logs="",s.addLog=e=>{s.logs+=`${(()=>{const e=Date.now();if(e!==Y){const t=new Date;Y=e,X=t.toJSON()}return X})()}:: ${e}\n`},s.dbInfo={...t},J[n]=s,n},ne="interrupt_port",re="main.js",se="state.json",ie="{#}",oe="$var_",ae="default";var ce,le,ue,de,pe,he,fe,ge;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(ce||(ce={})),function(e){e[e.Number=0]="Number",e[e.String=1]="String",e[e.ArrayBuffer=2]="ArrayBuffer",e[e.Array=3]="Array",e[e.Boolean=4]="Boolean",e[e.JsonObj=5]="JsonObj",e[e.Anything=6]="Anything",e[e.ImageData=7]="ImageData",e[e.AudioBuffer=8]="AudioBuffer",e[e.Rect=9]="Rect",e[e.Point=10]="Point",e[e.ImageBitmap=11]="ImageBitmap",e[e.BinaryFile=12]="BinaryFile"}(le||(le={})),function(e){e.Number="Number",e.String="String",e.ArrayBuffer="ArrayBuffer",e.Array="Array",e.Boolean="Boolean",e.JsonObj="JsonObj",e.Anything="Anything",e.ImageData="ImageData",e.AudioBuffer="AudioBuffer",e.Rect="Rect",e.Point="Point",e.ImageBitmap="ImageBitmap",e.BinaryFile="BinaryFile"}(ue||(ue={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(de||(de={})),function(e){e.IpcAcknowledge="iack:",e.SocketAcknowledge="sack:",e.AcknowledgeResponse="ackr:",e.ServicesListChanged="update-services",e.SendManifest="send-manifest",e.BroadcastStart="broadcast-start",e.BroadcastEnd="broadcast-end",e.AssumeSession="assume:"}(pe||(pe={})),function(e){e.GetServices="getServices",e.SubscribeToService="subscribeToService",e.UnsubscribeFromService="unsubscribeFromService",e.GetServiceContents="getServiceContents",e.SocketAckResponse="socketAckResponse",e.ShowSecretsConfigScreen="showSecretsConfigScreen",e.GetMappedSecrets="getMappedSecrets",e.GetSecretContexts="getSecretContexts",e.OnParentEvent="onParentEvent",e.GetDefaultState="getDefaultState",e.BroadcastEvent="broadcastEvent",e.HubBroadcastEvent="hubBroadcastEvent",e.ServiceManifest="serviceManifest",e.GetState="getState",e.SetState="setState",e.SetOutputs="setOutputs",e.UIEvent="uiEvent",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.GetUniqueId="getUniqueId"}(he||(he={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(fe||(fe={})),function(e){e.IPC="ipc",e.WS="ws"}(ge||(ge={}));const me="undefined"!=typeof window&&void 0!==window.document&&void 0!==typeof window.document.createElement,ve="object"==typeof self&&self.constructor&&"DedicatedWorkerGlobalScope"===self.constructor.name,ye="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node,be="-",Se=`inner${be}`,we=`outer${be}`,Ie=`${we}input${be}`,_e=`${we}output${be}`,$e=`${Se}input${be}`,Ce=`${Se}output${be}`,ke=e=>(new TextEncoder).encode(e),Ee=e=>e===ne,xe=e=>e&&void 0!==e.width&&void 0!==e.height&&void 0!==e.data&&e.data.constructor&&"Uint8ClampedArray"===e.data.constructor.name,Ae=e=>e&&void 0!==e.width&&void 0!==e.height&&void 0!==e.top&&void 0!==e.left&&"number"==typeof e.width&&"number"==typeof e.height&&"number"==typeof e.top&&"number"==typeof e.left,Ne=e=>e&&"number"==typeof e.x&&"number"==typeof e.y,Oe=e=>"number"==typeof e?le.Number:"string"==typeof e?le.String:"boolean"==typeof e?le.Boolean:Array.isArray(e)?le.Array:xe(e)?le.ImageData:e&&void 0!==e.duration&&void 0!==e.length&&void 0!==e.numberOfChannels&&void 0!==e.sampleRate&&"function"==typeof e.getChannelData&&"AudioBuffer"===e.constructor.name?le.AudioBuffer:e&&void 0!==e.byteLength?le.ArrayBuffer:Ae(e)?le.Rect:e&&void 0!==e.x&&void 0!==e.y&&"number"==typeof e.x&&"number"==typeof e.y?le.Point:le.JsonObj,Le=e=>{const t={};let n;n=Array.isArray(e)?e[0]:e;for(const e in n){const r=Oe(n[e]);t[e]=r}return t},Pe=(e,t,n)=>"inner"===e?"input"===t?`${$e}${n}`:`${Ce}${n}`:"input"===t?`${Ie}${n}`:`${_e}${n}`,Te=e=>{const t=(e||"")?.split("_");if(t.length<3)throw new Error(`Unknown child identifier format [${e}]`);const n=t[0];return{portType:t[1],widgetId:n,portName:t[2]}},Be=e=>new ImageData(e.data,e.width,e.height,{colorSpace:e.colorSpace});var je,De;!function(e){e.Action="action",e.CustomInput="customInput"}(je=je||(je={})),function(e){e.input="input",e.counter="counter",e.play="play",e.elapsed="elapsed",e.ifGate="ifGate",e.skipEvent="skipEvent",e.between="between",e.map="map",e.parser="parser",e.slider="slider",e.suspend="suspend",e.display="display",e.json="json",e.arrayItem="arrayItem",e.extractImage="extractImage",e.imageConvolution="imageConvolution",e.firstEvent="firstEvent",e.pixelDraw="pixelDraw",e.randomBetween="randomBetween",e.arrayCombine="arrayCombine",e.clock="clock",e.multiplication="multiplication",e.object="object",e.widgetGroup="widgetGroup",e.script="script",e.base64ToImageData="base64ToImageData",e.jsonParse="jsonParse",e.text="text",e.imageCrop="imageCrop",e.imageResize="imageResize",e.value="value",e.imageWarp="imageWarp",e.widgetBundle="widgetBundle",e.sequence="sequence",e.variable="variable",e.hubService="hubService",e.imageFilter="imageFilter",e.recipeLoad="recipeLoad"}(De=De||(De={}));const Ue={};let Me;const Fe=async e=>{const t=Ue[e],n={name:ne,type:le.Boolean};if(t){const r={name:t.portName},s=t.data||{type:le.Boolean,value:!0};Me?(await Me(!0,t.targetWidgetId,t.thingId,t.recipePoolId,n.name,r,{...s,timestamp:Date.now()},[n]),"timeout"===t.type&&Re(e)):console.warn("Interrupt service has not been initialized")}},Re=e=>{const t=Ue[e];return!!t&&(t.timerRef&&("interval"===t.type?clearInterval(t.timerRef):"timeout"===t.type&&clearTimeout(t.timerRef)),delete Ue[e],!0)};var We={interruptHandler:Fe,createInterrupt:(e,t,n,s,i,o,a,c)=>{if(c&&Ue[c])throw new Error("The given interrupt id already exists");const l=c||r().replace(/_/g,"-");if("interval"===e&&!o.interval)throw new Error(`Invalid interval. Expected a number greater than 0, but got '${o.interval}'`);if("timeout"===e&&!o.timeout)throw new Error(`Invalid timeout. Expected a number greater than 0, but got '${o.timeout}'`);if(Ue[l]={data:a,portName:i,recipePoolId:t,targetWidgetId:s,thingId:n,type:e},"interval"===e)Ue[l].timerRef=setInterval((async()=>await Fe(l)),o.interval);else{if("timeout"!==e)throw new Error(`Invalid interrupt type '${e}'`);Ue[l].timerRef=setTimeout((async()=>await Fe(l)),o.timeout)}return l},destroyInterrupt:Re,destroyAllInterrupts:()=>{Object.keys(Ue).forEach(Re)},setInvokeChildGateCb:e=>{Me=e}};const Ge=(e,t,n,r,s)=>{const i=ee(e,n,r);if(!i)return console.warn(`Gate ${r} not found in block ${n} for recipe ${e}`),null;const o=(t,s,i,o)=>We.createInterrupt(t,e,n,r,s,i,o),a=()=>Object.freeze({...i.state,...i.type===De.input&&{customInputs:[]}}),c=e=>{if("object"!=typeof e)return void console.warn(`Invalid state type [${typeof e}]. Expected an 'object'`);const t={...e,...i.type===De.input&&!e.customInputs&&{customInputs:[]}};i.state=t};if(s){return{getState:a,setState:c,registerInterrupt:o,getStorageData:async t=>{const r=((e,t,n)=>{const r=Z(e);if(!r)throw new Error(`Recipe [${e} does not exist]`);if(!r.storage)return null;const s=Q(e,t);if(!s)throw new Error(`The Thing "${t}" does not exist in recipe ${e}`);if(!(s.storageUnits||[]).includes(n))throw new Error(`The Thing "${t}" has no access to storage unit "${n}"`);return r.storage[n]||null})(e,n,t);return r},recipePoolId:e,recipeType:t,thingRecipeId:n,widgetThingId:r}}return{getState:a,setState:c,recipePoolId:e,widgetId:r}},Ve=[10001,"Invalid `sourcePort` parameter"],He=[10002,"The gate [%s] does not exist. Have you called `loadWidgets` yet?"],ze=[10110,"No storage medium has been loaded, call `loadMedium()` first"],qe=(e,...t)=>JSON.stringify({code:e[0],message:t[0]?o.format(e[1],...t):e[1].replace(/ \[%s\]/g,"")}),Ke=()=>({inputName:"",dataType:le.Anything}),Je="output",Ye={processEvent:async(e,t)=>{const n=t.getState(),r={...Ke(),...n};if(e.type===r.dataType||r.dataType===le.Anything)return t.nextWidget(Je,{type:e.type,value:e.value});console.error(`Invalid data type: ${e.type} for input: ${r.inputName}. Expected: ${r.dataType}`)},getOutputNames:e=>{const t={...Ke(),...e};return[{name:Je,type:t.dataType}]},getInputNames:()=>[]},Xe=Object.freeze({in:"in",reset:"reset",increment:"increment"}),Ze="output";var Qe={onParentEvent:async(e,t,n,r)=>{if(!e)throw new Error(qe(Ve));const s={currentValue:0,increment:1,...r.getState()};let i=s.increment,o=s.currentValue;const a=await r.getParentAtPort(Xe.increment);if(t.name===Xe.increment)return void(n.data.type===le.Number&&r.setState({...s,increment:Number(n.data.value)}));if(a){const e=a.getValue();null!==e&&(i=e)}if(t.name===Xe.reset)return r.setState({...s,currentValue:0});o+=i,r.setState({currentValue:o,increment:i});const c={type:le.Number,value:o};return r.nextGate(Ze,c)},getInputNames:()=>[{name:Xe.in,type:le.Anything},{name:Xe.reset,type:le.Anything},{name:Xe.increment,type:le.Number}],getOutputNames:()=>[{name:Ze,type:le.Number}]};const et=Object.freeze({in:"in",reset:"reset"}),tt="output";var nt={onParentEvent:async(e,t,n,r)=>{const s={updatedAt:0,elapsed:0,...r.getState()},i=Date.now(),o=i-(s.updatedAt||i);return t.name===et.reset?r.setState({...s,updatedAt:i,elapsed:0}):(r.setState({updatedAt:i,elapsed:o}),r.nextGate(tt,{type:le.Number,value:o}))},getInputNames:()=>[{name:et.in,type:le.Anything},{name:et.reset,type:le.Anything}],getOutputNames:()=>[{name:tt,type:le.Number}]};const rt=Object.freeze({data:"data",evaluation:"evaluation"}),st="then",it="else";var ot={onParentEvent:async(e,t,n,r)=>{const s={value:5,condition:"Equal",useDataPort:!1,...r.getState()},i=n.data.value,o=!isNaN(Number(i)),a="string"==typeof i;if(!s.useDataPort&&(n.data.type===le.Number||n.data.type===le.String||n.data.type===le.Anything&&o||n.data.type===le.Anything&&a)){let e=!1;return("Equal"===s.condition&&n.data.value==s.value||"Not Equal"===s.condition&&n.data.value!==s.value||"Greater"===s.condition&&n.data.value>Number(s.value)||"Less"===s.condition&&n.data.value<Number(s.value)||"Starts With"===s.condition&&String(n.data.value).startsWith(String(s.value))||"Ends With"===s.condition&&String(n.data.value).endsWith(String(s.value))||"Includes"===s.condition&&String(n.data.value).includes(String(s.value))||"Matches"===s.condition&&String(n.data.value).match(String(s.value)))&&(e=!0),e?r.nextGate(st,n.data):r.nextGate(it,n.data)}if((t.name===rt.evaluation&&n.data.type===le.Number||n.data.type===le.String||n.data.type===le.Anything&&(o||a))&&(s.$lastValue=n.data.value,r.setState({...s})),t.name===rt.data){let e=!1;return("Equal"===s.condition&&s.$lastValue==s.value||"Not Equal"===s.condition&&s.$lastValue!==s.value||"Greater"===s.condition&&Number(s.$lastValue)>Number(s.value)||"Less"===s.condition&&Number(s.$lastValue)<Number(s.value)||"Starts With"===s.condition&&String(s.$lastValue).startsWith(String(s.value))||"Ends With"===s.condition&&String(s.$lastValue).endsWith(String(s.value))||"Includes"===s.condition&&String(s.$lastValue).includes(String(s.value))||"Matches"===s.condition&&String(s.$lastValue).match(String(s.value)))&&(e=!0),r.setState({...s,$lastValue:void 0,$lastDataType:n.data.type}),e?r.nextGate(st,n.data):r.nextGate(it,n.data)}},getInputNames:e=>e.useDataPort?[{name:rt.data,type:le.Anything},{name:rt.evaluation,type:[le.Number,le.String]}]:[{name:"in",type:[le.Number,le.String]}],getOutputNames:e=>e.$lastDataType?[{name:st,type:e.$lastDataType},{name:it,type:e.$lastDataType}]:[{name:st,type:[le.Number,le.String]},{name:it,type:[le.Number,le.String]}]};const at=Object.freeze({in:"in",reset:"reset"}),ct="out";var lt={onParentEvent:async(e,t,n,r)=>{const s={totalCalls:0,callsLimit:1,...r.getState()};return t.name===at.reset?r.setState({...s,totalCalls:0}):(s.totalCalls=s.totalCalls+1,s.totalCalls>s.callsLimit?(s.totalCalls=0,r.setState(s),r.nextGate(ct,n.data)):void r.setState(s))},getInputNames:()=>[{name:at.in,type:le.Anything},{name:at.reset,type:le.Anything}],getOutputNames:()=>[{name:ct,type:le.Anything}]};const ut=Object.freeze({in:"in"}),dt="then",pt="else";var ht={onParentEvent:async(e,t,n,r)=>{const s={min:1,max:10,...r.getState()};if(n.data.type===le.Number)return n.data.value>=s.min&&n.data.value<=s.max?r.nextGate(dt,n.data):r.nextGate(pt,n.data)},getInputNames:()=>[{name:ut.in,type:le.Number}],getOutputNames:()=>[{name:dt,type:le.Number},{name:pt,type:le.Number}]};const ft=Object.freeze({in:"in"}),gt="out";var mt={onParentEvent:async(e,t,n,r)=>{const s={clamp:!0,...r.getState()},i=Number(n.data.value);if(void 0!==s.fromMax&&void 0!==s.fromMin&&void 0!==s.toMax&&void 0!==s.toMin&&""!==s.fromMax&&""!==s.fromMin&&""!==s.toMax&&""!==s.toMin&&(n.data.type===le.Number||n.data.type===le.Anything&&!isNaN(Number(i)))){let e=((e,t,n,r,s)=>(e-t)*(s-r)/(n-t)+r)(i,Number(s.fromMin),Number(s.fromMax),Number(s.toMin),Number(s.toMax));if(isNaN(e))return;return s.clamp&&(e<Number(s.toMin)&&(e=Number(s.toMin)),e>Number(s.toMax)&&(e=Number(s.toMax))),r.nextGate(gt,{type:le.Number,value:Number(e)})}},getInputNames:()=>[{name:ft.in,type:le.Number}],getOutputNames:()=>[{name:gt,type:le.Number}]};const vt=Object.freeze({in:"in"}),yt="out";var bt={onParentEvent:async(e,t,n,r)=>{const s={convertTo:"Integer",floatPlaces:2,...r.getState()};let i=n.data.value;if(n.data.type===le.Number||n.data.type===le.Anything||n.data.type===le.String){if((!isNaN(Number(i))||"string"==typeof i)&&!Array.isArray(i))return"Integer"===s.convertTo?i=parseInt(i):"Decimal"===s.convertTo?i=parseFloat(Number(i).toFixed(s.floatPlaces)):"String"===s.convertTo?i=String(i):"Abs"===s.convertTo?i=Math.abs(Number(i)):"Round"===s.convertTo&&(i=Math.round(Number(i))),r.nextGate(yt,{type:"String"===s.convertTo?le.String:le.Number,value:i})}},getInputNames:()=>[{name:vt.in,type:le.Number}],getOutputNames:e=>{const t="String"===e?.convertTo?le.String:le.Number;return[{name:yt,type:t}]}};const St=Object.freeze({in:"in"}),wt="out";var It={onParentEvent:async(e,t,n,r)=>{const s={currentValue:50,min:0,max:100,...r.getState()};let i=!1;return s.currentValue<s.min&&(s.currentValue=s.min,i=!0),s.currentValue>s.max&&(s.currentValue=s.max,i=!0),i&&r.setState(s),r.nextGate(wt,{type:le.Number,value:s.currentValue})},getInputNames:()=>[{name:St.in,type:le.Anything}],getOutputNames:()=>[{name:wt,type:le.Number}]};const _t=Object.freeze({in:"in",reset:"reset"}),$t="out";var Ct={onParentEvent:async(e,t,n,r)=>{const s={lastCalledAt:0,delayMs:500},i={lastCalledAt:0,delayMs:500,...r.getState()};if(t.name===_t.reset)return r.setState({...i,lastCalledAt:0});const o=Date.now(),a=o-i.lastCalledAt;return i.lastCalledAt===s.lastCalledAt||a>=i.delayMs&&i.delayMs>0?(i.lastCalledAt=o,r.setState(i),r.nextGate($t,n.data)):void 0},getInputNames:()=>[{name:_t.in,type:le.Anything},{name:_t.reset,type:le.Anything}],getOutputNames:()=>[{name:$t,type:le.Anything}]};const kt="in";var Et={onParentEvent:async()=>{},getInputNames:()=>[{name:kt,type:[le.ImageData,le.Number]}],getOutputNames:()=>[]};const xt=()=>({properties:[{label:"property1",name:"property1"}],detectedProperties:{}}),At=(e,t)=>t.split(".").reduce(((e,t)=>null!=e?e[t]:e),e);var Nt={onParentEvent:async(e,t,n,r)=>{const s={properties:[{label:"property1",name:"property1"}],detectedProperties:{},...r.getState()},i=n?.data?.value,o=Array.isArray(i);if(n.data.type===le.JsonObj||n.data.type===le.Rect||n.data.type===le.Anything||o){let e=!1;for(const t in i){const n=Oe(i[t]),r=!!s.detectedProperties[t],o=s.detectedProperties[t]?.type!==n;if(!r||o){const r=n===le.JsonObj||n===le.Rect||n===le.Array;s.detectedProperties[t]={type:n,...r?{shape:Le(i[t])}:void 0},e=!0}}if(o&&void 0===s.detectedProperties.length&&(s.detectedProperties.length={type:le.Number}),e&&r.setState(s),i){const e=[];for(const t of s.properties||[]){const n=At(i,t.label),o=t.label.includes(".");if(void 0!==n){const i=o?Oe(n):void 0!==s.detectedProperties[t.label]?.type?s.detectedProperties[t.label].type:le.Anything;e.push(r.nextGate(t.name,{type:i,value:n}))}}await Promise.allSettled(e)}}},getInputNames:()=>[{name:"in",type:le.JsonObj}],getOutputNames:e=>{const t={properties:[{label:"property1",name:"property1"}],detectedProperties:{},...e};return t.properties.map((e=>{const n=void 0!==t.detectedProperties[e.label]?t.detectedProperties[e.label]?.type:le.Anything,r=t.detectedProperties[e.label]?.shape||void 0,s="string"==typeof e;return{name:s?e:e.name,label:s?e:e.label,type:n,jsonShape:r}}))},getDefaultState:xt};const Ot="output",Lt="noItem";var Pt={onParentEvent:async(e,t,n,r)=>{const s={index:0,...r.getState()};let i=s.index;const o=n.data.value,a="string"==typeof n.data.value,c=Array.isArray(n.data.value);if(n.data.type===le.Anything&&(c||a)||n.data.type===le.String&&a||n.data.type===le.Array&&c){i<0&&(i=o.length+i);const e=a?le.String:Oe(o[i]);return e!==s.$$lastDetectedType&&r.setState({...s,$$lastDetectedType:e}),void 0!==o[i]?r.nextGate(Ot,{value:o[i],type:e}):r.nextGate(Lt,{value:!0,type:le.Boolean})}},getInputNames:()=>[{name:"in",type:[le.Array,le.String]}],getOutputNames:e=>[{name:Ot,type:e.$$lastDetectedType??le.Anything},{name:Lt,type:le.Boolean}]};let Tt;const Bt=e=>{Tt=e},jt=(e,t)=>(()=>{if(!Tt)throw new Error("CanvasManager not set");return Tt})().createCanvas(e,t),Dt=e=>me?e.getContext("2d",{willReadFrequently:!0}):e.getContext("2d"),Ut=Object.freeze({image:"image",rect:"rect"}),Mt="image";var Ft={onParentEvent:async(e,t,n,r)=>{const s={offset:{height:0,left:0,top:0,width:0},...r.getState()},i=await r.getParentAtPort(Ut.rect),o=[le.Anything,le.Rect,le.JsonObj];if(t.name!==Ut.rect){if(i){const e=i.getValue();null!==e&&(s.rect={...e},r.setState(s))}if(!me)return n.data.type===le.ImageData?r.nextGate(Mt,n.data):void 0;if(s.$$canvasFrom&&s.$$canvasFrom.getContext||(s.$$canvasFrom=jt(320,240)),s.$$canvasTo&&s.$$canvasTo.getContext||(s.$$canvasTo=jt(320,240)),(n.data.type===le.ImageData||n.data.type===le.Anything&&xe(n.data.value))&&!s.$$processing&&s.$$canvasFrom&&s.rect){const e=((e,t,n,r,s)=>{if(r&&r.getContext){const i=r.getContext("2d"),o=n.getContext("2d");if(i&&o){n.width=e.width,n.height=e.height,o.putImageData(e,0,0);const a={...s};s&&(a.height=Number(s.height),a.width=Number(s.width),a.left=Number(s.left),a.top=Number(s.top));const c={top:0,width:0,left:0,height:0,...a};return s&&(Number.isInteger(c.width)||(c.width=t.width*c.width),Number.isInteger(c.height)||(c.height=t.height*c.height),Number.isInteger(c.left)||(c.left=t.left+t.width*c.left),Number.isInteger(c.top)||(c.top=t.top+t.height*c.top)),r.width=t.width+c.width,r.height=t.height+c.height,i.drawImage(n,t.left+c.left,t.top+c.top,t.width+c.width,t.height+c.height,0,0,r.width+c.width,r.height+c.height),i.getImageData(0,0,r.width||1,r.height||1)}}return e})(n.data.value,s.rect,s.$$canvasFrom,s.$$canvasTo,s.offset);return r.nextGate(Mt,{type:le.ImageData,value:e})}}else Ae(n.data.value)&&o.includes(n.data.type)&&r.setState({...s,rect:n.data.value})},getInputNames:()=>[{name:Ut.image,type:le.ImageData},{name:Ut.rect,type:[le.Rect,le.JsonObj]}],getOutputNames:()=>[{name:Mt,type:le.ImageData}]};const Rt=(e,t)=>{const n=Math.round(Math.sqrt(t.length)),r=Math.floor(n/2),s=e.data,i=e.width,o=e.height,a=i,c=o,l=((e,t,n)=>{if(me)return new ImageData(t,n);return console.warn("Node environment detected. Aborting new ImageData creation"),e})(e,a,c),u=l.data;for(let e=0;e<c;e++)for(let c=0;c<a;c++){const l=e,d=c,p=4*(e*a+c);let h=0,f=0,g=0,m=0;for(let e=0;e<n;e++)for(let a=0;a<n;a++){const c=l+e-r,u=d+a-r;if(c>=0&&c<o&&u>=0&&u<i){const r=4*(c*i+u),o=t[e*n+a];h+=s[r]*o,f+=s[r+1]*o,g+=s[r+2]*o,m+=s[r+3]*o}}u[p]=h,u[p+1]=f,u[p+2]=g,u[p+3]=m+1*(255-m)}return l},Wt=[-1,0,1,-2,0,2,1,0,1],Gt=Object.freeze({image:"image"}),Vt="image";var Ht={onParentEvent:async(e,t,n,r)=>{const s=r.getState(),i={matrix:[...Wt],...s};if(n.data.type===le.ImageData||n.data.type===le.Anything&&xe(n.data.value)){const e=Rt(n.data.value,i.matrix);return r.nextGate(Vt,{type:le.ImageData,value:e})}},getInputNames:()=>[{name:Gt.image,type:le.ImageData}],getOutputNames:()=>[{name:Vt,type:le.ImageData}]};const zt=Object.freeze({output:"output",aborted:"aborted"}),qt=()=>({inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0}),Kt=e=>{const t={inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0,...e},n=Array(t.inputs).fill(0).map(((e,t)=>({name:`input${t+1}`,type:le.Anything})));return n.push({name:"reset",type:le.Anything}),n};var Jt={onParentEvent:async(e,t,n,r)=>{const s={inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0,...r.getState()};if("reset"===t.name)return r.setState({...s,triggeredAt:0});const i=Date.now(),o=i-s.triggeredAt;if(s.triggeredAt&&!(o>=s.delayMs&&s.delayMs>0)&&s.delayMs)return r.nextGate(zt.aborted,n.data);{s.triggeredAt=i;const e=Kt(s,(r.recipePoolId,r.recipeType,r.thingRecipeId,r.id)).findIndex((e=>e.name===t.name));-1!==e&&(s.lastInputIndex=e),s.matchingOutputs?-1!==e&&await r.nextGate(`output${e+1}`,n.data):await r.nextGate(zt.output,n.data),r.setState(s)}},getInputNames:Kt,getOutputNames:e=>{const t={inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0,...e};if(e.matchingOutputs){const e=Array(t.inputs).fill(0).map(((e,t)=>({name:`output${t+1}`,type:le.Anything})));return e.push({name:zt.aborted,type:le.Anything}),e}return[{name:zt.output,type:le.Anything},{name:zt.aborted,type:le.Anything}]},getDefaultState:qt};const Yt=(e,t,n,r,s,i)=>{if(s){const o=e.measureText(s),a=o.fontBoundingBoxAscent+o.fontBoundingBoxDescent;e.fillStyle=r,e.fillRect(t,n-i,1.1*o.width,a),e.font=`${i}px Arial`,e.fillStyle="black",e.fillText(s,t,n)}},Xt=(e,t,n,r,s,i,o)=>{e.fillStyle=s,e.fillRect(t,n,r,r),Yt(e,t,n,s,i,o)},Zt=(e,t,n,r,s,i)=>{e.beginPath(),e.strokeStyle=r,e.lineWidth=n,e.rect(t.left,t.top,t.width,t.height),e.stroke();const o=n/2;Yt(e,t.left-o,t.top-o,r,s,i)},Qt=Object.freeze({image:"image",pixels:"pixels"}),en="image";var tn={onParentEvent:async(e,t,n,r)=>{const s={fontSize:12,color:"#00ff00",size:2,...r.getState()},i=n.data.type===le.ImageData||n.data.type===le.Anything&&xe(n.data.value);if(t.name===Qt.pixels){const e=((e,t)=>t===le.Anything&&(xe(e)||Ne(e)||Ae(e)||Array.isArray(e))||t===le.Array||t===le.Rect||t===le.Point)(n.data.value,n.data.type);if(!e)return;s.$$pixels=n.data.value}if(t.name===Qt.image&&i){const e=n.data.value;s.$$memCanvas&&s.$$memCanvas.getContext||(s.$$memCanvas=jt(e.width||1,e.height||1)),s.$$lastFrame=e}if(s.$$lastFrame&&s.$$pixels&&s.$$memCanvas){const e=(e=>{const{sourceImage:t,pixels:n,memCanvas:r,size:s,color:i,labelProp:o,fontSize:a}=e;if(r){const e=Dt(r);if(e){r.width!==t.width&&(r.width=t.width),r.height!==t.height&&(r.height=t.height),e.putImageData(t,0,0);const c=Array.isArray(n)?n:[n];for(let t=0;t<c.length;t++){const n=c[t],r=o?n[o]:"";Ae(n)?Zt(e,n,s,i,r,a):Ne(n)&&Xt(e,n.x,n.y,s,i,r,a)}return e.getImageData(0,0,r.width,r.height)}}return t})({sourceImage:s.$$lastFrame,pixels:s.$$pixels||[],memCanvas:s.$$memCanvas,size:s.size,color:s.color,labelProp:s.labelProp,fontSize:s.fontSize});return r.setState({...s,$$lastFrame:void 0,$$pixels:void 0}),r.nextWidget(en,{type:le.ImageData,value:e})}r.setState(s)},getInputNames:()=>[{name:Qt.image,type:le.ImageData},{name:Qt.pixels,type:[le.Rect,le.Point,le.Array]}],getOutputNames:()=>[{name:en,type:le.ImageData}]};const nn=Object.freeze({in:"in"}),rn="output",sn=e=>{const t=String(e).split(".");return t.length<2?0:t[1].length};var on={onParentEvent:async(e,t,n,r)=>{const s={min:1,max:100,...r.getState()},i=!Number.isInteger(s.min),o=!Number.isInteger(s.max),a=i||o;let c=(l=s.min,u=s.max,Math.random()*(u-l)+l);var l,u;if(a){let e=0;if(i&&(e=sn(s.min)),o){const t=sn(s.max);t>e&&(e=t)}c=Number(c.toFixed(e))}else c=Math.floor(c);return r.nextGate(rn,{type:le.Number,value:c})},getInputNames:()=>[{name:nn.in,type:le.Anything}],getOutputNames:()=>[{name:rn,type:le.Number}]};const an=Object.freeze({output:"output",totalItems:"totalItems"}),cn=Object.freeze({trigger:"trigger",clear:"clear"}),ln=()=>({totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1}),un=async(e,t)=>t.nextGate(an.totalItems,{type:le.Number,value:e});var dn={onParentEvent:async(e,t,n,r)=>{const s={totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...r.getState()};if(t.name===cn.clear)return s.$$list=[],s.properties?.autoFilled&&delete s.properties,r.setState(s),un(s.$$list.length,r);const i=t.name===cn.trigger;if(!i)if(Array.isArray(n.data.value))n.data.type!==le.Array&&n.data.type!==le.Anything||(s.$$outputShape={...s.$$outputShape,...e?.jsonShape},s.$$list=s.$$list.concat(n.data.value),r.setState({...s}),await un(s.$$list.length,r));else{const t=`$$primitive_${Object.keys(s.$$outputShape).length}`;n.data.type===le.JsonObj?s.$$outputShape={...s.$$outputShape,...e?.jsonShape?e.jsonShape:void 0}:s.$$outputShape={...s.$$outputShape,[t]:n.data.type},s.$$list.push(n.data.value),r.setState({...s}),await un(s.$$list.length,r)}if(i){Object.keys(s.$$outputShape).length&&(s.properties={autoFilled:!0,jsonShape:{...s.$$outputShape}});const e=s.$$list.length,t=[...s.$$list];return s.$$list=[],r.setState({...s}),await un(e,r),r.nextGate(an.output,{type:le.Array,value:t})}},getInputNames:e=>{const t={totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...e},n=Array(t.totalInputs||1).fill(0).map(((e,t)=>({name:`array${t+1}`,type:le.Array})));return n.push({name:cn.clear,type:le.Anything},{name:cn.trigger,type:le.Anything}),n},getOutputNames:e=>[{name:an.output,type:le.Array,...e.properties?{jsonShape:e.properties?.jsonShape}:void 0},{name:an.totalItems,label:"Total Items",type:le.Number}],getDefaultState:ln};const pn=Object.freeze({start:"start",stop:"stop"}),hn="output",fn="clock_interrupt";var gn={onParentEvent:async(e,t,n,r)=>{const s={enabled:!1,interval:1e3,intervalMode:"ms",...r.getState()};if(Ee(e?.name||"")&&t.name===fn)return r.nextGate(hn,{type:le.Boolean,value:!0});if(t.name===pn.stop&&s.enabled&&s.$$interruptId){r.cancelInterrupt(s.$$interruptId)?(s.enabled=!1,s.$$interruptId=void 0,r.setState(s)):console.warn(`Failed to cancel interrupt [${s.$$interruptId}]`)}else t.name!==pn.start||s.enabled||s.$$interruptId||(s.$$interruptId=r.registerInterrupt("interval",fn,{interval:s.interval}),s.enabled=!0,r.setState(s))},getInputNames:()=>[{name:pn.start,type:le.Anything},{name:pn.stop,type:le.Anything}],getOutputNames:()=>[{name:hn,type:le.Boolean}],initialize:async e=>{const t=e.getState();if(t.enabled&&!t.$$interruptId){const n=e.registerInterrupt("interval",fn,{interval:t.interval});e.setState({...t,$$interruptId:n})}}};const mn=Object.freeze({in:"in"}),vn="output",yn=(e,t,n)=>"number"==typeof e?Number((e*t).toFixed(n)):e;var bn={onParentEvent:async(e,t,n,r)=>{const s={userProperties:[],factor:2,decimalPoints:2,...r.getState()},i=n.data.type;let o=n.data.value,a=!1;return e?.jsonShape&&(s.detectedInputJson={...s.detectedInputJson,...e?.jsonShape},a=!0),s.detectedInputType||(s.detectedInputType=i,a=!0),n.data.type===le.Array&&("number"==typeof n.data.value?.[0]?o=((e,t,n)=>{const r=(e||[]).map((e=>yn(e,t,n)));return r})(n.data.value,s.factor,s.decimalPoints):"object"==typeof n.data.value?.[0]&&(o=((e,t,n,r)=>{const s=(e||[]).map((e=>{const s={...e};return Object.keys(s).forEach((e=>{r?.length&&!r?.includes(e)||(s[e]=yn(s[e],t,n))})),s}));return s})(n.data.value,s.factor,s.decimalPoints,s.userProperties))),n.data.type===le.Number&&(o=yn(n.data.value,s.factor,s.decimalPoints)),a&&r.setState(s),r.nextGate(vn,{type:i,value:o})},getInputNames:()=>[{name:mn.in,type:[le.Array,le.Number]}],getOutputNames:e=>[{name:vn,type:e.detectedInputType||le.Number,jsonShape:e.detectedInputJson}]};const Sn=Object.freeze({output:"output"}),wn=Object.freeze({trigger:"trigger"}),In=()=>({useTriggerPort:!0,properties:[{name:"x",label:"x",type:le.Number,value:10},{name:"y",label:"y",type:le.Number,value:20}]}),_n=e=>{const t={};for(let n=0;n<e.properties.length;n++)t[e.properties[n].label]=e.properties[n].type;return t},$n=e=>{const t={};for(let n=0;n<e.properties.length;n++){let r=e.properties[n].value;const s=e.properties[n].type;s===le.Number?r=Number(r):s===le.String&&(r=String(r)),t[e.properties[n].label]=r}return t};var Cn={onParentEvent:async(e,t,n,r)=>{const s=r.getState(),i=structuredClone(s),o={...In(),...i};if(t.name===wn.trigger){const e=$n(o);return r.nextGate(Sn.output,{type:le.JsonObj,value:e})}const a=o.properties.findIndex((e=>e.name===t.name));if(-1!==a){let e=n.data.type===o.properties[a].type;if(!e&&n.data.type===le.Anything){e=Oe(n.data.type)===o.properties[a].type}if(e?(o.properties[a].value=n.data.value,o.properties[a].$$invalidInputType=!1):o.properties[a].$$invalidInputType=!0,r.setState(o),!o.useTriggerPort){const e=$n(o);return r.nextGate(Sn.output,{type:le.JsonObj,value:e})}}},getInputNames:e=>{const t={...In(),...e},n=t.properties.map((e=>({name:e.name,label:e.label,type:e.type})));return t.useTriggerPort&&n.push({name:wn.trigger,label:wn.trigger,type:le.Anything}),n},getOutputNames:e=>[{name:Sn.output,label:Sn.output,type:le.JsonObj,jsonShape:_n(e)}],getDefaultState:In};const kn=async e=>{const t=(e,t)=>e.split(t)[1];if(e.startsWith(Ie)){const n=t(e,Ie);return Pe("inner","input",n)}if(e.startsWith(Ce)){const n=t(e,Ce);return Pe("outer","output",n)}return null},En=()=>({canvasPosition:{x:0,y:0},canvasZoom:1,inputs:[{name:"input",type:[le.Anything],index:0}],outputs:[{name:"output",type:[le.Anything],index:0}],name:"Custom Widget 1",description:"",type:"custom"}),xn=e=>{const t={...En(),...e},n=t.inputs.map(((e,t)=>({name:Pe("outer","input",e.name),type:e.type,...e.jsonShape?{jsonShape:e.jsonShape}:void 0,...e.position?{position:e.position}:void 0,label:e.label,isInner:!1,index:t}))),r=t.outputs.map(((e,t)=>({name:Pe("inner","output",e.name),type:e.type,...e.jsonShape?{jsonShape:e.jsonShape}:void 0,...e.position?{position:e.position}:void 0,label:e.label,isInner:!0,index:n.length+t})));return[...n,...r]};var An={onParentEvent:async(e,t,n,r)=>{const s=r.getState(),i={...En(),...s},o=xn(i,(r.recipePoolId,r.recipeType,r.thingRecipeId,r.id));for(let e=0;e<o.length;e++){const s=o[e];if(t.name===s.name&&(s.type.includes(le.Anything)||s.type.includes(n.data.type))){const e=await kn(t.name);e&&await r.nextWidget(e,{type:n.data.type,value:n.data.value})}}},getInputNames:xn,getOutputNames:e=>{const t={...En(),...e},n=t.outputs.map(((e,t)=>({name:Pe("outer","output",e.name),type:e.type,...e.jsonShape?{jsonShape:e.jsonShape}:void 0,...e.position?{position:e.position}:void 0,label:e.label,isInner:!1,index:t})));return[...t.inputs.map(((e,t)=>({name:Pe("inner","input",e.name),type:e.type,...e.jsonShape?{jsonShape:e.jsonShape}:void 0,...e.position?{position:e.position}:void 0,label:e.label,isInner:!0,index:t+n.length}))),...n]},getDefaultState:En};const Nn=(e,t,n,r,s)=>{const i=4*(t*n.width+e),o=n.data[i],a=n.data[i+1],c=n.data[i+2];return Math.abs(o-r.r)<=s&&Math.abs(a-r.g)<=s&&Math.abs(c-r.b)<=s};var On,Ln,Pn,Tn,Bn,jn,Dn,Un,Mn,Fn,Rn={getPixelValueAtIndex:(e,t)=>{const n=e.data,r=n[t]||0,s=n[t+1]||0,i=n[t+2]||0;return{avr:(r+s+i)/3,r:r,g:s,b:i}},getBoundingBox:(e,t,n)=>{const r=e.width,s=e.height,i=new Set,o=Number(n.threshold||0),a=isNaN(o)?10:o,c=(n,o)=>{const c=[[n,o]];let l=n,u=n,d=o,p=o;for(;c.length>0;){const n=c.shift();if(!n)continue;const[o,h]=n;o<0||h<0||o>=r||h>=s||i.has(`${o},${h}`)||!Nn(o,h,e,t,a||0)||(i.add(`${o},${h}`),l=Math.min(l,o),u=Math.max(u,o),d=Math.min(d,h),p=Math.max(p,h),c.push([o+1,h],[o-1,h],[o,h+1],[o,h-1]))}return{minX:l,maxX:u,minY:d,maxY:p}},l=[];for(let o=0;o<s;o+=4)for(let s=0;s<r;s+=4)if(!i.has(`${s},${o}`)&&Nn(s,o,e,t,a)){const{minX:e,maxX:t,minY:r,maxY:i}=c(s,o),a=t-e,u=i-r;if(a>=(n.minWidth||1)&&u>=(n.minHeight||1)&&l.push({left:e,top:r,width:a,height:u}),n.maxBoxes&&l.length>=n.maxBoxes)return l}return l},copyImageData:e=>new ImageData(new Uint8ClampedArray(e.data),e.width,e.height),setPixelValueAtIndex:(e,t,n)=>{const r=e.data,s="object"==typeof n,i=s?n.r:n,o=s?n.g:n,a=s?n.b:n;r[t]=i,r[t+1]=o,r[t+2]=a,r[t+3]=255}};!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(On||(On={})),function(e){e.Bundle="bundle",e.Group="group"}(Ln||(Ln={})),function(e){e.Hardware="hardware",e.Virtual="virtual"}(Pn||(Pn={})),function(e){e.Cloud="cloud",e.Web="web"}(Tn||(Tn={})),function(e){e.Cpu_128M="kmu-cpu-128m",e.Cpu_256M="kmu-cpu-256m",e.Cpu_512M="kmu-cpu-512m",e.Cpu_1024M="kmu-cpu-1024m",e.Cpu_2048M="kmu-cpu-2048m",e.Cpu_4096M="kmu-cpu-4096m"}(Bn||(Bn={})),function(e){e.Gateway="gateway",e.Timer="timer"}(jn||(jn={})),(Dn||(Dn={})).InstallInProgress="installation-in-progress",function(e){e.InstallDependencies="install-dependencies",e.GetInstalledDependencies="get-installed-dep"}(Un||(Un={})),function(e){e.Success="success",e.Error="error",e.Pending="pending"}(Mn||(Mn={})),function(e){e.NotFound="not-found",e.BadRequest="bad-request",e.Forbidden="forbidden",e.InternalError="internal-error"}(Fn||(Fn={}));let Wn=null;var Gn=()=>{if(!Wn)throw new Error("Required function is not set");return Wn};class Vn extends Error{constructor(e,t){super(e),this.name="UserCodeError",t&&(this.stack=t)}}const Hn=(e,t)=>`\n\t\tfunction _user_code_(){\n\t\t\t${t===On.Browser?"\n\t\t\tvar global = {\n\t\t\t\t__user_code: true\n\t\t\t};\n\t\t\tvar process = {};\n\t\t\tvar console = this.console;\n\t\t\tvar globalThis = global;\n\t\t\tvar require = this.___notSupportedMethod;\n\t\t\t":"\n\t\t\tvar require = this.require;\n\t\t\tvar process = this.kemuProcess;\n\t\t\t"}\n\n\t\t\tvar eval = () => {};\n\t\t\tvar document = {};\n\t\t\tvar navigator = {};\n\t\t\tvar window = this.window;\n\t\t\tvar alert = this.notify.info;\n\t\t\tvar DataType = this.dataTypesEnum;\n\t\t\tvar setInterval = this.setInterval;\n\t\t\tvar setTimeout = this.setTimeout;\n\t\t\tvar addEventListener = this.addEventListener;\n\t\t\tvar removeEventListener = this.removeEventListener;\n\t\t\tvar requestAnimationFrame = this.___notSupportedMethod;\n\t\t\tvar __delay = (ms) => new Promise((resolve, reject) => setTimeout(resolve, ms, reject));\n\n\t\t\tvar Kemu = {\n\t\t\t\tservices: {\n\t\t\t\t\thttp: { ...this.httpWebService },\n\t\t\t\t\tdynamoDb: { ...this.dynamoService },\n\t\t\t\t\tgoogleSheets: {\n\t\t\t\t\t\t...this.googleSheetsService,\n\t\t\t\t\t}\n\t\t\t\t},\n\n\t\t\t\timage: this.imageHelpers,\n\t\t\t\tvariable: this.variablesManager,\n\n\t\t\t\thelpers: {\n\t\t\t\t\tcryptoJS: this.CryptoJS,\n\t\t\t\t\tjsonp: this.jsonp,\n\t\t\t\t\tdelay: __delay,\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tvar sendToPort;\n\n\t\t\t// --- User Methods Start ---\n\t\t\t${e||""};\n\t\t\t// --- User Methods End ---\n\t\t\t\n\t\t\t// Processes the user code asynchronously.\n\t\t\tconst asyncProcessEvent = async (targetPort, sourcePort, event) => {\n\t\t\t\tconst userProcessEvent = typeof processEvent === 'undefined' ? undefined : processEvent;\n\t\t\t\tif(userProcessEvent) {\n\t\t\t\t\ttry{\n\t\t\t\t\t\treturn await userProcessEvent(targetPort, sourcePort, event, sendToPort);\n\t\t\t\t\t}catch(e){\n\t\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/** invoked the very first time the recipe is initialized */\n\t\t\tconst asyncRecipeInit = async (context, logger) => {\n\t\t\t\ttry {\n\t\t\t\t\t${t===On.Browser?"if(logger) { console = logger; }":""}\n\t\t\t\t\tif(typeof recipeInit === 'function') {\n\t\t\t\t\t\treturn recipeInit(context);\n\t\t\t\t\t}\n\t\t\t\t}catch(e){\n\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/** invoked every time the code is about to be replaced */\n\t\t\tconst asyncOnTerminate = async (context) => {\n\t\t\t\ttry {\n\t\t\t\t\tif(typeof onTerminate === 'function') {\n\t\t\t\t\t\treturn onTerminate(context);\n\t\t\t\t\t}\n\t\t\t\t}catch(e){\n\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/** updates the function that allows widget contexts to send data to the next widget */\n\t\t\tconst setSendToPort = (sendNextFun) => {\n\t\t\t\tsendToPort = sendNextFun;\n\t\t\t}\n\n\t\t\t/** invoked the every time the user code is compiled. */\n\t\t\tconst asyncMainEvent = async (sendNextFun, logger) => {\n\t\t\t\ttry{\n\t\t\t\t\tsetSendToPort(sendNextFun);\n\t\t\t\t\tif(logger) { console = logger; }\n\t\t\t\t\tif(typeof main === 'function'){\n\t\t\t\t\t\treturn main();\n\t\t\t\t\t}\n\t\t\t\t}catch(e){\n\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tasyncProcessEvent: asyncProcessEvent,\n\t\t\t\tmain: asyncMainEvent,\n\t\t\t\trecipeInit: asyncRecipeInit,\n\t\t\t\tsetSendToPortFun: setSendToPort,\n\t\t\t\tonTerminate: asyncOnTerminate,\n\t\t\t\tgetLocalContext: () => global,\n\t\t\t\tgetWidgetInputs: typeof getWidgetInputs === 'undefined' ? undefined : getWidgetInputs,\n\t\t\t\tgetWidgetOutputs: typeof getWidgetOutputs === 'undefined' ? undefined : getWidgetOutputs,\n\t\t\t};\n\t\t}\n\t\t\n\t\treturn function compiler(context){\n\t\t\treturn _user_code_.call(context)\n\t\t}\n\n\t\treturn compiler;\n\t`,zn=(e,t,n,r)=>{const o=Hn(e,n),a={...t,document:{},__errorTracer:e=>{throw new Vn(e.message,e.stack)},__jest:void 0===globalThis.__jest?void 0:globalThis.__jest,___notSupportedMethod:()=>r?.error("This method is not supported."),console:console,setInterval:()=>r?.error("'setInterval' is not supported. Please use a \"Timer\" widget instead."),setTimeout:t?.setTimeout,imageHelpers:Rn,...n===On.Cloud?{require:Gn(),kemuProcess:process.env.KEMU_PROCESS?process.env.KEMU_PROCESS:{}}:{},jsonp:s,CryptoJS:i,window:{addEventListener:t?.addEventListener,removeEventListener:t?.removeEventListener}};try{const e="browser"===(()=>{if(me)return"browser";if(ye)return"node";if(ve)return"worker";throw new Error("Unsupported environment")})()?(e=>e.replace(/[//]{2}[ ]*@kemu-cloud[ \t]*\{[\s\S]*?[//]{2}[ ]*@kemu-cloud[ \t]*\}/gim,""))(o):(e=>e.replace(/[//]{2}[ ]*@kemu-browser[ \t]*\{[\s\S]*?[//]{2}[ ]*@kemu-browser[ \t]*\}/gim,""))(o),t=new Function(e);return{compiledModule:t()(a)}}catch(e){return{error:{name:"CompileError",message:e.message,stack:e.stack}}}},qn="main",Kn=()=>({pauseExecution:!1,autoPauseOnError:!0,$$eventListeners:{},pages:{[qn]:{code:"\nconst getWidgetInputs = () => [\n\t{ name: 'Input 1', type: DataType.Number }\n];\n\nconst getWidgetOutputs = () => [\n\t{ name: 'Output 1', type: DataType.Number }\n]\n\nlet counter = 0;\n\nconst processEvent = async (targetPort, sourceWidget, event) => {\n\tif(targetPort.name === 'Input 1'){\n\t\treturn sendToPort('Output 1', {\n\t\t\ttype: DataType.Number,\n\t\t\tvalue: counter++,\n\t\t});\n\t}\n}\n",language:"javascript",name:"My First Script"}},consoleVisible:!1,$$consoleLines:[]}),Jn=(e,t)=>{const n={message:"Unknown Error"};if(e?.stack){const r=e?.stack?.split(":")[0].trim();n.type=r;const s=(e=>{const t=/,[ ]?<anonymous>:([0-9]+:[0-9]+)\)/gm;let n;for(;null!==(n=t.exec(e));){n.index===t.lastIndex&&t.lastIndex++;const e=n[1].split(":");if(2===e.length)return{line:Number(e[0])||0,column:Number(e[1])||0}}return null})(e.stack);s&&(n.line=s.line-(e=>{const t="___user_code_section___";return Hn(t,e).split(t)[0].split("\n").length+2})(t),n.column=s.column)}return e.message&&(n.message=e.message),n},Yn=(e,t)=>{const n={...Kn(),...t.getState()},r={...n,...e?{$$error:e}:void 0,...n.autoPauseOnError&&e?{pauseExecution:!0}:void 0};e&&(r.$$consoleLines=[...r.$$consoleLines,{type:"error",text:e.message,timestamp:Date.now(),fileName:qn}]),t.setState(r)};var Xn,Zn;!function(e){e.ServiceCreationLog="service-creation-log"}(Xn=Xn||(Xn={})),function(e){e.Service="service",e.ServiceUI="serviceUI"}(Zn=Zn||(Zn={}));const Qn=new a,er=(e,t,n)=>{const r=Q(e,t);if(!r)throw new Error(`Thing ${t} not found in recipe ${e}`);const s=r.gates[n];if(!s)throw new Error(`Widget ${n} not found in thing ${t}`);return s},tr=(e,t,n)=>`${t}:${n}:${e}`,nr=e=>`${e}:new-var`,rr=async(e,t,n,r,s,i,o)=>{const a={...o},c={thingId:n,recipeId:t,variableName:e,changes:i,ownerId:r,callerWidgetId:s,varDefinition:Object.freeze(a)};if(i.includes("added")){const e=nr(n);return Qn.emit(e,c)}{const t=tr(e,n,r);return Qn.emit(t,c)}},sr=(e,t,n,r)=>{const s=er(e,t,r);s.variablesListener={...s.variablesListener,[n]:0},or(e,t)},ir=(e,t,n,r)=>{const s=er(e,t,r),i={...s.variablesListener};void 0!==s.variablesListener?.[n]&&(delete i[n],s.variablesListener=i)},or=async(e,t)=>{const n=Q(e,t);if(!n)throw new Error(`Thing "${t}" not found in recipe "${e}"`);const r={...n.variables},s=Object.keys(r);for(const i of s){const s=r[i],o=Object.keys(s);for(const s of o){!n.gates[s]&&(delete r[i][s],await rr(i,e,t,s,void 0,["removed"],null))}0===Object.keys(r[i]).length&&delete r[i]}n.variables=r},ar=(e,t,n)=>{for(const r in t){const s=t[r];if(s.createdByWidgetId===e.id)return s;if(e.type===De.variable&&s.ownerType===De.variable)return s;if(e.type===De.script){const t=s.createdByWidgetId===e.groupId,r=n[s.createdByWidgetId];if(!r)continue;const i=r.groupId===e.groupId;if(t||r.type===De.variable&&i)return s}}return null};var cr=async(e,t,n,r,s,i)=>{const o=Q(e,t);if(!o)throw new Error(`Thing ${t} not found in recipe ${e}`);const a={...o.variables};a[r]=a[r]||{};const c=a[r],l=o.gates[n];if(!l)throw new Error(`Widget ${n} not found in thing ${t}`);const u=Object.values(c);let d=!1,p=!1;const h=async s=>rr(r,e,t,s.createdByWidgetId,n,["value"],s);if(l.type===De.variable){d=!0;for(const e of u)e.ownerType===De.variable&&e.type===s.type&&(e.value=s.value,p=!0,await h(e))}if(l.type===De.script){d=!0;for(const e of u){const t=e.createdByWidgetId===l.groupId,n=o.gates[e.createdByWidgetId],r=n?.type===De.variable,i=n?.groupId===l.groupId;(t||r&&i)&&e.type===s.type&&(e.value=s.value,p=!0,await h(e))}}if(!d){d=!0;for(const e of u){e.createdByWidgetId===n&&e.type===s.type&&(e.value=s.value,p=!0,await h(e))}}if(!i?.skipNotifications&&p){const a=Object.values(o.gates);for(const o of a){if(o.id===n&&i?.skipCallerNotification)continue;const a=o.variablesListener?.[r];void 0!==a&&await ei(o.id,t,e,`${oe}${r}`,s)}}},lr=(e,t,n,r)=>{const s=Q(e,t);if(!s)throw new Error(`Thing ${t} not found in recipe ${e}`);if(!r.readerWidgetId&&!r.ownerWidgetId)throw new Error("readerWidgetId or ownerWidgetId must be provided");const i={...s.variables}[n];if(!i)return;if(r.ownerWidgetId){const e=i[r.ownerWidgetId];return e?.value}const o=s.gates[r.readerWidgetId];if(!o)throw new Error(`Widget ${r.readerWidgetId} not found in thing ${t}`);const a=ar(o,i,s.gates);return a?a.value:null},ur=sr,dr=ir;const pr="setTimeout",hr="variableChanged",fr=e=>{const{recipePoolId:t,thingId:n,scriptWidgetId:r}=e;if(!ee(t,n,r))throw new Error(`Widget "${r}" not found in recipe "${t}"`);return{get:(e,s)=>{const i=lr(t,n,e,{readerWidgetId:r});if(null===i){if(void 0===s)throw new Error(`Variable "${e}" is not defined`);return s}return i},set:async(e,s)=>{await cr(t,n,r,e,{type:Oe(s),value:s})},onValueChange:(s,i)=>{if(!e.setState)return void console.warn("Cannot subscribe to variable changes without a setState function");ur(t,n,s,r);const o={...Kn(),...e.getState()};o.$$eventListeners[s]={handler:i,abort:async()=>{dr(t,n,s,r)},name:hr},e.setState(o)}}},gr="__command-compile__";let mr;const vr=()=>{console.log("Method not implemented")},yr=(e,t,n)=>{const s=(e,...n)=>{const r={...Kn(),...t.getState()}.$$eventListeners[e];r&&r.handler(n)},i={};return Object.keys(le).forEach((e=>{i[e]=le[e]})),{dataTypesEnum:i,notify:{success:e=>{t.getState()?.$$managedUI?.notify?.success(e)},error:e=>{t.getState()?.$$managedUI?.notify?.error(e)},info:e=>{t.getState()?.$$managedUI?.notify?.info(e)}},variablesManager:e.variablesManager?fr({recipePoolId:n.recipePoolId,scriptWidgetId:n.widgetId,thingId:n.thingId,getState:t.getState,setState:t.setState}):{get:vr,set:async()=>vr(),onValueChange:vr},setTimeout:(n,s,i)=>{if(e.withTimers&&t&&t.setState&&t.registerInterrupt){const e=r(),o={...Kn(),...t.getState()};o.$$eventListeners[e]={handler:n,rejectHandler:i,name:pr},t.setState(o),t.registerInterrupt("timeout",e,{timeout:s},void 0,e)}},addEventListener:(e,n)=>{if(t.setState){const i=r(),o={...Kn(),...t.getState()};o.$$eventListeners[i]={handler:n,name:e},t.setState(o),window.addEventListener(e,s.bind(i))}else console.warn(`Cannot remove event listener '${e}' because the widget context is not available.`)},removeEventListener:(e,n)=>{if(t.setState){const r={...Kn(),...t.getState()},s=Object.keys(r.$$eventListeners).find((t=>r.$$eventListeners[t].name===e&&r.$$eventListeners[t].handler===n));t.setState(r),s&&removeEventListener(r.$$eventListeners[s].name,r.$$eventListeners[s].handler)}else console.warn(`Cannot remove event listener '${e}' because the widget context is not available.`)}}},br=(e,t,n,r)=>{const s={...Kn(),...n.getState()},i=s.pages[qn].$$compiledCode;if(i)return{compiledModule:i};{const i=yr(e,n,t);return zn(s.pages[qn].code,i,n.recipeType,r)}},Sr=e=>e.map((e=>({...e,name:e.name.replace("_","")}))),wr=async(e,t)=>{const n={...e};for(const r in e){if(e[r].name===pr){const e=n[r]?.rejectHandler;if("function"==typeof e)try{await e("TIMER_ABORTED")}catch(e){console.log("Error in reject interrupt handler: ",e)}t.cancelInterrupt(r),delete n[r]}}return n},Ir=async(e,t,n)=>{let r={...Kn(),...e.getState()};if(void 0!==n){r.pages[qn]?.$$compiledCode?.onTerminate&&await(r.pages[qn].$$compiledCode?.onTerminate());let t=await wr(r.$$eventListeners,e);t=await(async e=>{const t={...e};for(const n in e)if(e[n].name===hr){const r=e[n]?.abort;if("function"==typeof r)try{await r()}catch(e){console.log("Error in abort interrupt handler: ",e)}delete t[n]}return t})(t),r.$$eventListeners=t,r.$$error=void 0,r.pages[qn].$$compiledCode=void 0,r.pages[qn].code=n,e.setState({...r})}const s=!r.pages[qn].$$compiledCode,{compiledModule:i,error:o}=br({variablesManager:!0,withTimers:!0},{recipePoolId:e.recipePoolId,thingId:e.thingRecipeId,widgetId:e.id},{getState:e.getState,setState:e.setState,recipeType:e.recipeType,registerInterrupt:e.registerInterrupt});if(o){console.log("Failed to compile user code");const t=Jn(o,e.recipeType);return Yn(t,e),null}if(i){const n=(e=>{const t=(t,n)=>{if(mr)try{return mr[t](n)}catch(e){return void console.log("Error in custom logger: ",e)}const r={...Kn(),...e.getState()},s=[...r.$$consoleLines||[]];s.push({fileName:qn,text:n,type:t,timestamp:Date.now()}),s.length>100&&s.splice(0,30),e.setState({...r,$$consoleLines:s})},n={log:e=>{t("log",e)},error:e=>{t("error",e)},warn:e=>{t("warn",e)},info:e=>{t("info",e)}};return n})(e);let o;if(r={...e.getState()},r.pages[qn].$$compiledCode=i,e.nextGate&&i.setSendToPortFun(e.nextGate),t)try{await i.recipeInit({setState:e.setState,getState:e.getState},n)}catch(t){o=Jn(t,e.recipeType)}if(e.nextGate&&s)try{await i.main(e.nextGate,n)}catch(t){o=Jn(t,e.recipeType)}r.$$lastInputs=i.getWidgetInputs?i.getWidgetInputs():[],r.$$lastOutputs=i.getWidgetOutputs?i.getWidgetOutputs():[],e.setState(r),Yn(o,e)}};var _r={onParentEvent:async(e,t,n,r)=>{const s=r.getState(),i={...Kn(),...s};if(!i.pages[qn])return console.warn("Missing default page");if(i.pauseExecution){if(Object.keys(i.$$eventListeners).length){const e=await wr(i.$$eventListeners,r);r.setState({...i,$$eventListeners:e})}return}if(Ee(e?.name||""))return i.$$eventListeners[t.name]?(await i.$$eventListeners[t.name].handler(),i.$$eventListeners[t.name].name===pr&&delete i.$$eventListeners[t.name],void r.setState({...i})):void console.log(`Unknown interrupt id [${t.name}] `);if(t.name.startsWith(oe)){const e=t.name.replace(oe,""),r=n.data.value,s=i.$$eventListeners[e];return void(s?.handler&&await s.handler(r))}const o=t.name===gr;await Ir(r,!1,o?n.data.value:void 0);const a=i.pages[qn].$$compiledCode;if(e&&e.name!==gr&&a){let s;try{await a.asyncProcessEvent(t,e,n)}catch(e){"UserCodeError"===e.name&&(s=Jn(e,r.recipeType))}Yn(s,r)}},getInputNames:(e,t)=>{const n={...Kn(),...e},{compiledModule:r}=br({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetInputs){const e=r.getWidgetInputs();return Sr(e)}return e.$$lastInputs||[]},getOutputNames:(e,t)=>{const n={...Kn(),...e},{compiledModule:r}=br({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetOutputs){const e=r.getWidgetOutputs();return Sr(e)}return e.$$lastOutputs||[]},getDefaultState:Kn,initialize:async e=>{const t=e.getState(),n={...Kn(),...t};n.pages[qn].code&&await Ir({getState:e.getState,id:e.widgetThingId,recipePoolId:e.recipePoolId,recipeType:e.recipeType,registerInterrupt:e.registerInterrupt,setState:e.setState,thingRecipeId:e.thingRecipeId,cancelInterrupt:()=>!0},!0,n.pages[qn].code)}};const $r=async(e,t,n,r)=>{e.startsWith("data:image/")||(e=`data:image/png;base64,${e}`);const s=await Cr(e);return((e,t,n,r)=>{const s=r.getContext("2d");if(!s)throw new Error("Failed to get canvas context");const i=e.width,o=e.height;return r.width=t,r.height=n,s.drawImage(e,0,0,i,o,0,0,t,n),s.getImageData(0,0,t,n)})(s,n||s.naturalWidth,r||s.naturalHeight,t)},Cr=e=>new Promise(((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=e=>n(e),r.src=e})),kr=Object.freeze({image:"image"}),Er=Object.freeze({base64:"base64"}),xr=()=>({});var Ar={onParentEvent:async(e,t,n,r)=>{const s={...r.getState()};if(t.name===Er.base64){if("string"!=typeof n.data.value)return;if(n.data.type!==le.String&&n.data.type!==le.Anything)return;const e=n.data.value;me&&(s.$$memCanvas&&s.$$memCanvas.getContext||(s.$$memCanvas=jt(320,240)));try{const t=await $r(e,s.$$memCanvas,s.resize?.width,s.resize?.height);return r.setState(s),r.nextGate(kr.image,{type:le.ImageData,value:t})}catch(e){console.log("[base64ToImageData] Error: ",e)}}},getInputNames:()=>[{name:Er.base64,type:le.String}],getOutputNames:()=>[{name:kr.image,type:le.ImageData}],getDefaultState:xr};const Nr=Object.freeze({object:"object",error:"error"}),Or=Object.freeze({string:"string"}),Lr=()=>({outputIsArray:!1});var Pr={onParentEvent:async(e,t,n,r)=>{const s={outputIsArray:!1,...r.getState()};if((n.data.type===le.String||n.data.type===le.Anything)&&"string"==typeof n.data.value)try{const e=JSON.parse(n.data.value),t=Array.isArray(e);return t&&!s.outputIsArray?r.setState({...s,outputIsArray:!0}):!t&&s.outputIsArray&&r.setState({...s,outputIsArray:!1}),r.nextGate("object",{type:t?le.Array:le.JsonObj,value:e})}catch(e){return r.nextGate("error",{type:le.Boolean,value:!0})}},getInputNames:()=>[{name:Or.string,type:le.String}],getOutputNames:e=>[{name:Nr.object,type:[le.JsonObj,le.Array],label:e.outputIsArray?"array":Nr.object},{name:Nr.error,type:le.Boolean}],getDefaultState:Lr};const Tr=Object.freeze({string:"string",length:"length"}),Br=Object.freeze({trigger:"trigger",setText:"setText"}),jr=()=>({text:"",dispatchOnSet:!1});var Dr={onParentEvent:async(e,t,n,r)=>{const s={text:"",dispatchOnSet:!1,...r.getState()};if(t.name===Br.setText){if(!((n.data.type===le.String||n.data.type===le.Anything)&&"string"==typeof n.data.value))return;if("string"==typeof n.data.value&&(s.text=n.data.value,r.setState(s)),!s.dispatchOnSet)return}const i=r.nextGate(Tr.length,{type:le.Number,value:s.text.length}),o=r.nextGate(Tr.string,{type:le.String,value:s.text});await Promise.all([i,o])},getInputNames:e=>{const t=[{name:Br.setText,type:le.String}];return e.dispatchOnSet||t.push({name:Br.trigger,type:le.Anything}),t},getOutputNames:()=>[{name:Tr.string,type:le.String},{name:Tr.length,type:le.Number}],getDefaultState:jr};const Ur=Object.freeze({image:"image"}),Mr=Object.freeze({image:"image",x:"x",y:"y",width:"width",height:"height"}),Fr=()=>({showInputPorts:!1});var Rr={onParentEvent:async(e,t,n,r)=>{const s={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===Mr.x&&(s.cropX=n.data.value),t.name===Mr.y&&(s.cropY=n.data.value),t.name===Mr.width&&(s.cropWidth=n.data.value),t.name===Mr.height&&(s.cropHeight=n.data.value),void r.setState(s);if(t.name===Mr.image){if(n.data.type!==le.ImageData&&n.data.type!==le.Anything)return;if(!xe(n.data.value))return;const e=n.data.value;if(s.$$memCanvas&&s.$$memCanvas.getContext||(s.$$memCanvas=jt(320,240),s.$$memCanvasContext=Dt(s.$$memCanvas),r.setState(s)),!s.$$memCanvas||!s.$$memCanvasContext)return void console.error("Failed to get canvas or context");let t=e;return s.$$memCanvas.width=e.width,s.$$memCanvas.height=e.height,(s.cropX||s.cropY||s.cropWidth||s.cropHeight)&&(t=((e,t,n,r)=>{if(!n)return e;const s=Math.max(r.x||0,0),i=Math.max(r.y||0,0),o=e.width,a=e.height,c=Math.min(Math.ceil(r.width||o),o),l=Math.min(Math.ceil(r.height||a),a);return t.width=e.width,t.height=e.height,n.putImageData(e,0,0),n.drawImage(t,s,i,c,l,0,0,c,l),n.getImageData(0,0,c,l)})(e,s.$$memCanvas,s.$$memCanvasContext,{x:s.cropX,y:s.cropY,width:s.cropWidth,height:s.cropHeight})),r.nextGate(Ur.image,{type:le.ImageData,value:t})}},getInputNames:e=>{const t=[{name:Mr.image,type:[le.ImageData]}];return e.showInputPorts&&(t.push({name:Mr.x,type:le.Number}),t.push({name:Mr.y,type:le.Number}),t.push({name:Mr.width,type:le.Number}),t.push({name:Mr.height,type:le.Number})),t},getOutputNames:()=>[{name:Ur.image,type:le.ImageData}],getDefaultState:Fr};const Wr=Object.freeze({image:"image"}),Gr=Object.freeze({image:"image",width:"width",height:"height"}),Vr=()=>({showInputPorts:!1});var Hr={onParentEvent:async(e,t,n,r)=>{const s={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===Gr.width&&(s.width=n.data.value),t.name===Gr.height&&(s.height=n.data.value),void r.setState(s);if(t.name===Gr.image){if(n.data.type!==le.ImageData&&n.data.type!==le.Anything)return;if(!xe(n.data.value))return;const e=n.data.value;if(s.$$memCanvas&&s.$$memCanvas.getContext||(s.$$memCanvas=jt(320,240),r.setState(s)),!s.$$memCanvas)return;let t=e;return(s.width||s.height)&&(t=((e,t,n,r)=>{if(!n&&!r)return e;n&&!r?r=n*(e.height/e.width):!n&&r&&(n=r*(e.width/e.height));const s=Math.max(1,n||e.width),i=Math.max(1,r||e.height);t.width=Math.max(e.width,s),t.height=Math.max(e.height,i);const o=Dt(t);if(!o)throw new Error("Failed to get canvas context");return o.putImageData(e,0,0),o.drawImage(t,0,0,e.width,e.height,0,0,s,i),o.getImageData(0,0,s,i)})(e,s.$$memCanvas,s.width,s.height)),r.nextGate(Wr.image,{type:le.ImageData,value:t})}},getInputNames:e=>{const t=[{name:Gr.image,type:le.ImageData}];return e.showInputPorts&&(t.push({name:Gr.width,type:le.Number}),t.push({name:Gr.height,type:le.Number})),t},getOutputNames:()=>[{name:Wr.image,type:le.ImageData}],getDefaultState:Vr};const zr=Object.freeze({value:"value"}),qr=Object.freeze({trigger:"trigger",setValue:"setValue"}),Kr=()=>({value:0,dispatchOnSet:!1});var Jr={onParentEvent:async(e,t,n,r)=>{const s={value:0,dispatchOnSet:!1,...r.getState()};if(t.name===qr.setValue){const e=n.data.type===le.Number||n.data.type===le.Anything||n.data.type===le.String,t=!isNaN(Number(n.data.value))&&!Array.isArray(n.data.value);if(!e||!t)return;if(s.value=Number(n.data.value),r.setState(s),!s.dispatchOnSet)return}return r.nextGate(zr.value,{type:le.Number,value:s.value})},getInputNames:e=>{const t=[{name:qr.setValue,type:le.Number}];return e.dispatchOnSet||t.push({name:qr.trigger,type:le.Anything}),t},getOutputNames:()=>[{name:zr.value,type:le.Number}],getDefaultState:Kr};const Yr=Object.freeze({image:"image"}),Xr=Object.freeze({image:"image"}),Zr=()=>({anchors:[],vertices:[],matrix:[]}),Qr={onParentEvent:async(e,t,n,r)=>{const s={anchors:[],vertices:[],matrix:[],...r.getState()},i=window,o=n.data.type===le.ImageData;if(i.Speedy&&o){const e=i.Speedy,t=n.data.value;let o,u,d,p=s.$$private?.canvas,h=s.$$private?.context,f={...s};const g=4===s.anchors.length;if(s.$$private?.pipeline)o=s.$$private?.pipeline,u=s.$$private?.source;else{o=e.Pipeline(),u=e.Image.Source();const n=e.Image.Sink();d=e.Transform.PerspectiveWarp(),p?p.width===t.width&&p.height===t.height||(p.width=t.width,p.height=t.height,h=p.getContext("2d")):(c=t.width,l=t.height,p=jt(c,l),h=p.getContext("2d")),u.output().connectTo(d.input()),d.output().connectTo(n.input()),o.init(u,n,d);let r=e.Matrix(3,3,[1,0,0,0,1,0,0,0,1]);if(4===s.anchors.length){const t=e.Matrix(2,4,[(a=s.anchors)[0].x,a[0].y,a[1].x,a[1].y,a[2].x,a[2].y,a[3].x,a[3].y]),n=e.Matrix(2,4,s.vertices.reduce(((e,t)=>e.concat([t.x,t.y])),[])),i=e.Matrix.Zeros(3,3);await e.Matrix.perspective(i,t,n);const o=i.read();r=e.Matrix(3,3,o)}d.transform=r,f={...f,$$private:{...f.$$private,canvas:p,context:h,perspective:d,pipeline:o,source:u}}}let m=t;if(g){const e=await(async(e,t)=>{const n=window,r=e.$$private?.source,s=e.$$private?.pipeline;if(n.Speedy&&r&&s){const e=n.Speedy,i=await createImageBitmap(t),o=await e.load(i);return r.media=o,(await s.run()).image.source}return null})(f,m);e&&(p&&h&&(m=((e,t,n)=>(t.width=e.width,t.height=e.height,n.drawImage(e,0,0),n.getImageData(0,0,e.width,e.height)))(e,p,h)),f.$$private&&r.setState({...f,$$private:{...f.$$private,lastInputImage:t}}))}else f.$$private&&r.setState({...f,$$private:{...f.$$private,lastInputImage:t}});return r.nextGate(Yr.image,{type:le.ImageData,value:m})}var a,c,l;console.log("Environment not supported")},getInputNames:()=>[{name:Xr.image,type:le.ImageData}],getOutputNames:()=>[{name:Yr.image,type:le.ImageData}],getDefaultState:Zr,terminate:async e=>{const t=e.getState();t.$$private?.pipeline.release()}},es=()=>({name:"Default widget bundle",description:"",inputs:[{dataType:[le.Anything],name:"input"}],outputs:[{dataType:[le.Anything],name:"output"}]});let ts;const ns=()=>{if(!ts)throw new Error(qe(ze));return ts};const rs=async e=>{const t=new c,n=await t.loadAsync(e),r={};for(const e in n.files)if(!n.files[e].dir){const t=await n.file(e);t&&(r[e]=await t.async("uint8array"))}return r},ss={};var is=e=>ss[e]||null;const os=async(e,t,n)=>{try{const r=ns(),s=n?r.loadBlobAsString:r.loadBlob;return await s(e,t)}catch(e){return null}},as=async e=>{const t=re;try{const n=await os(e,t,!0);if(!n)return null;return Function(n)()}catch(e){return null}},cs=async e=>{const t=se;try{const n=await os(e,t,!0);if(!n)return null;return JSON.parse(n)}catch(n){return console.log(`Failed to parse the bundle's state [${e}/${t}] %j`,n),null}},ls=(e,t)=>`${e.replace(ie,"")}_${t}`,us=(e,t)=>`widget/${e.replace(ie,"")}/v/${t}`,ds=async(e,t)=>{const n=ns(),[r]=await Promise.all([rs(e),n.createLocation(t)]);for(const e in r)e.startsWith("__MACOSX")||await n.saveBlob(t,e,r[e])},ps=(e,t)=>{const n=ls(e,t),r=is(n);return r?{...r}:null},hs=(e,t,n)=>{const r=`${`widget/${e.replace(ie,"")}/tmp`}/${t}`;if(n){return ns().getCacheLocation(r)}return r};var fs=ps,gs=async(e,t,n)=>{const r=hs(t,n);await ds(e,r);const s=as(r),i=cs(r),o=ns(),a=o.getCacheLocation(r),[c,l]=await Promise.all([s,i]);if(!c)return null;let u=l;if(!l){const e=es(),t=JSON.stringify(e);await o.saveBlob(r,se,ke(t)),u=e}return{cachePath:a,processor:c,storedState:Object.freeze(u)}},ms=(e,t,n)=>{if(n.isTempStorage)return hs(e,t,n.fullStorageRoot);const r=ns(),s=us(e,t);return n.fullStorageRoot?r.getCacheLocation(s):s};const vs=()=>es();var ys={onParentEvent:async(e,t,n,r)=>{const s=r.getState();return s.$$processor?.onParentEvent({sourcePort:e?.name||"",targetPort:t?.name||"",data:n.data},{getState:r.getState,recipeId:r.recipePoolId,recipeType:r.recipeType,setState:r.setState,nextWidget:r.nextGate})},getInputNames:(e,t)=>{const n={...vs(),...e};return n.$$processor?.getInputNames?n.$$processor.getInputNames(e,t):n.inputs.map((e=>({name:e.name,type:e.dataType})))},getOutputNames:(e,t)=>{const n={...vs(),...e};return n.$$processor?.getOutputNames?n.$$processor.getOutputNames(e,t):n.outputs.map((e=>({name:e.name,type:e.dataType})))},getDefaultState:vs,initialize:async(e,t)=>{console.log("Widget bundle initialize",e);let n={...e.getState()},r=n.$$cacheInfo?.widgetThingId||n.collectionInfo?.widgetId||e.widgetThingId;const s=n.$$cacheInfo?.version.toString()||n.collectionInfo?.version.toString()||1;if(n.$$cacheInfo={...n.$$cacheInfo,version:Number(s),widgetThingId:r},!r||!s)throw new Error("Widget bundle state is missing cache id or version");console.log("Loading state from cache");const i=fs(r,s);let o=!i;if(!n.$$processor)if(n.storageUnitId&&!i){const t=await e.getStorageData(n.storageUnitId);if(t){r=e.widgetThingId;const i=await gs(t,r,s);o=!0,i&&(n={...n,$$processor:i.processor,$$cacheInfo:{...n.$$cacheInfo,widgetThingId:r,version:Number(s)}},e.setState(n))}}else if(i){o=!1;const r=n.collectionInfo?{...n.collectionInfo}:void 0;n={...n,...!t.keepCurrentState&&i.storedState?{...i.storedState,...r?{collectionInfo:r}:{}}:{},$$processor:i.processor},e.setState(n)}const a=ms(r,s,{fullStorageRoot:!0,isTempStorage:o});console.log("Invoking bundle initialize with cache: ",a);try{await(n.$$processor?.initialize({cacheLocation:a,getState:e.getState,setState:e.setState}));const t=e.getState();e.setState({...t,$$initializationError:void 0})}catch(t){const n=e.getState();throw e.setState({...n,$$initializationError:t.message||"An error occurred initializing the widget"}),t}},terminate:async e=>{const t={...e.getState()};console.log(`Terminating widget bundle ${t.name} [${t.$$cacheInfo?.widgetThingId||""}]`);const n=t.$$processor;n&&"function"==typeof n.terminate&&await n.terminate({getState:e.getState,setState:e.setState,recipePoolId:e.recipePoolId,widgetId:e.widgetId})}};const bs=Object.freeze({event:"event"}),Ss="1",ws="2",Is="3";var _s={onParentEvent:async(e,t,n,r)=>{const s={...r.getState()};r.setState({...s,$$lastEventType:n.data.type}),await r.nextGate(Ss,n.data),await r.nextGate(ws,n.data),await r.nextGate(Is,n.data)},getInputNames:()=>[{name:bs.event,type:le.Anything}],getOutputNames:e=>{const t={type:{...e}.$$lastEventType??le.Anything};return[{name:Ss,...t},{name:ws,...t},{name:Is,...t}]}};const $s=Object.freeze({set:"set",trigger:"trigger"}),Cs="value";var ks={onParentEvent:async(e,t,n,r)=>{const s=r.getState(),i={name:"myVar",type:le.String,reactive:!0,defaultValue:"",...s};if(t.name.startsWith(oe)){if(!i.reactive)return;if(n.data.type!==i.type)return;return r.nextWidget(Cs,n.data)}if(t.name!==$s.set){if(t.name===$s.trigger){const e=lr(r.recipePoolId,r.thingRecipeId,i.name,{ownerWidgetId:r.id}),t=e||i.defaultValue;await r.nextWidget(Cs,{type:i.type,value:t})}}else await cr(r.recipePoolId,r.thingRecipeId,r.id,i.name,n.data,{skipCallerNotification:!i.reactive})},getInputNames:e=>{const t={...e};return[{name:$s.set,type:t.type||le.Anything},{name:$s.trigger,type:le.Anything}]},getOutputNames:e=>{const t={...e};return[{name:Cs,type:t.type||le.Anything}]}};let Es;var xs=e=>{Es=e},As=()=>{if(!Es)throw new Error("Hub Connector not set");return Es};const Ns=async(e,t=!1)=>{const n=As();let r=e.$$$serviceId;if(!e.service)return console.log("Aborting service initialization, missing property `service` in state."),null;if(!r||t){const t=await n.getCompatibleService(e.service.name,e.service.version,"^");if(!t)return null;r=t.sessionId}return r};var Os={onParentEvent:async(e,t,n,r)=>{const s={dynamicInputs:{},dynamicOutputs:{},customState:{},...r.getState()};if(!e)return;const i=As();let o=s.$$$serviceId;if(!o){const e=i.getCachedServices().available.find((e=>e.name===s.service?.name&&e.version===s.service?.version));if(!e)return;o=e.sessionId,s.$$$serviceId=o,r.setState(s)}const a=s.service?.variants?.find((e=>e.id===s.variantId)),c=a?s.dynamicInputs[a.id]||a?.inputs||[]:s.service?.inputs||[];if(!c?.length)return;if(!a&&s.service?.ignoreParentEvents)return;const l=s.service?.processingTimeoutSec;return i.onParentEvent({recipeId:r.recipePoolId,data:n.data,targetServiceSessionId:o,currentState:s.customState,targetVariantId:s.variantId,target:{portName:t.name,widgetId:r.id,widgetType:r.type},source:e,config:{timeout:l?1e3*l:0,async:s.service?.asyncParentEvents}})},getInputNames:async e=>{const t=e.variantId;if(t&&e.dynamicInputs?.[t])return[...e.dynamicInputs[t]||[]];if(!t)return e.service?.inputs||[];{const n=e.service?.variants?.find((e=>e.id===t));if(n)return n.inputs||[]}return[]},getOutputNames:async e=>{const t=e.variantId;if(t&&e.dynamicOutputs?.[t])return[...e.dynamicOutputs[t]||[]];if(!t)return e.service?.outputs||[];{const n=e.service?.variants?.find((e=>e.id===t));if(n)return n.outputs||[]}return[]},initialize:async e=>{const t={dynamicInputs:{},dynamicOutputs:{},customState:{},...e.getState()},n=As(),r=await Ns(t);if(r)try{return await n.initializeServiceInstance({recipeId:e.recipePoolId,sessionId:r,widgetId:e.widgetThingId,recipeType:e.recipeType,variantId:t.variantId})}catch(t){if("FNC_NOT_FOUND"!==t?.errCode){if(!!("string"!=typeof t||!t.match('^Function ".*" not found.$')))throw t;console.warn(`Widget [${e.widgetThingId}] does not have an init function.`)}}else console.log(`Aborting service initialization, "${t.service?.name}" was not found in the current Hub.`)},terminate:async e=>{const t={dynamicInputs:{},dynamicOutputs:{},customState:{},...e.getState()},n=As(),r=await Ns(t,!0);if(r)return n.terminateServiceInstance(r,e.widgetId,e.recipePoolId,t.variantId)}};const Ls=Object.freeze({Image:"image"}),Ps=Object.freeze({Image:"image"}),Ts=()=>({filters:[{name:"grayscale",value:.5,id:"d-1"}]});const Bs="loaded";const js={input:Ye,counter:Qe,elapsed:nt,ifGate:ot,skipEvent:lt,between:ht,map:mt,parser:bt,slider:It,suspend:Ct,display:Et,json:Nt,arrayItem:Pt,extractImage:Ft,imageConvolution:Ht,firstEvent:Jt,pixelDraw:tn,randomBetween:on,arrayCombine:dn,clock:gn,multiplication:bn,object:Cn,widgetGroup:An,script:_r,base64ToImageData:Ar,jsonParse:Pr,text:Dr,imageCrop:Rr,imageResize:Hr,value:Jr,imageWarp:Qr,widgetBundle:ys,sequence:_s,variable:ks,hubService:Os,imageFilter:{onParentEvent:async(e,t,n,r)=>{const s={filters:[{name:"grayscale",value:.5,id:"d-1"}],...r.getState()};if(t.name===Ls.Image&&n.data.type===le.ImageData){if(!xe(n.data.value))return void console.log("ImageFilter: Invalid image data type, aborting process");const e=n.data.value;s.$$memCanvas||(s.$$memCanvas=jt(e.width,e.height)),s.$$context||(s.$$context=s.$$memCanvas.getContext("2d")),s.$$memCanvas.width!==e.width&&(s.$$memCanvas.width=e.width),s.$$memCanvas.height!==e.height&&(s.$$memCanvas.height=e.height),r.setState(s),s.$$context.putImageData(e,0,0),s.filters.length?s.$$context.filter=s.filters.map((e=>`${e.name}(${e.value}${"blur"===e.name?"px":""})`)).join(" "):s.$$context.filter="none",s.$$context.drawImage(s.$$memCanvas,0,0);const t=s.$$context.getImageData(0,0,e.width,e.height);return r.nextWidget(Ps.Image,{type:le.ImageData,value:t})}},getInputNames:()=>[{name:Ls.Image,type:le.ImageData}],getOutputNames:()=>[{name:Ps.Image,type:le.ImageData}],getDefaultState:Ts},recipeLoad:{onParentEvent:async(e,t,n,r)=>r.nextWidget(Bs,{value:!0,type:le.Boolean}),getInputNames:()=>[],getOutputNames:()=>[{name:Bs,type:le.Boolean,description:"Triggered when the recipe is fully loaded"}]},play:{getInputNames:()=>[],onParentEvent:()=>Promise.resolve(),getOutputNames:()=>[{name:"out",type:le.Boolean}]}},Ds={},Us=async()=>{if(!Object.keys(Ds).length)for(const e in js){const t=js[e];Ds[e]=Object.freeze({...t})}};var Ms=e=>{if(Ds[e])return Ds[e];throw new Error(qe(He,e))},Fs=Us;const Rs=new a,Ws="invoked";let Gs={},Vs={},Hs={},zs={};const qs=(e,t,n)=>`${e}-${t}${n?`-${n}`:""}`;var Ks=(e,t,n,r,s)=>{const i=qs(e,t,n),o=qs(e,t),a=qs(e,t,"produced"),c=Hs[o],l=Date.now();zs[o]=l,Gs[i]={data:r,sourcePortName:n,...s?{target:{widgetId:s.widgetId,portName:s.portName}}:{}},Rs.emit(a,{currentTime:l,prevTime:c,...s?{targetPort:s?.portName}:{}})},Js=(e,t,n,r,s)=>{const i=qs(e,t,n),o=qs(e,t),a=qs(e,t,Ws),c=Hs[o],l=Date.now();Hs[o]=l,Vs[i]={data:r,sourcePortName:n,...s?{source:{widgetId:s.widgetId,portName:s.portName}}:{}},Rs.emit(a,{prevTime:c,currentTime:l,targetPort:n,sourceInfo:s})},Ys=()=>{Gs={},Vs={},Hs={},zs={},Rs.clearListeners()};let Xs,Zs,Qs;const ei=async(e,t,n,r,s)=>{const i=Q(n,t);if(!i)return;const o=i.gates[e];if(!o||o.disabled)return;const a={...s,timestamp:Date.now()},c=Ms(o.type),l=si(e,a,i.recipeId,i.id,i.version,n);if(l&&c.onParentEvent){const t={name:r};return Xs&&await Xs({recipeId:n,blockId:i.recipeId,gateId:e,targetPort:t.name,data:s}),c.onParentEvent(null,t,{originalEvent:a,data:{...a}},l)}},ti=async(e,t,n,r,s,i,o,a,c,l)=>{if(!e&&!c)throw new Error("Missing parameter ['sourceGateId']");if(!e&&!l)throw new Error("Missing parameter ['originalEvent']");e&&(l={timestamp:Date.now(),type:le.Boolean,value:!0});const u=l;if("string"==typeof n){const e=Q(r,n);if(!e)return;n=e}const d=n.gates[t];if(!d||d.disabled)return;const p=a.findIndex((e=>e.name===s)),h=Ms(d.type),f=si(t,u,n.recipeId,n.id,n.version,r);if(f&&h.onParentEvent&&-1!==p){Xs&&await Xs({recipeId:r,blockId:n.recipeId,gateId:t,targetPort:i.name,data:o,sourceGate:e?"interrupt_widget":c,sourcePort:e?ne:s});const l={name:a[p].name,type:a[p].type,...a[p].jsonShape?{jsonShape:a[p].jsonShape}:void 0};return Js(n.recipeId,t,i.name,o,c?{widgetId:c,portName:s}:void 0),h.onParentEvent(l,i,{originalEvent:u,data:o},f)}},ni=async(e,t,n,r,s,i,o,a)=>{const c=Z(a);if(!c)throw new Error(`Failed to find recipe "${a}" in cache`);const l=c.dbInfo.recipeType,u=ee(a,s,r);if(!u)return;const d={...n,timestamp:t.timestamp},p=Ms(u.type);let h;h=u.type===De.input?p.getOutputNames(u.state,{thingRecipeId:s,thingDbId:i,thingVersion:o,id:r,recipeId:a,recipeType:l,recipePoolId:a}):await p.getOutputNames(u.state,{recipePoolId:a,recipeType:l,thingRecipeId:s,widgetId:r});const f=h.findIndex((t=>t.name===e));if(-1!==f){const n=Q(a,s);if(!n)return;Ks(s,r,e,d);const i=u.children.length;for(let o=0;o<i;o++){if(Te(u.children[o]?.sourcePort).portName===e){const i=n.gates[u.children[o].childId];if(i&&!i.disabled){const c=Ms(i.type);let p;const f={recipePoolId:a,recipeType:l,thingRecipeId:s,widgetId:r};p=i.type===De.hubService?await c.getInputNames(i.state,f):c.getInputNames(i.state,f);const g=Te(u.children[o].targetPort),m=p.find((e=>e.name===g.portName));m&&await ti(!1,i.id,n,a,e,{name:m.name},u.returnOriginalEvent?t:d,h,u.id,t)}}}}},ri=async(e,t,n,r)=>{const s=Z(r);if(!s)return null;const i=Q(r,n);if(!i)return i;const o=i.gates,a=i.gates[t],c=Ms(a.type),l=await c.getInputNames(a.state,{recipePoolId:r,recipeType:s.dbInfo.recipeType,thingRecipeId:n,widgetId:t}),u=l.findIndex((t=>t.name===e));if(-1!==u){const e=((e,t,n)=>{for(const r in n){const s=n[r],i=s.children.length;for(let n=0;n<i;n++){const r=s.children[n],i=Te(r.targetPort);if(r.childId===e&&i.portName===t)return s}}return null})(t,l[u].name,o);if(e){const t=Ms(e.type);return{getValue:()=>"function"==typeof t.getValue?t.getValue():null}}}return null},si=(e,t,n,r,s,i)=>{const o=Z(i);if(!o)throw new Error(`Failed to find recipe "${i}" in cache`);const a=ee(i,n,e);if(!a)return console.warn(`Gate ${e} not found in block ${n} for recipe ${i}`),null;const c=async(o,a)=>ni(o,t,a,e,n,r,s,i),l={id:e,type:a.type,recipePoolId:i,thingRecipeId:n,recipeType:o.dbInfo.recipeType,returnOriginalEvent:!!a.returnOriginalEvent,registerInterrupt:(t,r,s,o,a)=>We.createInterrupt(t,i,n,e,r,s,o,a),cancelInterrupt:e=>We.destroyInterrupt(e),nextWidget:c,nextGate:c,getParentAtPort:t=>ri(t,e,n,i),getState:()=>Object.freeze({...a.state,...a.type===De.input&&{customInputs:[]}}),setState:t=>{if("object"!=typeof t)return void console.warn(`Invalid state type [${typeof t}]. Expected an 'object'`);const r={...t,...a.type===De.input&&!t.customInputs&&{customInputs:[]}},s={...a.state};a.state=r,Zs&&Zs({blockId:n,gateId:e,prevState:s,newState:{...r},recipeId:i})}};return l};We.setInvokeChildGateCb(ti);const ii=new a,oi="invoked",ai="state",ci=()=>{We.destroyAllInterrupts()},li=async(e,t,n)=>{const r=Z(e),s=ee(e,t,n);if(s&&r){const i=Ms(s.type);if(i&&"function"==typeof i.terminate){const s=((e,t,n,r)=>Ge(e,t,n,r))(e,r.dbInfo.recipeType,t,n);if(s)try{await i.terminate(s)}catch(e){console.warn(`Error terminating widget "${n}" in thing "${t}". Failing silently: `,e)}}}},ui=async(e,t,n,r)=>{const s=Z(e),i=ee(e,t,n);if(i&&s){const o=Ms(i.type);if(o&&"function"==typeof o.initialize){const i=((e,t,n,r)=>Ge(e,t,n,r,!0))(e,s.dbInfo.recipeType,t,n);if(i){const e=o.initialize;try{await e(i,r||{})}catch(e){throw console.warn(`Error initializing widget "${n}" in thing "${t}": `,e),e}}}}},di=(e,t)=>{const n=Z(t);if(n)for(const t in n.blocks){const r=n.blocks[t];for(const t in r.gates)if(t===e)return{widget:r.gates[t],thing:r}}return null},pi=(e,t="",n="")=>`block:${t}:gate:${n||""}:${e}`,hi=e=>{ii.emit(pi(ai),e),ii.emit(pi(ai,e.blockId,e.gateId),e)};Xs=async e=>{await ii.emit(pi(oi),e),await ii.emit(pi(oi,e.blockId,e.gateId),e)},(e=>{Zs=e})(hi);var fi,gi,mi,vi,yi,bi,Si,wi,Ii,_i,$i,Ci,ki,Ei=async(e,t,n,r,s)=>{const i=te(e,{id:t,authorId:r,version:n,recipeType:s});Ys();const o=Z(i);return o&&(o.startedAt=Date.now(),o.retryAttempts=0,o.execCounter=0,o.status=K.STARTING,o.addLog("recipe registered")),i},xi=async e=>{const t=Z(e);var n;if(!t)return null;t.addLog("terminating recipe"),ci();for(const n in t.blocks){const r=t.blocks[n];for(const t in r.gates)await li(e,n,t)}J[n=e]&&delete J[n]},Ai=async(e,t)=>{const n=Z(e),r=[],s=[];if(n)for(const i in n.blocks){const o=n.blocks[i];if(!t||!Array.isArray(t)||t.includes(i))for(const t in o.gates)try{if(n.dbInfo?.recipeType===On.Desktop){const e=o.gates[t];if(e.type===De.hubService){const r=e.state;if(r?.service?.webOnly){n?.addLog(`skipping initialization of web-only widget "${t}"`);continue}}e.type===De.recipeLoad&&s.push(e)}await ui(e,i,t,{keepCurrentState:!0})}catch(e){r.push({widgetId:t,error:e.message})}}return{failed:r,sendToInputWidget:(t,n,r=ae)=>(async(e,t,n,r)=>{const s=Z(n),i=Q(n,r),o=Date.now();if(i&&s)for(const s in i.gates){const a=i.gates[s];if(a.type===De.input&&!a.disabled){const c=a.state.inputName||"";if(c===e){const e=Ms(a.type),l={...t,timestamp:o},u=si(s,l,r,i.id,i.version,n);if(u&&e.processEvent){const i={...u,getState:u.getState};Xs&&await Xs({recipeId:n,blockId:r,gateId:s,targetPort:Je,data:t}),Qs?await Qs(r,n,c,t):await e.processEvent(l,i)}}}}})(t,n,e,r),invokeRecipeLoadedWidgets:async()=>{for(const t of s)await ei(t.id,ae,e,Bs,{type:le.Boolean,value:!0})}}},Ni=e=>{xs(e)},Oi=(e,t,n,r=!1)=>{const s=di(t,e);if(s){const{widget:i,thing:o}=s,a={...i.state};i.state=n,r&&hi({blockId:o.recipeId,gateId:t,recipeId:e,newState:{...n},prevState:a})}},Li=(e,t)=>{const n=di(t,e);return n?n.widget.state:null},Pi=async(e,t,n,r,s)=>{const i=di(t,e);if(i)return ni(n,r,s,t,i.thing.recipeId,i.thing.id,i.thing.version,e)};!function(e){e.Seats="seats",e.RecipeInvocations="recipe_invocations",e.HubServices="hub_services",e.RecipeExports="recipe_exports"}(fi||(fi={})),function(e){e.UserFriendlyName="user_friendly_name",e.UserFriendlyDescription="user_friendly_description",e.InternalDescription="internal_description",e.TierLevel="tier_level",e.ProductFeatures="product_features",e.UserSubscribeCode="subscription_code"}(gi||(gi={})),function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(mi||(mi={})),function(e){e.Bundle="bundle",e.Group="group"}(vi||(vi={})),function(e){e.Hardware="hardware",e.Virtual="virtual"}(yi||(yi={})),function(e){e.Cloud="cloud",e.Web="web"}(bi||(bi={})),function(e){e.Cpu_128M="kmu-cpu-128m",e.Cpu_256M="kmu-cpu-256m",e.Cpu_512M="kmu-cpu-512m",e.Cpu_1024M="kmu-cpu-1024m",e.Cpu_2048M="kmu-cpu-2048m",e.Cpu_4096M="kmu-cpu-4096m"}(Si||(Si={})),function(e){e.Gateway="gateway",e.Timer="timer"}(wi||(wi={})),function(e){e.InstallInProgress="installation-in-progress"}(Ii||(Ii={})),function(e){e.InstallDependencies="install-dependencies",e.GetInstalledDependencies="get-installed-dep"}(_i||(_i={})),function(e){e.Success="success",e.Error="error",e.Pending="pending"}($i||($i={})),function(e){e.NotFound="not-found",e.BadRequest="bad-request",e.Forbidden="forbidden",e.InternalError="internal-error"}(Ci||(Ci={})),function(e){e.KeyCreated="key_created",e.ValidateKey="validate_key",e.ExecuteRecipe="execute_recipe",e.InstallHubService="install_hub_service",e.ExportRecipe="export_recipe"}(ki||(ki={}));const Ti=e=>{try{return JSON.parse(e)}catch(e){return null}},Bi="undefined"!=typeof window,ji={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},Di={protocolPrefix:4,txtLength:4},Ui=Object.values(ji).reduce(((e,t)=>e+t),0),Mi=Object.values(Di).reduce(((e,t)=>e+t),0),Fi=["width","height","colorSpace"],Ri=(e,t)=>{const n={},r=[];let s=0,i=Array.isArray(e)?[]:{};const o=(e,i)=>{const a=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,s=e instanceof Uint8Array,i=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":s?"Uint8Array":i?"Int8Array":null})(e);if(!a){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=o(e[n],`${i}[${n}]`);return t}if("object"==typeof e){const t={},n=(e=>{const t=e instanceof Int16Array,n=e instanceof Uint16Array,r=e instanceof Int32Array,s=e instanceof Uint32Array,i=e instanceof Float32Array,o=e instanceof Float64Array,a=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":s?"Uint32Array":i?"Float32Array":o?"Float64Array":a?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${i}"`);for(const n in e)e.hasOwnProperty(n)||Fi.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${i}`),t[n]=o(e[n],`${i.length?`${i}.`:""}${n}`);return t}return e}n[i]={index:s,length:e.byteLength,binaryType:a},"Buffer"===t?r.push(Buffer.from(e)):"ArrayBuffer"===a?r.push(e):r.push(e.buffer),s+=e.byteLength};i=o(e,"");let a=null;if(r.length>1)if("ArrayBuffer"===t){const e=r.reduce(((e,t)=>e+t.byteLength),0),t=new Uint8Array(e);let n=0;for(let e=0;e<r.length;e++)t.set(new Uint8Array(r[e]),n),n+=r[e].byteLength;a=t.buffer}else{a=Buffer.concat(r)}else 1===r.length&&(a=r[0]);return a?{map:n,combinedData:a,sourceCopy:i}:null},Wi=(e,t,n)=>{const r=t.match(/(\[\d+\])|([^[\].]+)/g)||[];let s=e;for(let e=0;e<r.length;e++){let t=r[e];const i=t.startsWith("[")&&t.endsWith("]"),o=e===r.length-1;if(i){t=t.slice(1,-1);const i=parseInt(t,10);if(!Array.isArray(s))throw new Error(`Expected an array at key "${r.slice(0,e).join(".")}" but found an object.`);o?s[i]=n:(s[i]||(s[i]=r[e+1].startsWith("[")?[]:{}),s=s[i])}else o?s[t]=n:(s[t]||(s[t]=r[e+1].startsWith("[")?[]:{}),s=s[t])}return e},Gi=(e,t,n)=>{const r="undefined"!=typeof Buffer,s=t instanceof Uint8Array;for(const i in n)if(n.hasOwnProperty(i)){const{index:o,length:a,binaryType:c}=n[i];let l=null;if(r&&t instanceof Buffer)switch(c){case"Buffer":l=t.subarray(o,o+a);break;case"ArrayBuffer":l=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a);break;case"Uint8Array":l=new Uint8Array(t.subarray(o,o+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.subarray(o,o+a));break;case"Int8Array":l=new Int8Array(t.subarray(o,o+a))}else if(t instanceof ArrayBuffer||t instanceof Uint8Array)switch(c){case"Buffer":if(r){l=Buffer.from(t.slice(o,o+a));break}case"ArrayBuffer":l=s?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a):t.slice(o,o+a);break;case"Uint8Array":l=s?t.slice(o,o+a):new Uint8Array(t.slice(o,o+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.slice(o,o+a));break;case"Int8Array":l=new Int8Array(t.slice(o,o+a))}l&&Wi(e,i,l)}return e},Vi=e=>u(e),Hi="KMSG",zi="KCMD",qi=Vi("klProtocol");var Ki={encode:(e,t,n)=>{const r={json:e.json},s=Ri(r.json,"Buffer"),i=s?.combinedData;s&&(r.jsonBinaryMap=s.map,r.json=s.sourceCopy);const o=i?i.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),l=c.byteLength,u=ji.protocolPrefix+ji.protocolVersion+ji.jsonLength+ji.binaryLength+ji.fromServiceId+ji.toServiceId+ji.sentAt+l+o,d=Buffer.alloc(u),p=Date.now();let h=0;return d.write(Hi,h),h+=ji.protocolPrefix,d.writeUInt8(1,h),h+=ji.protocolVersion,d.writeUInt32LE(l,h),h+=ji.jsonLength,d.writeUInt32LE(o,h),h+=ji.binaryLength,d.writeUInt32LE(t,h),h+=ji.fromServiceId,d.writeUInt32LE(n,h),h+=ji.toServiceId,d.writeBigInt64LE(BigInt(p),h),h+=ji.sentAt,c.copy(d,h),h+=l,i&&o&&i.copy(d,h),d},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,ji.protocolPrefix);if(t+=ji.protocolPrefix,n!==Hi)return null;if(e.byteLength<Ui)return qi(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=ji.protocolVersion;const s=e.readUInt32LE(t);t+=ji.jsonLength;const i=e.readUInt32LE(t);t+=ji.binaryLength;const o=e.readUInt32LE(t);t+=ji.fromServiceId;const a=e.readUInt32LE(t);t+=ji.toServiceId;const c=e.readBigInt64LE(t);t+=ji.sentAt;const l=s+i,u=e.subarray(t,t+l),d=e.subarray(0,Ui);let p=null;return e.byteLength-Ui-s-i>0&&(p=e.subarray(Ui+s+i)),{header:{protocolVersion:r,jsonLength:s,binaryLength:i,fromServiceId:o,toServiceId:a,sentAt:new Date(Number(c)),packages:[u],headerPackage:d},remaining:p}},decodeFullKlMessage:e=>{const t=Buffer.concat(e.packages),n=t.subarray(0,e.jsonLength).toString(),r=t.subarray(e.jsonLength,e.jsonLength+e.binaryLength),s=Ti(n);if(!s?.json)return qi("Invalid JSON in KL message"),null;s.jsonBinaryMap&&r.byteLength&&Gi(s.json,r,s.jsonBinaryMap);const i=Buffer.concat([e.headerPackage,t]);let o=i,a=null;const c=Ui+e.jsonLength+e.binaryLength;return i.byteLength>c&&(a=i.subarray(c),o=i.subarray(0,c)),{message:{json:s.json,rawMessage:o},remaining:a}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Ui)return qi("Invalid Header Size"),e;let n=0;return n+=ji.protocolPrefix,n+=ji.protocolVersion,n+=ji.jsonLength,n+=ji.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=ji.fromServiceId,void 0!==t.toServiceId&&e.writeUInt32LE(t.toServiceId,n),e},encodeCommand:e=>{let t=0;const n=Buffer.from(e),r=n.byteLength,s=Mi+r,i=Buffer.alloc(s);return i.write(zi,t),t+=Di.protocolPrefix,i.writeUint32LE(r,t),t+=Di.txtLength,n.copy(i,t),i},decodeCommand:e=>{let t=0;if(e.byteLength<Mi)return{command:null};const n=e.toString("utf-8",t,Di.protocolPrefix);if(t+=Di.protocolPrefix,n!==zi)return{command:null};const r=e.readUInt32LE(t);t+=Di.txtLength;const s=e.toString("utf-8",t,t+r),i=e.byteLength-Mi-r;let o=null;i>0&&(o=e.subarray(Mi+r));let a=0;return i<0&&(a=Math.abs(i)),{command:s,remainingData:o,missing:a}}};const Ji="KMSG",Yi="KCMD",Xi=Vi("klProtocol"),Zi=new TextEncoder;var Qi={encode:(e,t,n)=>{const r={json:e.json},s=Ri(e.json,"ArrayBuffer"),i=s?.combinedData;s&&(r.jsonBinaryMap=s.map,r.json=s.sourceCopy);const o=i?i.byteLength:0,a=JSON.stringify(r),c=Zi.encode(a),l=c.byteLength,u=new ArrayBuffer(ji.protocolPrefix+ji.protocolVersion+ji.jsonLength+ji.binaryLength+ji.fromServiceId+ji.toServiceId+ji.sentAt+l+o),d=new DataView(u),p=new Uint8Array(u),h=Date.now();let f=0;for(let e=0;e<4;++e)p[f++]=Ji.charCodeAt(e);return d.setUint8(f,1),f+=ji.protocolVersion,d.setUint32(f,l,!0),f+=ji.jsonLength,d.setUint32(f,o,!0),f+=ji.binaryLength,d.setUint32(f,t,!0),f+=ji.fromServiceId,d.setUint32(f,n,!0),f+=ji.toServiceId,d.setBigInt64(f,BigInt(h),!0),f+=ji.sentAt,p.set(c,f),f+=l,i&&o&&p.set(new Uint8Array(i),f),u},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<ji.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Ji)return null;if(e.byteLength<Ui)return Xi.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const s=t.getUint8(n);n+=ji.protocolVersion;const i=t.getUint32(n,!0);n+=ji.jsonLength;const o=t.getUint32(n,!0);n+=ji.binaryLength;const a=t.getUint32(n,!0);n+=ji.fromServiceId;const c=t.getUint32(n,!0);n+=ji.toServiceId;const l=t.getBigInt64(n,!0);n+=ji.sentAt;const u=i+o,d=e.slice(n,n+u),p=new Uint8Array(e,0,Ui);let h=null;if(e.byteLength-Ui-i-o>0){h=new Uint8Array(e,Ui+i+o).slice().buffer}return{header:{protocolVersion:s,jsonLength:i,binaryLength:o,fromServiceId:a,toServiceId:c,sentAt:new Date(Number(l)),packages:[d],headerPackage:p.slice().buffer},remaining:h}},decodeFullKlMessage:e=>{const t=e.packages.reduce(((e,t)=>e+t.byteLength),0),n=new Uint8Array(t);let r,s=0;for(const t of e.packages)r=new Uint8Array(t),n.set(r,s),s+=r.byteLength;const i=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),o=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=Ti(i);if(!a?.json)return Xi.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&o.byteLength&&Gi(a.json,o,a.jsonBinaryMap);const c=new Uint8Array(e.headerPackage.byteLength+n.byteLength);c.set(new Uint8Array(e.headerPackage),0),c.set(n,e.headerPackage.byteLength);let l=c,u=null;const d=Ui+e.jsonLength+e.binaryLength;return c.byteLength>d&&(u=c.subarray(d),l=c.subarray(0,d)),{message:{json:a.json,...o.length?{binaryData:o.buffer}:{},rawMessage:l.buffer},remaining:u?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Ui)return Xi("Invalid Header Size"),e;let n=0;n+=ji.protocolPrefix,n+=ji.protocolVersion,n+=ji.jsonLength,n+=ji.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=ji.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=Zi.encode(e),r=n.byteLength,s=new ArrayBuffer(Mi+r),i=new DataView(s),o=new Uint8Array(s);for(let e=0;e<4;++e)o[t++]=Yi.charCodeAt(e);return i.setUint32(t,r,!0),t+=Di.txtLength,o.set(n,t),s},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<Mi)return{command:null};let r="";for(let e=0;e<Di.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Yi)return{command:null};const s=t.getUint32(n,!0);n+=Di.txtLength;const i=e.byteLength-Mi-s,o=new Uint8Array(e,n,Math.min(s,e.byteLength-Mi)),a=(new TextDecoder).decode(o);let c=null;i>0&&(c=e.slice(Mi+s));let l=0;return i<0&&(l=Math.abs(i)),{command:a,remainingData:c,missing:l}}};let eo=Ki;Bi&&(eo=Qi);var to,no=eo;(to||(to={})).FunctionNotFound="FNC_NOT_FOUND";let ro=Math.ceil(Date.now()/1e3);let so,io,oo,ao,co,lo=!1;var uo=()=>{lo=!0},po=(e,t)=>{if(!so)throw new Error("Memory connection not set.");so.sendBuf(e,t)},ho=e=>io=e,fo=e=>co=e,go=e=>oo=e,mo=e=>ao=e;const vo=(e,t=2)=>{const n=(e,r)=>{if("object"==typeof e){const s=Object.keys(e);for(const i of s){const s=e[i];if(s&&"object"==typeof s){const o=s._kemuType;if(void 0!==o){if(o===le.ImageData){const t=e[i];e[i]=Be(t)}}else r<t&&n(s,++r)}}}};return n(e,1),e};Vi("klTransmissionManager"),Vi("ipcClient");Vi("kemuWidgetService"),w(process.argv.slice(2));const yo=e=>u(`runner:${e}`),bo=yo("connectionManager"),So=yo("remoteInvoke"),wo=new function(e){const t={};let n=console.log;const r={};let s=e||String(Date.now());const i={},o=e=>!i[e],a=(e,t,n,r,s,i)=>{let a=Bi?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:i.success?i.success:[i],messageId:t,type:i.success?"response":"error"}};return o(r)&&(a=no.encode(c,n,r)),s(a,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{n=e},processMessage:(e,s,i,o)=>{if(!o)return!1;const c=o;if(t[c.messageId]){const e=t[c.messageId];return e&&(clearTimeout(e.timer),e.fulfilled||(e.fulfilled=!0,"response"===c.type?e.resolve(c.args):"error"===c.type&&e.reject(c.args[0])),delete t[c.messageId]),!0}if("execute"!==c.type&&n&&n(`No pending execution found for message id "${c.messageId}"`),"execute"===c.type){const t=r[c.functionName];if(t){const n=e=>{a(c.functionName,c.messageId,i.targetServiceId,i.sourceServiceId,s,e)};t({transport:e,args:c.args,reply:n,messageId:c.messageId,sourceServiceId:i.sourceServiceId,send:s})}else{const e=`Function "${c.functionName}" not found.`;n&&n(e),a(c.functionName,c.messageId,i.targetServiceId,i.sourceServiceId,s,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(e,r,i,a,c,l)=>{if(!i){const e="No send buffer function provided.";throw n&&n(e),e}ro+=1;const u=`${s}-${ro}-exec-${e.substring(0,10)}`,d={messageId:u,functionName:e,send:i,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};d.promise=new Promise(((e,t)=>{d.resolve=e,d.reject=t}));let p=Bi?new ArrayBuffer(0):Buffer.alloc(0);const h={json:{functionName:e,args:r,messageId:u,type:"execute"}};o(c)&&(p=no.encode(h,a,c)),t[u]=d,n&&n(`Calling remote function "${e}" with message id "${u}"`);const f="true"===process.env.NO_INVOKE_TIMEOUT;return l?.async?(d.fulfilled=!0,d.resolve([void 0]),delete t[u]):0===l?.timeout||f||(d.timer=setTimeout((()=>{n&&n(`Remote function ${u} timed out`);const r=t[u];r&&!r.fulfilled&&(r.fulfilled=!0,d.reject(`Function ${e} Timed out`)),delete t[u]}),l?.timeout||3e4)),i(p,{sourceServiceId:a,targetServiceId:c,msg:h}),d.promise},sendResponse:a,registerFunction:(e,t)=>{r[e]=t},getTransportSendFunction:e=>{const n=t[e];return n?n.send:null},setServiceName:e=>{s=e},getPendingExecutions:()=>t,rejectAllPending:e=>{Object.keys(t).forEach((n=>{const r=t[n];r&&!r.fulfilled&&(clearTimeout(r.timer),r.fulfilled=!0,r.reject(e),delete t[n])}))},broadcast:(e,t,r,i)=>{ro+=1;const a=`${s}-${ro}-multicast-${e.substring(0,10)}`;let c=Bi?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:t,messageId:a,type:"execute"}};let u=o(r[0].serviceId);u&&(c=no.encode(l,i,r[0].serviceId));for(let t=0;t<r.length;t++)try{const s=r[t];n&&n(`Broadcasting function "${e}" with message id "${a}" to client [${s.serviceId}]`),0!==t&&(u=o(s.serviceId),u&&(c=no.patchEncodedHeader(c,{toServiceId:s.serviceId}))),s.sendFn(c,{msg:l,sourceServiceId:i,targetServiceId:s.serviceId})}catch(e){n&&n(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{i[e]=t}}}("kweb");wo.setLogger(So);const Io=new a,_o=new a;let $o,Co=null,ko=null,Eo=null;const xo={},Ao=()=>{if(!Eo)throw new Error("API key is required to interact with the hub");return Eo},No=(e,t,n)=>{const r=`${e}_${t}`,s={contents:n,lastRequestedAt:Date.now(),contentsChecksum:""};return xo[r]=s,s},Oo=(e,t)=>xo[`${e}_${t}`]||null,Lo=async(e,t)=>{if(!Co)return bo("Hub Link has not been acknowledged. Cannot get services."),null;const n=[{serviceName:e,version:t}];return(await wo.execute(he.GetServiceContents,n,To,Co,0))[0]},Po=async(e,t,n=!1)=>{if(!e||!t)return null;const r=Oo(e,t);if(!r||n){const n=r||No(e,t);try{const r=await Lo(e,t);return r&&(n.contents=r.uiContent,n.contentsChecksum=r.uiContentsChecksum||""),n.contents||null}catch(n){bo(`Failed to fetch service contents for ${e} v${t}`,n)}}return r?.contents||null},To=po,Bo=()=>{bo("Disconnected from the server"),Co=null,wo.rejectAllPending("Disconnected from the server"),Io.emit("disconnected")},jo=()=>{bo("Connected to the server"),Io.emit("connected")},Do=()=>ko,Uo=(e,t,n,r)=>`${e}_${t}_${n}_${r}`,Mo=async()=>{const e=Do();if(e){const t=Z(e)?.blocks;if(t){const n={};for(const r in t){const s=t[r];for(const t in s.gates){const r=s.gates[t];if(r.type===De.hubService){const t=r.state;if(t.service?.eventEmitter){const r=`${t.service.name}_${t.service.version}`;if(!n[r])try{bo(`Re-issuing subscription for service ${t.service.name} (${t.service.version})`),n[r]=!0,await ea({listener:{recipeId:e},targetService:{serviceName:t.service.name,version:t.service.version}})}catch(e){bo(`Failed to re-issue subscription for service ${t.service.name} (${t.service.version})`,e)}}}}}}}},Fo=async e=>{if(!e)return void bo("Hub sent ACK request without service id");const t={apiKey:Ao(),ackSessionId:e};await wo.execute(he.SocketAckResponse,[t],To,e,0),bo("Hub Link acknowledged"),Co=e,Io.emit("acknowledged"),Mo()},Ro=async e=>{const t=e.args[0],n=Uo("broadcast",`hub_${t.type}`,(0).toString(),"");await _o.emit(n,t)},Wo=async e=>{const t=e.args[0];for(const e of t.outputs||[])e.type===le.ImageData&&xe(e.value)&&(e.value=Be(e.value));const n=Do();if(n){const r=Z(n);if(r){const s=async e=>{const n=Uo("broadcast",t.source.serviceName,t.source.serviceVersion,e);try{await _o.emit(n,t)}catch(t){bo(`Failed to emit broadcast event for target ${e}`,t)}};await s("app");for(const i in r.blocks){const o=r.blocks[i];for(const r in o.gates){const i=o.gates[r];if(i.disabled)continue;const a=i.state;if(i.type===De.hubService&&a.service?.name===t.source.serviceName&&a.service?.version===t.source.serviceVersion&&a.variantId===t.variantId){await s(r);for(const s of t.outputs||[])if(null!==s.value&&void 0!==s.value){const t={type:s.type,value:s.value,timestamp:Date.now()};bo(`Sending data to output ${s.name} requested by messageId ${e.messageId}`),await Pi(n,r,s.name,t,t)}}}}}}},Go=async e=>{const t=e.args[0],{finalState:n,recipeId:r,widgetId:s}=t,i=Li(r,s);let o=i;if(n&&o&&i&&(o={...i,customState:n},Oi(r,s,o,!0)),o?.service)try{const e=Uo("setOutputs",o.service.name,o.service.version,s);await _o.emit(e,t.outputs)}catch(e){bo(`Failed to emit setOutputs event for widget ${s}`,e)}for(const n of t.outputs)if(null!==n.value&&void 0!==n.value){if(n.type===le.ImageData){if(!xe(n.value)){bo(`Invalid ImageData value received for output ${n.name}. Expected an ImageData-like object`);continue}n.value=Be(n.value)}else n.type===le.JsonObj&&vo(n.value);const t={type:n.type,value:n.value,timestamp:Date.now()};bo(`Sending data to output ${n.name} requested by messageId ${e.messageId}`),await Pi(r,s,n.name,t,t)}e.reply({success:[]})},Vo=async e=>{const t=e.args[0],{newState:n,recipeId:r,widgetId:s}=t,i=Li(r,s);if(i){const t={...i,customState:{...i.customState,...n}};return Oi(r,s,t,!0),e.reply({success:[]})}},Ho=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:s,path:i,key:o}=n;bo(`Received request to set a dependency path for "${o}" on widget "${s}" in recipe "${r}"`);const a=Li(r,s);if(a){const e={...a};e.dependencies=e.dependencies||{},e.dependencies[o]={path:i},Oi(r,s,e,!0)}return t({success:[]})},zo=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:s,key:i}=n;bo(`Received request to get a dependency path for "${i}" on widget "${s}" in recipe "${r}"`);const o=Li(r,s);if(o){const e=o.dependencies?.[i]?.path;return bo(`Returning dependency path for "${i}" on widget "${s}": "${e}"`),t({success:[e||null]})}return t({error:"Widget not found",errCode:"WIDGET_NOT_FOUND"})},qo=async()=>{if(bo(`Requesting services on ${(new Date).toISOString()}`),!Co)return bo("Hub Link has not been acknowledged. Cannot get services."),{available:[],installed:[],failed:[]};const[e]=await wo.execute(he.GetServices,[],To,Co,0);$o=e;for(const t of e.available){if(t.internal)continue;const e=Oo(t.name,t.version);if(!e||e?.contentsChecksum!==t.uiContentChecksum)try{const n=e||No(t.name,t.version);bo(`Service ${t.name} v${t.version} contents have changed, fetching new contents`);const r=await Lo(t.name,t.version);r&&(n.contents=r.uiContent,n.contentsChecksum=t.uiContentChecksum||"")}catch(e){bo(`Failed to update service contents for ${t.name} v${t.version}`,e)}}return e},Ko=()=>$o||{available:[],installed:[],failed:[]},Jo=()=>!!$o,Yo=async e=>{const{targetServiceSessionId:t}=e;if(!Co)return void bo("No target service session id provided");bo(`Forwarding "onParentEvent" to service ${t}`);return await wo.execute(he.OnParentEvent,[e],To,Co,t,e.config)},Xo=async e=>{if(!Co)return bo("Hub Link has not been acknowledged. Cannot get services."),{};const[t]=await wo.execute(he.GetDefaultState,[],To,Co,e);return t},Zo=async(e,t,n,r)=>{if(!Co)return bo("Hub Link has not been acknowledged. Cannot get services."),null;const[s]=await wo.execute(he.UIEvent,[t,n],To,Co,e,r);return s},Qo=(e,t)=>{const n=()=>{t()};return Io.on(e,n),()=>Io.off(e,n)},ea=async e=>{if(Co)return wo.execute(he.SubscribeToService,[e],To,Co,0);bo("Hub Link has not been acknowledged. Cannot subscribe to services.")},ta=async e=>{if(Co)return wo.execute(he.UnsubscribeFromService,[e],To,Co,0);bo("Hub Link has not been acknowledged. Cannot subscribe to services.")},na=(e,t,n,r)=>{const s=Uo("broadcast",t,n,e);return _o.on(s,r)},ra=(e,t,n,r)=>{const s=Uo("setOutputs",t,n,e);return _o.on(s,r)},sa=async(e,t,n)=>Co?wo.execute(e,t,To,Co,0,n):(bo("Hub Link has not been acknowledged. Cannot execute function."),null),ia=async e=>{if(!Co)return void bo("Hub Link has not been acknowledged. Cannot execute function.");const t=Li(e.recipeId,e.widgetId);if(!t)throw new Error("Widget or recipe pool not found. Cannot initialize service instance.");const n=Object.keys(t.dependencies||{}).reduce(((e,n)=>(e[n]=t.dependencies?.[n]?.path||null,e)),{}),r=[{currentState:t.customState,recipeId:e.recipeId,widgetId:e.widgetId,variantId:e.variantId,recipeType:e.recipeType,currentDependencies:n}],[s]=await wo.execute(he.InitializeInstance,r,To,Co,e.sessionId);if(s){const t=Li(e.recipeId,e.widgetId);if(t){const n={...t,customState:s};Oi(e.recipeId,e.widgetId,n,!0)}}},oa=async(e,t,n,r)=>{if(!Co)return void bo("Hub Link has not been acknowledged. Cannot execute function.");const s=Li(n,t);if(!s)throw new Error("Widget or recipe pool not found. Cannot initialize service instance.");const i=[{currentState:s.customState,recipeId:n,widgetId:t,variantId:r}];await wo.execute(he.TerminateInstance,i,To,Co,e)},aa=async(e,t,n="^",r)=>{const s=["^","~",">=",">","<=","<","="];if(!s.includes(n))throw new Error(`Invalid compare mode "${n}". Must be one of ${s.join(", ")}`);const i=Jo(),o=r||!i?await qo():Ko();for(const r of o.available)if(r.name===e){if(r.version===t)return r;if(l(r.version,`${n}${t}`))return r}return null};var ca,la,ua,da,pa,ha,fa,ga,ma=async e=>{go(jo),mo(Bo),Eo=e,fo((({json:e,transmission:t})=>{wo.processMessage("websocket",To,t,e)})),wo.registerFunction(he.SetState,Vo),wo.registerFunction(he.SetOutputs,Go),wo.registerFunction(he.BroadcastEvent,Wo),wo.registerFunction(he.HubBroadcastEvent,Ro),wo.registerFunction(fe.SetDependencyPath,Ho),wo.registerFunction(fe.GetDependencyPath,zo),ho((e=>{((e,t)=>{const n=pe.SocketAcknowledge,r=pe.IpcAcknowledge,s=e.startsWith(n);if(e===r)return t&&t(),0;if(s){const i=e.split(s?n:r),o=parseInt(i[1]);return t&&t(o),o}})(e,Fo),((e,t)=>{e===pe.ServicesListChanged&&(t&&t())})(e,(()=>{bo("Services list changed"),Io.emit("services-changed")}))})),await uo()},va=(e,t)=>{Io.on(e,t)},ya=()=>({getServices:qo,getServiceContents:Po,onParentEvent:Yo,onCommand:Qo,getDefaultState:Xo,getCachedServices:Ko,areServicesCached:Jo,subscribeToServiceEvents:ea,unsubscribeFromServiceEvents:ta,callProcessorHandler:Zo,onBroadcastEvent:na,onSetOutputsEvent:ra,executeHubFunction:sa,initializeServiceInstance:ia,terminateServiceInstance:oa,getCompatibleService:aa}),ba=e=>{ko=e},Sa=()=>wo;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(ca||(ca={})),function(e){e[e.Number=0]="Number",e[e.String=1]="String",e[e.ArrayBuffer=2]="ArrayBuffer",e[e.Array=3]="Array",e[e.Boolean=4]="Boolean",e[e.JsonObj=5]="JsonObj",e[e.Anything=6]="Anything",e[e.ImageData=7]="ImageData",e[e.AudioBuffer=8]="AudioBuffer",e[e.Rect=9]="Rect",e[e.Point=10]="Point",e[e.ImageBitmap=11]="ImageBitmap",e[e.BinaryFile=12]="BinaryFile"}(la||(la={})),function(e){e.Number="Number",e.String="String",e.ArrayBuffer="ArrayBuffer",e.Array="Array",e.Boolean="Boolean",e.JsonObj="JsonObj",e.Anything="Anything",e.ImageData="ImageData",e.AudioBuffer="AudioBuffer",e.Rect="Rect",e.Point="Point",e.ImageBitmap="ImageBitmap",e.BinaryFile="BinaryFile"}(ua||(ua={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(da||(da={})),function(e){e.IpcAcknowledge="iack:",e.SocketAcknowledge="sack:",e.AcknowledgeResponse="ackr:",e.ServicesListChanged="update-services",e.SendManifest="send-manifest",e.BroadcastStart="broadcast-start",e.BroadcastEnd="broadcast-end",e.AssumeSession="assume:"}(pa||(pa={})),function(e){e.GetServices="getServices",e.SubscribeToService="subscribeToService",e.UnsubscribeFromService="unsubscribeFromService",e.GetServiceContents="getServiceContents",e.SocketAckResponse="socketAckResponse",e.ShowSecretsConfigScreen="showSecretsConfigScreen",e.GetMappedSecrets="getMappedSecrets",e.GetSecretContexts="getSecretContexts",e.OnParentEvent="onParentEvent",e.GetDefaultState="getDefaultState",e.BroadcastEvent="broadcastEvent",e.HubBroadcastEvent="hubBroadcastEvent",e.ServiceManifest="serviceManifest",e.GetState="getState",e.SetState="setState",e.SetOutputs="setOutputs",e.UIEvent="uiEvent",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.GetUniqueId="getUniqueId"}(ha||(ha={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(fa||(fa={})),function(e){e.IPC="ipc",e.WS="ws"}(ga||(ga={}));const wa=e=>{try{return JSON.parse(e)}catch(e){return null}},Ia=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,_a=e=>{if("string"!=typeof e)throw new TypeError("Invalid argument expected string");const t=e.match(Ia);if(!t)throw new Error(`Invalid argument not valid semver ('${e}' received)`);return t.shift(),t},$a=e=>"*"===e||"x"===e||"X"===e,Ca=e=>{const t=parseInt(e,10);return isNaN(t)?e:t},ka=(e,t)=>{if($a(e)||$a(t))return 0;const[n,r]=((e,t)=>typeof e!=typeof t?[String(e),String(t)]:[e,t])(Ca(e),Ca(t));return n>r?1:n<r?-1:0},Ea=(e,t)=>{for(let n=0;n<Math.max(e.length,t.length);n++){const r=ka(e[n]||"0",t[n]||"0");if(0!==r)return r}return 0},xa=(e,t,n)=>{Oa(n);const r=((e,t)=>{const n=_a(e),r=_a(t),s=n.pop(),i=r.pop(),o=Ea(n,r);return 0!==o?o:s&&i?Ea(s.split("."),i.split(".")):s||i?s?-1:1:0})(e,t);return Aa[n].includes(r)},Aa={">":[1],">=":[0,1],"=":[0],"<=":[-1,0],"<":[-1],"!=":[-1,1]},Na=Object.keys(Aa),Oa=e=>{if(-1===Na.indexOf(e))throw new Error(`Invalid operator, expected one of ${Na.join("|")}`)};var La="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Pa(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ta,Ba,ja,Da,Ua,Ma={exports:{}},Fa={exports:{}};function Ra(){if(Ba)return Ta;Ba=1;var e=1e3,t=60*e,n=60*t,r=24*n,s=7*r,i=365.25*r;function o(e,t,n,r){var s=t>=1.5*n;return Math.round(e/n)+" "+r+(s?"s":"")}return Ta=function(a,c){c=c||{};var l=typeof a;if("string"===l&&a.length>0)return function(o){if((o=String(o)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(o);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*i;case"weeks":case"week":case"w":return c*s;case"days":case"day":case"d":return c*r;case"hours":case"hour":case"hrs":case"hr":case"h":return c*n;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(a);if("number"===l&&isFinite(a))return c.long?function(s){var i=Math.abs(s);if(i>=r)return o(s,i,r,"day");if(i>=n)return o(s,i,n,"hour");if(i>=t)return o(s,i,t,"minute");if(i>=e)return o(s,i,e,"second");return s+" ms"}(a):function(s){var i=Math.abs(s);if(i>=r)return Math.round(s/r)+"d";if(i>=n)return Math.round(s/n)+"h";if(i>=t)return Math.round(s/t)+"m";if(i>=e)return Math.round(s/e)+"s";return s+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))}}function Wa(){if(Da)return ja;return Da=1,ja=function(e){function t(e){let r,s,i,o=null;function a(...e){if(!a.enabled)return;const n=a,s=Number(new Date),i=s-(r||s);n.diff=i,n.prev=r,n.curr=s,r=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((r,s)=>{if("%%"===r)return"%";o++;const i=t.formatters[s];if("function"==typeof i){const t=e[o];r=i.call(n,t),e.splice(o,1),o--}return r})),t.formatArgs.call(n,e);(n.log||t.log).apply(n,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=n,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(s!==t.namespaces&&(s=t.namespaces,i=t.enabled(e)),i),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function n(e,n){const r=t(this.namespace+(void 0===n?":":n)+e);return r.log=this.log,r}function r(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(r),...t.skips.map(r).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let n;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").split(/[\s,]+/),s=r.length;for(n=0;n<s;n++)r[n]&&("-"===(e=r[n].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let n,r;for(n=0,r=t.skips.length;n<r;n++)if(t.skips[n].test(e))return!1;for(n=0,r=t.names.length;n<r;n++)if(t.names[n].test(e))return!0;return!1},t.humanize=Ra(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((n=>{t[n]=e[n]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t.colors[Math.abs(n)%t.colors.length]},t.enable(t.load()),t},ja}var Ga,Va,Ha,za,qa,Ka={exports:{}};function Ja(){return Va||(Va=1,Ga=(e,t=process.argv)=>{const n=e.startsWith("-")?"":1===e.length?"-":"--",r=t.indexOf(n+e),s=t.indexOf("--");return-1!==r&&(-1===s||r<s)}),Ga}"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?Ma.exports=(Ua||(Ua=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;t.splice(1,0,n,"color: inherit");let r=0,s=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(s=r))})),t.splice(s,0,n)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=Wa()(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Fa,Fa.exports)),Fa.exports):Ma.exports=(qa||(qa=1,function(e,t){const n=I,r=o;t.init=function(e){e.inspectOpts={};const n=Object.keys(t.inspectOpts);for(let r=0;r<n.length;r++)e.inspectOpts[n[r]]=t.inspectOpts[n[r]]},t.log=function(...e){return process.stderr.write(r.formatWithOptions(t.inspectOpts,...e)+"\n")},t.formatArgs=function(n){const{namespace:r,useColors:s}=this;if(s){const t=this.color,s="[3"+(t<8?t:"8;5;"+t),i=` ${s};1m${r} [0m`;n[0]=i+n[0].split("\n").join("\n"+i),n.push(s+"m+"+e.exports.humanize(this.diff)+"[0m")}else n[0]=(t.inspectOpts.hideDate?"":(new Date).toISOString()+" ")+r+" "+n[0]},t.save=function(e){e?process.env.DEBUG=e:delete process.env.DEBUG},t.load=function(){return process.env.DEBUG},t.useColors=function(){return"colors"in t.inspectOpts?Boolean(t.inspectOpts.colors):n.isatty(process.stderr.fd)},t.destroy=r.deprecate((()=>{}),"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),t.colors=[6,2,3,4,5,1];try{const e=function(){if(za)return Ha;za=1;const e=_,t=I,n=Ja(),{env:r}=process;let s;function i(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function o(t,i){if(0===s)return 0;if(n("color=16m")||n("color=full")||n("color=truecolor"))return 3;if(n("color=256"))return 2;if(t&&!i&&void 0===s)return 0;const o=s||0;if("dumb"===r.TERM)return o;if("win32"===process.platform){const t=e.release().split(".");return Number(t[0])>=10&&Number(t[2])>=10586?Number(t[2])>=14931?3:2:1}if("CI"in r)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((e=>e in r))||"codeship"===r.CI_NAME?1:o;if("TEAMCITY_VERSION"in r)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(r.TEAMCITY_VERSION)?1:0;if("truecolor"===r.COLORTERM)return 3;if("TERM_PROGRAM"in r){const e=parseInt((r.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(r.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(r.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(r.TERM)||"COLORTERM"in r?1:o}return n("no-color")||n("no-colors")||n("color=false")||n("color=never")?s=0:(n("color")||n("colors")||n("color=true")||n("color=always"))&&(s=1),"FORCE_COLOR"in r&&(s="true"===r.FORCE_COLOR?1:"false"===r.FORCE_COLOR?0:0===r.FORCE_COLOR.length?1:Math.min(parseInt(r.FORCE_COLOR,10),3)),Ha={supportsColor:function(e){return i(o(e,e&&e.isTTY))},stdout:i(o(!0,t.isatty(1))),stderr:i(o(!0,t.isatty(2)))}}();e&&(e.stderr||e).level>=2&&(t.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch(e){}t.inspectOpts=Object.keys(process.env).filter((e=>/^debug_/i.test(e))).reduce(((e,t)=>{const n=t.substring(6).toLowerCase().replace(/_([a-z])/g,((e,t)=>t.toUpperCase()));let r=process.env[t];return r=!!/^(yes|on|true|enabled)$/i.test(r)||!/^(no|off|false|disabled)$/i.test(r)&&("null"===r?null:Number(r)),e[n]=r,e}),{}),e.exports=Wa()(t);const{formatters:s}=e.exports;s.o=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts).split("\n").map((e=>e.trim())).join(" ")},s.O=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts)}}(Ka,Ka.exports)),Ka.exports);var Ya=Pa(Ma.exports);const Xa=e=>Ya(e),Za=Date.now();let Qa=Math.ceil(Za/1e3);var ec=()=>Qa+=1;const tc=p($(),"kemu-user-services"),nc=p($(),"kemu-test-services"),rc="KMU-CB-v1";var sc;!function(e){e.input="input",e.counter="counter",e.play="play",e.elapsed="elapsed",e.ifGate="ifGate",e.skipEvent="skipEvent",e.between="between",e.map="map",e.parser="parser",e.slider="slider",e.suspend="suspend",e.display="display",e.pixelfy="pixelfy",e.json="json",e.arrayItem="arrayItem",e.extractImage="extractImage",e.imageConvolution="imageConvolution",e.firstEvent="firstEvent",e.pixelDraw="pixelDraw",e.randomBetween="randomBetween",e.arrayCombine="arrayCombine",e.clock="clock",e.multiplication="multiplication",e.object="object",e.widgetGroup="widgetGroup",e.script="script",e.base64ToImageData="base64ToImageData",e.jsonParse="jsonParse",e.text="text",e.imageCrop="imageCrop",e.imageResize="imageResize",e.value="value",e.imageWarp="imageWarp",e.widgetBundle="widgetBundle",e.sequence="sequence",e.variable="variable",e.hubService="hubService"}(sc||(sc={}));const ic=e=>({...e,type:Array.isArray(e.type)?e.type.map((e=>la[e])):la[e.type]}),oc=async e=>{try{return await m(e,"utf-8")}catch(e){return null}},ac=e=>{if(e&&e.startsWith(rc)){const t=e.slice(9),n=decodeURI(t);return wa(n)}return null},cc=async(e,t,n)=>{let r=[];e.variants?.length&&(r=e.variants.map((e=>({...e,...e.inputs?{inputs:e.inputs.map(ic)}:{},...e.outputs?{outputs:e.outputs.map(ic)}:{}}))));const s={...e,path:t,customWidgets:[],...e.inputs?{inputs:e.inputs.map(ic)}:{inputs:[]},...e.outputs?{outputs:e.outputs.map(ic)}:{outputs:[]},variants:r,...e.widgetUI&&n?.widgetUIContents?{widgetUIContents:n.widgetUIContents}:{}},i=await(async(e,t,n=console.log)=>{const r=[];if(t.customWidgets?.length)for(const s of t.customWidgets){const t=await oc(p(e,s));if(!t){n(`Error loading custom widget file ${s}`);continue}const i=t.startsWith(rc)?t:`${rc}${t}`,o=ac(i);if(!o){n(`Custom widget file "${s}" is not a valid Kemu Clipboard item`);continue}const a=Object.values(o).filter((e=>e.type===sc.widgetGroup&&!e.groupId));if(a.length>1){n(`Custom widget file "${s}" contains more than one top level widgetGroup`);continue}const c=a[0];if(!c){n(`Custom widget file "${s}" does not contain a top level widgetGroup`);continue}const l=c.state,u={name:l.name,color:l.color,description:l.description,contents:i,rootGroupId:c.id,icon:l.icon,protocolVersion:l.protocolVersion||"2"};r.push(u)}return r})(t,e,n?.log);if(i.length?s.customWidgets=i:delete s.customWidgets,s.variants?.length)for(const e of s.variants)if(e.svgIcon)try{const n=await m(p(t,e.svgIcon),"utf-8");e.svgIcon=n}catch(t){n?.log&&n?.log(`Error loading svgIcon for variant ${e.id}: ${t}`)}return s},lc=async e=>{try{return await v(e,y.F_OK),!0}catch{return!1}};let uc=null,dc=null;const pc=()=>uc||tc,hc=Xa("servicesManager"),fc={};let gc=null,mc=null,vc=null;class yc extends Error{code;originalError;constructor(e,t,n){super(e),this.code=t,this.originalError=n,this.name="ServiceError"}}const bc=async e=>{try{return await v(e),!0}catch{return!1}},Sc=async e=>{if(!gc)throw new Error('IPC config not set, call "setHubIpcConfig" first.');try{if(e.processor===da.Javascript){hc(`Spawning service ${e.name} with sessionId ${e.sessionId}`);const t=d.join(e.path,"processor.js"),n=d.join(e.path,"processor.mjs"),r=await bc(t)?t:n,s=[`--sessionId=${e.sessionId.toString()}`,`--ipcSpace=${gc.appSpace}`,`--ipcId=${gc?.id}`,`--recipePath=${gc.recipePath||""}`];if(e.internal&&s.push("--internal=true"),!vc)throw new Error('Get secrets function not set, call "setGetSecretsFunction" first.');const i=await vc({name:e.name,version:e.version,requiredSecrets:e.requiredSecrets||{}}),o=Object.entries(e.requiredSecrets||{}).filter((([e,t])=>{const n=i[e];return null==n&&!t.optional})).map((([e])=>e));if(o?.length)throw new yc(`Missing required environment variables: ${o.join(", ")}`,"MISSING_REQUIRED_SECRETS");return new Promise(((t,n)=>{if(!mc)throw new Error('Spawn function not set, call "setSpawnNodeFunction" first.');const o=mc({args:[r,...s],options:{env:i}});o.stdout.on("data",(t=>{hc(`[${e.name}] - stdout: ${t}`)})),o.stderr.on("data",(t=>{hc(`[${e.name}] - stderr: ${t}`)})),o.on("exit",(t=>{hc(`[${e.name}] exited with code ${t}`)})),o.on("spawn",(()=>{hc(`[${e.name}] spawned with PID ${o.pid}`),t(o)})),o.on("error",(t=>{hc(`[${e.name}] error: ${t}`),n(new yc(`Error spawning service ${e.name}: ${t}`,"SPAWN_ERROR"))}))}))}throw`Unsupported processor type ${e.processor}`}catch(t){if(t instanceof yc)throw t;throw`Error spawning service ${e.name}: ${t}`}},wc=e=>{if(!e?.name)return"Missing name";if(!e?.version)return"Missing version";if(!e?.description)return"Missing description";if(!e?.processor)return"Missing processor";return[da.Javascript,da.Executable,da.Python].includes(e?.processor)?null:"Invalid processor"},Ic=async(e,t)=>{const n=d.join(e,"manifest.json");if(!await bc(n)){const t=`Missing manifest for service ${e}. Aborting.`;return hc(t),{error:t}}const r=await m(n,"utf-8"),s=wa(r),i=wc(s);if(!s||i){const t=`Invalid service manifest [${e}]: ${i}. Aborting.`;return hc(t),{error:t}}let o;if(delete s.internal,t?.singleServiceName&&s.name!==t.singleServiceName){return{error:`Skipping service ${s.name} as it does not match the singleServiceName option`}}await Promise.all([(async()=>{if(s.widgetUI)try{o=await m(d.join(e,"widgetUI.js"))}catch(e){const t=`Error loading widgetUI file ${s.name}: ${e}`;return hc(t),{error:t}}})(),(async()=>{if(s.svgIcon){const t=await oc(d.join(e,s.svgIcon));if(!t){return{error:`Error loading icon for service ${s.name}`}}s.svgIcon=t}})(),(async()=>{if(s.subServices?.length)for(const t of s.subServices){const n=d.join(e,t),{error:r,service:i}=await Ic(n);r?hc(`Error loading sub-service ${t}: ${r}`):i&&(i.info.parentService={name:s.name,version:s.version})}delete s.subServices})(),(async()=>{if(s.variants?.length)for(const t of s.variants)if(t.svgIcon)try{const n=await m(d.join(e,t.svgIcon),"utf-8");t.svgIcon=n}catch(e){hc(`Error loading svgIcon for variant ${t.id}: ${e}`)}})()]);const a=ec(),c=t?.fixedSession||a;hc(`Loaded service ${s.name} with sessionId ${c}`);const l=await cc(s,e,{widgetUIContents:o});return _c(l),fc[c]={info:{...l,path:e,sessionId:c},status:"loaded",childProcess:null},{service:fc[c]}},_c=e=>{e.widgetUIContents?e.uiContentChecksum=(e=>{const t=k("sha256");return t.update(e),t.digest("hex")})(e.widgetUIContents):e.uiContentChecksum=void 0},$c=async e=>{try{return e.childProcess=await Sc(e.info),e.status="started",e.errorMsg=void 0,e.errorCode=void 0,!0}catch(t){return hc(`Service [${e.info.name}] error: ${t}`),e.status="error",t instanceof yc?(e.errorMsg=t.message,e.errorCode=t.code):(e.errorMsg="string"==typeof t?t:JSON.stringify(t),e.errorCode="UNKNOWN_ERROR"),!1}},Cc=e=>{const{path:t,...n}=e.info;return{...n}},kc=()=>Object.values(fc).filter((e=>"running"===e.status)).map(Cc),Ec=(e,t)=>{const n=Object.values(fc).find((n=>n.info.name===e&&n.info.version===t));if(!n)return null;if(n.info.internal)throw`Cannot stop internal service ${e}`;if(n.childProcess){hc(`Stopping service "${e} (v${t})"`);n.childProcess.kill("SIGINT")||hc(`Failed to stop service ${e}`)}return n.status="stopped",hc(`Service ${e} stopped`),n},xc=e=>e.info.internal?e.info.path:d.join(e.info.path,".."),Ac=e=>!!e.internal;var Nc={isOfficialKemuService:e=>e.name.startsWith("kemu.io"),loadServices:async(e,t)=>{if(!await lc(e))return void hc(`Failed to load services from "${e}". Directory does not exist.`);const n=(await b(e,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name));hc(`Found ${n.length} services in "${e}"`);for(let r=0;r<n.length;r++){const s=n[r],i=d.join(e,s),{error:o,service:a}=await Ic(`${i}${t?.internalServices?"":"/dist"}`,t);o&&hc(`Failed to load service ${i}. Please check logs`),a&&t?.internalServices&&(a.info.internal=!0)}},launchServices:async e=>{if(hc("Initializing services"),!gc)throw new Error('IPC config not set, call "setHubIpcConfig" first.');for(const t in fc){const n=fc[t];e.noSpawningList&&e.noSpawningList.includes(n.info.name)?hc(`Service ${n.info.name} is in the noSpawningList. Skipping.`):$c(n)}hc("Services initialized")},setServiceStatus:(e,t)=>{const n=fc[e];return n?(n.status=t,!0):(hc(`Service with serviceId ${e} not found`),!1)},getActiveServices:kc,getMatchingService:(e,t)=>{const n=Object.values(fc).filter((e=>"running"===e.status));for(const r of n)if(r.info.name===e){if(r.info.version===t)return r;if(xa(r.info.version,t,">="))return r}return null},getServiceBySessionId:e=>fc[e]||null,killAllServices:()=>{for(const e in fc){const t=fc[e];if(t.childProcess)try{hc(`Killing service ${t.info.name} with PID ${t.childProcess.pid}`),t.childProcess.kill()}catch(e){hc(`Error killing service ${t.info.name}: ${e}`)}}},addDevService:async(e,t,n)=>{const r={info:{...await cc(t,t.path),sessionId:e},status:n,startedAt:new Date,devMode:!0,childProcess:null};fc[e]=r,_c(fc[e].info)},setServiceManifest:(e,t,n)=>{const r=fc[e];if(!r)return hc(`Service with sessionId ${e} not found`),!1;const s=wc(t);if(s)return hc(`Invalid manifest for service ${r.info.name}: ${s}`),!1;_c(t),r.info={...r.info,...t},n&&(r.status=n)},getMatchingDevService:(e,t,n)=>{const r=Object.values(fc).filter((e=>e.devMode));for(const s of r)if(s.info.name===e&&s.status===n&&s.info.version===t)return s;return null},getInternalServices:()=>kc().filter((e=>e.internal)),getAllServices:()=>Object.values(fc),stopService:Ec,uninstallService:async(e,t)=>{hc(`Uninstalling service ${e} v${t}`);const n=Ec(e,t);if(!n)return!1;hc(`Service ${e} stopped. Removing from disk...`);const r=xc(n),s=pc();return r.startsWith(s)?(await S(r,{recursive:!0,force:!0}),hc(`Service ${e} successfully removed from disk`),(e=>{const t=fc[e];delete fc[e]})(n.info.sessionId),!0):(hc(`Service ${e} is not installed in the user services directory. Aborting.`),!1)},getAllServiceVersions:e=>Object.values(fc).filter((t=>t.info.name===e)),setHubIpcConfig:e=>{gc={...e}},loadAndLaunch:async(e,t,n)=>{const r=f(e,t),{error:s,service:i}=await Ic(r);if(s||!i)return{errorMsg:s};try{i.info.internal=!!n,i.childProcess=await Sc(i.info),i.status="started"}catch(e){i.status="error",e instanceof yc?(hc(`Service spawning error: ${e.message} (${e.code})`),i.errorMsg=e.message,i.errorCode=e.code):(hc(`Error launching service ${i.info.name}: ${e}`),i.errorMsg="string"==typeof e?e:JSON.stringify(e))}return{service:i,errorCode:i.errorCode,errorMsg:i.errorMsg}},getServiceRootDirectory:xc,setSpawnNodeFunction:e=>{mc=e},setGetSecretsFunction:e=>{vc=e},restartService:async(e,t)=>{hc(`Restarting service ${e} v${t}`);const n=Ec(e,t);return!!n&&$c(n)},getFailedServices:()=>Object.values(fc).filter((e=>"error"===e.status)).map((e=>({...Cc(e),errorMsg:e.errorMsg||"",errorCode:e.errorCode,status:e.status}))),isInternalKemuService:Ac,isNotInternalKemuService:e=>!Ac(e),isNotDevService:e=>!e.devMode};class Oc{constructor(){}appspace="app.";socketRoot="/tmp/";id=_.hostname();encoding="utf8";rawBuffer=!1;sync=!1;unlink=!0;delimiter="\f";silent=!1;logDepth=5;logInColor=!0;logger=console.log.bind(console);maxConnections=100;retry=500;maxRetries=1/0;stopRetrying=!1;IPType=function(){const e=_.networkInterfaces();let t="";e&&Array.isArray(e)&&e.length>0&&(t=e[Object.keys(e)[0]][0].family);return t}();tls=!1;networkHost="IPv6"==this.IPType?"::1":"127.0.0.1";networkPort=8e3;readableAll=!1;writableAll=!1;interface={localAddress:!1,localPort:!1,family:!1,hints:!1,lookup:!1}}class Lc{constructor(e){e||(e=new Oc),this.delimiter=e.delimiter}format(e){return e.data||!1===e.data||0===e.data||(e.data={}),e.data._maxListeners&&(e.data={}),e=e.JSON+this.delimiter}parse(e){let t=e.split(this.delimiter);return t.pop(),t}}var Pc=function(){Object.defineProperties(this,{data:{enumerable:!0,get:function(){return t},set:function(e){t=e}},type:{enumerable:!0,get:function(){return e},set:function(t){e=t}},load:{enumerable:!0,writable:!1,value:function(n){try{n=JSON.parse(n);e=n.type,t=n.data}catch(r){e="error",t={message:"Invalid JSON response format",err:r,response:n}}}},JSON:{enumerable:!0,get:function(){return JSON.stringify({type:e,data:t})}}});var e="",t={}},Tc=Pa(Pc);var Bc=Pa((function(){Object.defineProperties(this,{add:{enumerable:!0,writable:!1,value:function(){for(var n in arguments)e.push(arguments[n]);t||this.stop||!this.autoRun||this.next()}},next:{enumerable:!0,writable:!1,value:function(){if(t=!0,e.length<1||this.stop)return void(t=!1);e.shift().bind(this)()}},clear:{enumerable:!0,writable:!1,value:function(){return e=[]}},contents:{enumerable:!1,get:function(){return e},set:function(t){return e=t}},autoRun:{enumerable:!0,writable:!0,value:!0},stop:{enumerable:!0,writable:!0,value:!1}});var e=[],t=!1}));class jc{}class Dc{}const Uc=new class{constructor(e=!0){this.strict=e}throw(e,t){let n=new TypeError;if(n.message=`expected type of ${e} to be ${t}`,!this.strict)return!1;throw n}typeCheck(e,t){return typeof e===t||this.throw(typeof e,t)}instanceCheck(e=new jc,t=Dc){return e instanceof t||this.throw(typeof e,t.name)}symbolStringCheck(e,t){return Object.prototype.toString.call(e)==`[object ${t}]`||this.throw(Object.prototype.toString.call(e),`[object ${t}]`)}compare(e,t,n){return e==t||this.throw(typeof e,n)}finite(e){return!!isFinite(e)||this.throw(typeof e,"finite")}NaN(e){return this.number(e)?!!isNaN(e)||this.throw(typeof e,"NaN"):this.number(e)}null(e){return this.compare(e,null,"null")}array(e){return this.instanceCheck(e,Array)}boolean(e){return this.typeCheck(e,"boolean")}bigint(e){return this.typeCheck(e,"bigint")}date(e){return this.instanceCheck(e,Date)}generator(e){return this.symbolStringCheck(e,"Generator")}asyncGenerator(e){return this.symbolStringCheck(e,"AsyncGenerator")}globalThis(e){return this.compare(e,globalThis,"explicitly globalThis, not window, global nor self")}infinity(e){return this.compare(e,1/0,"Infinity")}map(e){return this.instanceCheck(e,Map)}weakMap(e){return this.instanceCheck(e,WeakMap)}number(e){return this.typeCheck(e,"number")}object(e){return this.typeCheck(e,"object")}promise(e){return this.instanceCheck(e,Promise)}regExp(e){return this.instanceCheck(e,RegExp)}undefined(e){return this.typeCheck(e,"undefined")}set(e){return this.instanceCheck(e,Set)}weakSet(e){return this.instanceCheck(e,WeakSet)}string(e){return this.typeCheck(e,"string")}symbol(e){return this.typeCheck(e,"symbol")}function(e){return this.typeCheck(e,"function")}asyncFunction(e){return this.symbolStringCheck(e,"AsyncFunction")}generatorFunction(e){return this.symbolStringCheck(e,"GeneratorFunction")}asyncGeneratorFunction(e){return this.symbolStringCheck(e,"AsyncGeneratorFunction")}error(e){return this.instanceCheck(e,Error)}evalError(e){return this.instanceCheck(e,EvalError)}rangeError(e){return this.instanceCheck(e,RangeError)}referenceError(e){return this.instanceCheck(e,ReferenceError)}syntaxError(e){return this.instanceCheck(e,SyntaxError)}typeError(e){return this.instanceCheck(e,TypeError)}URIError(e){return this.instanceCheck(e,URIError)}bigInt64Array(e){return this.instanceCheck(e,BigInt64Array)}bigUint64Array(e){return this.instanceCheck(e,BigUint64Array)}float32Array(e){return this.instanceCheck(e,Float32Array)}float64Array(e){return this.instanceCheck(e,Float64Array)}int8Array(e){return this.instanceCheck(e,Int8Array)}int16Array(e){return this.instanceCheck(e,Int16Array)}int32Array(e){return this.instanceCheck(e,Int32Array)}uint8Array(e){return this.instanceCheck(e,Uint8Array)}uint8ClampedArray(e){return this.instanceCheck(e,Uint8ClampedArray)}uint16Array(e){return this.instanceCheck(e,Uint16Array)}uint32Array(e){return this.instanceCheck(e,Uint32Array)}arrayBuffer(e){return this.instanceCheck(e,ArrayBuffer)}dataView(e){return this.instanceCheck(e,DataView)}sharedArrayBuffer(e){return this.instanceCheck(e,function(){try{return SharedArrayBuffer}catch{return jc}}())}intlDateTimeFormat(e){return this.instanceCheck(e,Intl.DateTimeFormat)}intlCollator(e){return this.instanceCheck(e,Intl.Collator)}intlDisplayNames(e){return this.instanceCheck(e,Intl.DisplayNames)}intlListFormat(e){return this.instanceCheck(e,Intl.ListFormat)}intlLocale(e){return this.instanceCheck(e,Intl.Locale)}intlNumberFormat(e){return this.instanceCheck(e,Intl.NumberFormat)}intlPluralRules(e){return this.instanceCheck(e,Intl.PluralRules)}intlRelativeTimeFormat(e){return this.instanceCheck(e,Intl.RelativeTimeFormat)}intlRelativeTimeFormat(e){return this.instanceCheck(e,Intl.RelativeTimeFormat)}finalizationRegistry(e){return this.instanceCheck(e,FinalizationRegistry)}weakRef(e){return this.instanceCheck(e,WeakRef)}};class Mc{constructor(){}on(e,t,n=!1){return Uc.string(e),Uc.function(t),Uc.boolean(n),"*"==e&&(e=this.#e),this.#t[e]||(this.#t[e]=[]),t[this.#n]=n,this.#t[e].push(t),this}once(e,t){return this.on(e,t,!0)}off(e="*",t="*"){if(Uc.string(e),e!=this.#e.toString()&&"*"!=e||(e=this.#e),!this.#t[e])return this;if("*"==t)return delete this.#t[e],this;Uc.function(t);const n=this.#t[e];for(;n.includes(t);)n.splice(n.indexOf(t),1);return n.length<1&&delete this.#t[e],this}emit(e,...t){Uc.string(e);const n=this.#t[this.#e]||[];if(this.#r(this.#e.toString(),n,e,...t),!this.#t[e])return this;const r=this.#t[e];return this.#r(e,r,...t),this}reset(){this.off(this.#e.toString());for(let e in this.#t)this.off(e);return this}get list(){return Object.assign({},this.#t)}#r=(e,t,...n)=>{Uc.string(e),Uc.array(t);const r=[];for(let e of t)e(...n),e[this.#n]&&r.push(e);for(let t of r)this.off(e,t)};#e=Symbol.for("event-pubsub-all");#n=Symbol.for("event-pubsub-once");#t={}}let Fc=new Lc;class Rc extends Mc{constructor(e,t){super(),this.config=e,this.log=t,this.publish=super.emit,e.maxRetries&&(this.retriesRemaining=e.maxRetries),Fc=new Lc(this.config)}Client=Rc;queue=new Bc;socket=!1;connect=Vc;emit=Wc;retriesRemaining=0;explicitlyDisconnected=!1}function Wc(e,t){this.log("dispatching event to ",this.id,this.path," : ",e,",",t);let n=new Tc;n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Fc.format(n),this.config.sync?this.queue.add(Gc.bind(this,n)):this.socket.write(n)}function Gc(e){this.log("dispatching event to ",this.id,this.path," : ",e),this.socket.write(e)}function Vc(){let e=this;if(e.log("requested connection to ",e.id,e.path),!this.path)return void e.log("\n\n######\nerror: ",e.id," client has not specified socket path it wishes to connect to.");const t={};if(e.port)if(t.host=e.path,t.port=e.port,e.config.interface.localAddress&&(t.localAddress=e.config.interface.localAddress),e.config.interface.localPort&&(t.localPort=e.config.interface.localPort),e.config.interface.family&&(t.family=e.config.interface.family),e.config.interface.hints&&(t.hints=e.config.interface.hints),e.config.interface.lookup&&(t.lookup=e.config.interface.lookup),e.config.tls){if(e.log("Connecting client via TLS to",e.path,e.port,e.config.tls),e.config.tls.private&&(e.config.tls.key=A.readFileSync(e.config.tls.private)),e.config.tls.public&&(e.config.tls.cert=A.readFileSync(e.config.tls.public)),e.config.tls.trustedConnections){"string"==typeof e.config.tls.trustedConnections&&(e.config.tls.trustedConnections=[e.config.tls.trustedConnections]),e.config.tls.ca=[];for(let t=0;t<e.config.tls.trustedConnections.length;t++)e.config.tls.ca.push(A.readFileSync(e.config.tls.trustedConnections[t]))}Object.assign(e.config.tls,t),e.socket=x.connect(e.config.tls)}else e.log("Connecting client via TCP to",t),e.socket=E.connect(t);else e.log("Connecting client on Unix Socket :",e.path),t.path=e.path,"win32"!==process.platform||e.path.startsWith("\\\\.\\pipe\\")||(t.path=t.path.replace(/^\//,""),t.path=t.path.replace(/\//g,"-"),t.path=`\\\\.\\pipe\\${t.path}`),e.socket=E.connect(t);e.socket.setEncoding(this.config.encoding),e.socket.on("error",(function(t){e.log("\n\n######\nerror: ",t),e.publish("error",t)})),e.socket.on("connect",(function(){e.publish("connect"),e.retriesRemaining=e.config.maxRetries,e.log("retrying reset")})),e.socket.on("close",(function(){if(e.log("connection closed",e.id,e.path,e.retriesRemaining,"tries remaining of",e.config.maxRetries),e.config.stopRetrying||e.retriesRemaining<1||e.explicitlyDisconnected)return e.publish("disconnect"),e.log(e.config.id,"exceeded connection rety amount of"," or stopRetrying flag set."),e.socket.destroy(),e.publish("destroy"),void(e=void 0);setTimeout(function(){e.explicitlyDisconnected||(e.retriesRemaining--,e.connect())}.bind(null,e),e.config.retry),e.publish("disconnect")})),e.socket.on("data",(function(t){if(e.log("## received events ##"),e.config.rawBuffer){if(e.publish("data",Buffer.from(t,e.config.encoding)),!e.config.sync)return;return void e.queue.next()}if(this.ipcBuffer||(this.ipcBuffer=""),(t=this.ipcBuffer+=t).slice(-1)!=Fc.delimiter||-1==t.indexOf(Fc.delimiter))return void e.log("Messages are large, You may want to consider smaller messages.");this.ipcBuffer="";const n=Fc.parse(t),r=n.length;for(let t=0;t<r;t++){let r=new Tc;r.load(n[t]),e.log("detected event",r.type,r.data),e.publish(r.type,r.data)}e.config.sync&&e.queue.next()}))}let Hc=new Lc;class zc extends Mc{constructor(e,t,n,r){super(),this.config=t,this.path=e,this.port=r,this.log=n,this.publish=super.emit,Hc=new Lc(this.config),this.on("close",Jc.bind(this))}udp4=!1;udp6=!1;server=!1;sockets=[];emit=qc;broadcast=Kc;onStart(e){this.publish("start",e)}stop(){this.server.close()}start(){this.path?this.config.unlink?A.unlink(this.path,Qc.bind(this)):Qc.bind(this)():this.log("Socket Server Path not specified, refusing to start")}}function qc(e,t,n){this.log("dispatching event to socket"," : ",t,n);let r=new Tc;if(r.type=t,r.data=n,this.config.rawBuffer?(this.log(this.config.encoding),r=Buffer.from(t,this.config.encoding)):r=Hc.format(r),this.udp4||this.udp6)return e.address&&e.port?void this.server.write(r,e):(this.log("Attempting to emit to a single UDP socket without supplying socket address or port. Redispatching event as broadcast to all connected sockets"),void this.broadcast(t,n));e.write(r)}function Kc(e,t){this.log("broadcasting event to all known sockets listening to ",this.path," : ",this.port?this.port:"",e,t);let n=new Tc;if(n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Hc.format(n),this.udp4||this.udp6)for(let e=1,t=this.sockets.length;e<t;e++)this.server.write(n,this.sockets[e]);else for(let e=0,t=this.sockets.length;e<t;e++)this.sockets[e].write(n)}function Jc(){for(let e=0,t=this.sockets.length;e<t;e++){let t=this.sockets[e],n=!1;if(!t||!t.readable)return t.id&&(n=t.id),this.log("socket disconnected",n.toString()),t&&t.destroy&&t.destroy(),this.sockets.splice(e,1),void this.publish("socket.disconnected",t,n)}}function Yc(e,t,n){let r=this.udp4||this.udp6?n:e;if(this.config.rawBuffer)return t=Buffer.from(t,this.config.encoding),void this.publish("data",t,r);if(r.ipcBuffer||(r.ipcBuffer=""),(t=r.ipcBuffer+=t).slice(-1)==Hc.delimiter&&-1!=t.indexOf(Hc.delimiter))for(r.ipcBuffer="",t=Hc.parse(t);t.length>0;){let e=new Tc;e.load(t.shift()),e.data&&e.data.id&&(r.id=e.data.id),this.log("received event of : ",e.type,e.data),this.publish(e.type,e.data,r)}else this.log("Messages are large, You may want to consider smaller messages.")}function Xc(e){this.publish("close",e)}function Zc(e){this.sockets.push(e),e.setEncoding&&e.setEncoding(this.config.encoding),this.log("## socket connection to server detected ##"),e.on("close",Xc.bind(this)),e.on("error",function(e){this.log("server socket error",e),this.publish("error",e)}.bind(this)),e.on("data",Yc.bind(this,e)),e.on("message",function(t,n){if(!n)return;let r;this.log("Received UDP message from ",n.address,n.port),r=this.config.rawSocket?Buffer.from(t,this.config.encoding):t.toString(),e.emit("data",r,n)}.bind(this)),this.publish("connect",e),this.config.rawBuffer}function Qc(){return this.log("starting server on ",this.path,this.port?`:${this.port}`:""),this.udp4||this.udp6?(this.server=O.createSocket(this.udp4?"udp4":"udp6"),this.server.write=tl.bind(this),this.server.on("listening",function(){Zc.bind(this)(this.server)}.bind(this))):(this.log("starting TLS server",this.config.tls),this.config.tls?el.bind(this)():this.server=E.createServer(Zc.bind(this))),this.server.on("error",function(e){this.log("server error",e),this.publish("error",e)}.bind(this)),this.server.maxConnections=this.config.maxConnections,this.port?this.udp4||this.udp6?(this.log("starting server as",this.udp4?"udp4":"udp6"),this.server.bind(this.port,this.path),void this.onStart({address:this.path,port:this.port})):(this.log("starting server as",this.config.tls?"TLS":"TCP"),void this.server.listen(this.port,this.path,this.onStart.bind(this))):(this.log("starting server as","Unix || Windows Socket"),"win32"===process.platform&&(this.path=this.path.replace(/^\//,""),this.path=this.path.replace(/\//g,"-"),this.path=`\\\\.\\pipe\\${this.path}`),void this.server.listen({path:this.path,readableAll:this.config.readableAll,writableAll:this.config.writableAll},this.onStart.bind(this)))}function el(){if(this.log("starting TLS server",this.config.tls),this.config.tls.private?this.config.tls.key=A.readFileSync(this.config.tls.private):this.config.tls.key=A.readFileSync(`${__dirname}/../local-node-ipc-certs/private/server.key`),this.config.tls.public?this.config.tls.cert=A.readFileSync(this.config.tls.public):this.config.tls.cert=A.readFileSync(`${__dirname}/../local-node-ipc-certs/server.pub`),this.config.tls.dhparam&&(this.config.tls.dhparam=A.readFileSync(this.config.tls.dhparam)),this.config.tls.trustedConnections){"string"==typeof this.config.tls.trustedConnections&&(this.config.tls.trustedConnections=[this.config.tls.trustedConnections]),this.config.tls.ca=[];for(let e=0;e<this.config.tls.trustedConnections.length;e++)this.config.tls.ca.push(A.readFileSync(this.config.tls.trustedConnections[e]))}this.server=x.createServer(this.config.tls,Zc.bind(this))}function tl(e,t){let n=Buffer.from(e,this.config.encoding);this.server.send(n,0,n.length,t.port,t.address,(function(e){e&&(this.log("error writing data to socket",e),this.publish("error",(function(e){this.publish("error",e)})))}))}class nl{constructor(){}config=new Oc;of={};server=!1;get connectTo(){return cl}get connectToNet(){return ll}get disconnect(){return sl}get serve(){return il}get serveNet(){return al}get log(){return rl}set connectTo(e){return cl}set connectToNet(e){return ll}set disconnect(e){return sl}set serve(e){return il}set serveNet(e){return al}set log(e){return rl}}function rl(...e){if(!this.config.silent){for(let t=0,n=e.length;t<n;t++)"object"==typeof e[t]&&(e[t]=o.inspect(e[t],{depth:this.config.logDepth,colors:this.config.logInColor}));this.config.logger(e.join(" "))}}function sl(e){this.of[e]&&(this.of[e].explicitlyDisconnected=!0,this.of[e].off("*","*"),this.of[e].socket&&this.of[e].socket.destroy&&this.of[e].socket.destroy(),delete this.of[e])}function il(e,t){"function"==typeof e&&(t=e,e=!1),e||(this.log("Server path not specified, so defaulting to","ipc.config.socketRoot + ipc.config.appspace + ipc.config.id",this.config.socketRoot+this.config.appspace+this.config.id),e=this.config.socketRoot+this.config.appspace+this.config.id),t||(t=ol),this.server=new zc(e,this.config,rl),this.server.on("start",t)}function ol(){}function al(e,t,n,r){"number"==typeof e&&(r=n,n=t,t=e,e=!1),"function"==typeof e&&(r=e,n=!1,e=!1,t=!1),e||(this.log("Server host not specified, so defaulting to","ipc.config.networkHost",this.config.networkHost),e=this.config.networkHost),"udp4"!=e.toLowerCase()&&"udp6"!=e.toLowerCase()||(r=t,n=e.toLowerCase(),t=!1,e=this.config.networkHost),"string"==typeof t&&(r=n,n=t,t=!1),"function"==typeof t&&(r=t,n=!1,t=!1),t||(this.log("Server port not specified, so defaulting to","ipc.config.networkPort",this.config.networkPort),t=this.config.networkPort),"function"==typeof n&&(r=n,n=!1),r||(r=ol),this.server=new zc(e,this.config,rl,t),n&&(this.server[n]=!0,"udp4"===n&&"::1"===e&&(this.server.path="127.0.0.1")),this.server.on("start",r)}function cl(e,t,n){if("function"==typeof t&&(n=t,t=!1),n||(n=ol),e){if(t||(this.log("Service path not specified, so defaulting to","ipc.config.socketRoot + ipc.config.appspace + id",(this.config.socketRoot+this.config.appspace+e).data),t=this.config.socketRoot+this.config.appspace+e),this.of[e]){if(!this.of[e].socket.destroyed)return this.log("Already Connected to",e,"- So executing success without connection"),void n();this.of[e].socket.destroy()}this.of[e]=new Rc(this.config,this.log),this.of[e].id=e,this.of[e].socket&&(this.of[e].socket.id=e),this.of[e].path=t,this.of[e].connect(),n(this)}else this.log("Service id required","Requested service connection without specifying service id. Aborting connection attempt")}function ll(e,t,n,r){if(e){if("number"==typeof t&&(r=n,n=t,t=!1),"function"==typeof t&&(r=t,t=!1,n=!1),t||(this.log("Server host not specified, so defaulting to","ipc.config.networkHost",this.config.networkHost),t=this.config.networkHost),"function"==typeof n&&(r=n,n=!1),n||(this.log("Server port not specified, so defaulting to","ipc.config.networkPort",this.config.networkPort),n=this.config.networkPort),"string"==typeof r&&(UDPType=r,r=!1),r||(r=ol),this.of[e]){if(!this.of[e].socket.destroyed)return this.log("Already Connected to",e,"- So executing success without connection"),void r();this.of[e].socket.destroy()}this.of[e]=new Rc(this.config,this.log),this.of[e].id=e,this.of[e].socket&&(this.of[e].socket.id=e),this.of[e].path=t,this.of[e].port=n,this.of[e].connect(),r(this)}else this.log("Service id required","Requested service connection without specifying service id. Aborting connection attempt")}const ul=new class extends nl{constructor(){super()}IPC=nl};var dl={id:"widgets",retry:1500,silent:!0,rawBuffer:!0,appspace:"kemu.",encoding:"hex"};const pl=Object.values({protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8}).reduce(((e,t)=>e+t),0),hl=e=>{try{return JSON.parse(e)}catch(e){return null}},fl="undefined"!=typeof window,gl={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},ml={protocolPrefix:4,txtLength:4},vl=Object.values(gl).reduce(((e,t)=>e+t),0),yl=Object.values(ml).reduce(((e,t)=>e+t),0),bl=["width","height","colorSpace"],Sl=(e,t)=>{const n={},r=[];let s=0,i=Array.isArray(e)?[]:{};const o=(e,i)=>{const a=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,s=e instanceof Uint8Array,i=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":s?"Uint8Array":i?"Int8Array":null})(e);if(!a){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=o(e[n],`${i}[${n}]`);return t}if("object"==typeof e){const t={},n=(e=>{const t=e instanceof Int16Array,n=e instanceof Uint16Array,r=e instanceof Int32Array,s=e instanceof Uint32Array,i=e instanceof Float32Array,o=e instanceof Float64Array,a=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":s?"Uint32Array":i?"Float32Array":o?"Float64Array":a?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${i}"`);for(const n in e)e.hasOwnProperty(n)||bl.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${i}`),t[n]=o(e[n],`${i.length?`${i}.`:""}${n}`);return t}return e}n[i]={index:s,length:e.byteLength,binaryType:a},"Buffer"===t?r.push(Buffer.from(e)):"ArrayBuffer"===a?r.push(e):r.push(e.buffer),s+=e.byteLength};i=o(e,"");let a=null;if(r.length>1)if("ArrayBuffer"===t){const e=r.reduce(((e,t)=>e+t.byteLength),0),t=new Uint8Array(e);let n=0;for(let e=0;e<r.length;e++)t.set(new Uint8Array(r[e]),n),n+=r[e].byteLength;a=t.buffer}else{a=Buffer.concat(r)}else 1===r.length&&(a=r[0]);return a?{map:n,combinedData:a,sourceCopy:i}:null},wl=(e,t,n)=>{const r=t.match(/(\[\d+\])|([^[\].]+)/g)||[];let s=e;for(let e=0;e<r.length;e++){let t=r[e];const i=t.startsWith("[")&&t.endsWith("]"),o=e===r.length-1;if(i){t=t.slice(1,-1);const i=parseInt(t,10);if(!Array.isArray(s))throw new Error(`Expected an array at key "${r.slice(0,e).join(".")}" but found an object.`);o?s[i]=n:(s[i]||(s[i]=r[e+1].startsWith("[")?[]:{}),s=s[i])}else o?s[t]=n:(s[t]||(s[t]=r[e+1].startsWith("[")?[]:{}),s=s[t])}return e},Il=(e,t,n)=>{const r="undefined"!=typeof Buffer,s=t instanceof Uint8Array;for(const i in n)if(n.hasOwnProperty(i)){const{index:o,length:a,binaryType:c}=n[i];let l=null;if(r&&t instanceof Buffer)switch(c){case"Buffer":l=t.subarray(o,o+a);break;case"ArrayBuffer":l=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a);break;case"Uint8Array":l=new Uint8Array(t.subarray(o,o+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.subarray(o,o+a));break;case"Int8Array":l=new Int8Array(t.subarray(o,o+a))}else if(t instanceof ArrayBuffer||t instanceof Uint8Array)switch(c){case"Buffer":if(r){l=Buffer.from(t.slice(o,o+a));break}case"ArrayBuffer":l=s?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a):t.slice(o,o+a);break;case"Uint8Array":l=s?t.slice(o,o+a):new Uint8Array(t.slice(o,o+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.slice(o,o+a));break;case"Int8Array":l=new Int8Array(t.slice(o,o+a))}l&&wl(e,i,l)}return e},_l=e=>Ya(e),$l="KMSG",Cl="KCMD",kl=_l("klProtocol");var El={encode:(e,t,n)=>{const r={json:e.json},s=Sl(r.json,"Buffer"),i=s?.combinedData;s&&(r.jsonBinaryMap=s.map,r.json=s.sourceCopy);const o=i?i.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),l=c.byteLength,u=gl.protocolPrefix+gl.protocolVersion+gl.jsonLength+gl.binaryLength+gl.fromServiceId+gl.toServiceId+gl.sentAt+l+o,d=Buffer.alloc(u),p=Date.now();let h=0;return d.write($l,h),h+=gl.protocolPrefix,d.writeUInt8(1,h),h+=gl.protocolVersion,d.writeUInt32LE(l,h),h+=gl.jsonLength,d.writeUInt32LE(o,h),h+=gl.binaryLength,d.writeUInt32LE(t,h),h+=gl.fromServiceId,d.writeUInt32LE(n,h),h+=gl.toServiceId,d.writeBigInt64LE(BigInt(p),h),h+=gl.sentAt,c.copy(d,h),h+=l,i&&o&&i.copy(d,h),d},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,gl.protocolPrefix);if(t+=gl.protocolPrefix,n!==$l)return null;if(e.byteLength<vl)return kl(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=gl.protocolVersion;const s=e.readUInt32LE(t);t+=gl.jsonLength;const i=e.readUInt32LE(t);t+=gl.binaryLength;const o=e.readUInt32LE(t);t+=gl.fromServiceId;const a=e.readUInt32LE(t);t+=gl.toServiceId;const c=e.readBigInt64LE(t);t+=gl.sentAt;const l=s+i,u=e.subarray(t,t+l),d=e.subarray(0,vl);let p=null;return e.byteLength-vl-s-i>0&&(p=e.subarray(vl+s+i)),{header:{protocolVersion:r,jsonLength:s,binaryLength:i,fromServiceId:o,toServiceId:a,sentAt:new Date(Number(c)),packages:[u],headerPackage:d},remaining:p}},decodeFullKlMessage:e=>{const t=Buffer.concat(e.packages),n=t.subarray(0,e.jsonLength).toString(),r=t.subarray(e.jsonLength,e.jsonLength+e.binaryLength),s=hl(n);if(!s?.json)return kl("Invalid JSON in KL message"),null;s.jsonBinaryMap&&r.byteLength&&Il(s.json,r,s.jsonBinaryMap);const i=Buffer.concat([e.headerPackage,t]);let o=i,a=null;const c=vl+e.jsonLength+e.binaryLength;return i.byteLength>c&&(a=i.subarray(c),o=i.subarray(0,c)),{message:{json:s.json,rawMessage:o},remaining:a}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<vl)return kl("Invalid Header Size"),e;let n=0;return n+=gl.protocolPrefix,n+=gl.protocolVersion,n+=gl.jsonLength,n+=gl.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=gl.fromServiceId,void 0!==t.toServiceId&&e.writeUInt32LE(t.toServiceId,n),e},encodeCommand:e=>{let t=0;const n=Buffer.from(e),r=n.byteLength,s=yl+r,i=Buffer.alloc(s);return i.write(Cl,t),t+=ml.protocolPrefix,i.writeUint32LE(r,t),t+=ml.txtLength,n.copy(i,t),i},decodeCommand:e=>{let t=0;if(e.byteLength<yl)return{command:null};const n=e.toString("utf-8",t,ml.protocolPrefix);if(t+=ml.protocolPrefix,n!==Cl)return{command:null};const r=e.readUInt32LE(t);t+=ml.txtLength;const s=e.toString("utf-8",t,t+r),i=e.byteLength-yl-r;let o=null;i>0&&(o=e.subarray(yl+r));let a=0;return i<0&&(a=Math.abs(i)),{command:s,remainingData:o,missing:a}}};const xl="KMSG",Al="KCMD",Nl=_l("klProtocol"),Ol=new TextEncoder;var Ll={encode:(e,t,n)=>{const r={json:e.json},s=Sl(e.json,"ArrayBuffer"),i=s?.combinedData;s&&(r.jsonBinaryMap=s.map,r.json=s.sourceCopy);const o=i?i.byteLength:0,a=JSON.stringify(r),c=Ol.encode(a),l=c.byteLength,u=new ArrayBuffer(gl.protocolPrefix+gl.protocolVersion+gl.jsonLength+gl.binaryLength+gl.fromServiceId+gl.toServiceId+gl.sentAt+l+o),d=new DataView(u),p=new Uint8Array(u),h=Date.now();let f=0;for(let e=0;e<4;++e)p[f++]=xl.charCodeAt(e);return d.setUint8(f,1),f+=gl.protocolVersion,d.setUint32(f,l,!0),f+=gl.jsonLength,d.setUint32(f,o,!0),f+=gl.binaryLength,d.setUint32(f,t,!0),f+=gl.fromServiceId,d.setUint32(f,n,!0),f+=gl.toServiceId,d.setBigInt64(f,BigInt(h),!0),f+=gl.sentAt,p.set(c,f),f+=l,i&&o&&p.set(new Uint8Array(i),f),u},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<gl.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==xl)return null;if(e.byteLength<vl)return Nl.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const s=t.getUint8(n);n+=gl.protocolVersion;const i=t.getUint32(n,!0);n+=gl.jsonLength;const o=t.getUint32(n,!0);n+=gl.binaryLength;const a=t.getUint32(n,!0);n+=gl.fromServiceId;const c=t.getUint32(n,!0);n+=gl.toServiceId;const l=t.getBigInt64(n,!0);n+=gl.sentAt;const u=i+o,d=e.slice(n,n+u),p=new Uint8Array(e,0,vl);let h=null;if(e.byteLength-vl-i-o>0){h=new Uint8Array(e,vl+i+o).slice().buffer}return{header:{protocolVersion:s,jsonLength:i,binaryLength:o,fromServiceId:a,toServiceId:c,sentAt:new Date(Number(l)),packages:[d],headerPackage:p.slice().buffer},remaining:h}},decodeFullKlMessage:e=>{const t=e.packages.reduce(((e,t)=>e+t.byteLength),0),n=new Uint8Array(t);let r,s=0;for(const t of e.packages)r=new Uint8Array(t),n.set(r,s),s+=r.byteLength;const i=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),o=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=hl(i);if(!a?.json)return Nl.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&o.byteLength&&Il(a.json,o,a.jsonBinaryMap);const c=new Uint8Array(e.headerPackage.byteLength+n.byteLength);c.set(new Uint8Array(e.headerPackage),0),c.set(n,e.headerPackage.byteLength);let l=c,u=null;const d=vl+e.jsonLength+e.binaryLength;return c.byteLength>d&&(u=c.subarray(d),l=c.subarray(0,d)),{message:{json:a.json,...o.length?{binaryData:o.buffer}:{},rawMessage:l.buffer},remaining:u?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<vl)return Nl("Invalid Header Size"),e;let n=0;n+=gl.protocolPrefix,n+=gl.protocolVersion,n+=gl.jsonLength,n+=gl.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=gl.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=Ol.encode(e),r=n.byteLength,s=new ArrayBuffer(yl+r),i=new DataView(s),o=new Uint8Array(s);for(let e=0;e<4;++e)o[t++]=Al.charCodeAt(e);return i.setUint32(t,r,!0),t+=ml.txtLength,o.set(n,t),s},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<yl)return{command:null};let r="";for(let e=0;e<ml.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Al)return{command:null};const s=t.getUint32(n,!0);n+=ml.txtLength;const i=e.byteLength-yl-s,o=new Uint8Array(e,n,Math.min(s,e.byteLength-yl)),a=(new TextDecoder).decode(o);let c=null;i>0&&(c=e.slice(yl+s));let l=0;return i<0&&(l=Math.abs(i)),{command:a,remainingData:c,missing:l}}};const Pl=_l("klTransmissionManager"),Tl=()=>{const e=(t,n,r,s)=>{let i=n,o=null;const a=t instanceof ArrayBuffer;if(Pl(`RAW: ${t.toString()}`),!i||i.partialHeaderData){let c;if(a?(c=i?.partialHeaderData?new Uint8Array([...new Uint8Array(i.partialHeaderData),...new Uint8Array(t)]).buffer:t,o=Ll.decodeHeader(c)):(c=i?.partialHeaderData?Buffer.concat([i.partialHeaderData,t]):t,o=El.decodeHeader(c)),!o){const{command:t,missing:i,remainingData:o}=a?Ll.decodeCommand(c):El.decodeCommand(c);return t?s({command:t,complete:!0,rawMessage:c}):Pl(i?`ERROR: Missing ${i} bytes to complete the command. This partial command will be aborted.`:`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${c.byteLength} bytes`),o?(Pl(`${o.byteLength} bytes remain after processing command. Re-analyzing...`),e(o,n,r,s)):void 0}if(o.partialHeader)return i={firstPackageAt:Date.now(),partialHeaderData:c},r(i);if(!o.header)return Pl(`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${c.byteLength} bytes`);const l=o.header;i={firstPackageAt:Date.now(),header:{...l,totalBytesReceived:l.packages[0].byteLength,totalBytesExpected:l.binaryLength+l.jsonLength,remaining:o.remaining}},r(i)}else i.header&&i.header.totalBytesReceived<i.header.totalBytesExpected&&(i.header.packages.push(t),i.header.totalBytesReceived+=t.byteLength,r(i));if(i.header&&i.header.totalBytesReceived>=i.header.totalBytesExpected){const t=Date.now()-i.header.sentAt.getTime(),n=Date.now()-i.firstPackageAt;Pl(`Received ${i.header.totalBytesReceived} of ${i.header.totalBytesExpected} expected in ${t} ms, elapsed since first package: ${n}ms`);const o=a?Ll.decodeFullKlMessage(i.header):El.decodeFullKlMessage(i.header),c=i.header.totalBytesReceived,l=i.header.remaining;r(null),o&&s({klMessage:o.message,complete:!0,sourceServiceId:i.header.fromServiceId,targetServiceId:i.header.toServiceId,rawMessage:o.message.rawMessage});let u=l;if(o?.remaining&&(u=a?l?((e,t)=>{const n=e.byteLength+t.byteLength,r=new ArrayBuffer(n),s=new Uint8Array(e),i=new Uint8Array(t),o=new Uint8Array(r);return o.set(s),o.set(i,s.length),r})(l,o.remaining):o.remaining:l?Buffer.concat([l,o.remaining]):o.remaining),u)return Pl(`${u.byteLength} bytes remaining after processing message with ${c} bytes of data. Re-analyzing...`),e(u,null,r,s)}};return e};ul.config={...ul.config,...dl};const Bl={info:Xa("ipcServer:info"),data:Xa("ipcServer:data")};let jl,Dl,Ul,Ml,Fl={};const Rl=Tl(),Wl=e=>{Fl[e]&&(Bl.info(`Client disconnected [${e}]`),delete Fl[e],Dl&&Dl(e))};var Gl=e=>(e?.ipcId&&(ul.config.id=e.ipcId),e?.ipcAppSpace&&(ul.config.appspace=e.ipcAppSpace),new Promise((e=>{ul.serve((()=>{Bl.info("IPC Server Initiated"),ul.server.on("data",((e,t)=>{const n=Fl[t.id];n?(Bl.data(`IPC Socket [${t.id}] data ${e.byteLength} bytes`),Rl(e,n.activeMessage,(e=>n.activeMessage=e),(e=>{if(!e.complete)return;const n=e=>{t.write(e)};if(e.command)return Bl.data(`Received command from client [${t.id}]: ${e.command}`),void(Ul&&Ul(t.id,e.command,n));e.klMessage&&Ml&&Ml({send:n,transmission:{sourceServiceId:e.sourceServiceId??-1,targetServiceId:e.targetServiceId??-1,rawMessage:e.rawMessage},json:e.klMessage.json})}))):Bl.data(`Received data from unknown client [${t.id}]. Ignoring.`)})),ul.server.on("connect",(e=>{const t=ec();Bl.info(`New client connected. Registered as "${t}"`),e.id=t,Fl[t]={socket:e,activeMessage:null,disconnectHandler:()=>Wl(t)},e.on("close",Fl[t].disconnectHandler),jl&&jl(t)})),ul.server.on("disconnect",(e=>{Wl(e.id)})),ul.server.on("error",(e=>{console.log(`IPC Server Error: ${e}`)})),e()})),ul.server.start()}))),Vl=e=>{jl=e},Hl=e=>{Dl=e},zl=e=>Ml=e,ql=(e,t)=>{const n=Fl[e];if(!n)return Bl.info(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=pl)return Bl.info("Message is too long to be a command. Use sendMessage instead."),!1;const r=El.encodeCommand(t);return n.socket.write(r),!0},Kl=(e,t)=>{const n=Fl[e];return!!n&&(Bl.info(`Renaming socket id [${e}] to [${t}]`),delete Fl[e],n.socket.id=t,Fl[t]=n,n.socket.removeListener("close",n.disconnectHandler),n.disconnectHandler=()=>Wl(t),n.socket.on("close",n.disconnectHandler),!0)},Jl=e=>{Ul=e};let Yl=El;fl&&(Yl=Ll);var Xl,Zl=Yl;!function(e){e.FunctionNotFound="FNC_NOT_FOUND"}(Xl||(Xl={}));let Ql=Math.ceil(Date.now()/1e3);var eu={exports:{}};const tu=["nodebuffer","arraybuffer","fragments"],nu="undefined"!=typeof Blob;nu&&tu.push("blob");var ru={BINARY_TYPES:tu,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:nu,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:su}=ru,iu=Buffer[Symbol.species];function ou(e,t,n,r,s){for(let i=0;i<s;i++)n[r+i]=e[i]^t[3&i]}function au(e,t){for(let n=0;n<e.length;n++)e[n]^=t[3&n]}if(eu.exports={concat:function(e,t){if(0===e.length)return su;if(1===e.length)return e[0];const n=Buffer.allocUnsafe(t);let r=0;for(let t=0;t<e.length;t++){const s=e[t];n.set(s,r),r+=s.length}return r<t?new iu(n.buffer,n.byteOffset,r):n},mask:ou,toArrayBuffer:function(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)},toBuffer:function e(t){if(e.readOnly=!0,Buffer.isBuffer(t))return t;let n;return t instanceof ArrayBuffer?n=new iu(t):ArrayBuffer.isView(t)?n=new iu(t.buffer,t.byteOffset,t.byteLength):(n=Buffer.from(t),e.readOnly=!1),n},unmask:au},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");eu.exports.mask=function(t,n,r,s,i){i<48?ou(t,n,r,s,i):e.mask(t,n,r,s,i)},eu.exports.unmask=function(t,n){t.length<32?au(t,n):e.unmask(t,n)}}catch(e){}var cu=eu.exports;const lu=Symbol("kDone"),uu=Symbol("kRun");const du=P,pu=cu,hu=class{constructor(e){this[lu]=()=>{this.pending--,this[uu]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[uu]()}[uu](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[lu])}}},{kStatusCode:fu}=ru,gu=Buffer[Symbol.species],mu=Buffer.from([0,0,255,255]),vu=Symbol("permessage-deflate"),yu=Symbol("total-length"),bu=Symbol("callback"),Su=Symbol("buffers"),wu=Symbol("error");let Iu;var _u=class{constructor(e,t,n){if(this._maxPayload=0|n,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!Iu){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;Iu=new hu(e)}}static get extensionName(){return"permessage-deflate"}offer(){const e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){const e=this._deflate[bu];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){const t=this._options,n=e.find((e=>!(!1===t.serverNoContextTakeover&&e.server_no_context_takeover||e.server_max_window_bits&&(!1===t.serverMaxWindowBits||"number"==typeof t.serverMaxWindowBits&&t.serverMaxWindowBits>e.server_max_window_bits)||"number"==typeof t.clientMaxWindowBits&&!e.client_max_window_bits)));if(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(n.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?n.client_max_window_bits=t.clientMaxWindowBits:!0!==n.client_max_window_bits&&!1!==t.clientMaxWindowBits||delete n.client_max_window_bits,n}acceptAsClient(e){const t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach((e=>{Object.keys(e).forEach((t=>{let n=e[t];if(n.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(n=n[0],"client_max_window_bits"===t){if(!0!==n){const e=+n;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${n}`)}else if("server_max_window_bits"===t){const e=+n;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else{if("client_no_context_takeover"!==t&&"server_no_context_takeover"!==t)throw new Error(`Unknown parameter "${t}"`);if(!0!==n)throw new TypeError(`Invalid value for parameter "${t}": ${n}`)}e[t]=n}))})),e}decompress(e,t,n){Iu.add((r=>{this._decompress(e,t,((e,t)=>{r(),n(e,t)}))}))}compress(e,t,n){Iu.add((r=>{this._compress(e,t,((e,t)=>{r(),n(e,t)}))}))}_decompress(e,t,n){const r=this._isServer?"client":"server";if(!this._inflate){const e=`${r}_max_window_bits`,t="number"!=typeof this.params[e]?du.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=du.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[vu]=this,this._inflate[yu]=0,this._inflate[Su]=[],this._inflate.on("error",ku),this._inflate.on("data",Cu)}this._inflate[bu]=n,this._inflate.write(e),t&&this._inflate.write(mu),this._inflate.flush((()=>{const e=this._inflate[wu];if(e)return this._inflate.close(),this._inflate=null,void n(e);const s=pu.concat(this._inflate[Su],this._inflate[yu]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[yu]=0,this._inflate[Su]=[],t&&this.params[`${r}_no_context_takeover`]&&this._inflate.reset()),n(null,s)}))}_compress(e,t,n){const r=this._isServer?"server":"client";if(!this._deflate){const e=`${r}_max_window_bits`,t="number"!=typeof this.params[e]?du.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=du.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[yu]=0,this._deflate[Su]=[],this._deflate.on("data",$u)}this._deflate[bu]=n,this._deflate.write(e),this._deflate.flush(du.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=pu.concat(this._deflate[Su],this._deflate[yu]);t&&(e=new gu(e.buffer,e.byteOffset,e.length-4)),this._deflate[bu]=null,this._deflate[yu]=0,this._deflate[Su]=[],t&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),n(null,e)}))}};function $u(e){this[Su].push(e),this[yu]+=e.length}function Cu(e){this[yu]+=e.length,this[vu]._maxPayload<1||this[yu]<=this[vu]._maxPayload?this[Su].push(e):(this[wu]=new RangeError("Max payload size exceeded"),this[wu].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[wu][fu]=1009,this.removeListener("data",Cu),this.reset())}function ku(e){this[vu]._inflate=null,e[fu]=1007,this[bu](e)}var Eu={exports:{}};const{isUtf8:xu}=T,{hasBlob:Au}=ru;function Nu(e){const t=e.length;let n=0;for(;n<t;)if(128&e[n])if(192==(224&e[n])){if(n+1===t||128!=(192&e[n+1])||192==(254&e[n]))return!1;n+=2}else if(224==(240&e[n])){if(n+2>=t||128!=(192&e[n+1])||128!=(192&e[n+2])||224===e[n]&&128==(224&e[n+1])||237===e[n]&&160==(224&e[n+1]))return!1;n+=3}else{if(240!=(248&e[n]))return!1;if(n+3>=t||128!=(192&e[n+1])||128!=(192&e[n+2])||128!=(192&e[n+3])||240===e[n]&&128==(240&e[n+1])||244===e[n]&&e[n+1]>143||e[n]>244)return!1;n+=4}else n++;return!0}if(Eu.exports={isBlob:function(e){return Au&&"object"==typeof e&&"function"==typeof e.arrayBuffer&&"string"==typeof e.type&&"function"==typeof e.stream&&("Blob"===e[Symbol.toStringTag]||"File"===e[Symbol.toStringTag])},isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:Nu,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},xu)Eu.exports.isValidUTF8=function(e){return e.length<24?Nu(e):xu(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");Eu.exports.isValidUTF8=function(t){return t.length<32?Nu(t):e(t)}}catch(e){}var Ou=Eu.exports;const{Writable:Lu}=L,Pu=_u,{BINARY_TYPES:Tu,EMPTY_BUFFER:Bu,kStatusCode:ju,kWebSocket:Du}=ru,{concat:Uu,toArrayBuffer:Mu,unmask:Fu}=cu,{isValidStatusCode:Ru,isValidUTF8:Wu}=Ou,Gu=Buffer[Symbol.species];var Vu=class extends Lu{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||Tu[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Du]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(8===this._opcode&&0==this._state)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){const t=this._buffers[0];return this._buffers[0]=new Gu(t.buffer,t.byteOffset+e,t.length-e),new Gu(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new Gu(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do{switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:return void(this._loop=!1)}}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2)return void(this._loop=!1);const t=this.consume(2);if(48&t[0]){return void e(this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3"))}const n=!(64&~t[0]);if(!n||this._extensions[Pu.extensionName]){if(this._fin=!(128&~t[0]),this._opcode=15&t[0],this._payloadLength=127&t[1],0===this._opcode){if(n){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(!this._fragmented){return void e(this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE"))}this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented){return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"))}this._compressed=n}else{if(!(this._opcode>7&&this._opcode<11)){return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"))}if(!this._fin){return void e(this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN"))}if(n){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength){return void e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"))}}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=!(128&~t[1]),this._isServer){if(!this._masked){return void e(this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK"))}}else if(this._masked){return void e(this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK"))}126===this._payloadLength?this._state=1:127===this._payloadLength?this._state=2:this.haveLength(e)}else{e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}}getPayloadLength16(e){this._bufferedBytes<2?this._loop=!1:(this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e))}getPayloadLength64(e){if(this._bufferedBytes<8)return void(this._loop=!1);const t=this.consume(8),n=t.readUInt32BE(0);if(n>Math.pow(2,21)-1){e(this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"))}else this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"))}else this._masked?this._state=3:this._state=4}getMask(){this._bufferedBytes<4?this._loop=!1:(this._mask=this.consume(4),this._state=4)}getData(e){let t=Bu;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength)return void(this._loop=!1);t=this.consume(this._payloadLength),this._masked&&this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3]&&Fu(t,this._mask)}if(this._opcode>7)this.controlMessage(t,e);else{if(this._compressed)return this._state=5,void this.decompress(t,e);t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}}decompress(e,t){this._extensions[Pu.extensionName].decompress(e,this._fin,((e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){const e=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");return void t(e)}this._fragments.push(n)}this.dataMessage(t),0===this._state&&this.startLoop(t)}))}dataMessage(e){if(!this._fin)return void(this._state=0);const t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let r;r="nodebuffer"===this._binaryType?Uu(n,t):"arraybuffer"===this._binaryType?Mu(Uu(n,t)):"blob"===this._binaryType?new Blob(n):n,this._allowSynchronousEvents?(this.emit("message",r,!0),this._state=0):(this._state=6,setImmediate((()=>{this.emit("message",r,!0),this._state=0,this.startLoop(e)})))}else{const r=Uu(n,t);if(!this._skipUTF8Validation&&!Wu(r)){const t=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void e(t)}5===this._state||this._allowSynchronousEvents?(this.emit("message",r,!1),this._state=0):(this._state=6,setImmediate((()=>{this.emit("message",r,!1),this._state=0,this.startLoop(e)})))}}controlMessage(e,t){if(8!==this._opcode)this._allowSynchronousEvents?(this.emit(9===this._opcode?"ping":"pong",e),this._state=0):(this._state=6,setImmediate((()=>{this.emit(9===this._opcode?"ping":"pong",e),this._state=0,this.startLoop(t)})));else{if(0===e.length)this._loop=!1,this.emit("conclude",1005,Bu),this.end();else{const n=e.readUInt16BE(0);if(!Ru(n)){const e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const r=new Gu(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Wu(r)){const e=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void t(e)}this._loop=!1,this.emit("conclude",n,r),this.end()}this._state=0}}createError(e,t,n,r,s){this._loop=!1,this._errored=!0;const i=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(i,this.createError),i.code=s,i[ju]=r,i}};const{randomFillSync:Hu}=C,zu=_u,{EMPTY_BUFFER:qu,kWebSocket:Ku,NOOP:Ju}=ru,{isBlob:Yu,isValidStatusCode:Xu}=Ou,{mask:Zu,toBuffer:Qu}=cu,ed=Symbol("kByteLength"),td=Buffer.alloc(4),nd=8192;let rd,sd=nd;var id=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=Ju,this[Ku]=void 0}static frame(e,t){let n,r,s=!1,i=2,o=!1;t.mask&&(n=t.maskBuffer||td,t.generateMask?t.generateMask(n):(sd===nd&&(void 0===rd&&(rd=Buffer.alloc(nd)),Hu(rd,0,nd),sd=0),n[0]=rd[sd++],n[1]=rd[sd++],n[2]=rd[sd++],n[3]=rd[sd++]),o=!(n[0]|n[1]|n[2]|n[3]),i=6),"string"==typeof e?r=t.mask&&!o||void 0===t[ed]?(e=Buffer.from(e)).length:t[ed]:(r=e.length,s=t.mask&&t.readOnly&&!o);let a=r;r>=65536?(i+=8,a=127):r>125&&(i+=2,a=126);const c=Buffer.allocUnsafe(s?r+i:i);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=a,126===a?c.writeUInt16BE(r,2):127===a&&(c[2]=c[3]=0,c.writeUIntBE(r,4,6)),t.mask?(c[1]|=128,c[i-4]=n[0],c[i-3]=n[1],c[i-2]=n[2],c[i-1]=n[3],o?[c,e]:s?(Zu(e,n,c,i,r),[c]):(Zu(e,n,e,0,r),[c,e])):[c,e]}close(t,n,r,s){let i;if(void 0===t)i=qu;else{if("number"!=typeof t||!Xu(t))throw new TypeError("First argument must be a valid error code number");if(void 0!==n&&n.length){const e=Buffer.byteLength(n);if(e>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+e),i.writeUInt16BE(t,0),"string"==typeof n?i.write(n,2):i.set(n,2)}else i=Buffer.allocUnsafe(2),i.writeUInt16BE(t,0)}const o={[ed]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(e.frame(i,o),s)}ping(t,n,r){let s,i;if("string"==typeof t?(s=Buffer.byteLength(t),i=!1):Yu(t)?(s=t.size,i=!1):(s=(t=Qu(t)).length,i=Qu.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[ed]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Yu(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,o,r]):this.getBlobData(t,!1,o,r):0!==this._state?this.enqueue([this.dispatch,t,!1,o,r]):this.sendFrame(e.frame(t,o),r)}pong(t,n,r){let s,i;if("string"==typeof t?(s=Buffer.byteLength(t),i=!1):Yu(t)?(s=t.size,i=!1):(s=(t=Qu(t)).length,i=Qu.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[ed]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Yu(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,o,r]):this.getBlobData(t,!1,o,r):0!==this._state?this.enqueue([this.dispatch,t,!1,o,r]):this.sendFrame(e.frame(t,o),r)}send(e,t,n){const r=this._extensions[zu.extensionName];let s,i,o=t.binary?2:1,a=t.compress;"string"==typeof e?(s=Buffer.byteLength(e),i=!1):Yu(e)?(s=e.size,i=!1):(s=(e=Qu(e)).length,i=Qu.readOnly),this._firstFragment?(this._firstFragment=!1,a&&r&&r.params[r._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=s>=r._threshold),this._compress=a):(a=!1,o=0),t.fin&&(this._firstFragment=!0);const c={[ed]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:i,rsv1:a};Yu(e)?0!==this._state?this.enqueue([this.getBlobData,e,this._compress,c,n]):this.getBlobData(e,this._compress,c,n):0!==this._state?this.enqueue([this.dispatch,e,this._compress,c,n]):this.dispatch(e,this._compress,c,n)}getBlobData(t,n,r,s){this._bufferedBytes+=r[ed],this._state=2,t.arrayBuffer().then((t=>{if(this._socket.destroyed){const e=new Error("The socket was closed while the blob was being read");return void process.nextTick(od,this,e,s)}this._bufferedBytes-=r[ed];const i=Qu(t);n?this.dispatch(i,n,r,s):(this._state=0,this.sendFrame(e.frame(i,r),s),this.dequeue())})).catch((e=>{process.nextTick(ad,this,e,s)}))}dispatch(t,n,r,s){if(!n)return void this.sendFrame(e.frame(t,r),s);const i=this._extensions[zu.extensionName];this._bufferedBytes+=r[ed],this._state=1,i.compress(t,r.fin,((t,n)=>{if(this._socket.destroyed){od(this,new Error("The socket was closed while data was being compressed"),s)}else this._bufferedBytes-=r[ed],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),s),this.dequeue()}))}dequeue(){for(;0===this._state&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][ed],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][ed],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function od(e,t,n){"function"==typeof n&&n(t);for(let n=0;n<e._queue.length;n++){const r=e._queue[n],s=r[r.length-1];"function"==typeof s&&s(t)}}function ad(e,t,n){od(e,t,n),e.onerror(t)}const{kForOnEventAttribute:cd,kListener:ld}=ru,ud=Symbol("kCode"),dd=Symbol("kData"),pd=Symbol("kError"),hd=Symbol("kMessage"),fd=Symbol("kReason"),gd=Symbol("kTarget"),md=Symbol("kType"),vd=Symbol("kWasClean");class yd{constructor(e){this[gd]=null,this[md]=e}get target(){return this[gd]}get type(){return this[md]}}Object.defineProperty(yd.prototype,"target",{enumerable:!0}),Object.defineProperty(yd.prototype,"type",{enumerable:!0});class bd extends yd{constructor(e,t={}){super(e),this[ud]=void 0===t.code?0:t.code,this[fd]=void 0===t.reason?"":t.reason,this[vd]=void 0!==t.wasClean&&t.wasClean}get code(){return this[ud]}get reason(){return this[fd]}get wasClean(){return this[vd]}}Object.defineProperty(bd.prototype,"code",{enumerable:!0}),Object.defineProperty(bd.prototype,"reason",{enumerable:!0}),Object.defineProperty(bd.prototype,"wasClean",{enumerable:!0});class Sd extends yd{constructor(e,t={}){super(e),this[pd]=void 0===t.error?null:t.error,this[hd]=void 0===t.message?"":t.message}get error(){return this[pd]}get message(){return this[hd]}}Object.defineProperty(Sd.prototype,"error",{enumerable:!0}),Object.defineProperty(Sd.prototype,"message",{enumerable:!0});class wd extends yd{constructor(e,t={}){super(e),this[dd]=void 0===t.data?null:t.data}get data(){return this[dd]}}Object.defineProperty(wd.prototype,"data",{enumerable:!0});const Id={addEventListener(e,t,n={}){for(const r of this.listeners(e))if(!n[cd]&&r[ld]===t&&!r[cd])return;let r;if("message"===e)r=function(e,n){const r=new wd("message",{data:n?e:e.toString()});r[gd]=this,$d(t,this,r)};else if("close"===e)r=function(e,n){const r=new bd("close",{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[gd]=this,$d(t,this,r)};else if("error"===e)r=function(e){const n=new Sd("error",{error:e,message:e.message});n[gd]=this,$d(t,this,n)};else{if("open"!==e)return;r=function(){const e=new yd("open");e[gd]=this,$d(t,this,e)}}r[cd]=!!n[cd],r[ld]=t,n.once?this.once(e,r):this.on(e,r)},removeEventListener(e,t){for(const n of this.listeners(e))if(n[ld]===t&&!n[cd]){this.removeListener(e,n);break}}};var _d={CloseEvent:bd,ErrorEvent:Sd,Event:yd,EventTarget:Id,MessageEvent:wd};function $d(e,t,n){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}const{tokenChars:Cd}=Ou;function kd(e,t,n){void 0===e[t]?e[t]=[n]:e[t].push(n)}var Ed={format:function(e){return Object.keys(e).map((t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map((e=>[t].concat(Object.keys(e).map((t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map((e=>!0===e?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")},parse:function(e){const t=Object.create(null);let n,r,s=Object.create(null),i=!1,o=!1,a=!1,c=-1,l=-1,u=-1,d=0;for(;d<e.length;d++)if(l=e.charCodeAt(d),void 0===n)if(-1===u&&1===Cd[l])-1===c&&(c=d);else if(0===d||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${d}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${d}`);-1===u&&(u=d);const r=e.slice(c,u);44===l?(kd(t,r,s),s=Object.create(null)):n=r,c=u=-1}}else-1===u&&-1!==c&&(u=d);else if(void 0===r)if(-1===u&&1===Cd[l])-1===c&&(c=d);else if(32===l||9===l)-1===u&&-1!==c&&(u=d);else if(59===l||44===l){if(-1===c)throw new SyntaxError(`Unexpected character at index ${d}`);-1===u&&(u=d),kd(s,e.slice(c,u),!0),44===l&&(kd(t,n,s),s=Object.create(null),n=void 0),c=u=-1}else{if(61!==l||-1===c||-1!==u)throw new SyntaxError(`Unexpected character at index ${d}`);r=e.slice(c,d),c=u=-1}else if(o){if(1!==Cd[l])throw new SyntaxError(`Unexpected character at index ${d}`);-1===c?c=d:i||(i=!0),o=!1}else if(a)if(1===Cd[l])-1===c&&(c=d);else if(34===l&&-1!==c)a=!1,u=d;else{if(92!==l)throw new SyntaxError(`Unexpected character at index ${d}`);o=!0}else if(34===l&&61===e.charCodeAt(d-1))a=!0;else if(-1===u&&1===Cd[l])-1===c&&(c=d);else if(-1===c||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${d}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${d}`);-1===u&&(u=d);let o=e.slice(c,u);i&&(o=o.replace(/\\/g,""),i=!1),kd(s,r,o),44===l&&(kd(t,n,s),s=Object.create(null),n=void 0),r=void 0,c=u=-1}}else-1===u&&(u=d);if(-1===c||a||32===l||9===l)throw new SyntaxError("Unexpected end of input");-1===u&&(u=d);const p=e.slice(c,u);return void 0===n?kd(t,p,s):(void 0===r?kd(s,p,!0):kd(s,r,i?p.replace(/\\/g,""):p),kd(t,n,s)),t}};const xd=B,Ad=j,Nd=D,Od=E,Ld=x,{randomBytes:Pd,createHash:Td}=C,{URL:Bd}=U,jd=_u,Dd=Vu,Ud=id,{isBlob:Md}=Ou,{BINARY_TYPES:Fd,EMPTY_BUFFER:Rd,GUID:Wd,kForOnEventAttribute:Gd,kListener:Vd,kStatusCode:Hd,kWebSocket:zd,NOOP:qd}=ru,{EventTarget:{addEventListener:Kd,removeEventListener:Jd}}=_d,{format:Yd,parse:Xd}=Ed,{toBuffer:Zd}=cu,Qd=3e4,ep=Symbol("kAborted"),tp=[8,13],np=["CONNECTING","OPEN","CLOSING","CLOSED"],rp=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;let sp=class e extends xd{constructor(t,n,r){super(),this._binaryType=Fd[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Rd,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==t?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===n?n=[]:Array.isArray(n)||("object"==typeof n&&null!==n?(r=n,n=[]):n=[n]),op(this,t,n,r)):(this._autoPong=r.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Fd.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){const s=new Dd({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Ud(t,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=t,s[zd]=this,i[zd]=this,t[zd]=this,s.on("conclude",pp),s.on("drain",hp),s.on("error",fp),s.on("message",mp),s.on("ping",vp),s.on("pong",yp),i.onerror=Sp,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on("close",Ip),t.on("data",_p),t.on("end",$p),t.on("error",Cp),this._readyState=e.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=e.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[jd.extensionName]&&this._extensions[jd.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED)if(this.readyState!==e.CONNECTING)this.readyState!==e.CLOSING?(this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,(e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())})),wp(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";up(this,this._req,e)}}pause(){this.readyState!==e.CONNECTING&&this.readyState!==e.CLOSED&&(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof t?(r=t,t=n=void 0):"function"==typeof n&&(r=n,n=void 0),"number"==typeof t&&(t=t.toString()),this.readyState===e.OPEN?(void 0===n&&(n=!this._isServer),this._sender.ping(t||Rd,n,r)):dp(this,t,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof t?(r=t,t=n=void 0):"function"==typeof n&&(r=n,n=void 0),"number"==typeof t&&(t=t.toString()),this.readyState===e.OPEN?(void 0===n&&(n=!this._isServer),this._sender.pong(t||Rd,n,r)):dp(this,t,r)}resume(){this.readyState!==e.CONNECTING&&this.readyState!==e.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof n&&(r=n,n={}),"number"==typeof t&&(t=t.toString()),this.readyState!==e.OPEN)return void dp(this,t,r);const s={binary:"string"!=typeof t,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[jd.extensionName]||(s.compress=!1),this._sender.send(t||Rd,s,r)}terminate(){if(this.readyState!==e.CLOSED)if(this.readyState!==e.CONNECTING)this._socket&&(this._readyState=e.CLOSING,this._socket.destroy());else{const e="WebSocket was closed before the connection was established";up(this,this._req,e)}}};Object.defineProperty(sp,"CONNECTING",{enumerable:!0,value:np.indexOf("CONNECTING")}),Object.defineProperty(sp.prototype,"CONNECTING",{enumerable:!0,value:np.indexOf("CONNECTING")}),Object.defineProperty(sp,"OPEN",{enumerable:!0,value:np.indexOf("OPEN")}),Object.defineProperty(sp.prototype,"OPEN",{enumerable:!0,value:np.indexOf("OPEN")}),Object.defineProperty(sp,"CLOSING",{enumerable:!0,value:np.indexOf("CLOSING")}),Object.defineProperty(sp.prototype,"CLOSING",{enumerable:!0,value:np.indexOf("CLOSING")}),Object.defineProperty(sp,"CLOSED",{enumerable:!0,value:np.indexOf("CLOSED")}),Object.defineProperty(sp.prototype,"CLOSED",{enumerable:!0,value:np.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(sp.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(sp.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[Gd])return t[Vd];return null},set(t){for(const t of this.listeners(e))if(t[Gd]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[Gd]:!0})}})})),sp.prototype.addEventListener=Kd,sp.prototype.removeEventListener=Jd;var ip=sp;function op(e,t,n,r){const s={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:tp[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=s.autoPong,!tp.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${tp.join(", ")})`);let i;if(t instanceof Bd)i=t;else try{i=new Bd(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}"http:"===i.protocol?i.protocol="ws:":"https:"===i.protocol&&(i.protocol="wss:"),e._url=i.href;const o="wss:"===i.protocol,a="ws+unix:"===i.protocol;let c;if("ws:"===i.protocol||o||a?a&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"):c='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https", or "ws+unix:"',c){const t=new SyntaxError(c);if(0===e._redirects)throw t;return void ap(e,t)}const l=o?443:80,u=Pd(16).toString("base64"),d=o?Ad.request:Nd.request,p=new Set;let h,f;if(s.createConnection=s.createConnection||(o?lp:cp),s.defaultPort=s.defaultPort||l,s.port=i.port||l,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(h=new jd(!0!==s.perMessageDeflate?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=Yd({[jd.extensionName]:h.offer()})),n.length){for(const e of n){if("string"!=typeof e||!rp.test(e)||p.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");p.add(e)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){const e=s.path.split(":");s.socketPath=e[0],s.path=e[1]}if(s.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=o,e._originalHostOrSocketPath=a?s.socketPath:i.host;const t=r&&r.headers;if(r={...r,headers:{}},t)for(const[e,n]of Object.entries(t))r.headers[e.toLowerCase()]=n}else if(0===e.listenerCount("redirect")){const t=a?!!e._originalIpc&&s.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&i.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,t||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),f=e._req=d(s),e._redirects&&e.emit("redirect",e.url,f)}else f=e._req=d(s);s.timeout&&f.on("timeout",(()=>{up(e,f,"Opening handshake has timed out")})),f.on("error",(t=>{null===f||f[ep]||(f=e._req=null,ap(e,t))})),f.on("response",(i=>{const o=i.headers.location,a=i.statusCode;if(o&&s.followRedirects&&a>=300&&a<400){if(++e._redirects>s.maxRedirects)return void up(e,f,"Maximum redirects exceeded");let i;f.abort();try{i=new Bd(o,t)}catch(t){const n=new SyntaxError(`Invalid URL: ${o}`);return void ap(e,n)}op(e,i,n,r)}else e.emit("unexpected-response",f,i)||up(e,f,`Unexpected server response: ${i.statusCode}`)})),f.on("upgrade",((t,n,r)=>{if(e.emit("upgrade",t),e.readyState!==sp.CONNECTING)return;f=e._req=null;const i=t.headers.upgrade;if(void 0===i||"websocket"!==i.toLowerCase())return void up(e,n,"Invalid Upgrade header");const o=Td("sha1").update(u+Wd).digest("base64");if(t.headers["sec-websocket-accept"]!==o)return void up(e,n,"Invalid Sec-WebSocket-Accept header");const a=t.headers["sec-websocket-protocol"];let c;if(void 0!==a?p.size?p.has(a)||(c="Server sent an invalid subprotocol"):c="Server sent a subprotocol but none was requested":p.size&&(c="Server sent no subprotocol"),c)return void up(e,n,c);a&&(e._protocol=a);const l=t.headers["sec-websocket-extensions"];if(void 0!==l){if(!h){return void up(e,n,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=Xd(l)}catch(t){return void up(e,n,"Invalid Sec-WebSocket-Extensions header")}const r=Object.keys(t);if(1!==r.length||r[0]!==jd.extensionName){return void up(e,n,"Server indicated an extension that was not requested")}try{h.accept(t[jd.extensionName])}catch(t){return void up(e,n,"Invalid Sec-WebSocket-Extensions header")}e._extensions[jd.extensionName]=h}e.setSocket(n,r,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})})),s.finishRequest?s.finishRequest(f,e):f.end()}function ap(e,t){e._readyState=sp.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function cp(e){return e.path=e.socketPath,Od.connect(e)}function lp(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=Od.isIP(e.host)?"":e.host),Ld.connect(e)}function up(e,t,n){e._readyState=sp.CLOSING;const r=new Error(n);Error.captureStackTrace(r,up),t.setHeader?(t[ep]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(ap,e,r)):(t.destroy(r),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function dp(e,t,n){if(t){const n=Md(t)?t.size:Zd(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${np[e.readyState]})`);process.nextTick(n,t)}}function pp(e,t){const n=this[zd];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,void 0!==n._socket[zd]&&(n._socket.removeListener("data",_p),process.nextTick(bp,n._socket),1005===e?n.close():n.close(e,t))}function hp(){const e=this[zd];e.isPaused||e._socket.resume()}function fp(e){const t=this[zd];void 0!==t._socket[zd]&&(t._socket.removeListener("data",_p),process.nextTick(bp,t._socket),t.close(e[Hd])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function gp(){this[zd].emitClose()}function mp(e,t){this[zd].emit("message",e,t)}function vp(e){const t=this[zd];t._autoPong&&t.pong(e,!this._isServer,qd),t.emit("ping",e)}function yp(e){this[zd].emit("pong",e)}function bp(e){e.resume()}function Sp(e){const t=this[zd];t.readyState!==sp.CLOSED&&(t.readyState===sp.OPEN&&(t._readyState=sp.CLOSING,wp(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function wp(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),Qd)}function Ip(){const e=this[zd];let t;this.removeListener("close",Ip),this.removeListener("data",_p),this.removeListener("end",$p),e._readyState=sp.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[zd]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",gp),e._receiver.on("finish",gp))}function _p(e){this[zd]._receiver.write(e)||this.pause()}function $p(){const e=this[zd];e._readyState=sp.CLOSING,e._receiver.end(),this.end()}function Cp(){const e=this[zd];this.removeListener("error",Cp),this.on("error",qd),e&&(e._readyState=sp.CLOSING,this.destroy())}const{tokenChars:kp}=Ou;var Ep={parse:function(e){const t=new Set;let n=-1,r=-1,s=0;for(;s<e.length;s++){const i=e.charCodeAt(s);if(-1===r&&1===kp[i])-1===n&&(n=s);else if(0===s||32!==i&&9!==i){if(44!==i)throw new SyntaxError(`Unexpected character at index ${s}`);{if(-1===n)throw new SyntaxError(`Unexpected character at index ${s}`);-1===r&&(r=s);const i=e.slice(n,r);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);t.add(i),n=r=-1}}else-1===r&&-1!==n&&(r=s)}if(-1===n||-1!==r)throw new SyntaxError("Unexpected end of input");const i=e.slice(n,s);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return t.add(i),t}};const xp=B,Ap=D,{createHash:Np}=C,Op=Ed,Lp=_u,Pp=Ep,Tp=ip,{GUID:Bp,kWebSocket:jp}=ru,Dp=/^[+/0-9A-Za-z]{22}==$/;var Up=class extends xp{constructor(e,t){if(super(),null==(e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Tp,...e}).port&&!e.server&&!e.noServer||null!=e.port&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=e.port?(this._server=Ap.createServer(((e,t)=>{const n=Ap.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":"text/plain"}),t.end(n)})),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){const e=this.emit.bind(this,"connection");this._removeListeners=function(e,t){for(const n of Object.keys(t))e.on(n,t[n]);return function(){for(const n of Object.keys(t))e.removeListener(n,t[n])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(2===this._state)return e&&this.once("close",(()=>{e(new Error("The server is not running"))})),void process.nextTick(Mp,this);if(e&&this.once("close",e),1!==this._state)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(Mp,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{Mp(this)}))}}shouldHandle(e){if(this.options.path){const t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on("error",Fp);const s=e.headers["sec-websocket-key"],i=e.headers.upgrade,o=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void Wp(this,e,t,405,"Invalid HTTP method")}if(void 0===i||"websocket"!==i.toLowerCase()){return void Wp(this,e,t,400,"Invalid Upgrade header")}if(void 0===s||!Dp.test(s)){return void Wp(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==o&&13!==o){return void Wp(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void Rp(t,400);const a=e.headers["sec-websocket-protocol"];let c=new Set;if(void 0!==a)try{c=Pp.parse(a)}catch(n){return void Wp(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const l=e.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&void 0!==l){const n=new Lp(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=Op.parse(l);e[Lp.extensionName]&&(n.accept(e[Lp.extensionName]),u[Lp.extensionName]=n)}catch(n){return void Wp(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const i={origin:e.headers[""+(8===o?"sec-websocket-origin":"origin")],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(i,((i,o,a,l)=>{if(!i)return Rp(t,o||401,a,l);this.completeUpgrade(u,s,c,e,t,n,r)}));if(!this.options.verifyClient(i))return Rp(t,401)}this.completeUpgrade(u,s,c,e,t,n,r)}completeUpgrade(e,t,n,r,s,i,o){if(!s.readable||!s.writable)return s.destroy();if(s[jp])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return Rp(s,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Np("sha1").update(t+Bp).digest("base64")}`],c=new this.options.WebSocket(null,void 0,this.options);if(n.size){const e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(a.push(`Sec-WebSocket-Protocol: ${e}`),c._protocol=e)}if(e[Lp.extensionName]){const t=e[Lp.extensionName].params,n=Op.format({[Lp.extensionName]:[t]});a.push(`Sec-WebSocket-Extensions: ${n}`),c._extensions=e}this.emit("headers",a,r),s.write(a.concat("\r\n").join("\r\n")),s.removeListener("error",Fp),c.setSocket(s,i,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(c),c.on("close",(()=>{this.clients.delete(c),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Mp,this)}))),o(c,r)}};function Mp(e){e._state=2,e.emit("close")}function Fp(){this.destroy()}function Rp(e,t,n,r){n=n||Ap.STATUS_CODES[t],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${Ap.STATUS_CODES[t]}\r\n`+Object.keys(r).map((e=>`${e}: ${r[e]}`)).join("\r\n")+"\r\n\r\n"+n)}function Wp(e,t,n,r,s){if(e.listenerCount("wsClientError")){const r=new Error(s);Error.captureStackTrace(r,Wp),e.emit("wsClientError",r,n,t)}else Rp(n,r,s)}var Gp=Pa(Up);const Vp=Xa("websocketServer"),Hp={},zp=Tl();let qp,Kp,Jp,Yp,Xp;const Zp=e=>{const t=Hp[e];t&&t.socket.close()};var Qp={startServer:e=>{Xp=new Gp({port:e,maxPayload:104857600}),Xp.on("connection",(e=>{const t=ec();Vp(`New client connected. Registered as "${t}"`),e.id=t,Hp[t]={socket:e,activeMessage:null},qp&&qp(t),e.on("message",(t=>{if(t instanceof Buffer){const n=Hp[e.id];zp(t,n.activeMessage,(e=>n.activeMessage=e),(t=>{if(!t.complete)return;const r=t=>{e.send(t),Vp(`Writing ${t.byteLength} bytes to socket [${n.socket.id}]: ${t.toString()}`)},s=()=>{Zp(n.socket.id)};if(t.command)return Vp(`Received command from client [${n.socket.id}]: ${t.command}`),void(Jp&&Jp(n.socket.id,t.command,r,s));t.klMessage&&Yp&&Yp({send:r,terminateWebsocket:s,websocketId:n.socket.id,transmission:{sourceServiceId:t.sourceServiceId??-1,targetServiceId:t.targetServiceId??-1,rawMessage:t.rawMessage},json:t.klMessage.json})}))}})),e.on("close",(()=>{Vp(`Client disconnected: ${e.id}`),Kp&&Kp(e.id),delete Hp[e.id]})),e.on("error",(()=>{Vp(`Error on client connection: ${e.id}`)}))})),console.log(`WebSocket server is running on port ${e}`)},stopServer:()=>{Xp.close((()=>{console.log("WebSocket server stopped")}))},onClientConnected:e=>{qp=e},onClientDisconnected:e=>{Kp=e},onClientCommand:e=>{Jp=e},sendCommand:(e,t)=>{const n=Hp[e];if(!n)return Vp(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=pl)return Vp("Message is too long to be a command. Use sendMessage instead."),!1;const r=El.encodeCommand(t);return n.socket.send(r),!0},onMessageReceived:e=>Yp=e,terminateConnection:Zp};const eh=Xa("stopService"),th=async e=>{const t=e.args[0];if(!t)return e.reply({error:"No service name provided"});const n=Nc.getAllServiceVersions(t);eh(`Stopping ${n.length} services with name: ${t}`);for(const e of n)await Nc.stopService(e.info.name,e.info.version);const r=n.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[r]})},nh=Xa("removeService"),rh=async e=>{const t=e.args[0],n=e.args[1];if(!t)return e.reply({error:"No service name provided"});let r=Nc.getAllServiceVersions(t);n&&(r=r.filter((e=>e.info.version===n))),nh(`Removing ${r.length} service(s) with name: ${t}`);for(const e of r)await Nc.uninstallService(e.info.name,e.info.version);const s=r.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[s]})},sh=Xa("launchService"),ih=async e=>{const t=e.args[0],n=e.args[1];if(!t)return e.reply({error:"No service name provided"});if(!n)return e.reply({error:"No service version provided"});const r=`${t}@${n}/dist`;try{const s=pc();sh(`Loading service ${t}@${n} from ${s}`);const{errorMsg:i,service:o,errorCode:a}=await Nc.loadAndLaunch(s,r,!1);if(i||"started"!==o?.status)return e.reply({error:`Failed to launch service ${t}@${n}: ${i||"error-not-provided"}`,errCode:a});const c=Date.now(),l=3e4,u=async()=>{const r=o.status;return"running"===r?(sh(`Service ${t}@${n} loaded and started`),e.reply({success:[]})):(sh(`Service ${t}@${n} not yet started, status: ${r}`),"stopped"===r||"error"===r?e.reply({error:`Error launching service: "${o.errorMsg||"failed to initiate"}"`}):Date.now()-c>l?e.reply({error:"Timeout waiting for service to start"}):(sh("Retrying in 1 second..."),void setTimeout(u,1e3)))};u()}catch(r){return sh(`Error loading service ${t}@${n}: ${r?.message||r}`),e.reply({error:r?.message||"There was an error loading the service"})}},oh=Xa("getMatchingServices"),ah=async e=>{const t=e.args[0],n=[],r=[];oh(`Checking for matching services: ${t.map((e=>e.name)).join(", ")}`);for(const{name:e,version:s}of t){const t=Nc.getMatchingService(e,s);t?n.push({name:e,version:s,installationPath:Nc.getServiceRootDirectory(t)}):r.push({name:e,version:s})}oh(`Found ${n.length} available services and ${r.length} missing services.`),e.reply({success:[{available:n,missing:r}]})},ch=Xa("getSecretsValues");let lh;var uh=async e=>{const t=e.args[0].services;if(!lh)throw new Error("getSecretValuesFn is not set. Please call setGetSecretValuesFunction before using this function.");ch(`Checking for secrets values for services: ${t.map((e=>`${e.name}@${e.version}`)).join(", ")}`);const n=[];for(const e of t){const t=e.secrets,r=await lh({name:e.name,version:e.version,requiredSecrets:t.reduce(((e,t)=>(e[t]={optional:!1,description:""},e)),{})});n.push({name:e.name,version:e.version,secrets:t.map((e=>({name:e,value:r[e]})))})}const r=[{services:n}];e.reply({success:r})},dh=e=>{lh=e};const ph=Xa("getMappedSecrets");let hh;var fh=async e=>{const t=e.args[0].services;ph(`Getting mapped secrets for services: ${t.map((e=>`${e.name}@${e.version}`)).join(", ")}`);const n=await hh(t),r=[{services:t.map((e=>({name:e.name,version:e.version,secrets:n[e.name]||[]})))}];e.reply({success:r})},gh=e=>{hh=e};const mh=Xa("getServiceContents"),vh=({reply:e,args:t})=>{const[n]=t;mh(`Received GetServiceContents request for service ${n.serviceName} v${n.version}`);const r=Nc.getMatchingService(n.serviceName,n.version);if(r){return e({success:[{serviceName:r.info.name,serviceVersion:r.info.version,uiContent:r.info.widgetUIContents,uiContentsChecksum:r.info.uiContentChecksum}]})}mh(`Service ${n.serviceName} v${n.version} not found`),e({error:`Service ${n.serviceName} v${n.version} not found`})};let yh=null;const bh=async e=>{const{data:t,error:n}=await(async(e,t)=>{try{const n=await fetch(e,{method:"POST",body:JSON.stringify(t)});return n.ok?{data:await n.json(),statusCode:n.status,success:!0}:{statusCode:n.status,error:await n.text(),success:!1}}catch(e){return{statusCode:500,error:e instanceof Error?e.message:"Internal server error",success:!1}}})(`${(()=>{if(!yh)throw new Error("Unknown server URL. Please call `setServerUrl` before using the APIs.");return yh})()}/v1/validate/validate_key`,{apiKey:e});return n?(console.warn(`Error validating Kemu API key: ${n}`),{valid:!1,features:{},error:n}):t?.features?{valid:!0,features:t.features,error:null}:{valid:!1,features:{},error:"No features returned from the server"}},Sh={},wh=async e=>{const t=(e=>{const t=Sh[e],n=Date.now()-(t?.lastCheckedAt.getTime()??0);return t&&n<3e5?t.features:null})(e);if(t)return{valid:!0,features:t,error:null};const{valid:n,features:r,error:s}=await bh(e);return n&&(Sh[e]={features:r,lastCheckedAt:new Date}),{valid:n,features:r,error:s}},Ih=Xa("activeClients");let _h={},$h={};const Ch=(e,t)=>`${e}_${t}`,kh=e=>_h[e]||null,Eh=(e,t)=>{const n=Ch(e,t);return $h[n]||[]},xh=()=>{for(const e in _h){const t=_h[e];if(t?.transport===ga.WS){const e=El.encodeCommand(pa.ServicesListChanged);t.send(e)}}},Ah=async e=>{const t=[],{serviceSessionId:n,transport:r,send:s,terminateFn:i,extraInfo:o,isDevClient:a}=e,c=e=>{console.warn(e),i&&i()};if(r===ga.WS){if(!o.wsApiKey)return void c(`Attempted to register a WebSocket client without an API key. SessionId: ${n}`);const{valid:e,error:t}=await wh(o.wsApiKey);if(!e&&!t)return void c(`Attempted to register a WebSocket client with an invalid API key. SessionId: ${n}`);t&&Ih(`Unable to validate API Key, usage will be limited. SessionId: ${n}`)}_h[n]={serviceSessionId:n,transport:r,isDevClient:!!a,broadcastSubscriptions:t,send:s,extraInfo:o,terminate:()=>{i&&i()},addSubscription:e=>{if(!t.some((t=>t.targetService.serviceName===e.serviceName&&t.targetService.version===e.version))){t.push({targetService:e});const r=Ch(e.serviceName,e.version);$h[r]=$h[r]||[];return $h[r].some((e=>e.serviceId===n))||$h[r].push({sendFn:s,serviceId:n}),!0}return!1},removeSubscription:e=>{const r=t.findIndex((t=>t.targetService.serviceName===e.serviceName));if(-1!==r){t.splice(r,1);const s=Ch(e.serviceName,e.version),i=$h[s]?.findIndex((e=>e.serviceId===n));if(-1!==i&&($h[s].splice(i,1),!$h[s].length)){const t=Nc.getMatchingService(e.serviceName,e.version);if(t?.info.eventEmitter&&"running"===t.status){const e=kh(t.info.sessionId);e?.extraInfo.ipcSocketId&&ql(e?.extraInfo.ipcSocketId,pa.BroadcastEnd)}}}},removeAllSubscriptions:()=>{for(const e of t){const t=Ch(e.targetService.serviceName,e.targetService.version),r=$h[t].findIndex((e=>e.serviceId===n));-1!==r&&$h[t].splice(r,1)}t.length=0}},r===ga.IPC&&(xh(),Oh(n))},Nh=()=>{const e=Object.values(_h);for(const t of e)if(t.transport===ga.IPC){const e=t.extraInfo.ipcSocketId,n=Nc.getServiceBySessionId(t.serviceSessionId);if(n?.info.eventEmitter){Eh(n.info.name,n.info.version).length||e&&ql(e,pa.BroadcastEnd)}}},Oh=e=>{const t=Nc.getServiceBySessionId(e);if(t?.info.eventEmitter){if(Eh(t.info.name,t.info.version).length){const t=kh(e);t?.extraInfo.ipcSocketId&&ql(t?.extraInfo.ipcSocketId,pa.BroadcastStart)}}},Lh=e=>{const t=_h[e];delete _h[e],t.transport===ga.IPC?xh():(t.removeAllSubscriptions(),Nh())},Ph=Xa("ipc:handleIpcClientCommand"),Th=(e,t,n)=>{const r=((e,t)=>{if(e.startsWith(pa.AcknowledgeResponse)){const n=e.split(":"),r=parseInt(n[1]),s=parseInt(n[2]);return t&&t(r,isNaN(s)?void 0:s),!0}return!1})(t,((e,t)=>{if(!e)return void Ph(`Ignoring ACK response from IPC service ${e} with no service id`);Ph(`Received ACK from IPC service ${e}. Marking as running.`);let r=e;t&&e&&e!==t&&(Kl(e,t),r=t);let s=!1;t&&(s=Nc.setServiceStatus(t,"running")),s?Ah({serviceSessionId:t||e,transport:ga.IPC,send:n,extraInfo:{ipcSocketId:t}}):ql(r,pa.SendManifest)}));!r&&Ph(`Received unknown command [${t}] from service ${e}`)};let Bh={};F.platform();const jh=async e=>{const t=e.args[0];if(Bh.chooseDirectory)try{const n=await Bh.chooseDirectory(t);return e.reply({success:[String(n).trim()]})}catch(t){return console.error(t),e.reply({error:t instanceof Error?t.message:"Unknown error"})}return e.reply({error:"This hub does not support showing file dialogs",errCode:"GUI_NOT_SUPPORTED"})},Dh=async e=>{const t=e.args[0];if(Bh.chooseFile)try{const n=await Bh.chooseFile(t);return e.reply({success:[String(n).trim()]})}catch(t){return console.error(t),e.reply({error:t instanceof Error?t.message:"Unknown error"})}return e.reply({error:"This hub does not support showing file dialogs",errCode:"GUI_NOT_SUPPORTED"})},Uh=e=>{Bh=e};var Mh={},Fh={},Rh={};function Wh(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function Gh(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function Vh(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function Hh(e,...t){if(!Vh(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function zh(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");Wh(e.outputLen),Wh(e.blockLen)}function qh(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Kh(e,t){Hh(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}Object.defineProperty(Rh,"__esModule",{value:!0}),Rh.output=Rh.exists=Rh.hash=Rh.bytes=Rh.bool=Rh.number=Rh.isBytes=void 0,Rh.number=Wh,Rh.bool=Gh,Rh.isBytes=Vh,Rh.bytes=Hh,Rh.hash=zh,Rh.exists=qh,Rh.output=Kh;const Jh={number:Wh,bool:Gh,bytes:Hh,hash:zh,exists:qh,output:Kh};Rh.default=Jh;var Yh={};Object.defineProperty(Yh,"__esModule",{value:!0}),Yh.add5L=Yh.add5H=Yh.add4H=Yh.add4L=Yh.add3H=Yh.add3L=Yh.add=Yh.rotlBL=Yh.rotlBH=Yh.rotlSL=Yh.rotlSH=Yh.rotr32L=Yh.rotr32H=Yh.rotrBL=Yh.rotrBH=Yh.rotrSL=Yh.rotrSH=Yh.shrSL=Yh.shrSH=Yh.toBig=Yh.split=Yh.fromBig=void 0;const Xh=BigInt(2**32-1),Zh=BigInt(32);function Qh(e,t=!1){return t?{h:Number(e&Xh),l:Number(e>>Zh&Xh)}:{h:0|Number(e>>Zh&Xh),l:0|Number(e&Xh)}}function ef(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let s=0;s<e.length;s++){const{h:i,l:o}=Qh(e[s],t);[n[s],r[s]]=[i,o]}return[n,r]}Yh.fromBig=Qh,Yh.split=ef;const tf=(e,t)=>BigInt(e>>>0)<<Zh|BigInt(t>>>0);Yh.toBig=tf;const nf=(e,t,n)=>e>>>n;Yh.shrSH=nf;const rf=(e,t,n)=>e<<32-n|t>>>n;Yh.shrSL=rf;const sf=(e,t,n)=>e>>>n|t<<32-n;Yh.rotrSH=sf;const of=(e,t,n)=>e<<32-n|t>>>n;Yh.rotrSL=of;const af=(e,t,n)=>e<<64-n|t>>>n-32;Yh.rotrBH=af;const cf=(e,t,n)=>e>>>n-32|t<<64-n;Yh.rotrBL=cf;const lf=(e,t)=>t;Yh.rotr32H=lf;const uf=e=>e;Yh.rotr32L=uf;const df=(e,t,n)=>e<<n|t>>>32-n;Yh.rotlSH=df;const pf=(e,t,n)=>t<<n|e>>>32-n;Yh.rotlSL=pf;const hf=(e,t,n)=>t<<n-32|e>>>64-n;Yh.rotlBH=hf;const ff=(e,t,n)=>e<<n-32|t>>>64-n;function gf(e,t,n,r){const s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:0|s}}Yh.rotlBL=ff,Yh.add=gf;const mf=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0);Yh.add3L=mf;const vf=(e,t,n,r)=>t+n+r+(e/2**32|0)|0;Yh.add3H=vf;const yf=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0);Yh.add4L=yf;const bf=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0;Yh.add4H=bf;const Sf=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0);Yh.add5L=Sf;const wf=(e,t,n,r,s,i)=>t+n+r+s+i+(e/2**32|0)|0;Yh.add5H=wf;const If={fromBig:Qh,split:ef,toBig:tf,shrSH:nf,shrSL:rf,rotrSH:sf,rotrSL:of,rotrBH:af,rotrBL:cf,rotr32H:lf,rotr32L:uf,rotlSH:df,rotlSL:pf,rotlBH:hf,rotlBL:ff,add:gf,add3L:mf,add3H:vf,add4L:yf,add4H:bf,add5H:wf,add5L:Sf};Yh.default=If;var _f={},$f={};Object.defineProperty($f,"__esModule",{value:!0}),$f.crypto=void 0,$f.crypto="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,function(e){
|
|
1
|
+
import{config as e}from"dotenv";import{readFile as t,access as n}from"node:fs/promises";import{nanoid as r}from"nanoid";import s from"jsonp";import i from"crypto-js";import o from"util";import a from"emittery";import"axios";import c from"jszip";import l,{scryptSync as u,createDecipheriv as d,createHash as p}from"crypto";import{satisfies as h}from"compare-versions";import f from"debug";import g,{join as m,dirname as v,resolve as y}from"path";import"node-ipc";import{mkdir as b,readFile as S,access as w,constants as I,readdir as _,rm as $}from"fs/promises";import C from"minimist";import k from"tty";import E,{homedir as x}from"os";import A from"net";import N from"tls";import O,{promises as P}from"fs";import L from"dgram";import T from"stream";import B from"zlib";import j from"buffer";import D from"events";import U from"https";import M from"http";import F,{fileURLToPath as R}from"url";import W from"node:os";import{spawn as G}from"child_process";import{join as V,resolve as H,dirname as z}from"node:path";import{ImageData as q,loadImage as K,createCanvas as J}from"@napi-rs/canvas";var Y;!function(e){e.STARTING="STARTING",e.PENDING="PENDING",e.RUNNING="RUNNING",e.PAUSED="PAUSED",e.DRAINING="DRAINING",e.STOPPED="STOPPED",e.ERROR="ERROR"}(Y=Y||(Y={}));const X={};let Z=0,Q="";const ee=e=>X[e]?X[e]:null,te=(e,t)=>{const n=ee(e);if(!n)return n;return n.blocks[t]||null},ne=(e,t,n)=>{const r=te(e,t);if(!r)return r;return r.gates[n]},re=(e,t)=>{let n=r(4);for(;X[n];)n=r(4);const s=(i=e,JSON.parse(JSON.stringify(i)));var i;return s.logs="",s.addLog=e=>{s.logs+=`${(()=>{const e=Date.now();if(e!==Z){const t=new Date;Z=e,Q=t.toJSON()}return Q})()}:: ${e}\n`},s.dbInfo={...t},X[n]=s,n},se="interrupt_port",ie="main.js",oe="state.json",ae="{#}",ce="$var_",le="default";var ue,de,pe,he,fe,ge,me,ve;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(ue||(ue={})),function(e){e[e.Number=0]="Number",e[e.String=1]="String",e[e.ArrayBuffer=2]="ArrayBuffer",e[e.Array=3]="Array",e[e.Boolean=4]="Boolean",e[e.JsonObj=5]="JsonObj",e[e.Anything=6]="Anything",e[e.ImageData=7]="ImageData",e[e.AudioBuffer=8]="AudioBuffer",e[e.Rect=9]="Rect",e[e.Point=10]="Point",e[e.ImageBitmap=11]="ImageBitmap",e[e.BinaryFile=12]="BinaryFile"}(de||(de={})),function(e){e.Number="Number",e.String="String",e.ArrayBuffer="ArrayBuffer",e.Array="Array",e.Boolean="Boolean",e.JsonObj="JsonObj",e.Anything="Anything",e.ImageData="ImageData",e.AudioBuffer="AudioBuffer",e.Rect="Rect",e.Point="Point",e.ImageBitmap="ImageBitmap",e.BinaryFile="BinaryFile"}(pe||(pe={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(he||(he={})),function(e){e.IpcAcknowledge="iack:",e.SocketAcknowledge="sack:",e.AcknowledgeResponse="ackr:",e.ServicesListChanged="update-services",e.SendManifest="send-manifest",e.BroadcastStart="broadcast-start",e.BroadcastEnd="broadcast-end",e.AssumeSession="assume:"}(fe||(fe={})),function(e){e.GetServices="getServices",e.SubscribeToService="subscribeToService",e.UnsubscribeFromService="unsubscribeFromService",e.GetServiceContents="getServiceContents",e.SocketAckResponse="socketAckResponse",e.ShowSecretsConfigScreen="showSecretsConfigScreen",e.GetMappedSecrets="getMappedSecrets",e.GetSecretContexts="getSecretContexts",e.OnParentEvent="onParentEvent",e.GetDefaultState="getDefaultState",e.BroadcastEvent="broadcastEvent",e.HubBroadcastEvent="hubBroadcastEvent",e.ServiceManifest="serviceManifest",e.GetState="getState",e.SetState="setState",e.SetOutputs="setOutputs",e.UIEvent="uiEvent",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.GetUniqueId="getUniqueId"}(ge||(ge={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(me||(me={})),function(e){e.IPC="ipc",e.WS="ws"}(ve||(ve={}));const ye="undefined"!=typeof window&&void 0!==window.document&&void 0!==typeof window.document.createElement,be="object"==typeof self&&self.constructor&&"DedicatedWorkerGlobalScope"===self.constructor.name,Se="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node,we="-",Ie=`inner${we}`,_e=`outer${we}`,$e=`${_e}input${we}`,Ce=`${_e}output${we}`,ke=`${Ie}input${we}`,Ee=`${Ie}output${we}`,xe=e=>(new TextEncoder).encode(e),Ae=e=>e===se,Ne=e=>e&&void 0!==e.width&&void 0!==e.height&&void 0!==e.data&&e.data.constructor&&"Uint8ClampedArray"===e.data.constructor.name,Oe=e=>e&&void 0!==e.width&&void 0!==e.height&&void 0!==e.top&&void 0!==e.left&&"number"==typeof e.width&&"number"==typeof e.height&&"number"==typeof e.top&&"number"==typeof e.left,Pe=e=>e&&"number"==typeof e.x&&"number"==typeof e.y,Le=e=>"number"==typeof e?de.Number:"string"==typeof e?de.String:"boolean"==typeof e?de.Boolean:Array.isArray(e)?de.Array:Ne(e)?de.ImageData:e&&void 0!==e.duration&&void 0!==e.length&&void 0!==e.numberOfChannels&&void 0!==e.sampleRate&&"function"==typeof e.getChannelData&&"AudioBuffer"===e.constructor.name?de.AudioBuffer:e&&void 0!==e.byteLength?de.ArrayBuffer:Oe(e)?de.Rect:e&&void 0!==e.x&&void 0!==e.y&&"number"==typeof e.x&&"number"==typeof e.y?de.Point:de.JsonObj,Te=e=>{const t={};let n;n=Array.isArray(e)?e[0]:e;for(const e in n){const r=Le(n[e]);t[e]=r}return t},Be=(e,t,n)=>"inner"===e?"input"===t?`${ke}${n}`:`${Ee}${n}`:"input"===t?`${$e}${n}`:`${Ce}${n}`,je=e=>{const t=(e||"")?.split("_");if(t.length<3)throw new Error(`Unknown child identifier format [${e}]`);const n=t[0];return{portType:t[1],widgetId:n,portName:t[2]}},De=e=>new ImageData(e.data,e.width,e.height,{colorSpace:e.colorSpace});var Ue,Me;!function(e){e.Action="action",e.CustomInput="customInput"}(Ue=Ue||(Ue={})),function(e){e.input="input",e.counter="counter",e.play="play",e.elapsed="elapsed",e.ifGate="ifGate",e.skipEvent="skipEvent",e.between="between",e.map="map",e.parser="parser",e.slider="slider",e.suspend="suspend",e.display="display",e.json="json",e.arrayItem="arrayItem",e.extractImage="extractImage",e.imageConvolution="imageConvolution",e.firstEvent="firstEvent",e.pixelDraw="pixelDraw",e.randomBetween="randomBetween",e.arrayCombine="arrayCombine",e.clock="clock",e.multiplication="multiplication",e.object="object",e.widgetGroup="widgetGroup",e.script="script",e.base64ToImageData="base64ToImageData",e.jsonParse="jsonParse",e.text="text",e.imageCrop="imageCrop",e.imageResize="imageResize",e.value="value",e.imageWarp="imageWarp",e.widgetBundle="widgetBundle",e.sequence="sequence",e.variable="variable",e.hubService="hubService",e.imageFilter="imageFilter",e.recipeLoad="recipeLoad"}(Me=Me||(Me={}));const Fe={};let Re;const We=async e=>{const t=Fe[e],n={name:se,type:de.Boolean};if(t){const r={name:t.portName},s=t.data||{type:de.Boolean,value:!0};Re?(await Re(!0,t.targetWidgetId,t.thingId,t.recipePoolId,n.name,r,{...s,timestamp:Date.now()},[n]),"timeout"===t.type&&Ge(e)):console.warn("Interrupt service has not been initialized")}},Ge=e=>{const t=Fe[e];return!!t&&(t.timerRef&&("interval"===t.type?clearInterval(t.timerRef):"timeout"===t.type&&clearTimeout(t.timerRef)),delete Fe[e],!0)};var Ve={interruptHandler:We,createInterrupt:(e,t,n,s,i,o,a,c)=>{if(c&&Fe[c])throw new Error("The given interrupt id already exists");const l=c||r().replace(/_/g,"-");if("interval"===e&&!o.interval)throw new Error(`Invalid interval. Expected a number greater than 0, but got '${o.interval}'`);if("timeout"===e&&!o.timeout)throw new Error(`Invalid timeout. Expected a number greater than 0, but got '${o.timeout}'`);if(Fe[l]={data:a,portName:i,recipePoolId:t,targetWidgetId:s,thingId:n,type:e},"interval"===e)Fe[l].timerRef=setInterval((async()=>await We(l)),o.interval);else{if("timeout"!==e)throw new Error(`Invalid interrupt type '${e}'`);Fe[l].timerRef=setTimeout((async()=>await We(l)),o.timeout)}return l},destroyInterrupt:Ge,destroyAllInterrupts:()=>{Object.keys(Fe).forEach(Ge)},setInvokeChildGateCb:e=>{Re=e}};const He=(e,t,n,r,s)=>{const i=ne(e,n,r);if(!i)return console.warn(`Gate ${r} not found in block ${n} for recipe ${e}`),null;const o=(t,s,i,o)=>Ve.createInterrupt(t,e,n,r,s,i,o),a=()=>Object.freeze({...i.state,...i.type===Me.input&&{customInputs:[]}}),c=e=>{if("object"!=typeof e)return void console.warn(`Invalid state type [${typeof e}]. Expected an 'object'`);const t={...e,...i.type===Me.input&&!e.customInputs&&{customInputs:[]}};i.state=t};if(s){return{getState:a,setState:c,registerInterrupt:o,getStorageData:async t=>{const r=((e,t,n)=>{const r=ee(e);if(!r)throw new Error(`Recipe [${e} does not exist]`);if(!r.storage)return null;const s=te(e,t);if(!s)throw new Error(`The Thing "${t}" does not exist in recipe ${e}`);if(!(s.storageUnits||[]).includes(n))throw new Error(`The Thing "${t}" has no access to storage unit "${n}"`);return r.storage[n]||null})(e,n,t);return r},recipePoolId:e,recipeType:t,thingRecipeId:n,widgetThingId:r}}return{getState:a,setState:c,recipePoolId:e,widgetId:r}},ze=[10001,"Invalid `sourcePort` parameter"],qe=[10002,"The gate [%s] does not exist. Have you called `loadWidgets` yet?"],Ke=[10110,"No storage medium has been loaded, call `loadMedium()` first"],Je=(e,...t)=>JSON.stringify({code:e[0],message:t[0]?o.format(e[1],...t):e[1].replace(/ \[%s\]/g,"")}),Ye=()=>({inputName:"",dataType:de.Anything}),Xe="output",Ze={processEvent:async(e,t)=>{const n=t.getState(),r={...Ye(),...n};if(e.type===r.dataType||r.dataType===de.Anything)return t.nextWidget(Xe,{type:e.type,value:e.value});console.error(`Invalid data type: ${e.type} for input: ${r.inputName}. Expected: ${r.dataType}`)},getOutputNames:e=>{const t={...Ye(),...e};return[{name:Xe,type:t.dataType}]},getInputNames:()=>[]},Qe=Object.freeze({in:"in",reset:"reset",increment:"increment"}),et="output";var tt={onParentEvent:async(e,t,n,r)=>{if(!e)throw new Error(Je(ze));const s={currentValue:0,increment:1,...r.getState()};let i=s.increment,o=s.currentValue;const a=await r.getParentAtPort(Qe.increment);if(t.name===Qe.increment)return void(n.data.type===de.Number&&r.setState({...s,increment:Number(n.data.value)}));if(a){const e=a.getValue();null!==e&&(i=e)}if(t.name===Qe.reset)return r.setState({...s,currentValue:0});o+=i,r.setState({currentValue:o,increment:i});const c={type:de.Number,value:o};return r.nextGate(et,c)},getInputNames:()=>[{name:Qe.in,type:de.Anything},{name:Qe.reset,type:de.Anything},{name:Qe.increment,type:de.Number}],getOutputNames:()=>[{name:et,type:de.Number}]};const nt=Object.freeze({in:"in",reset:"reset"}),rt="output";var st={onParentEvent:async(e,t,n,r)=>{const s={updatedAt:0,elapsed:0,...r.getState()},i=Date.now(),o=i-(s.updatedAt||i);return t.name===nt.reset?r.setState({...s,updatedAt:i,elapsed:0}):(r.setState({updatedAt:i,elapsed:o}),r.nextGate(rt,{type:de.Number,value:o}))},getInputNames:()=>[{name:nt.in,type:de.Anything},{name:nt.reset,type:de.Anything}],getOutputNames:()=>[{name:rt,type:de.Number}]};const it=Object.freeze({data:"data",evaluation:"evaluation"}),ot="then",at="else";var ct={onParentEvent:async(e,t,n,r)=>{const s={value:5,condition:"Equal",useDataPort:!1,...r.getState()},i=n.data.value,o=!isNaN(Number(i)),a="string"==typeof i;if(!s.useDataPort&&(n.data.type===de.Number||n.data.type===de.String||n.data.type===de.Anything&&o||n.data.type===de.Anything&&a)){let e=!1;return("Equal"===s.condition&&n.data.value==s.value||"Not Equal"===s.condition&&n.data.value!==s.value||"Greater"===s.condition&&n.data.value>Number(s.value)||"Less"===s.condition&&n.data.value<Number(s.value)||"Starts With"===s.condition&&String(n.data.value).startsWith(String(s.value))||"Ends With"===s.condition&&String(n.data.value).endsWith(String(s.value))||"Includes"===s.condition&&String(n.data.value).includes(String(s.value))||"Matches"===s.condition&&String(n.data.value).match(String(s.value)))&&(e=!0),e?r.nextGate(ot,n.data):r.nextGate(at,n.data)}if((t.name===it.evaluation&&n.data.type===de.Number||n.data.type===de.String||n.data.type===de.Anything&&(o||a))&&(s.$lastValue=n.data.value,r.setState({...s})),t.name===it.data){let e=!1;return("Equal"===s.condition&&s.$lastValue==s.value||"Not Equal"===s.condition&&s.$lastValue!==s.value||"Greater"===s.condition&&Number(s.$lastValue)>Number(s.value)||"Less"===s.condition&&Number(s.$lastValue)<Number(s.value)||"Starts With"===s.condition&&String(s.$lastValue).startsWith(String(s.value))||"Ends With"===s.condition&&String(s.$lastValue).endsWith(String(s.value))||"Includes"===s.condition&&String(s.$lastValue).includes(String(s.value))||"Matches"===s.condition&&String(s.$lastValue).match(String(s.value)))&&(e=!0),r.setState({...s,$lastValue:void 0,$lastDataType:n.data.type}),e?r.nextGate(ot,n.data):r.nextGate(at,n.data)}},getInputNames:e=>e.useDataPort?[{name:it.data,type:de.Anything},{name:it.evaluation,type:[de.Number,de.String]}]:[{name:"in",type:[de.Number,de.String]}],getOutputNames:e=>e.$lastDataType?[{name:ot,type:e.$lastDataType},{name:at,type:e.$lastDataType}]:[{name:ot,type:[de.Number,de.String]},{name:at,type:[de.Number,de.String]}]};const lt=Object.freeze({in:"in",reset:"reset"}),ut="out";var dt={onParentEvent:async(e,t,n,r)=>{const s={totalCalls:0,callsLimit:1,...r.getState()};return t.name===lt.reset?r.setState({...s,totalCalls:0}):(s.totalCalls=s.totalCalls+1,s.totalCalls>s.callsLimit?(s.totalCalls=0,r.setState(s),r.nextGate(ut,n.data)):void r.setState(s))},getInputNames:()=>[{name:lt.in,type:de.Anything},{name:lt.reset,type:de.Anything}],getOutputNames:()=>[{name:ut,type:de.Anything}]};const pt=Object.freeze({in:"in"}),ht="then",ft="else";var gt={onParentEvent:async(e,t,n,r)=>{const s={min:1,max:10,...r.getState()};if(n.data.type===de.Number)return n.data.value>=s.min&&n.data.value<=s.max?r.nextGate(ht,n.data):r.nextGate(ft,n.data)},getInputNames:()=>[{name:pt.in,type:de.Number}],getOutputNames:()=>[{name:ht,type:de.Number},{name:ft,type:de.Number}]};const mt=Object.freeze({in:"in"}),vt="out";var yt={onParentEvent:async(e,t,n,r)=>{const s={clamp:!0,...r.getState()},i=Number(n.data.value);if(void 0!==s.fromMax&&void 0!==s.fromMin&&void 0!==s.toMax&&void 0!==s.toMin&&""!==s.fromMax&&""!==s.fromMin&&""!==s.toMax&&""!==s.toMin&&(n.data.type===de.Number||n.data.type===de.Anything&&!isNaN(Number(i)))){let e=((e,t,n,r,s)=>(e-t)*(s-r)/(n-t)+r)(i,Number(s.fromMin),Number(s.fromMax),Number(s.toMin),Number(s.toMax));if(isNaN(e))return;return s.clamp&&(e<Number(s.toMin)&&(e=Number(s.toMin)),e>Number(s.toMax)&&(e=Number(s.toMax))),r.nextGate(vt,{type:de.Number,value:Number(e)})}},getInputNames:()=>[{name:mt.in,type:de.Number}],getOutputNames:()=>[{name:vt,type:de.Number}]};const bt=Object.freeze({in:"in"}),St="out";var wt={onParentEvent:async(e,t,n,r)=>{const s={convertTo:"Integer",floatPlaces:2,...r.getState()};let i=n.data.value;if(n.data.type===de.Number||n.data.type===de.Anything||n.data.type===de.String){if((!isNaN(Number(i))||"string"==typeof i)&&!Array.isArray(i))return"Integer"===s.convertTo?i=parseInt(i):"Decimal"===s.convertTo?i=parseFloat(Number(i).toFixed(s.floatPlaces)):"String"===s.convertTo?i=String(i):"Abs"===s.convertTo?i=Math.abs(Number(i)):"Round"===s.convertTo&&(i=Math.round(Number(i))),r.nextGate(St,{type:"String"===s.convertTo?de.String:de.Number,value:i})}},getInputNames:()=>[{name:bt.in,type:de.Number}],getOutputNames:e=>{const t="String"===e?.convertTo?de.String:de.Number;return[{name:St,type:t}]}};const It=Object.freeze({in:"in"}),_t="out";var $t={onParentEvent:async(e,t,n,r)=>{const s={currentValue:50,min:0,max:100,...r.getState()};let i=!1;return s.currentValue<s.min&&(s.currentValue=s.min,i=!0),s.currentValue>s.max&&(s.currentValue=s.max,i=!0),i&&r.setState(s),r.nextGate(_t,{type:de.Number,value:s.currentValue})},getInputNames:()=>[{name:It.in,type:de.Anything}],getOutputNames:()=>[{name:_t,type:de.Number}]};const Ct=Object.freeze({in:"in",reset:"reset"}),kt="out";var Et={onParentEvent:async(e,t,n,r)=>{const s={lastCalledAt:0,delayMs:500},i={lastCalledAt:0,delayMs:500,...r.getState()};if(t.name===Ct.reset)return r.setState({...i,lastCalledAt:0});const o=Date.now(),a=o-i.lastCalledAt;return i.lastCalledAt===s.lastCalledAt||a>=i.delayMs&&i.delayMs>0?(i.lastCalledAt=o,r.setState(i),r.nextGate(kt,n.data)):void 0},getInputNames:()=>[{name:Ct.in,type:de.Anything},{name:Ct.reset,type:de.Anything}],getOutputNames:()=>[{name:kt,type:de.Anything}]};const xt="in";var At={onParentEvent:async()=>{},getInputNames:()=>[{name:xt,type:[de.ImageData,de.Number]}],getOutputNames:()=>[]};const Nt=()=>({properties:[{label:"property1",name:"property1"}],detectedProperties:{}}),Ot=(e,t)=>t.split(".").reduce(((e,t)=>null!=e?e[t]:e),e);var Pt={onParentEvent:async(e,t,n,r)=>{const s={properties:[{label:"property1",name:"property1"}],detectedProperties:{},...r.getState()},i=n?.data?.value,o=Array.isArray(i);if(n.data.type===de.JsonObj||n.data.type===de.Rect||n.data.type===de.Anything||o){let e=!1;for(const t in i){const n=Le(i[t]),r=!!s.detectedProperties[t],o=s.detectedProperties[t]?.type!==n;if(!r||o){const r=n===de.JsonObj||n===de.Rect||n===de.Array;s.detectedProperties[t]={type:n,...r?{shape:Te(i[t])}:void 0},e=!0}}if(o&&void 0===s.detectedProperties.length&&(s.detectedProperties.length={type:de.Number}),e&&r.setState(s),i){const e=[];for(const t of s.properties||[]){const n=Ot(i,t.label),o=t.label.includes(".");if(void 0!==n){const i=o?Le(n):void 0!==s.detectedProperties[t.label]?.type?s.detectedProperties[t.label].type:de.Anything;e.push(r.nextGate(t.name,{type:i,value:n}))}}await Promise.allSettled(e)}}},getInputNames:()=>[{name:"in",type:de.JsonObj}],getOutputNames:e=>{const t={properties:[{label:"property1",name:"property1"}],detectedProperties:{},...e};return t.properties.map((e=>{const n=void 0!==t.detectedProperties[e.label]?t.detectedProperties[e.label]?.type:de.Anything,r=t.detectedProperties[e.label]?.shape||void 0,s="string"==typeof e;return{name:s?e:e.name,label:s?e:e.label,type:n,jsonShape:r}}))},getDefaultState:Nt};const Lt="output",Tt="noItem";var Bt={onParentEvent:async(e,t,n,r)=>{const s={index:0,...r.getState()};let i=s.index;const o=n.data.value,a="string"==typeof n.data.value,c=Array.isArray(n.data.value);if(n.data.type===de.Anything&&(c||a)||n.data.type===de.String&&a||n.data.type===de.Array&&c){i<0&&(i=o.length+i);const e=a?de.String:Le(o[i]);return e!==s.$$lastDetectedType&&r.setState({...s,$$lastDetectedType:e}),void 0!==o[i]?r.nextGate(Lt,{value:o[i],type:e}):r.nextGate(Tt,{value:!0,type:de.Boolean})}},getInputNames:()=>[{name:"in",type:[de.Array,de.String]}],getOutputNames:e=>[{name:Lt,type:e.$$lastDetectedType??de.Anything},{name:Tt,type:de.Boolean}]};let jt;const Dt=e=>{jt=e},Ut=(e,t)=>(()=>{if(!jt)throw new Error("CanvasManager not set");return jt})().createCanvas(e,t),Mt=e=>ye?e.getContext("2d",{willReadFrequently:!0}):e.getContext("2d"),Ft=Object.freeze({image:"image",rect:"rect"}),Rt="image";var Wt={onParentEvent:async(e,t,n,r)=>{const s={offset:{height:0,left:0,top:0,width:0},...r.getState()},i=await r.getParentAtPort(Ft.rect),o=[de.Anything,de.Rect,de.JsonObj];if(t.name!==Ft.rect){if(i){const e=i.getValue();null!==e&&(s.rect={...e},r.setState(s))}if(!ye)return n.data.type===de.ImageData?r.nextGate(Rt,n.data):void 0;if(s.$$canvasFrom&&s.$$canvasFrom.getContext||(s.$$canvasFrom=Ut(320,240)),s.$$canvasTo&&s.$$canvasTo.getContext||(s.$$canvasTo=Ut(320,240)),(n.data.type===de.ImageData||n.data.type===de.Anything&&Ne(n.data.value))&&!s.$$processing&&s.$$canvasFrom&&s.rect){const e=((e,t,n,r,s)=>{if(r&&r.getContext){const i=r.getContext("2d"),o=n.getContext("2d");if(i&&o){n.width=e.width,n.height=e.height,o.putImageData(e,0,0);const a={...s};s&&(a.height=Number(s.height),a.width=Number(s.width),a.left=Number(s.left),a.top=Number(s.top));const c={top:0,width:0,left:0,height:0,...a};return s&&(Number.isInteger(c.width)||(c.width=t.width*c.width),Number.isInteger(c.height)||(c.height=t.height*c.height),Number.isInteger(c.left)||(c.left=t.left+t.width*c.left),Number.isInteger(c.top)||(c.top=t.top+t.height*c.top)),r.width=t.width+c.width,r.height=t.height+c.height,i.drawImage(n,t.left+c.left,t.top+c.top,t.width+c.width,t.height+c.height,0,0,r.width+c.width,r.height+c.height),i.getImageData(0,0,r.width||1,r.height||1)}}return e})(n.data.value,s.rect,s.$$canvasFrom,s.$$canvasTo,s.offset);return r.nextGate(Rt,{type:de.ImageData,value:e})}}else Oe(n.data.value)&&o.includes(n.data.type)&&r.setState({...s,rect:n.data.value})},getInputNames:()=>[{name:Ft.image,type:de.ImageData},{name:Ft.rect,type:[de.Rect,de.JsonObj]}],getOutputNames:()=>[{name:Rt,type:de.ImageData}]};const Gt=(e,t)=>{const n=Math.round(Math.sqrt(t.length)),r=Math.floor(n/2),s=e.data,i=e.width,o=e.height,a=i,c=o,l=((e,t,n)=>{if(ye)return new ImageData(t,n);return console.warn("Node environment detected. Aborting new ImageData creation"),e})(e,a,c),u=l.data;for(let e=0;e<c;e++)for(let c=0;c<a;c++){const l=e,d=c,p=4*(e*a+c);let h=0,f=0,g=0,m=0;for(let e=0;e<n;e++)for(let a=0;a<n;a++){const c=l+e-r,u=d+a-r;if(c>=0&&c<o&&u>=0&&u<i){const r=4*(c*i+u),o=t[e*n+a];h+=s[r]*o,f+=s[r+1]*o,g+=s[r+2]*o,m+=s[r+3]*o}}u[p]=h,u[p+1]=f,u[p+2]=g,u[p+3]=m+1*(255-m)}return l},Vt=[-1,0,1,-2,0,2,1,0,1],Ht=Object.freeze({image:"image"}),zt="image";var qt={onParentEvent:async(e,t,n,r)=>{const s=r.getState(),i={matrix:[...Vt],...s};if(n.data.type===de.ImageData||n.data.type===de.Anything&&Ne(n.data.value)){const e=Gt(n.data.value,i.matrix);return r.nextGate(zt,{type:de.ImageData,value:e})}},getInputNames:()=>[{name:Ht.image,type:de.ImageData}],getOutputNames:()=>[{name:zt,type:de.ImageData}]};const Kt=Object.freeze({output:"output",aborted:"aborted"}),Jt=()=>({inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0}),Yt=e=>{const t={inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0,...e},n=Array(t.inputs).fill(0).map(((e,t)=>({name:`input${t+1}`,type:de.Anything})));return n.push({name:"reset",type:de.Anything}),n};var Xt={onParentEvent:async(e,t,n,r)=>{const s={inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0,...r.getState()};if("reset"===t.name)return r.setState({...s,triggeredAt:0});const i=Date.now(),o=i-s.triggeredAt;if(s.triggeredAt&&!(o>=s.delayMs&&s.delayMs>0)&&s.delayMs)return r.nextGate(Kt.aborted,n.data);{s.triggeredAt=i;const e=Yt(s,(r.recipePoolId,r.recipeType,r.thingRecipeId,r.id)).findIndex((e=>e.name===t.name));-1!==e&&(s.lastInputIndex=e),s.matchingOutputs?-1!==e&&await r.nextGate(`output${e+1}`,n.data):await r.nextGate(Kt.output,n.data),r.setState(s)}},getInputNames:Yt,getOutputNames:e=>{const t={inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0,...e};if(e.matchingOutputs){const e=Array(t.inputs).fill(0).map(((e,t)=>({name:`output${t+1}`,type:de.Anything})));return e.push({name:Kt.aborted,type:de.Anything}),e}return[{name:Kt.output,type:de.Anything},{name:Kt.aborted,type:de.Anything}]},getDefaultState:Jt};const Zt=(e,t,n,r,s,i)=>{if(s){const o=e.measureText(s),a=o.fontBoundingBoxAscent+o.fontBoundingBoxDescent;e.fillStyle=r,e.fillRect(t,n-i,1.1*o.width,a),e.font=`${i}px Arial`,e.fillStyle="black",e.fillText(s,t,n)}},Qt=(e,t,n,r,s,i,o)=>{e.fillStyle=s,e.fillRect(t,n,r,r),Zt(e,t,n,s,i,o)},en=(e,t,n,r,s,i)=>{e.beginPath(),e.strokeStyle=r,e.lineWidth=n,e.rect(t.left,t.top,t.width,t.height),e.stroke();const o=n/2;Zt(e,t.left-o,t.top-o,r,s,i)},tn=Object.freeze({image:"image",pixels:"pixels"}),nn="image";var rn={onParentEvent:async(e,t,n,r)=>{const s={fontSize:12,color:"#00ff00",size:2,...r.getState()},i=n.data.type===de.ImageData||n.data.type===de.Anything&&Ne(n.data.value);if(t.name===tn.pixels){const e=((e,t)=>t===de.Anything&&(Ne(e)||Pe(e)||Oe(e)||Array.isArray(e))||t===de.Array||t===de.Rect||t===de.Point)(n.data.value,n.data.type);if(!e)return;s.$$pixels=n.data.value}if(t.name===tn.image&&i){const e=n.data.value;s.$$memCanvas&&s.$$memCanvas.getContext||(s.$$memCanvas=Ut(e.width||1,e.height||1)),s.$$lastFrame=e}if(s.$$lastFrame&&s.$$pixels&&s.$$memCanvas){const e=(e=>{const{sourceImage:t,pixels:n,memCanvas:r,size:s,color:i,labelProp:o,fontSize:a}=e;if(r){const e=Mt(r);if(e){r.width!==t.width&&(r.width=t.width),r.height!==t.height&&(r.height=t.height),e.putImageData(t,0,0);const c=Array.isArray(n)?n:[n];for(let t=0;t<c.length;t++){const n=c[t],r=o?n[o]:"";Oe(n)?en(e,n,s,i,r,a):Pe(n)&&Qt(e,n.x,n.y,s,i,r,a)}return e.getImageData(0,0,r.width,r.height)}}return t})({sourceImage:s.$$lastFrame,pixels:s.$$pixels||[],memCanvas:s.$$memCanvas,size:s.size,color:s.color,labelProp:s.labelProp,fontSize:s.fontSize});return r.setState({...s,$$lastFrame:void 0,$$pixels:void 0}),r.nextWidget(nn,{type:de.ImageData,value:e})}r.setState(s)},getInputNames:()=>[{name:tn.image,type:de.ImageData},{name:tn.pixels,type:[de.Rect,de.Point,de.Array]}],getOutputNames:()=>[{name:nn,type:de.ImageData}]};const sn=Object.freeze({in:"in"}),on="output",an=e=>{const t=String(e).split(".");return t.length<2?0:t[1].length};var cn={onParentEvent:async(e,t,n,r)=>{const s={min:1,max:100,...r.getState()},i=!Number.isInteger(s.min),o=!Number.isInteger(s.max),a=i||o;let c=(l=s.min,u=s.max,Math.random()*(u-l)+l);var l,u;if(a){let e=0;if(i&&(e=an(s.min)),o){const t=an(s.max);t>e&&(e=t)}c=Number(c.toFixed(e))}else c=Math.floor(c);return r.nextGate(on,{type:de.Number,value:c})},getInputNames:()=>[{name:sn.in,type:de.Anything}],getOutputNames:()=>[{name:on,type:de.Number}]};const ln=Object.freeze({output:"output",totalItems:"totalItems"}),un=Object.freeze({trigger:"trigger",clear:"clear"}),dn=()=>({totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1}),pn=async(e,t)=>t.nextGate(ln.totalItems,{type:de.Number,value:e});var hn={onParentEvent:async(e,t,n,r)=>{const s={totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...r.getState()};if(t.name===un.clear)return s.$$list=[],s.properties?.autoFilled&&delete s.properties,r.setState(s),pn(s.$$list.length,r);const i=t.name===un.trigger;if(!i)if(Array.isArray(n.data.value))n.data.type!==de.Array&&n.data.type!==de.Anything||(s.$$outputShape={...s.$$outputShape,...e?.jsonShape},s.$$list=s.$$list.concat(n.data.value),r.setState({...s}),await pn(s.$$list.length,r));else{const t=`$$primitive_${Object.keys(s.$$outputShape).length}`;n.data.type===de.JsonObj?s.$$outputShape={...s.$$outputShape,...e?.jsonShape?e.jsonShape:void 0}:s.$$outputShape={...s.$$outputShape,[t]:n.data.type},s.$$list.push(n.data.value),r.setState({...s}),await pn(s.$$list.length,r)}if(i){Object.keys(s.$$outputShape).length&&(s.properties={autoFilled:!0,jsonShape:{...s.$$outputShape}});const e=s.$$list.length,t=[...s.$$list];return s.$$list=[],r.setState({...s}),await pn(e,r),r.nextGate(ln.output,{type:de.Array,value:t})}},getInputNames:e=>{const t={totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...e},n=Array(t.totalInputs||1).fill(0).map(((e,t)=>({name:`array${t+1}`,type:de.Array})));return n.push({name:un.clear,type:de.Anything},{name:un.trigger,type:de.Anything}),n},getOutputNames:e=>[{name:ln.output,type:de.Array,...e.properties?{jsonShape:e.properties?.jsonShape}:void 0},{name:ln.totalItems,label:"Total Items",type:de.Number}],getDefaultState:dn};const fn=Object.freeze({start:"start",stop:"stop"}),gn="output",mn="clock_interrupt";var vn={onParentEvent:async(e,t,n,r)=>{const s={enabled:!1,interval:1e3,intervalMode:"ms",...r.getState()};if(Ae(e?.name||"")&&t.name===mn)return r.nextGate(gn,{type:de.Boolean,value:!0});if(t.name===fn.stop&&s.enabled&&s.$$interruptId){r.cancelInterrupt(s.$$interruptId)?(s.enabled=!1,s.$$interruptId=void 0,r.setState(s)):console.warn(`Failed to cancel interrupt [${s.$$interruptId}]`)}else t.name!==fn.start||s.enabled||s.$$interruptId||(s.$$interruptId=r.registerInterrupt("interval",mn,{interval:s.interval}),s.enabled=!0,r.setState(s))},getInputNames:()=>[{name:fn.start,type:de.Anything},{name:fn.stop,type:de.Anything}],getOutputNames:()=>[{name:gn,type:de.Boolean}],initialize:async e=>{const t=e.getState();if(t.enabled&&!t.$$interruptId){const n=e.registerInterrupt("interval",mn,{interval:t.interval});e.setState({...t,$$interruptId:n})}}};const yn=Object.freeze({in:"in"}),bn="output",Sn=(e,t,n)=>"number"==typeof e?Number((e*t).toFixed(n)):e;var wn={onParentEvent:async(e,t,n,r)=>{const s={userProperties:[],factor:2,decimalPoints:2,...r.getState()},i=n.data.type;let o=n.data.value,a=!1;return e?.jsonShape&&(s.detectedInputJson={...s.detectedInputJson,...e?.jsonShape},a=!0),s.detectedInputType||(s.detectedInputType=i,a=!0),n.data.type===de.Array&&("number"==typeof n.data.value?.[0]?o=((e,t,n)=>{const r=(e||[]).map((e=>Sn(e,t,n)));return r})(n.data.value,s.factor,s.decimalPoints):"object"==typeof n.data.value?.[0]&&(o=((e,t,n,r)=>{const s=(e||[]).map((e=>{const s={...e};return Object.keys(s).forEach((e=>{r?.length&&!r?.includes(e)||(s[e]=Sn(s[e],t,n))})),s}));return s})(n.data.value,s.factor,s.decimalPoints,s.userProperties))),n.data.type===de.Number&&(o=Sn(n.data.value,s.factor,s.decimalPoints)),a&&r.setState(s),r.nextGate(bn,{type:i,value:o})},getInputNames:()=>[{name:yn.in,type:[de.Array,de.Number]}],getOutputNames:e=>[{name:bn,type:e.detectedInputType||de.Number,jsonShape:e.detectedInputJson}]};const In=Object.freeze({output:"output"}),_n=Object.freeze({trigger:"trigger"}),$n=()=>({useTriggerPort:!0,properties:[{name:"x",label:"x",type:de.Number,value:10},{name:"y",label:"y",type:de.Number,value:20}]}),Cn=e=>{const t={};for(let n=0;n<e.properties.length;n++)t[e.properties[n].label]=e.properties[n].type;return t},kn=e=>{const t={};for(let n=0;n<e.properties.length;n++){let r=e.properties[n].value;const s=e.properties[n].type;s===de.Number?r=Number(r):s===de.String&&(r=String(r)),t[e.properties[n].label]=r}return t};var En={onParentEvent:async(e,t,n,r)=>{const s=r.getState(),i=structuredClone(s),o={...$n(),...i};if(t.name===_n.trigger){const e=kn(o);return r.nextGate(In.output,{type:de.JsonObj,value:e})}const a=o.properties.findIndex((e=>e.name===t.name));if(-1!==a){let e=n.data.type===o.properties[a].type;if(!e&&n.data.type===de.Anything){e=Le(n.data.type)===o.properties[a].type}if(e?(o.properties[a].value=n.data.value,o.properties[a].$$invalidInputType=!1):o.properties[a].$$invalidInputType=!0,r.setState(o),!o.useTriggerPort){const e=kn(o);return r.nextGate(In.output,{type:de.JsonObj,value:e})}}},getInputNames:e=>{const t={...$n(),...e},n=t.properties.map((e=>({name:e.name,label:e.label,type:e.type})));return t.useTriggerPort&&n.push({name:_n.trigger,label:_n.trigger,type:de.Anything}),n},getOutputNames:e=>[{name:In.output,label:In.output,type:de.JsonObj,jsonShape:Cn(e)}],getDefaultState:$n};const xn=async e=>{const t=(e,t)=>e.split(t)[1];if(e.startsWith($e)){const n=t(e,$e);return Be("inner","input",n)}if(e.startsWith(Ee)){const n=t(e,Ee);return Be("outer","output",n)}return null},An=()=>({canvasPosition:{x:0,y:0},canvasZoom:1,inputs:[{name:"input",type:[de.Anything],index:0}],outputs:[{name:"output",type:[de.Anything],index:0}],name:"Custom Widget 1",description:"",type:"custom"}),Nn=e=>{const t={...An(),...e},n=t.inputs.map(((e,t)=>({name:Be("outer","input",e.name),type:e.type,...e.jsonShape?{jsonShape:e.jsonShape}:void 0,...e.position?{position:e.position}:void 0,label:e.label,isInner:!1,index:t}))),r=t.outputs.map(((e,t)=>({name:Be("inner","output",e.name),type:e.type,...e.jsonShape?{jsonShape:e.jsonShape}:void 0,...e.position?{position:e.position}:void 0,label:e.label,isInner:!0,index:n.length+t})));return[...n,...r]};var On={onParentEvent:async(e,t,n,r)=>{const s=r.getState(),i={...An(),...s},o=Nn(i,(r.recipePoolId,r.recipeType,r.thingRecipeId,r.id));for(let e=0;e<o.length;e++){const s=o[e];if(t.name===s.name&&(s.type.includes(de.Anything)||s.type.includes(n.data.type))){const e=await xn(t.name);e&&await r.nextWidget(e,{type:n.data.type,value:n.data.value})}}},getInputNames:Nn,getOutputNames:e=>{const t={...An(),...e},n=t.outputs.map(((e,t)=>({name:Be("outer","output",e.name),type:e.type,...e.jsonShape?{jsonShape:e.jsonShape}:void 0,...e.position?{position:e.position}:void 0,label:e.label,isInner:!1,index:t})));return[...t.inputs.map(((e,t)=>({name:Be("inner","input",e.name),type:e.type,...e.jsonShape?{jsonShape:e.jsonShape}:void 0,...e.position?{position:e.position}:void 0,label:e.label,isInner:!0,index:t+n.length}))),...n]},getDefaultState:An};const Pn=(e,t,n,r,s)=>{const i=4*(t*n.width+e),o=n.data[i],a=n.data[i+1],c=n.data[i+2];return Math.abs(o-r.r)<=s&&Math.abs(a-r.g)<=s&&Math.abs(c-r.b)<=s};var Ln,Tn,Bn,jn,Dn,Un,Mn,Fn,Rn,Wn,Gn={getPixelValueAtIndex:(e,t)=>{const n=e.data,r=n[t]||0,s=n[t+1]||0,i=n[t+2]||0;return{avr:(r+s+i)/3,r:r,g:s,b:i}},getBoundingBox:(e,t,n)=>{const r=e.width,s=e.height,i=new Set,o=Number(n.threshold||0),a=isNaN(o)?10:o,c=(n,o)=>{const c=[[n,o]];let l=n,u=n,d=o,p=o;for(;c.length>0;){const n=c.shift();if(!n)continue;const[o,h]=n;o<0||h<0||o>=r||h>=s||i.has(`${o},${h}`)||!Pn(o,h,e,t,a||0)||(i.add(`${o},${h}`),l=Math.min(l,o),u=Math.max(u,o),d=Math.min(d,h),p=Math.max(p,h),c.push([o+1,h],[o-1,h],[o,h+1],[o,h-1]))}return{minX:l,maxX:u,minY:d,maxY:p}},l=[];for(let o=0;o<s;o+=4)for(let s=0;s<r;s+=4)if(!i.has(`${s},${o}`)&&Pn(s,o,e,t,a)){const{minX:e,maxX:t,minY:r,maxY:i}=c(s,o),a=t-e,u=i-r;if(a>=(n.minWidth||1)&&u>=(n.minHeight||1)&&l.push({left:e,top:r,width:a,height:u}),n.maxBoxes&&l.length>=n.maxBoxes)return l}return l},copyImageData:e=>new ImageData(new Uint8ClampedArray(e.data),e.width,e.height),setPixelValueAtIndex:(e,t,n)=>{const r=e.data,s="object"==typeof n,i=s?n.r:n,o=s?n.g:n,a=s?n.b:n;r[t]=i,r[t+1]=o,r[t+2]=a,r[t+3]=255}};!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(Ln||(Ln={})),function(e){e.Bundle="bundle",e.Group="group"}(Tn||(Tn={})),function(e){e.Hardware="hardware",e.Virtual="virtual"}(Bn||(Bn={})),function(e){e.Cloud="cloud",e.Web="web"}(jn||(jn={})),function(e){e.Cpu_128M="kmu-cpu-128m",e.Cpu_256M="kmu-cpu-256m",e.Cpu_512M="kmu-cpu-512m",e.Cpu_1024M="kmu-cpu-1024m",e.Cpu_2048M="kmu-cpu-2048m",e.Cpu_4096M="kmu-cpu-4096m"}(Dn||(Dn={})),function(e){e.Gateway="gateway",e.Timer="timer"}(Un||(Un={})),(Mn||(Mn={})).InstallInProgress="installation-in-progress",function(e){e.InstallDependencies="install-dependencies",e.GetInstalledDependencies="get-installed-dep"}(Fn||(Fn={})),function(e){e.Success="success",e.Error="error",e.Pending="pending"}(Rn||(Rn={})),function(e){e.NotFound="not-found",e.BadRequest="bad-request",e.Forbidden="forbidden",e.InternalError="internal-error"}(Wn||(Wn={}));let Vn=null;var Hn=()=>{if(!Vn)throw new Error("Required function is not set");return Vn};class zn extends Error{constructor(e,t){super(e),this.name="UserCodeError",t&&(this.stack=t)}}const qn=(e,t)=>`\n\t\tfunction _user_code_(){\n\t\t\t${t===Ln.Browser?"\n\t\t\tvar global = {\n\t\t\t\t__user_code: true\n\t\t\t};\n\t\t\tvar process = {};\n\t\t\tvar console = this.console;\n\t\t\tvar globalThis = global;\n\t\t\tvar require = this.___notSupportedMethod;\n\t\t\t":"\n\t\t\tvar require = this.require;\n\t\t\tvar process = this.kemuProcess;\n\t\t\t"}\n\n\t\t\tvar eval = () => {};\n\t\t\tvar document = {};\n\t\t\tvar navigator = {};\n\t\t\tvar window = this.window;\n\t\t\tvar alert = this.notify.info;\n\t\t\tvar DataType = this.dataTypesEnum;\n\t\t\tvar setInterval = this.setInterval;\n\t\t\tvar setTimeout = this.setTimeout;\n\t\t\tvar addEventListener = this.addEventListener;\n\t\t\tvar removeEventListener = this.removeEventListener;\n\t\t\tvar requestAnimationFrame = this.___notSupportedMethod;\n\t\t\tvar __delay = (ms) => new Promise((resolve, reject) => setTimeout(resolve, ms, reject));\n\n\t\t\tvar Kemu = {\n\t\t\t\tservices: {\n\t\t\t\t\thttp: { ...this.httpWebService },\n\t\t\t\t\tdynamoDb: { ...this.dynamoService },\n\t\t\t\t\tgoogleSheets: {\n\t\t\t\t\t\t...this.googleSheetsService,\n\t\t\t\t\t}\n\t\t\t\t},\n\n\t\t\t\timage: this.imageHelpers,\n\t\t\t\tvariable: this.variablesManager,\n\n\t\t\t\thelpers: {\n\t\t\t\t\tcryptoJS: this.CryptoJS,\n\t\t\t\t\tjsonp: this.jsonp,\n\t\t\t\t\tdelay: __delay,\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tvar sendToPort;\n\n\t\t\t// --- User Methods Start ---\n\t\t\t${e||""};\n\t\t\t// --- User Methods End ---\n\t\t\t\n\t\t\t// Processes the user code asynchronously.\n\t\t\tconst asyncProcessEvent = async (targetPort, sourcePort, event) => {\n\t\t\t\tconst userProcessEvent = typeof processEvent === 'undefined' ? undefined : processEvent;\n\t\t\t\tif(userProcessEvent) {\n\t\t\t\t\ttry{\n\t\t\t\t\t\treturn await userProcessEvent(targetPort, sourcePort, event, sendToPort);\n\t\t\t\t\t}catch(e){\n\t\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/** invoked the very first time the recipe is initialized */\n\t\t\tconst asyncRecipeInit = async (context, logger) => {\n\t\t\t\ttry {\n\t\t\t\t\t${t===Ln.Browser?"if(logger) { console = logger; }":""}\n\t\t\t\t\tif(typeof recipeInit === 'function') {\n\t\t\t\t\t\treturn recipeInit(context);\n\t\t\t\t\t}\n\t\t\t\t}catch(e){\n\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/** invoked every time the code is about to be replaced */\n\t\t\tconst asyncOnTerminate = async (context) => {\n\t\t\t\ttry {\n\t\t\t\t\tif(typeof onTerminate === 'function') {\n\t\t\t\t\t\treturn onTerminate(context);\n\t\t\t\t\t}\n\t\t\t\t}catch(e){\n\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/** updates the function that allows widget contexts to send data to the next widget */\n\t\t\tconst setSendToPort = (sendNextFun) => {\n\t\t\t\tsendToPort = sendNextFun;\n\t\t\t}\n\n\t\t\t/** invoked the every time the user code is compiled. */\n\t\t\tconst asyncMainEvent = async (sendNextFun, logger) => {\n\t\t\t\ttry{\n\t\t\t\t\tsetSendToPort(sendNextFun);\n\t\t\t\t\tif(logger) { console = logger; }\n\t\t\t\t\tif(typeof main === 'function'){\n\t\t\t\t\t\treturn main();\n\t\t\t\t\t}\n\t\t\t\t}catch(e){\n\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tasyncProcessEvent: asyncProcessEvent,\n\t\t\t\tmain: asyncMainEvent,\n\t\t\t\trecipeInit: asyncRecipeInit,\n\t\t\t\tsetSendToPortFun: setSendToPort,\n\t\t\t\tonTerminate: asyncOnTerminate,\n\t\t\t\tgetLocalContext: () => global,\n\t\t\t\tgetWidgetInputs: typeof getWidgetInputs === 'undefined' ? undefined : getWidgetInputs,\n\t\t\t\tgetWidgetOutputs: typeof getWidgetOutputs === 'undefined' ? undefined : getWidgetOutputs,\n\t\t\t};\n\t\t}\n\t\t\n\t\treturn function compiler(context){\n\t\t\treturn _user_code_.call(context)\n\t\t}\n\n\t\treturn compiler;\n\t`,Kn=(e,t,n,r)=>{const o=qn(e,n),a={...t,document:{},__errorTracer:e=>{throw new zn(e.message,e.stack)},__jest:void 0===globalThis.__jest?void 0:globalThis.__jest,___notSupportedMethod:()=>r?.error("This method is not supported."),console:console,setInterval:()=>r?.error("'setInterval' is not supported. Please use a \"Timer\" widget instead."),setTimeout:t?.setTimeout,imageHelpers:Gn,...n===Ln.Cloud?{require:Hn(),kemuProcess:process.env.KEMU_PROCESS?process.env.KEMU_PROCESS:{}}:{},jsonp:s,CryptoJS:i,window:{addEventListener:t?.addEventListener,removeEventListener:t?.removeEventListener}};try{const e="browser"===(()=>{if(ye)return"browser";if(Se)return"node";if(be)return"worker";throw new Error("Unsupported environment")})()?(e=>e.replace(/[//]{2}[ ]*@kemu-cloud[ \t]*\{[\s\S]*?[//]{2}[ ]*@kemu-cloud[ \t]*\}/gim,""))(o):(e=>e.replace(/[//]{2}[ ]*@kemu-browser[ \t]*\{[\s\S]*?[//]{2}[ ]*@kemu-browser[ \t]*\}/gim,""))(o),t=new Function(e);return{compiledModule:t()(a)}}catch(e){return{error:{name:"CompileError",message:e.message,stack:e.stack}}}},Jn="main",Yn=()=>({pauseExecution:!1,autoPauseOnError:!0,$$eventListeners:{},pages:{[Jn]:{code:"\nconst getWidgetInputs = () => [\n\t{ name: 'Input 1', type: DataType.Number }\n];\n\nconst getWidgetOutputs = () => [\n\t{ name: 'Output 1', type: DataType.Number }\n]\n\nlet counter = 0;\n\nconst processEvent = async (targetPort, sourceWidget, event) => {\n\tif(targetPort.name === 'Input 1'){\n\t\treturn sendToPort('Output 1', {\n\t\t\ttype: DataType.Number,\n\t\t\tvalue: counter++,\n\t\t});\n\t}\n}\n",language:"javascript",name:"My First Script"}},consoleVisible:!1,$$consoleLines:[]}),Xn=(e,t)=>{const n={message:"Unknown Error"};if(e?.stack){const r=e?.stack?.split(":")[0].trim();n.type=r;const s=(e=>{const t=/,[ ]?<anonymous>:([0-9]+:[0-9]+)\)/gm;let n;for(;null!==(n=t.exec(e));){n.index===t.lastIndex&&t.lastIndex++;const e=n[1].split(":");if(2===e.length)return{line:Number(e[0])||0,column:Number(e[1])||0}}return null})(e.stack);s&&(n.line=s.line-(e=>{const t="___user_code_section___";return qn(t,e).split(t)[0].split("\n").length+2})(t),n.column=s.column)}return e.message&&(n.message=e.message),n},Zn=(e,t)=>{const n={...Yn(),...t.getState()},r={...n,...e?{$$error:e}:void 0,...n.autoPauseOnError&&e?{pauseExecution:!0}:void 0};e&&(r.$$consoleLines=[...r.$$consoleLines,{type:"error",text:e.message,timestamp:Date.now(),fileName:Jn}]),t.setState(r)};var Qn,er;!function(e){e.ServiceCreationLog="service-creation-log"}(Qn=Qn||(Qn={})),function(e){e.Service="service",e.ServiceUI="serviceUI"}(er=er||(er={}));const tr=new a,nr=(e,t,n)=>{const r=te(e,t);if(!r)throw new Error(`Thing ${t} not found in recipe ${e}`);const s=r.gates[n];if(!s)throw new Error(`Widget ${n} not found in thing ${t}`);return s},rr=(e,t,n)=>`${t}:${n}:${e}`,sr=e=>`${e}:new-var`,ir=async(e,t,n,r,s,i,o)=>{const a={...o},c={thingId:n,recipeId:t,variableName:e,changes:i,ownerId:r,callerWidgetId:s,varDefinition:Object.freeze(a)};if(i.includes("added")){const e=sr(n);return tr.emit(e,c)}{const t=rr(e,n,r);return tr.emit(t,c)}},or=(e,t,n,r)=>{const s=nr(e,t,r);s.variablesListener={...s.variablesListener,[n]:0},cr(e,t)},ar=(e,t,n,r)=>{const s=nr(e,t,r),i={...s.variablesListener};void 0!==s.variablesListener?.[n]&&(delete i[n],s.variablesListener=i)},cr=async(e,t)=>{const n=te(e,t);if(!n)throw new Error(`Thing "${t}" not found in recipe "${e}"`);const r={...n.variables},s=Object.keys(r);for(const i of s){const s=r[i],o=Object.keys(s);for(const s of o){!n.gates[s]&&(delete r[i][s],await ir(i,e,t,s,void 0,["removed"],null))}0===Object.keys(r[i]).length&&delete r[i]}n.variables=r},lr=(e,t,n)=>{for(const r in t){const s=t[r];if(s.createdByWidgetId===e.id)return s;if(e.type===Me.variable&&s.ownerType===Me.variable)return s;if(e.type===Me.script){const t=s.createdByWidgetId===e.groupId,r=n[s.createdByWidgetId];if(!r)continue;const i=r.groupId===e.groupId;if(t||r.type===Me.variable&&i)return s}}return null};var ur=async(e,t,n,r,s,i)=>{const o=te(e,t);if(!o)throw new Error(`Thing ${t} not found in recipe ${e}`);const a={...o.variables};a[r]=a[r]||{};const c=a[r],l=o.gates[n];if(!l)throw new Error(`Widget ${n} not found in thing ${t}`);const u=Object.values(c);let d=!1,p=!1;const h=async s=>ir(r,e,t,s.createdByWidgetId,n,["value"],s);if(l.type===Me.variable){d=!0;for(const e of u)e.ownerType===Me.variable&&e.type===s.type&&(e.value=s.value,p=!0,await h(e))}if(l.type===Me.script){d=!0;for(const e of u){const t=e.createdByWidgetId===l.groupId,n=o.gates[e.createdByWidgetId],r=n?.type===Me.variable,i=n?.groupId===l.groupId;(t||r&&i)&&e.type===s.type&&(e.value=s.value,p=!0,await h(e))}}if(!d){d=!0;for(const e of u){e.createdByWidgetId===n&&e.type===s.type&&(e.value=s.value,p=!0,await h(e))}}if(!i?.skipNotifications&&p){const a=Object.values(o.gates);for(const o of a){if(o.id===n&&i?.skipCallerNotification)continue;const a=o.variablesListener?.[r];void 0!==a&&await ni(o.id,t,e,`${ce}${r}`,s)}}},dr=(e,t,n,r)=>{const s=te(e,t);if(!s)throw new Error(`Thing ${t} not found in recipe ${e}`);if(!r.readerWidgetId&&!r.ownerWidgetId)throw new Error("readerWidgetId or ownerWidgetId must be provided");const i={...s.variables}[n];if(!i)return;if(r.ownerWidgetId){const e=i[r.ownerWidgetId];return e?.value}const o=s.gates[r.readerWidgetId];if(!o)throw new Error(`Widget ${r.readerWidgetId} not found in thing ${t}`);const a=lr(o,i,s.gates);return a?a.value:null},pr=or,hr=ar;const fr="setTimeout",gr="variableChanged",mr=e=>{const{recipePoolId:t,thingId:n,scriptWidgetId:r}=e;if(!ne(t,n,r))throw new Error(`Widget "${r}" not found in recipe "${t}"`);return{get:(e,s)=>{const i=dr(t,n,e,{readerWidgetId:r});if(null===i){if(void 0===s)throw new Error(`Variable "${e}" is not defined`);return s}return i},set:async(e,s)=>{await ur(t,n,r,e,{type:Le(s),value:s})},onValueChange:(s,i)=>{if(!e.setState)return void console.warn("Cannot subscribe to variable changes without a setState function");pr(t,n,s,r);const o={...Yn(),...e.getState()};o.$$eventListeners[s]={handler:i,abort:async()=>{hr(t,n,s,r)},name:gr},e.setState(o)}}},vr="__command-compile__";let yr;const br=()=>{console.log("Method not implemented")},Sr=(e,t,n)=>{const s=(e,...n)=>{const r={...Yn(),...t.getState()}.$$eventListeners[e];r&&r.handler(n)},i={};return Object.keys(de).forEach((e=>{i[e]=de[e]})),{dataTypesEnum:i,notify:{success:e=>{t.getState()?.$$managedUI?.notify?.success(e)},error:e=>{t.getState()?.$$managedUI?.notify?.error(e)},info:e=>{t.getState()?.$$managedUI?.notify?.info(e)}},variablesManager:e.variablesManager?mr({recipePoolId:n.recipePoolId,scriptWidgetId:n.widgetId,thingId:n.thingId,getState:t.getState,setState:t.setState}):{get:br,set:async()=>br(),onValueChange:br},setTimeout:(n,s,i)=>{if(e.withTimers&&t&&t.setState&&t.registerInterrupt){const e=r(),o={...Yn(),...t.getState()};o.$$eventListeners[e]={handler:n,rejectHandler:i,name:fr},t.setState(o),t.registerInterrupt("timeout",e,{timeout:s},void 0,e)}},addEventListener:(e,n)=>{if(t.setState){const i=r(),o={...Yn(),...t.getState()};o.$$eventListeners[i]={handler:n,name:e},t.setState(o),window.addEventListener(e,s.bind(i))}else console.warn(`Cannot remove event listener '${e}' because the widget context is not available.`)},removeEventListener:(e,n)=>{if(t.setState){const r={...Yn(),...t.getState()},s=Object.keys(r.$$eventListeners).find((t=>r.$$eventListeners[t].name===e&&r.$$eventListeners[t].handler===n));t.setState(r),s&&removeEventListener(r.$$eventListeners[s].name,r.$$eventListeners[s].handler)}else console.warn(`Cannot remove event listener '${e}' because the widget context is not available.`)}}},wr=(e,t,n,r)=>{const s={...Yn(),...n.getState()},i=s.pages[Jn].$$compiledCode;if(i)return{compiledModule:i};{const i=Sr(e,n,t);return Kn(s.pages[Jn].code,i,n.recipeType,r)}},Ir=e=>e.map((e=>({...e,name:e.name.replace("_","")}))),_r=async(e,t)=>{const n={...e};for(const r in e){if(e[r].name===fr){const e=n[r]?.rejectHandler;if("function"==typeof e)try{await e("TIMER_ABORTED")}catch(e){console.log("Error in reject interrupt handler: ",e)}t.cancelInterrupt(r),delete n[r]}}return n},$r=async(e,t,n)=>{let r={...Yn(),...e.getState()};if(void 0!==n){r.pages[Jn]?.$$compiledCode?.onTerminate&&await(r.pages[Jn].$$compiledCode?.onTerminate());let t=await _r(r.$$eventListeners,e);t=await(async e=>{const t={...e};for(const n in e)if(e[n].name===gr){const r=e[n]?.abort;if("function"==typeof r)try{await r()}catch(e){console.log("Error in abort interrupt handler: ",e)}delete t[n]}return t})(t),r.$$eventListeners=t,r.$$error=void 0,r.pages[Jn].$$compiledCode=void 0,r.pages[Jn].code=n,e.setState({...r})}const s=!r.pages[Jn].$$compiledCode,{compiledModule:i,error:o}=wr({variablesManager:!0,withTimers:!0},{recipePoolId:e.recipePoolId,thingId:e.thingRecipeId,widgetId:e.id},{getState:e.getState,setState:e.setState,recipeType:e.recipeType,registerInterrupt:e.registerInterrupt});if(o){console.log("Failed to compile user code");const t=Xn(o,e.recipeType);return Zn(t,e),null}if(i){const n=(e=>{const t=(t,n)=>{if(yr)try{return yr[t](n)}catch(e){return void console.log("Error in custom logger: ",e)}const r={...Yn(),...e.getState()},s=[...r.$$consoleLines||[]];s.push({fileName:Jn,text:n,type:t,timestamp:Date.now()}),s.length>100&&s.splice(0,30),e.setState({...r,$$consoleLines:s})},n={log:e=>{t("log",e)},error:e=>{t("error",e)},warn:e=>{t("warn",e)},info:e=>{t("info",e)}};return n})(e);let o;if(r={...e.getState()},r.pages[Jn].$$compiledCode=i,e.nextGate&&i.setSendToPortFun(e.nextGate),t)try{await i.recipeInit({setState:e.setState,getState:e.getState},n)}catch(t){o=Xn(t,e.recipeType)}if(e.nextGate&&s)try{await i.main(e.nextGate,n)}catch(t){o=Xn(t,e.recipeType)}r.$$lastInputs=i.getWidgetInputs?i.getWidgetInputs():[],r.$$lastOutputs=i.getWidgetOutputs?i.getWidgetOutputs():[],e.setState(r),Zn(o,e)}};var Cr={onParentEvent:async(e,t,n,r)=>{const s=r.getState(),i={...Yn(),...s};if(!i.pages[Jn])return console.warn("Missing default page");if(i.pauseExecution){if(Object.keys(i.$$eventListeners).length){const e=await _r(i.$$eventListeners,r);r.setState({...i,$$eventListeners:e})}return}if(Ae(e?.name||""))return i.$$eventListeners[t.name]?(await i.$$eventListeners[t.name].handler(),i.$$eventListeners[t.name].name===fr&&delete i.$$eventListeners[t.name],void r.setState({...i})):void console.log(`Unknown interrupt id [${t.name}] `);if(t.name.startsWith(ce)){const e=t.name.replace(ce,""),r=n.data.value,s=i.$$eventListeners[e];return void(s?.handler&&await s.handler(r))}const o=t.name===vr;await $r(r,!1,o?n.data.value:void 0);const a=i.pages[Jn].$$compiledCode;if(e&&e.name!==vr&&a){let s;try{await a.asyncProcessEvent(t,e,n)}catch(e){"UserCodeError"===e.name&&(s=Xn(e,r.recipeType))}Zn(s,r)}},getInputNames:(e,t)=>{const n={...Yn(),...e},{compiledModule:r}=wr({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetInputs){const e=r.getWidgetInputs();return Ir(e)}return e.$$lastInputs||[]},getOutputNames:(e,t)=>{const n={...Yn(),...e},{compiledModule:r}=wr({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetOutputs){const e=r.getWidgetOutputs();return Ir(e)}return e.$$lastOutputs||[]},getDefaultState:Yn,initialize:async e=>{const t=e.getState(),n={...Yn(),...t};n.pages[Jn].code&&await $r({getState:e.getState,id:e.widgetThingId,recipePoolId:e.recipePoolId,recipeType:e.recipeType,registerInterrupt:e.registerInterrupt,setState:e.setState,thingRecipeId:e.thingRecipeId,cancelInterrupt:()=>!0},!0,n.pages[Jn].code)}};const kr=async(e,t,n,r)=>{e.startsWith("data:image/")||(e=`data:image/png;base64,${e}`);const s=await Er(e);return((e,t,n,r)=>{const s=r.getContext("2d");if(!s)throw new Error("Failed to get canvas context");const i=e.width,o=e.height;return r.width=t,r.height=n,s.drawImage(e,0,0,i,o,0,0,t,n),s.getImageData(0,0,t,n)})(s,n||s.naturalWidth,r||s.naturalHeight,t)},Er=e=>new Promise(((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=e=>n(e),r.src=e})),xr=Object.freeze({image:"image"}),Ar=Object.freeze({base64:"base64"}),Nr=()=>({});var Or={onParentEvent:async(e,t,n,r)=>{const s={...r.getState()};if(t.name===Ar.base64){if("string"!=typeof n.data.value)return;if(n.data.type!==de.String&&n.data.type!==de.Anything)return;const e=n.data.value;ye&&(s.$$memCanvas&&s.$$memCanvas.getContext||(s.$$memCanvas=Ut(320,240)));try{const t=await kr(e,s.$$memCanvas,s.resize?.width,s.resize?.height);return r.setState(s),r.nextGate(xr.image,{type:de.ImageData,value:t})}catch(e){console.log("[base64ToImageData] Error: ",e)}}},getInputNames:()=>[{name:Ar.base64,type:de.String}],getOutputNames:()=>[{name:xr.image,type:de.ImageData}],getDefaultState:Nr};const Pr=Object.freeze({object:"object",error:"error"}),Lr=Object.freeze({string:"string"}),Tr=()=>({outputIsArray:!1});var Br={onParentEvent:async(e,t,n,r)=>{const s={outputIsArray:!1,...r.getState()};if((n.data.type===de.String||n.data.type===de.Anything)&&"string"==typeof n.data.value)try{const e=JSON.parse(n.data.value),t=Array.isArray(e);return t&&!s.outputIsArray?r.setState({...s,outputIsArray:!0}):!t&&s.outputIsArray&&r.setState({...s,outputIsArray:!1}),r.nextGate("object",{type:t?de.Array:de.JsonObj,value:e})}catch(e){return r.nextGate("error",{type:de.Boolean,value:!0})}},getInputNames:()=>[{name:Lr.string,type:de.String}],getOutputNames:e=>[{name:Pr.object,type:[de.JsonObj,de.Array],label:e.outputIsArray?"array":Pr.object},{name:Pr.error,type:de.Boolean}],getDefaultState:Tr};const jr=Object.freeze({string:"string",length:"length"}),Dr=Object.freeze({trigger:"trigger",setText:"setText"}),Ur=()=>({text:"",dispatchOnSet:!1});var Mr={onParentEvent:async(e,t,n,r)=>{const s={text:"",dispatchOnSet:!1,...r.getState()};if(t.name===Dr.setText){if(!((n.data.type===de.String||n.data.type===de.Anything)&&"string"==typeof n.data.value))return;if("string"==typeof n.data.value&&(s.text=n.data.value,r.setState(s)),!s.dispatchOnSet)return}const i=r.nextGate(jr.length,{type:de.Number,value:s.text.length}),o=r.nextGate(jr.string,{type:de.String,value:s.text});await Promise.all([i,o])},getInputNames:e=>{const t=[{name:Dr.setText,type:de.String}];return e.dispatchOnSet||t.push({name:Dr.trigger,type:de.Anything}),t},getOutputNames:()=>[{name:jr.string,type:de.String},{name:jr.length,type:de.Number}],getDefaultState:Ur};const Fr=Object.freeze({image:"image"}),Rr=Object.freeze({image:"image",x:"x",y:"y",width:"width",height:"height"}),Wr=()=>({showInputPorts:!1});var Gr={onParentEvent:async(e,t,n,r)=>{const s={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===Rr.x&&(s.cropX=n.data.value),t.name===Rr.y&&(s.cropY=n.data.value),t.name===Rr.width&&(s.cropWidth=n.data.value),t.name===Rr.height&&(s.cropHeight=n.data.value),void r.setState(s);if(t.name===Rr.image){if(n.data.type!==de.ImageData&&n.data.type!==de.Anything)return;if(!Ne(n.data.value))return;const e=n.data.value;if(s.$$memCanvas&&s.$$memCanvas.getContext||(s.$$memCanvas=Ut(320,240),s.$$memCanvasContext=Mt(s.$$memCanvas),r.setState(s)),!s.$$memCanvas||!s.$$memCanvasContext)return void console.error("Failed to get canvas or context");let t=e;return s.$$memCanvas.width=e.width,s.$$memCanvas.height=e.height,(s.cropX||s.cropY||s.cropWidth||s.cropHeight)&&(t=((e,t,n,r)=>{if(!n)return e;const s=Math.max(r.x||0,0),i=Math.max(r.y||0,0),o=e.width,a=e.height,c=Math.min(Math.ceil(r.width||o),o),l=Math.min(Math.ceil(r.height||a),a);return t.width=e.width,t.height=e.height,n.putImageData(e,0,0),n.drawImage(t,s,i,c,l,0,0,c,l),n.getImageData(0,0,c,l)})(e,s.$$memCanvas,s.$$memCanvasContext,{x:s.cropX,y:s.cropY,width:s.cropWidth,height:s.cropHeight})),r.nextGate(Fr.image,{type:de.ImageData,value:t})}},getInputNames:e=>{const t=[{name:Rr.image,type:[de.ImageData]}];return e.showInputPorts&&(t.push({name:Rr.x,type:de.Number}),t.push({name:Rr.y,type:de.Number}),t.push({name:Rr.width,type:de.Number}),t.push({name:Rr.height,type:de.Number})),t},getOutputNames:()=>[{name:Fr.image,type:de.ImageData}],getDefaultState:Wr};const Vr=Object.freeze({image:"image"}),Hr=Object.freeze({image:"image",width:"width",height:"height"}),zr=()=>({showInputPorts:!1});var qr={onParentEvent:async(e,t,n,r)=>{const s={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===Hr.width&&(s.width=n.data.value),t.name===Hr.height&&(s.height=n.data.value),void r.setState(s);if(t.name===Hr.image){if(n.data.type!==de.ImageData&&n.data.type!==de.Anything)return;if(!Ne(n.data.value))return;const e=n.data.value;if(s.$$memCanvas&&s.$$memCanvas.getContext||(s.$$memCanvas=Ut(320,240),r.setState(s)),!s.$$memCanvas)return;let t=e;return(s.width||s.height)&&(t=((e,t,n,r)=>{if(!n&&!r)return e;n&&!r?r=n*(e.height/e.width):!n&&r&&(n=r*(e.width/e.height));const s=Math.max(1,n||e.width),i=Math.max(1,r||e.height);t.width=Math.max(e.width,s),t.height=Math.max(e.height,i);const o=Mt(t);if(!o)throw new Error("Failed to get canvas context");return o.putImageData(e,0,0),o.drawImage(t,0,0,e.width,e.height,0,0,s,i),o.getImageData(0,0,s,i)})(e,s.$$memCanvas,s.width,s.height)),r.nextGate(Vr.image,{type:de.ImageData,value:t})}},getInputNames:e=>{const t=[{name:Hr.image,type:de.ImageData}];return e.showInputPorts&&(t.push({name:Hr.width,type:de.Number}),t.push({name:Hr.height,type:de.Number})),t},getOutputNames:()=>[{name:Vr.image,type:de.ImageData}],getDefaultState:zr};const Kr=Object.freeze({value:"value"}),Jr=Object.freeze({trigger:"trigger",setValue:"setValue"}),Yr=()=>({value:0,dispatchOnSet:!1});var Xr={onParentEvent:async(e,t,n,r)=>{const s={value:0,dispatchOnSet:!1,...r.getState()};if(t.name===Jr.setValue){const e=n.data.type===de.Number||n.data.type===de.Anything||n.data.type===de.String,t=!isNaN(Number(n.data.value))&&!Array.isArray(n.data.value);if(!e||!t)return;if(s.value=Number(n.data.value),r.setState(s),!s.dispatchOnSet)return}return r.nextGate(Kr.value,{type:de.Number,value:s.value})},getInputNames:e=>{const t=[{name:Jr.setValue,type:de.Number}];return e.dispatchOnSet||t.push({name:Jr.trigger,type:de.Anything}),t},getOutputNames:()=>[{name:Kr.value,type:de.Number}],getDefaultState:Yr};const Zr=Object.freeze({image:"image"}),Qr=Object.freeze({image:"image"}),es=()=>({anchors:[],vertices:[],matrix:[]}),ts={onParentEvent:async(e,t,n,r)=>{const s={anchors:[],vertices:[],matrix:[],...r.getState()},i=window,o=n.data.type===de.ImageData;if(i.Speedy&&o){const e=i.Speedy,t=n.data.value;let o,u,d,p=s.$$private?.canvas,h=s.$$private?.context,f={...s};const g=4===s.anchors.length;if(s.$$private?.pipeline)o=s.$$private?.pipeline,u=s.$$private?.source;else{o=e.Pipeline(),u=e.Image.Source();const n=e.Image.Sink();d=e.Transform.PerspectiveWarp(),p?p.width===t.width&&p.height===t.height||(p.width=t.width,p.height=t.height,h=p.getContext("2d")):(c=t.width,l=t.height,p=Ut(c,l),h=p.getContext("2d")),u.output().connectTo(d.input()),d.output().connectTo(n.input()),o.init(u,n,d);let r=e.Matrix(3,3,[1,0,0,0,1,0,0,0,1]);if(4===s.anchors.length){const t=e.Matrix(2,4,[(a=s.anchors)[0].x,a[0].y,a[1].x,a[1].y,a[2].x,a[2].y,a[3].x,a[3].y]),n=e.Matrix(2,4,s.vertices.reduce(((e,t)=>e.concat([t.x,t.y])),[])),i=e.Matrix.Zeros(3,3);await e.Matrix.perspective(i,t,n);const o=i.read();r=e.Matrix(3,3,o)}d.transform=r,f={...f,$$private:{...f.$$private,canvas:p,context:h,perspective:d,pipeline:o,source:u}}}let m=t;if(g){const e=await(async(e,t)=>{const n=window,r=e.$$private?.source,s=e.$$private?.pipeline;if(n.Speedy&&r&&s){const e=n.Speedy,i=await createImageBitmap(t),o=await e.load(i);return r.media=o,(await s.run()).image.source}return null})(f,m);e&&(p&&h&&(m=((e,t,n)=>(t.width=e.width,t.height=e.height,n.drawImage(e,0,0),n.getImageData(0,0,e.width,e.height)))(e,p,h)),f.$$private&&r.setState({...f,$$private:{...f.$$private,lastInputImage:t}}))}else f.$$private&&r.setState({...f,$$private:{...f.$$private,lastInputImage:t}});return r.nextGate(Zr.image,{type:de.ImageData,value:m})}var a,c,l;console.log("Environment not supported")},getInputNames:()=>[{name:Qr.image,type:de.ImageData}],getOutputNames:()=>[{name:Zr.image,type:de.ImageData}],getDefaultState:es,terminate:async e=>{const t=e.getState();t.$$private?.pipeline.release()}},ns=()=>({name:"Default widget bundle",description:"",inputs:[{dataType:[de.Anything],name:"input"}],outputs:[{dataType:[de.Anything],name:"output"}]});let rs;const ss=()=>{if(!rs)throw new Error(Je(Ke));return rs};const is=async e=>{const t=new c,n=await t.loadAsync(e),r={};for(const e in n.files)if(!n.files[e].dir){const t=await n.file(e);t&&(r[e]=await t.async("uint8array"))}return r},os={};var as=e=>os[e]||null;const cs=async(e,t,n)=>{try{const r=ss(),s=n?r.loadBlobAsString:r.loadBlob;return await s(e,t)}catch(e){return null}},ls=async e=>{const t=ie;try{const n=await cs(e,t,!0);if(!n)return null;return Function(n)()}catch(e){return null}},us=async e=>{const t=oe;try{const n=await cs(e,t,!0);if(!n)return null;return JSON.parse(n)}catch(n){return console.log(`Failed to parse the bundle's state [${e}/${t}] %j`,n),null}},ds=(e,t)=>`${e.replace(ae,"")}_${t}`,ps=(e,t)=>`widget/${e.replace(ae,"")}/v/${t}`,hs=async(e,t)=>{const n=ss(),[r]=await Promise.all([is(e),n.createLocation(t)]);for(const e in r)e.startsWith("__MACOSX")||await n.saveBlob(t,e,r[e])},fs=(e,t)=>{const n=ds(e,t),r=as(n);return r?{...r}:null},gs=(e,t,n)=>{const r=`${`widget/${e.replace(ae,"")}/tmp`}/${t}`;if(n){return ss().getCacheLocation(r)}return r};var ms=fs,vs=async(e,t,n)=>{const r=gs(t,n);await hs(e,r);const s=ls(r),i=us(r),o=ss(),a=o.getCacheLocation(r),[c,l]=await Promise.all([s,i]);if(!c)return null;let u=l;if(!l){const e=ns(),t=JSON.stringify(e);await o.saveBlob(r,oe,xe(t)),u=e}return{cachePath:a,processor:c,storedState:Object.freeze(u)}},ys=(e,t,n)=>{if(n.isTempStorage)return gs(e,t,n.fullStorageRoot);const r=ss(),s=ps(e,t);return n.fullStorageRoot?r.getCacheLocation(s):s};const bs=()=>ns();var Ss={onParentEvent:async(e,t,n,r)=>{const s=r.getState();return s.$$processor?.onParentEvent({sourcePort:e?.name||"",targetPort:t?.name||"",data:n.data},{getState:r.getState,recipeId:r.recipePoolId,recipeType:r.recipeType,setState:r.setState,nextWidget:r.nextGate})},getInputNames:(e,t)=>{const n={...bs(),...e};return n.$$processor?.getInputNames?n.$$processor.getInputNames(e,t):n.inputs.map((e=>({name:e.name,type:e.dataType})))},getOutputNames:(e,t)=>{const n={...bs(),...e};return n.$$processor?.getOutputNames?n.$$processor.getOutputNames(e,t):n.outputs.map((e=>({name:e.name,type:e.dataType})))},getDefaultState:bs,initialize:async(e,t)=>{console.log("Widget bundle initialize",e);let n={...e.getState()},r=n.$$cacheInfo?.widgetThingId||n.collectionInfo?.widgetId||e.widgetThingId;const s=n.$$cacheInfo?.version.toString()||n.collectionInfo?.version.toString()||1;if(n.$$cacheInfo={...n.$$cacheInfo,version:Number(s),widgetThingId:r},!r||!s)throw new Error("Widget bundle state is missing cache id or version");console.log("Loading state from cache");const i=ms(r,s);let o=!i;if(!n.$$processor)if(n.storageUnitId&&!i){const t=await e.getStorageData(n.storageUnitId);if(t){r=e.widgetThingId;const i=await vs(t,r,s);o=!0,i&&(n={...n,$$processor:i.processor,$$cacheInfo:{...n.$$cacheInfo,widgetThingId:r,version:Number(s)}},e.setState(n))}}else if(i){o=!1;const r=n.collectionInfo?{...n.collectionInfo}:void 0;n={...n,...!t.keepCurrentState&&i.storedState?{...i.storedState,...r?{collectionInfo:r}:{}}:{},$$processor:i.processor},e.setState(n)}const a=ys(r,s,{fullStorageRoot:!0,isTempStorage:o});console.log("Invoking bundle initialize with cache: ",a);try{await(n.$$processor?.initialize({cacheLocation:a,getState:e.getState,setState:e.setState}));const t=e.getState();e.setState({...t,$$initializationError:void 0})}catch(t){const n=e.getState();throw e.setState({...n,$$initializationError:t.message||"An error occurred initializing the widget"}),t}},terminate:async e=>{const t={...e.getState()};console.log(`Terminating widget bundle ${t.name} [${t.$$cacheInfo?.widgetThingId||""}]`);const n=t.$$processor;n&&"function"==typeof n.terminate&&await n.terminate({getState:e.getState,setState:e.setState,recipePoolId:e.recipePoolId,widgetId:e.widgetId})}};const ws=Object.freeze({event:"event"}),Is="1",_s="2",$s="3";var Cs={onParentEvent:async(e,t,n,r)=>{const s={...r.getState()};r.setState({...s,$$lastEventType:n.data.type}),await r.nextGate(Is,n.data),await r.nextGate(_s,n.data),await r.nextGate($s,n.data)},getInputNames:()=>[{name:ws.event,type:de.Anything}],getOutputNames:e=>{const t={type:{...e}.$$lastEventType??de.Anything};return[{name:Is,...t},{name:_s,...t},{name:$s,...t}]}};const ks=Object.freeze({set:"set",trigger:"trigger"}),Es="value";var xs={onParentEvent:async(e,t,n,r)=>{const s=r.getState(),i={name:"myVar",type:de.String,reactive:!0,defaultValue:"",...s};if(t.name.startsWith(ce)){if(!i.reactive)return;if(n.data.type!==i.type)return;return r.nextWidget(Es,n.data)}if(t.name!==ks.set){if(t.name===ks.trigger){const e=dr(r.recipePoolId,r.thingRecipeId,i.name,{ownerWidgetId:r.id}),t=e||i.defaultValue;await r.nextWidget(Es,{type:i.type,value:t})}}else await ur(r.recipePoolId,r.thingRecipeId,r.id,i.name,n.data,{skipCallerNotification:!i.reactive})},getInputNames:e=>{const t={...e};return[{name:ks.set,type:t.type||de.Anything},{name:ks.trigger,type:de.Anything}]},getOutputNames:e=>{const t={...e};return[{name:Es,type:t.type||de.Anything}]}};let As;var Ns=e=>{As=e},Os=()=>{if(!As)throw new Error("Hub Connector not set");return As};const Ps=async(e,t=!1)=>{const n=Os();let r=e.$$$serviceId;if(!e.service)return console.log("Aborting service initialization, missing property `service` in state."),null;if(!r||t){const t=await n.getCompatibleService(e.service.name,e.service.version,"^");if(!t)return null;r=t.sessionId}return r};var Ls={onParentEvent:async(e,t,n,r)=>{const s={dynamicInputs:{},dynamicOutputs:{},customState:{},...r.getState()};if(!e)return;const i=Os();let o=s.$$$serviceId;if(!o){const e=i.getCachedServices().available.find((e=>e.name===s.service?.name&&e.version===s.service?.version));if(!e)return;o=e.sessionId,s.$$$serviceId=o,r.setState(s)}const a=s.service?.variants?.find((e=>e.id===s.variantId)),c=a?s.dynamicInputs[a.id]||a?.inputs||[]:s.service?.inputs||[];if(!c?.length)return;if(!a&&s.service?.ignoreParentEvents)return;const l=s.service?.processingTimeoutSec;return i.onParentEvent({recipeId:r.recipePoolId,data:n.data,targetServiceSessionId:o,currentState:s.customState,targetVariantId:s.variantId,target:{portName:t.name,widgetId:r.id,widgetType:r.type},source:e,config:{timeout:l?1e3*l:0,async:s.service?.asyncParentEvents}})},getInputNames:async e=>{const t=e.variantId;if(t&&e.dynamicInputs?.[t])return[...e.dynamicInputs[t]||[]];if(!t)return e.service?.inputs||[];{const n=e.service?.variants?.find((e=>e.id===t));if(n)return n.inputs||[]}return[]},getOutputNames:async e=>{const t=e.variantId;if(t&&e.dynamicOutputs?.[t])return[...e.dynamicOutputs[t]||[]];if(!t)return e.service?.outputs||[];{const n=e.service?.variants?.find((e=>e.id===t));if(n)return n.outputs||[]}return[]},initialize:async e=>{const t={dynamicInputs:{},dynamicOutputs:{},customState:{},...e.getState()},n=Os(),r=await Ps(t);if(r)try{return await n.initializeServiceInstance({recipeId:e.recipePoolId,sessionId:r,widgetId:e.widgetThingId,recipeType:e.recipeType,variantId:t.variantId})}catch(t){if("FNC_NOT_FOUND"!==t?.errCode){if(!!("string"!=typeof t||!t.match('^Function ".*" not found.$')))throw t;console.warn(`Widget [${e.widgetThingId}] does not have an init function.`)}}else console.log(`Aborting service initialization, "${t.service?.name}" was not found in the current Hub.`)},terminate:async e=>{const t={dynamicInputs:{},dynamicOutputs:{},customState:{},...e.getState()},n=Os(),r=await Ps(t,!0);if(r)return n.terminateServiceInstance(r,e.widgetId,e.recipePoolId,t.variantId)}};const Ts=Object.freeze({Image:"image"}),Bs=Object.freeze({Image:"image"}),js=()=>({filters:[{name:"grayscale",value:.5,id:"d-1"}]});const Ds="loaded";const Us={input:Ze,counter:tt,elapsed:st,ifGate:ct,skipEvent:dt,between:gt,map:yt,parser:wt,slider:$t,suspend:Et,display:At,json:Pt,arrayItem:Bt,extractImage:Wt,imageConvolution:qt,firstEvent:Xt,pixelDraw:rn,randomBetween:cn,arrayCombine:hn,clock:vn,multiplication:wn,object:En,widgetGroup:On,script:Cr,base64ToImageData:Or,jsonParse:Br,text:Mr,imageCrop:Gr,imageResize:qr,value:Xr,imageWarp:ts,widgetBundle:Ss,sequence:Cs,variable:xs,hubService:Ls,imageFilter:{onParentEvent:async(e,t,n,r)=>{const s={filters:[{name:"grayscale",value:.5,id:"d-1"}],...r.getState()};if(t.name===Ts.Image&&n.data.type===de.ImageData){if(!Ne(n.data.value))return void console.log("ImageFilter: Invalid image data type, aborting process");const e=n.data.value;s.$$memCanvas||(s.$$memCanvas=Ut(e.width,e.height)),s.$$context||(s.$$context=s.$$memCanvas.getContext("2d")),s.$$memCanvas.width!==e.width&&(s.$$memCanvas.width=e.width),s.$$memCanvas.height!==e.height&&(s.$$memCanvas.height=e.height),r.setState(s),s.$$context.putImageData(e,0,0),s.filters.length?s.$$context.filter=s.filters.map((e=>`${e.name}(${e.value}${"blur"===e.name?"px":""})`)).join(" "):s.$$context.filter="none",s.$$context.drawImage(s.$$memCanvas,0,0);const t=s.$$context.getImageData(0,0,e.width,e.height);return r.nextWidget(Bs.Image,{type:de.ImageData,value:t})}},getInputNames:()=>[{name:Ts.Image,type:de.ImageData}],getOutputNames:()=>[{name:Bs.Image,type:de.ImageData}],getDefaultState:js},recipeLoad:{onParentEvent:async(e,t,n,r)=>r.nextWidget(Ds,{value:!0,type:de.Boolean}),getInputNames:()=>[],getOutputNames:()=>[{name:Ds,type:de.Boolean,description:"Triggered when the recipe is fully loaded"}]},play:{getInputNames:()=>[],onParentEvent:()=>Promise.resolve(),getOutputNames:()=>[{name:"out",type:de.Boolean}]}},Ms={},Fs=async()=>{if(!Object.keys(Ms).length)for(const e in Us){const t=Us[e];Ms[e]=Object.freeze({...t})}};var Rs=e=>{if(Ms[e])return Ms[e];throw new Error(Je(qe,e))},Ws=Fs;const Gs=new a,Vs="invoked";let Hs={},zs={},qs={},Ks={};const Js=(e,t,n)=>`${e}-${t}${n?`-${n}`:""}`;var Ys=(e,t,n,r,s)=>{const i=Js(e,t,n),o=Js(e,t),a=Js(e,t,"produced"),c=qs[o],l=Date.now();Ks[o]=l,Hs[i]={data:r,sourcePortName:n,...s?{target:{widgetId:s.widgetId,portName:s.portName}}:{}},Gs.emit(a,{currentTime:l,prevTime:c,...s?{targetPort:s?.portName}:{}})},Xs=(e,t,n,r,s)=>{const i=Js(e,t,n),o=Js(e,t),a=Js(e,t,Vs),c=qs[o],l=Date.now();qs[o]=l,zs[i]={data:r,sourcePortName:n,...s?{source:{widgetId:s.widgetId,portName:s.portName}}:{}},Gs.emit(a,{prevTime:c,currentTime:l,targetPort:n,sourceInfo:s})},Zs=()=>{Hs={},zs={},qs={},Ks={},Gs.clearListeners()};let Qs,ei,ti;const ni=async(e,t,n,r,s)=>{const i=te(n,t);if(!i)return;const o=i.gates[e];if(!o||o.disabled)return;const a={...s,timestamp:Date.now()},c=Rs(o.type),l=oi(e,a,i.recipeId,i.id,i.version,n);if(l&&c.onParentEvent){const t={name:r};return Qs&&await Qs({recipeId:n,blockId:i.recipeId,gateId:e,targetPort:t.name,data:s}),c.onParentEvent(null,t,{originalEvent:a,data:{...a}},l)}},ri=async(e,t,n,r,s,i,o,a,c,l)=>{if(!e&&!c)throw new Error("Missing parameter ['sourceGateId']");if(!e&&!l)throw new Error("Missing parameter ['originalEvent']");e&&(l={timestamp:Date.now(),type:de.Boolean,value:!0});const u=l;if("string"==typeof n){const e=te(r,n);if(!e)return;n=e}const d=n.gates[t];if(!d||d.disabled)return;const p=a.findIndex((e=>e.name===s)),h=Rs(d.type),f=oi(t,u,n.recipeId,n.id,n.version,r);if(f&&h.onParentEvent&&-1!==p){Qs&&await Qs({recipeId:r,blockId:n.recipeId,gateId:t,targetPort:i.name,data:o,sourceGate:e?"interrupt_widget":c,sourcePort:e?se:s});const l={name:a[p].name,type:a[p].type,...a[p].jsonShape?{jsonShape:a[p].jsonShape}:void 0};return Xs(n.recipeId,t,i.name,o,c?{widgetId:c,portName:s}:void 0),h.onParentEvent(l,i,{originalEvent:u,data:o},f)}},si=async(e,t,n,r,s,i,o,a)=>{const c=ee(a);if(!c)throw new Error(`Failed to find recipe "${a}" in cache`);const l=c.dbInfo.recipeType,u=ne(a,s,r);if(!u)return;const d={...n,timestamp:t.timestamp},p=Rs(u.type);let h;h=u.type===Me.input?p.getOutputNames(u.state,{thingRecipeId:s,thingDbId:i,thingVersion:o,id:r,recipeId:a,recipeType:l,recipePoolId:a}):await p.getOutputNames(u.state,{recipePoolId:a,recipeType:l,thingRecipeId:s,widgetId:r});const f=h.findIndex((t=>t.name===e));if(-1!==f){const n=te(a,s);if(!n)return;Ys(s,r,e,d);const i=u.children.length;for(let o=0;o<i;o++){if(je(u.children[o]?.sourcePort).portName===e){const i=n.gates[u.children[o].childId];if(i&&!i.disabled){const c=Rs(i.type);let p;const f={recipePoolId:a,recipeType:l,thingRecipeId:s,widgetId:r};p=i.type===Me.hubService?await c.getInputNames(i.state,f):c.getInputNames(i.state,f);const g=je(u.children[o].targetPort),m=p.find((e=>e.name===g.portName));m&&await ri(!1,i.id,n,a,e,{name:m.name},u.returnOriginalEvent?t:d,h,u.id,t)}}}}},ii=async(e,t,n,r)=>{const s=ee(r);if(!s)return null;const i=te(r,n);if(!i)return i;const o=i.gates,a=i.gates[t],c=Rs(a.type),l=await c.getInputNames(a.state,{recipePoolId:r,recipeType:s.dbInfo.recipeType,thingRecipeId:n,widgetId:t}),u=l.findIndex((t=>t.name===e));if(-1!==u){const e=((e,t,n)=>{for(const r in n){const s=n[r],i=s.children.length;for(let n=0;n<i;n++){const r=s.children[n],i=je(r.targetPort);if(r.childId===e&&i.portName===t)return s}}return null})(t,l[u].name,o);if(e){const t=Rs(e.type);return{getValue:()=>"function"==typeof t.getValue?t.getValue():null}}}return null},oi=(e,t,n,r,s,i)=>{const o=ee(i);if(!o)throw new Error(`Failed to find recipe "${i}" in cache`);const a=ne(i,n,e);if(!a)return console.warn(`Gate ${e} not found in block ${n} for recipe ${i}`),null;const c=async(o,a)=>si(o,t,a,e,n,r,s,i),l={id:e,type:a.type,recipePoolId:i,thingRecipeId:n,recipeType:o.dbInfo.recipeType,returnOriginalEvent:!!a.returnOriginalEvent,registerInterrupt:(t,r,s,o,a)=>Ve.createInterrupt(t,i,n,e,r,s,o,a),cancelInterrupt:e=>Ve.destroyInterrupt(e),nextWidget:c,nextGate:c,getParentAtPort:t=>ii(t,e,n,i),getState:()=>Object.freeze({...a.state,...a.type===Me.input&&{customInputs:[]}}),setState:t=>{if("object"!=typeof t)return void console.warn(`Invalid state type [${typeof t}]. Expected an 'object'`);const r={...t,...a.type===Me.input&&!t.customInputs&&{customInputs:[]}},s={...a.state};a.state=r,ei&&ei({blockId:n,gateId:e,prevState:s,newState:{...r},recipeId:i})}};return l};Ve.setInvokeChildGateCb(ri);const ai=new a,ci="invoked",li="state",ui=()=>{Ve.destroyAllInterrupts()},di=async(e,t,n)=>{const r=ee(e),s=ne(e,t,n);if(s&&r){const i=Rs(s.type);if(i&&"function"==typeof i.terminate){const s=((e,t,n,r)=>He(e,t,n,r))(e,r.dbInfo.recipeType,t,n);if(s)try{await i.terminate(s)}catch(e){console.warn(`Error terminating widget "${n}" in thing "${t}". Failing silently: `,e)}}}},pi=async(e,t,n,r)=>{const s=ee(e),i=ne(e,t,n);if(i&&s){const o=Rs(i.type);if(o&&"function"==typeof o.initialize){const i=((e,t,n,r)=>He(e,t,n,r,!0))(e,s.dbInfo.recipeType,t,n);if(i){const e=o.initialize;try{await e(i,r||{})}catch(e){throw console.warn(`Error initializing widget "${n}" in thing "${t}": `,e),e}}}}},hi=(e,t)=>{const n=ee(t);if(n)for(const t in n.blocks){const r=n.blocks[t];for(const t in r.gates)if(t===e)return{widget:r.gates[t],thing:r}}return null},fi=(e,t="",n="")=>`block:${t}:gate:${n||""}:${e}`,gi=e=>{ai.emit(fi(li),e),ai.emit(fi(li,e.blockId,e.gateId),e)};Qs=async e=>{await ai.emit(fi(ci),e),await ai.emit(fi(ci,e.blockId,e.gateId),e)},(e=>{ei=e})(gi);var mi,vi,yi,bi,Si,wi,Ii,_i,$i,Ci,ki,Ei,xi,Ai=async(e,t,n,r,s)=>{const i=re(e,{id:t,authorId:r,version:n,recipeType:s});Zs();const o=ee(i);return o&&(o.startedAt=Date.now(),o.retryAttempts=0,o.execCounter=0,o.status=Y.STARTING,o.addLog("recipe registered")),i},Ni=async e=>{const t=ee(e);var n;if(!t)return null;t.addLog("terminating recipe"),ui();for(const n in t.blocks){const r=t.blocks[n];for(const t in r.gates)await di(e,n,t)}X[n=e]&&delete X[n]},Oi=async(e,t)=>{const n=ee(e),r=[],s=[];if(n)for(const i in n.blocks){const o=n.blocks[i];if(!t||!Array.isArray(t)||t.includes(i))for(const t in o.gates)try{if(n.dbInfo?.recipeType===Ln.Desktop){const e=o.gates[t];if(e.type===Me.hubService){const r=e.state;if(r?.service?.webOnly){n?.addLog(`skipping initialization of web-only widget "${t}"`);continue}}e.type===Me.recipeLoad&&s.push(e)}await pi(e,i,t,{keepCurrentState:!0})}catch(e){r.push({widgetId:t,error:e.message})}}return{failed:r,sendToInputWidget:(t,n,r=le)=>(async(e,t,n,r)=>{const s=ee(n),i=te(n,r),o=Date.now();if(i&&s)for(const s in i.gates){const a=i.gates[s];if(a.type===Me.input&&!a.disabled){const c=a.state.inputName||"";if(c===e){const e=Rs(a.type),l={...t,timestamp:o},u=oi(s,l,r,i.id,i.version,n);if(u&&e.processEvent){const i={...u,getState:u.getState};Qs&&await Qs({recipeId:n,blockId:r,gateId:s,targetPort:Xe,data:t}),ti?await ti(r,n,c,t):await e.processEvent(l,i)}}}}})(t,n,e,r),invokeRecipeLoadedWidgets:async()=>{for(const t of s)await ni(t.id,le,e,Ds,{type:de.Boolean,value:!0})}}},Pi=e=>{Ns(e)},Li=(e,t,n,r=!1)=>{const s=hi(t,e);if(s){const{widget:i,thing:o}=s,a={...i.state};i.state=n,r&&gi({blockId:o.recipeId,gateId:t,recipeId:e,newState:{...n},prevState:a})}},Ti=(e,t)=>{const n=hi(t,e);return n?n.widget.state:null},Bi=async(e,t,n,r,s)=>{const i=hi(t,e);if(i)return si(n,r,s,t,i.thing.recipeId,i.thing.id,i.thing.version,e)};!function(e){e.Seats="seats",e.RecipeInvocations="recipe_invocations",e.HubServices="hub_services",e.RecipeExports="recipe_exports"}(mi||(mi={})),function(e){e.UserFriendlyName="user_friendly_name",e.UserFriendlyDescription="user_friendly_description",e.InternalDescription="internal_description",e.TierLevel="tier_level",e.ProductFeatures="product_features",e.UserSubscribeCode="subscription_code"}(vi||(vi={})),function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(yi||(yi={})),function(e){e.Bundle="bundle",e.Group="group"}(bi||(bi={})),function(e){e.Hardware="hardware",e.Virtual="virtual"}(Si||(Si={})),function(e){e.Cloud="cloud",e.Web="web"}(wi||(wi={})),function(e){e.Cpu_128M="kmu-cpu-128m",e.Cpu_256M="kmu-cpu-256m",e.Cpu_512M="kmu-cpu-512m",e.Cpu_1024M="kmu-cpu-1024m",e.Cpu_2048M="kmu-cpu-2048m",e.Cpu_4096M="kmu-cpu-4096m"}(Ii||(Ii={})),function(e){e.Gateway="gateway",e.Timer="timer"}(_i||(_i={})),function(e){e.InstallInProgress="installation-in-progress"}($i||($i={})),function(e){e.InstallDependencies="install-dependencies",e.GetInstalledDependencies="get-installed-dep"}(Ci||(Ci={})),function(e){e.Success="success",e.Error="error",e.Pending="pending"}(ki||(ki={})),function(e){e.NotFound="not-found",e.BadRequest="bad-request",e.Forbidden="forbidden",e.InternalError="internal-error"}(Ei||(Ei={})),function(e){e.KeyCreated="key_created",e.ValidateKey="validate_key",e.ExecuteRecipe="execute_recipe",e.InstallHubService="install_hub_service",e.ExportRecipe="export_recipe"}(xi||(xi={}));const ji=(e,t)=>((e,t,n)=>{const r=Buffer.from(n,"base64"),s=r.subarray(0,16),i=r.subarray(16).toString("base64"),o=u(e,t,32),a=d("aes-256-cbc",o,s);let c=a.update(i,"base64","utf8");return c+=a.final("utf8"),c})(e.id,"kemu",t),Di=e=>{try{return JSON.parse(e)}catch(e){return null}},Ui="undefined"!=typeof window,Mi={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},Fi={protocolPrefix:4,txtLength:4},Ri=Object.values(Mi).reduce(((e,t)=>e+t),0),Wi=Object.values(Fi).reduce(((e,t)=>e+t),0),Gi=["width","height","colorSpace"],Vi=(e,t)=>{const n={},r=[];let s=0,i=Array.isArray(e)?[]:{};const o=(e,i)=>{const a=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,s=e instanceof Uint8Array,i=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":s?"Uint8Array":i?"Int8Array":null})(e);if(!a){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=o(e[n],`${i}[${n}]`);return t}if("object"==typeof e){const t={},n=(e=>{const t=e instanceof Int16Array,n=e instanceof Uint16Array,r=e instanceof Int32Array,s=e instanceof Uint32Array,i=e instanceof Float32Array,o=e instanceof Float64Array,a=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":s?"Uint32Array":i?"Float32Array":o?"Float64Array":a?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${i}"`);for(const n in e)e.hasOwnProperty(n)||Gi.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${i}`),t[n]=o(e[n],`${i.length?`${i}.`:""}${n}`);return t}return e}n[i]={index:s,length:e.byteLength,binaryType:a},"Buffer"===t?r.push(Buffer.from(e)):"ArrayBuffer"===a?r.push(e):r.push(e.buffer),s+=e.byteLength};i=o(e,"");let a=null;if(r.length>1)if("ArrayBuffer"===t){const e=r.reduce(((e,t)=>e+t.byteLength),0),t=new Uint8Array(e);let n=0;for(let e=0;e<r.length;e++)t.set(new Uint8Array(r[e]),n),n+=r[e].byteLength;a=t.buffer}else{a=Buffer.concat(r)}else 1===r.length&&(a=r[0]);return a?{map:n,combinedData:a,sourceCopy:i}:null},Hi=(e,t,n)=>{const r=t.match(/(\[\d+\])|([^[\].]+)/g)||[];let s=e;for(let e=0;e<r.length;e++){let t=r[e];const i=t.startsWith("[")&&t.endsWith("]"),o=e===r.length-1;if(i){t=t.slice(1,-1);const i=parseInt(t,10);if(!Array.isArray(s))throw new Error(`Expected an array at key "${r.slice(0,e).join(".")}" but found an object.`);o?s[i]=n:(s[i]||(s[i]=r[e+1].startsWith("[")?[]:{}),s=s[i])}else o?s[t]=n:(s[t]||(s[t]=r[e+1].startsWith("[")?[]:{}),s=s[t])}return e},zi=(e,t,n)=>{const r="undefined"!=typeof Buffer,s=t instanceof Uint8Array;for(const i in n)if(n.hasOwnProperty(i)){const{index:o,length:a,binaryType:c}=n[i];let l=null;if(r&&t instanceof Buffer)switch(c){case"Buffer":l=t.subarray(o,o+a);break;case"ArrayBuffer":l=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a);break;case"Uint8Array":l=new Uint8Array(t.subarray(o,o+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.subarray(o,o+a));break;case"Int8Array":l=new Int8Array(t.subarray(o,o+a))}else if(t instanceof ArrayBuffer||t instanceof Uint8Array)switch(c){case"Buffer":if(r){l=Buffer.from(t.slice(o,o+a));break}case"ArrayBuffer":l=s?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a):t.slice(o,o+a);break;case"Uint8Array":l=s?t.slice(o,o+a):new Uint8Array(t.slice(o,o+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.slice(o,o+a));break;case"Int8Array":l=new Int8Array(t.slice(o,o+a))}l&&Hi(e,i,l)}return e},qi=e=>f(e),Ki="KMSG",Ji="KCMD",Yi=qi("klProtocol");var Xi={encode:(e,t,n)=>{const r={json:e.json},s=Vi(r.json,"Buffer"),i=s?.combinedData;s&&(r.jsonBinaryMap=s.map,r.json=s.sourceCopy);const o=i?i.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),l=c.byteLength,u=Mi.protocolPrefix+Mi.protocolVersion+Mi.jsonLength+Mi.binaryLength+Mi.fromServiceId+Mi.toServiceId+Mi.sentAt+l+o,d=Buffer.alloc(u),p=Date.now();let h=0;return d.write(Ki,h),h+=Mi.protocolPrefix,d.writeUInt8(1,h),h+=Mi.protocolVersion,d.writeUInt32LE(l,h),h+=Mi.jsonLength,d.writeUInt32LE(o,h),h+=Mi.binaryLength,d.writeUInt32LE(t,h),h+=Mi.fromServiceId,d.writeUInt32LE(n,h),h+=Mi.toServiceId,d.writeBigInt64LE(BigInt(p),h),h+=Mi.sentAt,c.copy(d,h),h+=l,i&&o&&i.copy(d,h),d},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,Mi.protocolPrefix);if(t+=Mi.protocolPrefix,n!==Ki)return null;if(e.byteLength<Ri)return Yi(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=Mi.protocolVersion;const s=e.readUInt32LE(t);t+=Mi.jsonLength;const i=e.readUInt32LE(t);t+=Mi.binaryLength;const o=e.readUInt32LE(t);t+=Mi.fromServiceId;const a=e.readUInt32LE(t);t+=Mi.toServiceId;const c=e.readBigInt64LE(t);t+=Mi.sentAt;const l=s+i,u=e.subarray(t,t+l),d=e.subarray(0,Ri);let p=null;return e.byteLength-Ri-s-i>0&&(p=e.subarray(Ri+s+i)),{header:{protocolVersion:r,jsonLength:s,binaryLength:i,fromServiceId:o,toServiceId:a,sentAt:new Date(Number(c)),packages:[u],headerPackage:d},remaining:p}},decodeFullKlMessage:e=>{const t=Buffer.concat(e.packages),n=t.subarray(0,e.jsonLength).toString(),r=t.subarray(e.jsonLength,e.jsonLength+e.binaryLength),s=Di(n);if(!s?.json)return Yi("Invalid JSON in KL message"),null;s.jsonBinaryMap&&r.byteLength&&zi(s.json,r,s.jsonBinaryMap);const i=Buffer.concat([e.headerPackage,t]);let o=i,a=null;const c=Ri+e.jsonLength+e.binaryLength;return i.byteLength>c&&(a=i.subarray(c),o=i.subarray(0,c)),{message:{json:s.json,rawMessage:o},remaining:a}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Ri)return Yi("Invalid Header Size"),e;let n=0;return n+=Mi.protocolPrefix,n+=Mi.protocolVersion,n+=Mi.jsonLength,n+=Mi.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=Mi.fromServiceId,void 0!==t.toServiceId&&e.writeUInt32LE(t.toServiceId,n),e},encodeCommand:e=>{let t=0;const n=Buffer.from(e),r=n.byteLength,s=Wi+r,i=Buffer.alloc(s);return i.write(Ji,t),t+=Fi.protocolPrefix,i.writeUint32LE(r,t),t+=Fi.txtLength,n.copy(i,t),i},decodeCommand:e=>{let t=0;if(e.byteLength<Wi)return{command:null};const n=e.toString("utf-8",t,Fi.protocolPrefix);if(t+=Fi.protocolPrefix,n!==Ji)return{command:null};const r=e.readUInt32LE(t);t+=Fi.txtLength;const s=e.toString("utf-8",t,t+r),i=e.byteLength-Wi-r;let o=null;i>0&&(o=e.subarray(Wi+r));let a=0;return i<0&&(a=Math.abs(i)),{command:s,remainingData:o,missing:a}}};const Zi="KMSG",Qi="KCMD",eo=qi("klProtocol"),to=new TextEncoder;var no={encode:(e,t,n)=>{const r={json:e.json},s=Vi(e.json,"ArrayBuffer"),i=s?.combinedData;s&&(r.jsonBinaryMap=s.map,r.json=s.sourceCopy);const o=i?i.byteLength:0,a=JSON.stringify(r),c=to.encode(a),l=c.byteLength,u=new ArrayBuffer(Mi.protocolPrefix+Mi.protocolVersion+Mi.jsonLength+Mi.binaryLength+Mi.fromServiceId+Mi.toServiceId+Mi.sentAt+l+o),d=new DataView(u),p=new Uint8Array(u),h=Date.now();let f=0;for(let e=0;e<4;++e)p[f++]=Zi.charCodeAt(e);return d.setUint8(f,1),f+=Mi.protocolVersion,d.setUint32(f,l,!0),f+=Mi.jsonLength,d.setUint32(f,o,!0),f+=Mi.binaryLength,d.setUint32(f,t,!0),f+=Mi.fromServiceId,d.setUint32(f,n,!0),f+=Mi.toServiceId,d.setBigInt64(f,BigInt(h),!0),f+=Mi.sentAt,p.set(c,f),f+=l,i&&o&&p.set(new Uint8Array(i),f),u},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<Mi.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Zi)return null;if(e.byteLength<Ri)return eo.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const s=t.getUint8(n);n+=Mi.protocolVersion;const i=t.getUint32(n,!0);n+=Mi.jsonLength;const o=t.getUint32(n,!0);n+=Mi.binaryLength;const a=t.getUint32(n,!0);n+=Mi.fromServiceId;const c=t.getUint32(n,!0);n+=Mi.toServiceId;const l=t.getBigInt64(n,!0);n+=Mi.sentAt;const u=i+o,d=e.slice(n,n+u),p=new Uint8Array(e,0,Ri);let h=null;if(e.byteLength-Ri-i-o>0){h=new Uint8Array(e,Ri+i+o).slice().buffer}return{header:{protocolVersion:s,jsonLength:i,binaryLength:o,fromServiceId:a,toServiceId:c,sentAt:new Date(Number(l)),packages:[d],headerPackage:p.slice().buffer},remaining:h}},decodeFullKlMessage:e=>{const t=e.packages.reduce(((e,t)=>e+t.byteLength),0),n=new Uint8Array(t);let r,s=0;for(const t of e.packages)r=new Uint8Array(t),n.set(r,s),s+=r.byteLength;const i=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),o=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=Di(i);if(!a?.json)return eo.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&o.byteLength&&zi(a.json,o,a.jsonBinaryMap);const c=new Uint8Array(e.headerPackage.byteLength+n.byteLength);c.set(new Uint8Array(e.headerPackage),0),c.set(n,e.headerPackage.byteLength);let l=c,u=null;const d=Ri+e.jsonLength+e.binaryLength;return c.byteLength>d&&(u=c.subarray(d),l=c.subarray(0,d)),{message:{json:a.json,...o.length?{binaryData:o.buffer}:{},rawMessage:l.buffer},remaining:u?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Ri)return eo("Invalid Header Size"),e;let n=0;n+=Mi.protocolPrefix,n+=Mi.protocolVersion,n+=Mi.jsonLength,n+=Mi.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=Mi.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=to.encode(e),r=n.byteLength,s=new ArrayBuffer(Wi+r),i=new DataView(s),o=new Uint8Array(s);for(let e=0;e<4;++e)o[t++]=Qi.charCodeAt(e);return i.setUint32(t,r,!0),t+=Fi.txtLength,o.set(n,t),s},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<Wi)return{command:null};let r="";for(let e=0;e<Fi.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Qi)return{command:null};const s=t.getUint32(n,!0);n+=Fi.txtLength;const i=e.byteLength-Wi-s,o=new Uint8Array(e,n,Math.min(s,e.byteLength-Wi)),a=(new TextDecoder).decode(o);let c=null;i>0&&(c=e.slice(Wi+s));let l=0;return i<0&&(l=Math.abs(i)),{command:a,remainingData:c,missing:l}}};let ro=Xi;Ui&&(ro=no);var so,io=ro;(so||(so={})).FunctionNotFound="FNC_NOT_FOUND";let oo=Math.ceil(Date.now()/1e3);let ao,co,lo,uo,po,ho=!1;var fo=()=>{ho=!0},go=(e,t)=>{if(!ao)throw new Error("Memory connection not set.");ao.sendBuf(e,t)},mo=e=>co=e,vo=e=>po=e,yo=e=>lo=e,bo=e=>uo=e;const So=(e,t=2)=>{const n=(e,r)=>{if("object"==typeof e){const s=Object.keys(e);for(const i of s){const s=e[i];if(s&&"object"==typeof s){const o=s._kemuType;if(void 0!==o){if(o===de.ImageData){const t=e[i];e[i]=De(t)}}else r<t&&n(s,++r)}}}};return n(e,1),e};qi("klTransmissionManager"),qi("ipcClient");qi("kemuWidgetService"),C(process.argv.slice(2));const wo=e=>f(`runner:${e}`),Io=wo("connectionManager"),_o=wo("remoteInvoke"),$o=new function(e){const t={};let n=console.log;const r={};let s=e||String(Date.now());const i={},o=e=>!i[e],a=(e,t,n,r,s,i)=>{let a=Ui?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:i.success?i.success:[i],messageId:t,type:i.success?"response":"error"}};return o(r)&&(a=io.encode(c,n,r)),s(a,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{n=e},processMessage:(e,s,i,o)=>{if(!o)return!1;const c=o;if(t[c.messageId]){const e=t[c.messageId];return e&&(clearTimeout(e.timer),e.fulfilled||(e.fulfilled=!0,"response"===c.type?e.resolve(c.args):"error"===c.type&&e.reject(c.args[0])),delete t[c.messageId]),!0}if("execute"!==c.type&&n&&n(`No pending execution found for message id "${c.messageId}"`),"execute"===c.type){const t=r[c.functionName];if(t){const n=e=>{a(c.functionName,c.messageId,i.targetServiceId,i.sourceServiceId,s,e)};t({transport:e,args:c.args,reply:n,messageId:c.messageId,sourceServiceId:i.sourceServiceId,send:s})}else{const e=`Function "${c.functionName}" not found.`;n&&n(e),a(c.functionName,c.messageId,i.targetServiceId,i.sourceServiceId,s,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(e,r,i,a,c,l)=>{if(!i){const e="No send buffer function provided.";throw n&&n(e),e}oo+=1;const u=`${s}-${oo}-exec-${e.substring(0,10)}`,d={messageId:u,functionName:e,send:i,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};d.promise=new Promise(((e,t)=>{d.resolve=e,d.reject=t}));let p=Ui?new ArrayBuffer(0):Buffer.alloc(0);const h={json:{functionName:e,args:r,messageId:u,type:"execute"}};o(c)&&(p=io.encode(h,a,c)),t[u]=d,n&&n(`Calling remote function "${e}" with message id "${u}"`);const f="true"===process.env.NO_INVOKE_TIMEOUT;return l?.async?(d.fulfilled=!0,d.resolve([void 0]),delete t[u]):0===l?.timeout||f||(d.timer=setTimeout((()=>{n&&n(`Remote function ${u} timed out`);const r=t[u];r&&!r.fulfilled&&(r.fulfilled=!0,d.reject(`Function ${e} Timed out`)),delete t[u]}),l?.timeout||3e4)),i(p,{sourceServiceId:a,targetServiceId:c,msg:h}),d.promise},sendResponse:a,registerFunction:(e,t)=>{r[e]=t},getTransportSendFunction:e=>{const n=t[e];return n?n.send:null},setServiceName:e=>{s=e},getPendingExecutions:()=>t,rejectAllPending:e=>{Object.keys(t).forEach((n=>{const r=t[n];r&&!r.fulfilled&&(clearTimeout(r.timer),r.fulfilled=!0,r.reject(e),delete t[n])}))},broadcast:(e,t,r,i)=>{oo+=1;const a=`${s}-${oo}-multicast-${e.substring(0,10)}`;let c=Ui?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:t,messageId:a,type:"execute"}};let u=o(r[0].serviceId);u&&(c=io.encode(l,i,r[0].serviceId));for(let t=0;t<r.length;t++)try{const s=r[t];n&&n(`Broadcasting function "${e}" with message id "${a}" to client [${s.serviceId}]`),0!==t&&(u=o(s.serviceId),u&&(c=io.patchEncodedHeader(c,{toServiceId:s.serviceId}))),s.sendFn(c,{msg:l,sourceServiceId:i,targetServiceId:s.serviceId})}catch(e){n&&n(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{i[e]=t}}}("kweb");$o.setLogger(_o);const Co=new a,ko=new a;let Eo,xo=null,Ao=null,No=null;const Oo={},Po=()=>{if(!No)throw new Error("API key is required to interact with the hub");return No},Lo=(e,t,n)=>{const r=`${e}_${t}`,s={contents:n,lastRequestedAt:Date.now(),contentsChecksum:""};return Oo[r]=s,s},To=(e,t)=>Oo[`${e}_${t}`]||null,Bo=async(e,t)=>{if(!xo)return Io("Hub Link has not been acknowledged. Cannot get services."),null;const n=[{serviceName:e,version:t}];return(await $o.execute(ge.GetServiceContents,n,Do,xo,0))[0]},jo=async(e,t,n=!1)=>{if(!e||!t)return null;const r=To(e,t);if(!r||n){const n=r||Lo(e,t);try{const r=await Bo(e,t);return r&&(n.contents=r.uiContent,n.contentsChecksum=r.uiContentsChecksum||""),n.contents||null}catch(n){Io(`Failed to fetch service contents for ${e} v${t}`,n)}}return r?.contents||null},Do=go,Uo=()=>{Io("Disconnected from the server"),xo=null,$o.rejectAllPending("Disconnected from the server"),Co.emit("disconnected")},Mo=()=>{Io("Connected to the server"),Co.emit("connected")},Fo=()=>Ao,Ro=(e,t,n,r)=>`${e}_${t}_${n}_${r}`,Wo=async()=>{const e=Fo();if(e){const t=ee(e)?.blocks;if(t){const n={};for(const r in t){const s=t[r];for(const t in s.gates){const r=s.gates[t];if(r.type===Me.hubService){const t=r.state;if(t.service?.eventEmitter){const r=`${t.service.name}_${t.service.version}`;if(!n[r])try{Io(`Re-issuing subscription for service ${t.service.name} (${t.service.version})`),n[r]=!0,await ra({listener:{recipeId:e},targetService:{serviceName:t.service.name,version:t.service.version}})}catch(e){Io(`Failed to re-issue subscription for service ${t.service.name} (${t.service.version})`,e)}}}}}}}},Go=async e=>{if(!e)return void Io("Hub sent ACK request without service id");const t={apiKey:Po(),ackSessionId:e};await $o.execute(ge.SocketAckResponse,[t],Do,e,0),Io("Hub Link acknowledged"),xo=e,Co.emit("acknowledged"),Wo()},Vo=async e=>{const t=e.args[0],n=Ro("broadcast",`hub_${t.type}`,(0).toString(),"");await ko.emit(n,t)},Ho=async e=>{const t=e.args[0];for(const e of t.outputs||[])e.type===de.ImageData&&Ne(e.value)&&(e.value=De(e.value));const n=Fo();if(n){const r=ee(n);if(r){const s=async e=>{const n=Ro("broadcast",t.source.serviceName,t.source.serviceVersion,e);try{await ko.emit(n,t)}catch(t){Io(`Failed to emit broadcast event for target ${e}`,t)}};await s("app");for(const i in r.blocks){const o=r.blocks[i];for(const r in o.gates){const i=o.gates[r];if(i.disabled)continue;const a=i.state;if(i.type===Me.hubService&&a.service?.name===t.source.serviceName&&a.service?.version===t.source.serviceVersion&&a.variantId===t.variantId){await s(r);for(const s of t.outputs||[])if(null!==s.value&&void 0!==s.value){const t={type:s.type,value:s.value,timestamp:Date.now()};Io(`Sending data to output ${s.name} requested by messageId ${e.messageId}`),await Bi(n,r,s.name,t,t)}}}}}}},zo=async e=>{const t=e.args[0],{finalState:n,recipeId:r,widgetId:s}=t,i=Ti(r,s);let o=i;if(n&&o&&i&&(o={...i,customState:n},Li(r,s,o,!0)),o?.service)try{const e=Ro("setOutputs",o.service.name,o.service.version,s);await ko.emit(e,t.outputs)}catch(e){Io(`Failed to emit setOutputs event for widget ${s}`,e)}for(const n of t.outputs)if(null!==n.value&&void 0!==n.value){if(n.type===de.ImageData){if(!Ne(n.value)){Io(`Invalid ImageData value received for output ${n.name}. Expected an ImageData-like object`);continue}n.value=De(n.value)}else n.type===de.JsonObj&&So(n.value);const t={type:n.type,value:n.value,timestamp:Date.now()};Io(`Sending data to output ${n.name} requested by messageId ${e.messageId}`),await Bi(r,s,n.name,t,t)}e.reply({success:[]})},qo=async e=>{const t=e.args[0],{newState:n,recipeId:r,widgetId:s}=t,i=Ti(r,s);if(i){const t={...i,customState:{...i.customState,...n}};return Li(r,s,t,!0),e.reply({success:[]})}},Ko=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:s,path:i,key:o}=n;Io(`Received request to set a dependency path for "${o}" on widget "${s}" in recipe "${r}"`);const a=Ti(r,s);if(a){const e={...a};e.dependencies=e.dependencies||{},e.dependencies[o]={path:i},Li(r,s,e,!0)}return t({success:[]})},Jo=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:s,key:i}=n;Io(`Received request to get a dependency path for "${i}" on widget "${s}" in recipe "${r}"`);const o=Ti(r,s);if(o){const e=o.dependencies?.[i]?.path;return Io(`Returning dependency path for "${i}" on widget "${s}": "${e}"`),t({success:[e||null]})}return t({error:"Widget not found",errCode:"WIDGET_NOT_FOUND"})},Yo=async()=>{if(Io(`Requesting services on ${(new Date).toISOString()}`),!xo)return Io("Hub Link has not been acknowledged. Cannot get services."),{available:[],installed:[],failed:[]};const[e]=await $o.execute(ge.GetServices,[],Do,xo,0);Eo=e;for(const t of e.available){if(t.internal)continue;const e=To(t.name,t.version);if(!e||e?.contentsChecksum!==t.uiContentChecksum)try{const n=e||Lo(t.name,t.version);Io(`Service ${t.name} v${t.version} contents have changed, fetching new contents`);const r=await Bo(t.name,t.version);r&&(n.contents=r.uiContent,n.contentsChecksum=t.uiContentChecksum||"")}catch(e){Io(`Failed to update service contents for ${t.name} v${t.version}`,e)}}return e},Xo=()=>Eo||{available:[],installed:[],failed:[]},Zo=()=>!!Eo,Qo=async e=>{const{targetServiceSessionId:t}=e;if(!xo)return void Io("No target service session id provided");Io(`Forwarding "onParentEvent" to service ${t}`);return await $o.execute(ge.OnParentEvent,[e],Do,xo,t,e.config)},ea=async e=>{if(!xo)return Io("Hub Link has not been acknowledged. Cannot get services."),{};const[t]=await $o.execute(ge.GetDefaultState,[],Do,xo,e);return t},ta=async(e,t,n,r)=>{if(!xo)return Io("Hub Link has not been acknowledged. Cannot get services."),null;const[s]=await $o.execute(ge.UIEvent,[t,n],Do,xo,e,r);return s},na=(e,t)=>{const n=()=>{t()};return Co.on(e,n),()=>Co.off(e,n)},ra=async e=>{if(xo)return $o.execute(ge.SubscribeToService,[e],Do,xo,0);Io("Hub Link has not been acknowledged. Cannot subscribe to services.")},sa=async e=>{if(xo)return $o.execute(ge.UnsubscribeFromService,[e],Do,xo,0);Io("Hub Link has not been acknowledged. Cannot subscribe to services.")},ia=(e,t,n,r)=>{const s=Ro("broadcast",t,n,e);return ko.on(s,r)},oa=(e,t,n,r)=>{const s=Ro("setOutputs",t,n,e);return ko.on(s,r)},aa=async(e,t,n)=>xo?$o.execute(e,t,Do,xo,0,n):(Io("Hub Link has not been acknowledged. Cannot execute function."),null),ca=async e=>{if(!xo)return void Io("Hub Link has not been acknowledged. Cannot execute function.");const t=Ti(e.recipeId,e.widgetId);if(!t)throw new Error("Widget or recipe pool not found. Cannot initialize service instance.");const n=Object.keys(t.dependencies||{}).reduce(((e,n)=>(e[n]=t.dependencies?.[n]?.path||null,e)),{}),r=[{currentState:t.customState,recipeId:e.recipeId,widgetId:e.widgetId,variantId:e.variantId,recipeType:e.recipeType,currentDependencies:n}],[s]=await $o.execute(ge.InitializeInstance,r,Do,xo,e.sessionId);if(s){const t=Ti(e.recipeId,e.widgetId);if(t){const n={...t,customState:s};Li(e.recipeId,e.widgetId,n,!0)}}},la=async(e,t,n,r)=>{if(!xo)return void Io("Hub Link has not been acknowledged. Cannot execute function.");const s=Ti(n,t);if(!s)throw new Error("Widget or recipe pool not found. Cannot initialize service instance.");const i=[{currentState:s.customState,recipeId:n,widgetId:t,variantId:r}];await $o.execute(ge.TerminateInstance,i,Do,xo,e)},ua=async(e,t,n="^",r)=>{const s=["^","~",">=",">","<=","<","="];if(!s.includes(n))throw new Error(`Invalid compare mode "${n}". Must be one of ${s.join(", ")}`);const i=Zo(),o=r||!i?await Yo():Xo();for(const r of o.available)if(r.name===e){if(r.version===t)return r;if(h(r.version,`${n}${t}`))return r}return null};var da,pa,ha,fa,ga,ma,va,ya,ba=async e=>{yo(Mo),bo(Uo),No=e,vo((({json:e,transmission:t})=>{$o.processMessage("websocket",Do,t,e)})),$o.registerFunction(ge.SetState,qo),$o.registerFunction(ge.SetOutputs,zo),$o.registerFunction(ge.BroadcastEvent,Ho),$o.registerFunction(ge.HubBroadcastEvent,Vo),$o.registerFunction(me.SetDependencyPath,Ko),$o.registerFunction(me.GetDependencyPath,Jo),mo((e=>{((e,t)=>{const n=fe.SocketAcknowledge,r=fe.IpcAcknowledge,s=e.startsWith(n);if(e===r)return t&&t(),0;if(s){const i=e.split(s?n:r),o=parseInt(i[1]);return t&&t(o),o}})(e,Go),((e,t)=>{e===fe.ServicesListChanged&&(t&&t())})(e,(()=>{Io("Services list changed"),Co.emit("services-changed")}))})),await fo()},Sa=(e,t)=>{Co.on(e,t)},wa=()=>({getServices:Yo,getServiceContents:jo,onParentEvent:Qo,onCommand:na,getDefaultState:ea,getCachedServices:Xo,areServicesCached:Zo,subscribeToServiceEvents:ra,unsubscribeFromServiceEvents:sa,callProcessorHandler:ta,onBroadcastEvent:ia,onSetOutputsEvent:oa,executeHubFunction:aa,initializeServiceInstance:ca,terminateServiceInstance:la,getCompatibleService:ua}),Ia=e=>{Ao=e},_a=()=>$o;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(da||(da={})),function(e){e[e.Number=0]="Number",e[e.String=1]="String",e[e.ArrayBuffer=2]="ArrayBuffer",e[e.Array=3]="Array",e[e.Boolean=4]="Boolean",e[e.JsonObj=5]="JsonObj",e[e.Anything=6]="Anything",e[e.ImageData=7]="ImageData",e[e.AudioBuffer=8]="AudioBuffer",e[e.Rect=9]="Rect",e[e.Point=10]="Point",e[e.ImageBitmap=11]="ImageBitmap",e[e.BinaryFile=12]="BinaryFile"}(pa||(pa={})),function(e){e.Number="Number",e.String="String",e.ArrayBuffer="ArrayBuffer",e.Array="Array",e.Boolean="Boolean",e.JsonObj="JsonObj",e.Anything="Anything",e.ImageData="ImageData",e.AudioBuffer="AudioBuffer",e.Rect="Rect",e.Point="Point",e.ImageBitmap="ImageBitmap",e.BinaryFile="BinaryFile"}(ha||(ha={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(fa||(fa={})),function(e){e.IpcAcknowledge="iack:",e.SocketAcknowledge="sack:",e.AcknowledgeResponse="ackr:",e.ServicesListChanged="update-services",e.SendManifest="send-manifest",e.BroadcastStart="broadcast-start",e.BroadcastEnd="broadcast-end",e.AssumeSession="assume:"}(ga||(ga={})),function(e){e.GetServices="getServices",e.SubscribeToService="subscribeToService",e.UnsubscribeFromService="unsubscribeFromService",e.GetServiceContents="getServiceContents",e.SocketAckResponse="socketAckResponse",e.ShowSecretsConfigScreen="showSecretsConfigScreen",e.GetMappedSecrets="getMappedSecrets",e.GetSecretContexts="getSecretContexts",e.OnParentEvent="onParentEvent",e.GetDefaultState="getDefaultState",e.BroadcastEvent="broadcastEvent",e.HubBroadcastEvent="hubBroadcastEvent",e.ServiceManifest="serviceManifest",e.GetState="getState",e.SetState="setState",e.SetOutputs="setOutputs",e.UIEvent="uiEvent",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.GetUniqueId="getUniqueId"}(ma||(ma={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(va||(va={})),function(e){e.IPC="ipc",e.WS="ws"}(ya||(ya={}));const $a=e=>{try{return JSON.parse(e)}catch(e){return null}},Ca=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,ka=e=>{if("string"!=typeof e)throw new TypeError("Invalid argument expected string");const t=e.match(Ca);if(!t)throw new Error(`Invalid argument not valid semver ('${e}' received)`);return t.shift(),t},Ea=e=>"*"===e||"x"===e||"X"===e,xa=e=>{const t=parseInt(e,10);return isNaN(t)?e:t},Aa=(e,t)=>{if(Ea(e)||Ea(t))return 0;const[n,r]=((e,t)=>typeof e!=typeof t?[String(e),String(t)]:[e,t])(xa(e),xa(t));return n>r?1:n<r?-1:0},Na=(e,t)=>{for(let n=0;n<Math.max(e.length,t.length);n++){const r=Aa(e[n]||"0",t[n]||"0");if(0!==r)return r}return 0},Oa=(e,t,n)=>{Ta(n);const r=((e,t)=>{const n=ka(e),r=ka(t),s=n.pop(),i=r.pop(),o=Na(n,r);return 0!==o?o:s&&i?Na(s.split("."),i.split(".")):s||i?s?-1:1:0})(e,t);return Pa[n].includes(r)},Pa={">":[1],">=":[0,1],"=":[0],"<=":[-1,0],"<":[-1],"!=":[-1,1]},La=Object.keys(Pa),Ta=e=>{if(-1===La.indexOf(e))throw new Error(`Invalid operator, expected one of ${La.join("|")}`)};var Ba="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function ja(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Da,Ua,Ma,Fa,Ra,Wa={exports:{}},Ga={exports:{}};function Va(){if(Ua)return Da;Ua=1;var e=1e3,t=60*e,n=60*t,r=24*n,s=7*r,i=365.25*r;function o(e,t,n,r){var s=t>=1.5*n;return Math.round(e/n)+" "+r+(s?"s":"")}return Da=function(a,c){c=c||{};var l=typeof a;if("string"===l&&a.length>0)return function(o){if((o=String(o)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(o);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*i;case"weeks":case"week":case"w":return c*s;case"days":case"day":case"d":return c*r;case"hours":case"hour":case"hrs":case"hr":case"h":return c*n;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(a);if("number"===l&&isFinite(a))return c.long?function(s){var i=Math.abs(s);if(i>=r)return o(s,i,r,"day");if(i>=n)return o(s,i,n,"hour");if(i>=t)return o(s,i,t,"minute");if(i>=e)return o(s,i,e,"second");return s+" ms"}(a):function(s){var i=Math.abs(s);if(i>=r)return Math.round(s/r)+"d";if(i>=n)return Math.round(s/n)+"h";if(i>=t)return Math.round(s/t)+"m";if(i>=e)return Math.round(s/e)+"s";return s+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))}}function Ha(){if(Fa)return Ma;return Fa=1,Ma=function(e){function t(e){let r,s,i,o=null;function a(...e){if(!a.enabled)return;const n=a,s=Number(new Date),i=s-(r||s);n.diff=i,n.prev=r,n.curr=s,r=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((r,s)=>{if("%%"===r)return"%";o++;const i=t.formatters[s];if("function"==typeof i){const t=e[o];r=i.call(n,t),e.splice(o,1),o--}return r})),t.formatArgs.call(n,e);(n.log||t.log).apply(n,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=n,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(s!==t.namespaces&&(s=t.namespaces,i=t.enabled(e)),i),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function n(e,n){const r=t(this.namespace+(void 0===n?":":n)+e);return r.log=this.log,r}function r(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(r),...t.skips.map(r).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let n;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").split(/[\s,]+/),s=r.length;for(n=0;n<s;n++)r[n]&&("-"===(e=r[n].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let n,r;for(n=0,r=t.skips.length;n<r;n++)if(t.skips[n].test(e))return!1;for(n=0,r=t.names.length;n<r;n++)if(t.names[n].test(e))return!0;return!1},t.humanize=Va(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((n=>{t[n]=e[n]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t.colors[Math.abs(n)%t.colors.length]},t.enable(t.load()),t},Ma}var za,qa,Ka,Ja,Ya,Xa={exports:{}};function Za(){return qa||(qa=1,za=(e,t=process.argv)=>{const n=e.startsWith("-")?"":1===e.length?"-":"--",r=t.indexOf(n+e),s=t.indexOf("--");return-1!==r&&(-1===s||r<s)}),za}"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?Wa.exports=(Ra||(Ra=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;t.splice(1,0,n,"color: inherit");let r=0,s=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(s=r))})),t.splice(s,0,n)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=Ha()(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Ga,Ga.exports)),Ga.exports):Wa.exports=(Ya||(Ya=1,function(e,t){const n=k,r=o;t.init=function(e){e.inspectOpts={};const n=Object.keys(t.inspectOpts);for(let r=0;r<n.length;r++)e.inspectOpts[n[r]]=t.inspectOpts[n[r]]},t.log=function(...e){return process.stderr.write(r.formatWithOptions(t.inspectOpts,...e)+"\n")},t.formatArgs=function(n){const{namespace:r,useColors:s}=this;if(s){const t=this.color,s="[3"+(t<8?t:"8;5;"+t),i=` ${s};1m${r} [0m`;n[0]=i+n[0].split("\n").join("\n"+i),n.push(s+"m+"+e.exports.humanize(this.diff)+"[0m")}else n[0]=(t.inspectOpts.hideDate?"":(new Date).toISOString()+" ")+r+" "+n[0]},t.save=function(e){e?process.env.DEBUG=e:delete process.env.DEBUG},t.load=function(){return process.env.DEBUG},t.useColors=function(){return"colors"in t.inspectOpts?Boolean(t.inspectOpts.colors):n.isatty(process.stderr.fd)},t.destroy=r.deprecate((()=>{}),"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),t.colors=[6,2,3,4,5,1];try{const e=function(){if(Ja)return Ka;Ja=1;const e=E,t=k,n=Za(),{env:r}=process;let s;function i(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function o(t,i){if(0===s)return 0;if(n("color=16m")||n("color=full")||n("color=truecolor"))return 3;if(n("color=256"))return 2;if(t&&!i&&void 0===s)return 0;const o=s||0;if("dumb"===r.TERM)return o;if("win32"===process.platform){const t=e.release().split(".");return Number(t[0])>=10&&Number(t[2])>=10586?Number(t[2])>=14931?3:2:1}if("CI"in r)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((e=>e in r))||"codeship"===r.CI_NAME?1:o;if("TEAMCITY_VERSION"in r)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(r.TEAMCITY_VERSION)?1:0;if("truecolor"===r.COLORTERM)return 3;if("TERM_PROGRAM"in r){const e=parseInt((r.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(r.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(r.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(r.TERM)||"COLORTERM"in r?1:o}return n("no-color")||n("no-colors")||n("color=false")||n("color=never")?s=0:(n("color")||n("colors")||n("color=true")||n("color=always"))&&(s=1),"FORCE_COLOR"in r&&(s="true"===r.FORCE_COLOR?1:"false"===r.FORCE_COLOR?0:0===r.FORCE_COLOR.length?1:Math.min(parseInt(r.FORCE_COLOR,10),3)),Ka={supportsColor:function(e){return i(o(e,e&&e.isTTY))},stdout:i(o(!0,t.isatty(1))),stderr:i(o(!0,t.isatty(2)))}}();e&&(e.stderr||e).level>=2&&(t.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch(e){}t.inspectOpts=Object.keys(process.env).filter((e=>/^debug_/i.test(e))).reduce(((e,t)=>{const n=t.substring(6).toLowerCase().replace(/_([a-z])/g,((e,t)=>t.toUpperCase()));let r=process.env[t];return r=!!/^(yes|on|true|enabled)$/i.test(r)||!/^(no|off|false|disabled)$/i.test(r)&&("null"===r?null:Number(r)),e[n]=r,e}),{}),e.exports=Ha()(t);const{formatters:s}=e.exports;s.o=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts).split("\n").map((e=>e.trim())).join(" ")},s.O=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts)}}(Xa,Xa.exports)),Xa.exports);var Qa=ja(Wa.exports);const ec=e=>Qa(e),tc=Date.now();let nc=Math.ceil(tc/1e3);var rc=()=>nc+=1;const sc=m(x(),"kemu-user-services"),ic=m(x(),"kemu-test-services"),oc="KMU-CB-v1";var ac;!function(e){e.input="input",e.counter="counter",e.play="play",e.elapsed="elapsed",e.ifGate="ifGate",e.skipEvent="skipEvent",e.between="between",e.map="map",e.parser="parser",e.slider="slider",e.suspend="suspend",e.display="display",e.pixelfy="pixelfy",e.json="json",e.arrayItem="arrayItem",e.extractImage="extractImage",e.imageConvolution="imageConvolution",e.firstEvent="firstEvent",e.pixelDraw="pixelDraw",e.randomBetween="randomBetween",e.arrayCombine="arrayCombine",e.clock="clock",e.multiplication="multiplication",e.object="object",e.widgetGroup="widgetGroup",e.script="script",e.base64ToImageData="base64ToImageData",e.jsonParse="jsonParse",e.text="text",e.imageCrop="imageCrop",e.imageResize="imageResize",e.value="value",e.imageWarp="imageWarp",e.widgetBundle="widgetBundle",e.sequence="sequence",e.variable="variable",e.hubService="hubService"}(ac||(ac={}));const cc=e=>({...e,type:Array.isArray(e.type)?e.type.map((e=>pa[e])):pa[e.type]}),lc=async e=>{try{return await S(e,"utf-8")}catch(e){return null}},uc=e=>{if(e&&e.startsWith(oc)){const t=e.slice(9),n=decodeURI(t);return $a(n)}return null},dc=async(e,t,n)=>{let r=[];e.variants?.length&&(r=e.variants.map((e=>({...e,...e.inputs?{inputs:e.inputs.map(cc)}:{},...e.outputs?{outputs:e.outputs.map(cc)}:{}}))));const s={...e,path:t,customWidgets:[],...e.inputs?{inputs:e.inputs.map(cc)}:{inputs:[]},...e.outputs?{outputs:e.outputs.map(cc)}:{outputs:[]},variants:r,...e.widgetUI&&n?.widgetUIContents?{widgetUIContents:n.widgetUIContents}:{}},i=await(async(e,t,n=console.log)=>{const r=[];if(t.customWidgets?.length)for(const s of t.customWidgets){const t=await lc(m(e,s));if(!t){n(`Error loading custom widget file ${s}`);continue}const i=t.startsWith(oc)?t:`${oc}${t}`,o=uc(i);if(!o){n(`Custom widget file "${s}" is not a valid Kemu Clipboard item`);continue}const a=Object.values(o).filter((e=>e.type===ac.widgetGroup&&!e.groupId));if(a.length>1){n(`Custom widget file "${s}" contains more than one top level widgetGroup`);continue}const c=a[0];if(!c){n(`Custom widget file "${s}" does not contain a top level widgetGroup`);continue}const l=c.state,u={name:l.name,color:l.color,description:l.description,contents:i,rootGroupId:c.id,icon:l.icon,protocolVersion:l.protocolVersion||"2"};r.push(u)}return r})(t,e,n?.log);if(i.length?s.customWidgets=i:delete s.customWidgets,s.variants?.length)for(const e of s.variants)if(e.svgIcon)try{const n=await S(m(t,e.svgIcon),"utf-8");e.svgIcon=n}catch(t){n?.log&&n?.log(`Error loading svgIcon for variant ${e.id}: ${t}`)}return s},pc=async e=>{try{return await w(e,I.F_OK),!0}catch{return!1}};let hc=null,fc=null;const gc=()=>hc||sc,mc=ec("servicesManager"),vc={};let yc=null,bc=null,Sc=null;class wc extends Error{code;originalError;constructor(e,t,n){super(e),this.code=t,this.originalError=n,this.name="ServiceError"}}const Ic=async e=>{try{return await w(e),!0}catch{return!1}},_c=async e=>{if(!yc)throw new Error('IPC config not set, call "setHubIpcConfig" first.');try{if(e.processor===fa.Javascript){mc(`Spawning service ${e.name} with sessionId ${e.sessionId}`);const t=g.join(e.path,"processor.js"),n=g.join(e.path,"processor.mjs"),r=await Ic(t)?t:n,s=[`--sessionId=${e.sessionId.toString()}`,`--ipcSpace=${yc.appSpace}`,`--ipcId=${yc?.id}`,`--recipePath=${yc.recipePath||""}`];if(e.internal&&s.push("--internal=true"),!Sc)throw new Error('Get secrets function not set, call "setGetSecretsFunction" first.');const i=await Sc({name:e.name,version:e.version,requiredSecrets:e.requiredSecrets||{}}),o=Object.entries(e.requiredSecrets||{}).filter((([e,t])=>{const n=i[e];return null==n&&!t.optional})).map((([e])=>e));if(o?.length)throw new wc(`Missing required environment variables: ${o.join(", ")}`,"MISSING_REQUIRED_SECRETS");return new Promise(((t,n)=>{if(!bc)throw new Error('Spawn function not set, call "setSpawnNodeFunction" first.');const o=bc({args:[r,...s],options:{env:i}});o.stdout.on("data",(t=>{mc(`[${e.name}] - stdout: ${t}`)})),o.stderr.on("data",(t=>{mc(`[${e.name}] - stderr: ${t}`)})),o.on("exit",(t=>{mc(`[${e.name}] exited with code ${t}`)})),o.on("spawn",(()=>{mc(`[${e.name}] spawned with PID ${o.pid}`),t(o)})),o.on("error",(t=>{mc(`[${e.name}] error: ${t}`),n(new wc(`Error spawning service ${e.name}: ${t}`,"SPAWN_ERROR"))}))}))}throw`Unsupported processor type ${e.processor}`}catch(t){if(t instanceof wc)throw t;throw`Error spawning service ${e.name}: ${t}`}},$c=e=>{if(!e?.name)return"Missing name";if(!e?.version)return"Missing version";if(!e?.description)return"Missing description";if(!e?.processor)return"Missing processor";return[fa.Javascript,fa.Executable,fa.Python].includes(e?.processor)?null:"Invalid processor"},Cc=async(e,t)=>{const n=g.join(e,"manifest.json");if(!await Ic(n)){const t=`Missing manifest for service ${e}. Aborting.`;return mc(t),{error:t}}const r=await S(n,"utf-8"),s=$a(r),i=$c(s);if(!s||i){const t=`Invalid service manifest [${e}]: ${i}. Aborting.`;return mc(t),{error:t}}let o;if(delete s.internal,t?.singleServiceName&&s.name!==t.singleServiceName){return{error:`Skipping service ${s.name} as it does not match the singleServiceName option`}}await Promise.all([(async()=>{if(s.widgetUI)try{o=await S(g.join(e,"widgetUI.js"))}catch(e){const t=`Error loading widgetUI file ${s.name}: ${e}`;return mc(t),{error:t}}})(),(async()=>{if(s.svgIcon){const t=await lc(g.join(e,s.svgIcon));if(!t){return{error:`Error loading icon for service ${s.name}`}}s.svgIcon=t}})(),(async()=>{if(s.subServices?.length)for(const t of s.subServices){const n=g.join(e,t),{error:r,service:i}=await Cc(n);r?mc(`Error loading sub-service ${t}: ${r}`):i&&(i.info.parentService={name:s.name,version:s.version})}delete s.subServices})(),(async()=>{if(s.variants?.length)for(const t of s.variants)if(t.svgIcon)try{const n=await S(g.join(e,t.svgIcon),"utf-8");t.svgIcon=n}catch(e){mc(`Error loading svgIcon for variant ${t.id}: ${e}`)}})()]);const a=rc(),c=t?.fixedSession||a;mc(`Loaded service ${s.name} with sessionId ${c}`);const l=await dc(s,e,{widgetUIContents:o});return kc(l),vc[c]={info:{...l,path:e,sessionId:c},status:"loaded",childProcess:null},{service:vc[c]}},kc=e=>{e.widgetUIContents?e.uiContentChecksum=(e=>{const t=p("sha256");return t.update(e),t.digest("hex")})(e.widgetUIContents):e.uiContentChecksum=void 0},Ec=async e=>{try{return e.childProcess=await _c(e.info),e.status="started",e.errorMsg=void 0,e.errorCode=void 0,!0}catch(t){return mc(`Service [${e.info.name}] error: ${t}`),e.status="error",t instanceof wc?(e.errorMsg=t.message,e.errorCode=t.code):(e.errorMsg="string"==typeof t?t:JSON.stringify(t),e.errorCode="UNKNOWN_ERROR"),!1}},xc=e=>{const{path:t,...n}=e.info;return{...n}},Ac=()=>Object.values(vc).filter((e=>"running"===e.status)).map(xc),Nc=(e,t)=>{const n=Object.values(vc).find((n=>n.info.name===e&&n.info.version===t));if(!n)return null;if(n.info.internal)throw`Cannot stop internal service ${e}`;if(n.childProcess){mc(`Stopping service "${e} (v${t})"`);n.childProcess.kill("SIGINT")||mc(`Failed to stop service ${e}`)}return n.status="stopped",mc(`Service ${e} stopped`),n},Oc=e=>e.info.internal?e.info.path:g.join(e.info.path,".."),Pc=e=>!!e.internal;var Lc={isOfficialKemuService:e=>e.name.startsWith("kemu.io"),loadServices:async(e,t)=>{if(!await pc(e))return void mc(`Failed to load services from "${e}". Directory does not exist.`);const n=(await _(e,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name));mc(`Found ${n.length} services in "${e}"`);for(let r=0;r<n.length;r++){const s=n[r],i=g.join(e,s),{error:o,service:a}=await Cc(`${i}${t?.internalServices?"":"/dist"}`,t);o&&mc(`Failed to load service ${i}. Please check logs`),a&&t?.internalServices&&(a.info.internal=!0)}},launchServices:async e=>{if(mc("Initializing services"),!yc)throw new Error('IPC config not set, call "setHubIpcConfig" first.');for(const t in vc){const n=vc[t];e.noSpawningList&&e.noSpawningList.includes(n.info.name)?mc(`Service ${n.info.name} is in the noSpawningList. Skipping.`):Ec(n)}mc("Services initialized")},setServiceStatus:(e,t)=>{const n=vc[e];return n?(n.status=t,!0):(mc(`Service with serviceId ${e} not found`),!1)},getActiveServices:Ac,getMatchingService:(e,t)=>{const n=Object.values(vc).filter((e=>"running"===e.status));for(const r of n)if(r.info.name===e){if(r.info.version===t)return r;if(Oa(r.info.version,t,">="))return r}return null},getServiceBySessionId:e=>vc[e]||null,killAllServices:()=>{for(const e in vc){const t=vc[e];if(t.childProcess)try{mc(`Killing service ${t.info.name} with PID ${t.childProcess.pid}`),t.childProcess.kill()}catch(e){mc(`Error killing service ${t.info.name}: ${e}`)}}},addDevService:async(e,t,n)=>{const r={info:{...await dc(t,t.path),sessionId:e},status:n,startedAt:new Date,devMode:!0,childProcess:null};vc[e]=r,kc(vc[e].info)},setServiceManifest:(e,t,n)=>{const r=vc[e];if(!r)return mc(`Service with sessionId ${e} not found`),!1;const s=$c(t);if(s)return mc(`Invalid manifest for service ${r.info.name}: ${s}`),!1;kc(t),r.info={...r.info,...t},n&&(r.status=n)},getMatchingDevService:(e,t,n)=>{const r=Object.values(vc).filter((e=>e.devMode));for(const s of r)if(s.info.name===e&&s.status===n&&s.info.version===t)return s;return null},getInternalServices:()=>Ac().filter((e=>e.internal)),getAllServices:()=>Object.values(vc),stopService:Nc,uninstallService:async(e,t)=>{mc(`Uninstalling service ${e} v${t}`);const n=Nc(e,t);if(!n)return!1;mc(`Service ${e} stopped. Removing from disk...`);const r=Oc(n),s=gc();return r.startsWith(s)?(await $(r,{recursive:!0,force:!0}),mc(`Service ${e} successfully removed from disk`),(e=>{const t=vc[e];delete vc[e]})(n.info.sessionId),!0):(mc(`Service ${e} is not installed in the user services directory. Aborting.`),!1)},getAllServiceVersions:e=>Object.values(vc).filter((t=>t.info.name===e)),setHubIpcConfig:e=>{yc={...e}},loadAndLaunch:async(e,t,n)=>{const r=y(e,t),{error:s,service:i}=await Cc(r);if(s||!i)return{errorMsg:s};try{i.info.internal=!!n,i.childProcess=await _c(i.info),i.status="started"}catch(e){i.status="error",e instanceof wc?(mc(`Service spawning error: ${e.message} (${e.code})`),i.errorMsg=e.message,i.errorCode=e.code):(mc(`Error launching service ${i.info.name}: ${e}`),i.errorMsg="string"==typeof e?e:JSON.stringify(e))}return{service:i,errorCode:i.errorCode,errorMsg:i.errorMsg}},getServiceRootDirectory:Oc,setSpawnNodeFunction:e=>{bc=e},setGetSecretsFunction:e=>{Sc=e},restartService:async(e,t)=>{mc(`Restarting service ${e} v${t}`);const n=Nc(e,t);return!!n&&Ec(n)},getFailedServices:()=>Object.values(vc).filter((e=>"error"===e.status)).map((e=>({...xc(e),errorMsg:e.errorMsg||"",errorCode:e.errorCode,status:e.status}))),isInternalKemuService:Pc,isNotInternalKemuService:e=>!Pc(e),isNotDevService:e=>!e.devMode};class Tc{constructor(){}appspace="app.";socketRoot="/tmp/";id=E.hostname();encoding="utf8";rawBuffer=!1;sync=!1;unlink=!0;delimiter="\f";silent=!1;logDepth=5;logInColor=!0;logger=console.log.bind(console);maxConnections=100;retry=500;maxRetries=1/0;stopRetrying=!1;IPType=function(){const e=E.networkInterfaces();let t="";e&&Array.isArray(e)&&e.length>0&&(t=e[Object.keys(e)[0]][0].family);return t}();tls=!1;networkHost="IPv6"==this.IPType?"::1":"127.0.0.1";networkPort=8e3;readableAll=!1;writableAll=!1;interface={localAddress:!1,localPort:!1,family:!1,hints:!1,lookup:!1}}class Bc{constructor(e){e||(e=new Tc),this.delimiter=e.delimiter}format(e){return e.data||!1===e.data||0===e.data||(e.data={}),e.data._maxListeners&&(e.data={}),e=e.JSON+this.delimiter}parse(e){let t=e.split(this.delimiter);return t.pop(),t}}var jc=function(){Object.defineProperties(this,{data:{enumerable:!0,get:function(){return t},set:function(e){t=e}},type:{enumerable:!0,get:function(){return e},set:function(t){e=t}},load:{enumerable:!0,writable:!1,value:function(n){try{n=JSON.parse(n);e=n.type,t=n.data}catch(r){e="error",t={message:"Invalid JSON response format",err:r,response:n}}}},JSON:{enumerable:!0,get:function(){return JSON.stringify({type:e,data:t})}}});var e="",t={}},Dc=ja(jc);var Uc=ja((function(){Object.defineProperties(this,{add:{enumerable:!0,writable:!1,value:function(){for(var n in arguments)e.push(arguments[n]);t||this.stop||!this.autoRun||this.next()}},next:{enumerable:!0,writable:!1,value:function(){if(t=!0,e.length<1||this.stop)return void(t=!1);e.shift().bind(this)()}},clear:{enumerable:!0,writable:!1,value:function(){return e=[]}},contents:{enumerable:!1,get:function(){return e},set:function(t){return e=t}},autoRun:{enumerable:!0,writable:!0,value:!0},stop:{enumerable:!0,writable:!0,value:!1}});var e=[],t=!1}));class Mc{}class Fc{}const Rc=new class{constructor(e=!0){this.strict=e}throw(e,t){let n=new TypeError;if(n.message=`expected type of ${e} to be ${t}`,!this.strict)return!1;throw n}typeCheck(e,t){return typeof e===t||this.throw(typeof e,t)}instanceCheck(e=new Mc,t=Fc){return e instanceof t||this.throw(typeof e,t.name)}symbolStringCheck(e,t){return Object.prototype.toString.call(e)==`[object ${t}]`||this.throw(Object.prototype.toString.call(e),`[object ${t}]`)}compare(e,t,n){return e==t||this.throw(typeof e,n)}finite(e){return!!isFinite(e)||this.throw(typeof e,"finite")}NaN(e){return this.number(e)?!!isNaN(e)||this.throw(typeof e,"NaN"):this.number(e)}null(e){return this.compare(e,null,"null")}array(e){return this.instanceCheck(e,Array)}boolean(e){return this.typeCheck(e,"boolean")}bigint(e){return this.typeCheck(e,"bigint")}date(e){return this.instanceCheck(e,Date)}generator(e){return this.symbolStringCheck(e,"Generator")}asyncGenerator(e){return this.symbolStringCheck(e,"AsyncGenerator")}globalThis(e){return this.compare(e,globalThis,"explicitly globalThis, not window, global nor self")}infinity(e){return this.compare(e,1/0,"Infinity")}map(e){return this.instanceCheck(e,Map)}weakMap(e){return this.instanceCheck(e,WeakMap)}number(e){return this.typeCheck(e,"number")}object(e){return this.typeCheck(e,"object")}promise(e){return this.instanceCheck(e,Promise)}regExp(e){return this.instanceCheck(e,RegExp)}undefined(e){return this.typeCheck(e,"undefined")}set(e){return this.instanceCheck(e,Set)}weakSet(e){return this.instanceCheck(e,WeakSet)}string(e){return this.typeCheck(e,"string")}symbol(e){return this.typeCheck(e,"symbol")}function(e){return this.typeCheck(e,"function")}asyncFunction(e){return this.symbolStringCheck(e,"AsyncFunction")}generatorFunction(e){return this.symbolStringCheck(e,"GeneratorFunction")}asyncGeneratorFunction(e){return this.symbolStringCheck(e,"AsyncGeneratorFunction")}error(e){return this.instanceCheck(e,Error)}evalError(e){return this.instanceCheck(e,EvalError)}rangeError(e){return this.instanceCheck(e,RangeError)}referenceError(e){return this.instanceCheck(e,ReferenceError)}syntaxError(e){return this.instanceCheck(e,SyntaxError)}typeError(e){return this.instanceCheck(e,TypeError)}URIError(e){return this.instanceCheck(e,URIError)}bigInt64Array(e){return this.instanceCheck(e,BigInt64Array)}bigUint64Array(e){return this.instanceCheck(e,BigUint64Array)}float32Array(e){return this.instanceCheck(e,Float32Array)}float64Array(e){return this.instanceCheck(e,Float64Array)}int8Array(e){return this.instanceCheck(e,Int8Array)}int16Array(e){return this.instanceCheck(e,Int16Array)}int32Array(e){return this.instanceCheck(e,Int32Array)}uint8Array(e){return this.instanceCheck(e,Uint8Array)}uint8ClampedArray(e){return this.instanceCheck(e,Uint8ClampedArray)}uint16Array(e){return this.instanceCheck(e,Uint16Array)}uint32Array(e){return this.instanceCheck(e,Uint32Array)}arrayBuffer(e){return this.instanceCheck(e,ArrayBuffer)}dataView(e){return this.instanceCheck(e,DataView)}sharedArrayBuffer(e){return this.instanceCheck(e,function(){try{return SharedArrayBuffer}catch{return Mc}}())}intlDateTimeFormat(e){return this.instanceCheck(e,Intl.DateTimeFormat)}intlCollator(e){return this.instanceCheck(e,Intl.Collator)}intlDisplayNames(e){return this.instanceCheck(e,Intl.DisplayNames)}intlListFormat(e){return this.instanceCheck(e,Intl.ListFormat)}intlLocale(e){return this.instanceCheck(e,Intl.Locale)}intlNumberFormat(e){return this.instanceCheck(e,Intl.NumberFormat)}intlPluralRules(e){return this.instanceCheck(e,Intl.PluralRules)}intlRelativeTimeFormat(e){return this.instanceCheck(e,Intl.RelativeTimeFormat)}intlRelativeTimeFormat(e){return this.instanceCheck(e,Intl.RelativeTimeFormat)}finalizationRegistry(e){return this.instanceCheck(e,FinalizationRegistry)}weakRef(e){return this.instanceCheck(e,WeakRef)}};class Wc{constructor(){}on(e,t,n=!1){return Rc.string(e),Rc.function(t),Rc.boolean(n),"*"==e&&(e=this.#e),this.#t[e]||(this.#t[e]=[]),t[this.#n]=n,this.#t[e].push(t),this}once(e,t){return this.on(e,t,!0)}off(e="*",t="*"){if(Rc.string(e),e!=this.#e.toString()&&"*"!=e||(e=this.#e),!this.#t[e])return this;if("*"==t)return delete this.#t[e],this;Rc.function(t);const n=this.#t[e];for(;n.includes(t);)n.splice(n.indexOf(t),1);return n.length<1&&delete this.#t[e],this}emit(e,...t){Rc.string(e);const n=this.#t[this.#e]||[];if(this.#r(this.#e.toString(),n,e,...t),!this.#t[e])return this;const r=this.#t[e];return this.#r(e,r,...t),this}reset(){this.off(this.#e.toString());for(let e in this.#t)this.off(e);return this}get list(){return Object.assign({},this.#t)}#r=(e,t,...n)=>{Rc.string(e),Rc.array(t);const r=[];for(let e of t)e(...n),e[this.#n]&&r.push(e);for(let t of r)this.off(e,t)};#e=Symbol.for("event-pubsub-all");#n=Symbol.for("event-pubsub-once");#t={}}let Gc=new Bc;class Vc extends Wc{constructor(e,t){super(),this.config=e,this.log=t,this.publish=super.emit,e.maxRetries&&(this.retriesRemaining=e.maxRetries),Gc=new Bc(this.config)}Client=Vc;queue=new Uc;socket=!1;connect=qc;emit=Hc;retriesRemaining=0;explicitlyDisconnected=!1}function Hc(e,t){this.log("dispatching event to ",this.id,this.path," : ",e,",",t);let n=new Dc;n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Gc.format(n),this.config.sync?this.queue.add(zc.bind(this,n)):this.socket.write(n)}function zc(e){this.log("dispatching event to ",this.id,this.path," : ",e),this.socket.write(e)}function qc(){let e=this;if(e.log("requested connection to ",e.id,e.path),!this.path)return void e.log("\n\n######\nerror: ",e.id," client has not specified socket path it wishes to connect to.");const t={};if(e.port)if(t.host=e.path,t.port=e.port,e.config.interface.localAddress&&(t.localAddress=e.config.interface.localAddress),e.config.interface.localPort&&(t.localPort=e.config.interface.localPort),e.config.interface.family&&(t.family=e.config.interface.family),e.config.interface.hints&&(t.hints=e.config.interface.hints),e.config.interface.lookup&&(t.lookup=e.config.interface.lookup),e.config.tls){if(e.log("Connecting client via TLS to",e.path,e.port,e.config.tls),e.config.tls.private&&(e.config.tls.key=O.readFileSync(e.config.tls.private)),e.config.tls.public&&(e.config.tls.cert=O.readFileSync(e.config.tls.public)),e.config.tls.trustedConnections){"string"==typeof e.config.tls.trustedConnections&&(e.config.tls.trustedConnections=[e.config.tls.trustedConnections]),e.config.tls.ca=[];for(let t=0;t<e.config.tls.trustedConnections.length;t++)e.config.tls.ca.push(O.readFileSync(e.config.tls.trustedConnections[t]))}Object.assign(e.config.tls,t),e.socket=N.connect(e.config.tls)}else e.log("Connecting client via TCP to",t),e.socket=A.connect(t);else e.log("Connecting client on Unix Socket :",e.path),t.path=e.path,"win32"!==process.platform||e.path.startsWith("\\\\.\\pipe\\")||(t.path=t.path.replace(/^\//,""),t.path=t.path.replace(/\//g,"-"),t.path=`\\\\.\\pipe\\${t.path}`),e.socket=A.connect(t);e.socket.setEncoding(this.config.encoding),e.socket.on("error",(function(t){e.log("\n\n######\nerror: ",t),e.publish("error",t)})),e.socket.on("connect",(function(){e.publish("connect"),e.retriesRemaining=e.config.maxRetries,e.log("retrying reset")})),e.socket.on("close",(function(){if(e.log("connection closed",e.id,e.path,e.retriesRemaining,"tries remaining of",e.config.maxRetries),e.config.stopRetrying||e.retriesRemaining<1||e.explicitlyDisconnected)return e.publish("disconnect"),e.log(e.config.id,"exceeded connection rety amount of"," or stopRetrying flag set."),e.socket.destroy(),e.publish("destroy"),void(e=void 0);setTimeout(function(){e.explicitlyDisconnected||(e.retriesRemaining--,e.connect())}.bind(null,e),e.config.retry),e.publish("disconnect")})),e.socket.on("data",(function(t){if(e.log("## received events ##"),e.config.rawBuffer){if(e.publish("data",Buffer.from(t,e.config.encoding)),!e.config.sync)return;return void e.queue.next()}if(this.ipcBuffer||(this.ipcBuffer=""),(t=this.ipcBuffer+=t).slice(-1)!=Gc.delimiter||-1==t.indexOf(Gc.delimiter))return void e.log("Messages are large, You may want to consider smaller messages.");this.ipcBuffer="";const n=Gc.parse(t),r=n.length;for(let t=0;t<r;t++){let r=new Dc;r.load(n[t]),e.log("detected event",r.type,r.data),e.publish(r.type,r.data)}e.config.sync&&e.queue.next()}))}let Kc=new Bc;class Jc extends Wc{constructor(e,t,n,r){super(),this.config=t,this.path=e,this.port=r,this.log=n,this.publish=super.emit,Kc=new Bc(this.config),this.on("close",Zc.bind(this))}udp4=!1;udp6=!1;server=!1;sockets=[];emit=Yc;broadcast=Xc;onStart(e){this.publish("start",e)}stop(){this.server.close()}start(){this.path?this.config.unlink?O.unlink(this.path,nl.bind(this)):nl.bind(this)():this.log("Socket Server Path not specified, refusing to start")}}function Yc(e,t,n){this.log("dispatching event to socket"," : ",t,n);let r=new Dc;if(r.type=t,r.data=n,this.config.rawBuffer?(this.log(this.config.encoding),r=Buffer.from(t,this.config.encoding)):r=Kc.format(r),this.udp4||this.udp6)return e.address&&e.port?void this.server.write(r,e):(this.log("Attempting to emit to a single UDP socket without supplying socket address or port. Redispatching event as broadcast to all connected sockets"),void this.broadcast(t,n));e.write(r)}function Xc(e,t){this.log("broadcasting event to all known sockets listening to ",this.path," : ",this.port?this.port:"",e,t);let n=new Dc;if(n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Kc.format(n),this.udp4||this.udp6)for(let e=1,t=this.sockets.length;e<t;e++)this.server.write(n,this.sockets[e]);else for(let e=0,t=this.sockets.length;e<t;e++)this.sockets[e].write(n)}function Zc(){for(let e=0,t=this.sockets.length;e<t;e++){let t=this.sockets[e],n=!1;if(!t||!t.readable)return t.id&&(n=t.id),this.log("socket disconnected",n.toString()),t&&t.destroy&&t.destroy(),this.sockets.splice(e,1),void this.publish("socket.disconnected",t,n)}}function Qc(e,t,n){let r=this.udp4||this.udp6?n:e;if(this.config.rawBuffer)return t=Buffer.from(t,this.config.encoding),void this.publish("data",t,r);if(r.ipcBuffer||(r.ipcBuffer=""),(t=r.ipcBuffer+=t).slice(-1)==Kc.delimiter&&-1!=t.indexOf(Kc.delimiter))for(r.ipcBuffer="",t=Kc.parse(t);t.length>0;){let e=new Dc;e.load(t.shift()),e.data&&e.data.id&&(r.id=e.data.id),this.log("received event of : ",e.type,e.data),this.publish(e.type,e.data,r)}else this.log("Messages are large, You may want to consider smaller messages.")}function el(e){this.publish("close",e)}function tl(e){this.sockets.push(e),e.setEncoding&&e.setEncoding(this.config.encoding),this.log("## socket connection to server detected ##"),e.on("close",el.bind(this)),e.on("error",function(e){this.log("server socket error",e),this.publish("error",e)}.bind(this)),e.on("data",Qc.bind(this,e)),e.on("message",function(t,n){if(!n)return;let r;this.log("Received UDP message from ",n.address,n.port),r=this.config.rawSocket?Buffer.from(t,this.config.encoding):t.toString(),e.emit("data",r,n)}.bind(this)),this.publish("connect",e),this.config.rawBuffer}function nl(){return this.log("starting server on ",this.path,this.port?`:${this.port}`:""),this.udp4||this.udp6?(this.server=L.createSocket(this.udp4?"udp4":"udp6"),this.server.write=sl.bind(this),this.server.on("listening",function(){tl.bind(this)(this.server)}.bind(this))):(this.log("starting TLS server",this.config.tls),this.config.tls?rl.bind(this)():this.server=A.createServer(tl.bind(this))),this.server.on("error",function(e){this.log("server error",e),this.publish("error",e)}.bind(this)),this.server.maxConnections=this.config.maxConnections,this.port?this.udp4||this.udp6?(this.log("starting server as",this.udp4?"udp4":"udp6"),this.server.bind(this.port,this.path),void this.onStart({address:this.path,port:this.port})):(this.log("starting server as",this.config.tls?"TLS":"TCP"),void this.server.listen(this.port,this.path,this.onStart.bind(this))):(this.log("starting server as","Unix || Windows Socket"),"win32"===process.platform&&(this.path=this.path.replace(/^\//,""),this.path=this.path.replace(/\//g,"-"),this.path=`\\\\.\\pipe\\${this.path}`),void this.server.listen({path:this.path,readableAll:this.config.readableAll,writableAll:this.config.writableAll},this.onStart.bind(this)))}function rl(){if(this.log("starting TLS server",this.config.tls),this.config.tls.private?this.config.tls.key=O.readFileSync(this.config.tls.private):this.config.tls.key=O.readFileSync(`${__dirname}/../local-node-ipc-certs/private/server.key`),this.config.tls.public?this.config.tls.cert=O.readFileSync(this.config.tls.public):this.config.tls.cert=O.readFileSync(`${__dirname}/../local-node-ipc-certs/server.pub`),this.config.tls.dhparam&&(this.config.tls.dhparam=O.readFileSync(this.config.tls.dhparam)),this.config.tls.trustedConnections){"string"==typeof this.config.tls.trustedConnections&&(this.config.tls.trustedConnections=[this.config.tls.trustedConnections]),this.config.tls.ca=[];for(let e=0;e<this.config.tls.trustedConnections.length;e++)this.config.tls.ca.push(O.readFileSync(this.config.tls.trustedConnections[e]))}this.server=N.createServer(this.config.tls,tl.bind(this))}function sl(e,t){let n=Buffer.from(e,this.config.encoding);this.server.send(n,0,n.length,t.port,t.address,(function(e){e&&(this.log("error writing data to socket",e),this.publish("error",(function(e){this.publish("error",e)})))}))}class il{constructor(){}config=new Tc;of={};server=!1;get connectTo(){return dl}get connectToNet(){return pl}get disconnect(){return al}get serve(){return cl}get serveNet(){return ul}get log(){return ol}set connectTo(e){return dl}set connectToNet(e){return pl}set disconnect(e){return al}set serve(e){return cl}set serveNet(e){return ul}set log(e){return ol}}function ol(...e){if(!this.config.silent){for(let t=0,n=e.length;t<n;t++)"object"==typeof e[t]&&(e[t]=o.inspect(e[t],{depth:this.config.logDepth,colors:this.config.logInColor}));this.config.logger(e.join(" "))}}function al(e){this.of[e]&&(this.of[e].explicitlyDisconnected=!0,this.of[e].off("*","*"),this.of[e].socket&&this.of[e].socket.destroy&&this.of[e].socket.destroy(),delete this.of[e])}function cl(e,t){"function"==typeof e&&(t=e,e=!1),e||(this.log("Server path not specified, so defaulting to","ipc.config.socketRoot + ipc.config.appspace + ipc.config.id",this.config.socketRoot+this.config.appspace+this.config.id),e=this.config.socketRoot+this.config.appspace+this.config.id),t||(t=ll),this.server=new Jc(e,this.config,ol),this.server.on("start",t)}function ll(){}function ul(e,t,n,r){"number"==typeof e&&(r=n,n=t,t=e,e=!1),"function"==typeof e&&(r=e,n=!1,e=!1,t=!1),e||(this.log("Server host not specified, so defaulting to","ipc.config.networkHost",this.config.networkHost),e=this.config.networkHost),"udp4"!=e.toLowerCase()&&"udp6"!=e.toLowerCase()||(r=t,n=e.toLowerCase(),t=!1,e=this.config.networkHost),"string"==typeof t&&(r=n,n=t,t=!1),"function"==typeof t&&(r=t,n=!1,t=!1),t||(this.log("Server port not specified, so defaulting to","ipc.config.networkPort",this.config.networkPort),t=this.config.networkPort),"function"==typeof n&&(r=n,n=!1),r||(r=ll),this.server=new Jc(e,this.config,ol,t),n&&(this.server[n]=!0,"udp4"===n&&"::1"===e&&(this.server.path="127.0.0.1")),this.server.on("start",r)}function dl(e,t,n){if("function"==typeof t&&(n=t,t=!1),n||(n=ll),e){if(t||(this.log("Service path not specified, so defaulting to","ipc.config.socketRoot + ipc.config.appspace + id",(this.config.socketRoot+this.config.appspace+e).data),t=this.config.socketRoot+this.config.appspace+e),this.of[e]){if(!this.of[e].socket.destroyed)return this.log("Already Connected to",e,"- So executing success without connection"),void n();this.of[e].socket.destroy()}this.of[e]=new Vc(this.config,this.log),this.of[e].id=e,this.of[e].socket&&(this.of[e].socket.id=e),this.of[e].path=t,this.of[e].connect(),n(this)}else this.log("Service id required","Requested service connection without specifying service id. Aborting connection attempt")}function pl(e,t,n,r){if(e){if("number"==typeof t&&(r=n,n=t,t=!1),"function"==typeof t&&(r=t,t=!1,n=!1),t||(this.log("Server host not specified, so defaulting to","ipc.config.networkHost",this.config.networkHost),t=this.config.networkHost),"function"==typeof n&&(r=n,n=!1),n||(this.log("Server port not specified, so defaulting to","ipc.config.networkPort",this.config.networkPort),n=this.config.networkPort),"string"==typeof r&&(UDPType=r,r=!1),r||(r=ll),this.of[e]){if(!this.of[e].socket.destroyed)return this.log("Already Connected to",e,"- So executing success without connection"),void r();this.of[e].socket.destroy()}this.of[e]=new Vc(this.config,this.log),this.of[e].id=e,this.of[e].socket&&(this.of[e].socket.id=e),this.of[e].path=t,this.of[e].port=n,this.of[e].connect(),r(this)}else this.log("Service id required","Requested service connection without specifying service id. Aborting connection attempt")}const hl=new class extends il{constructor(){super()}IPC=il};var fl={id:"widgets",retry:1500,silent:!0,rawBuffer:!0,appspace:"kemu.",encoding:"hex"};const gl=Object.values({protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8}).reduce(((e,t)=>e+t),0),ml=e=>{try{return JSON.parse(e)}catch(e){return null}},vl="undefined"!=typeof window,yl={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},bl={protocolPrefix:4,txtLength:4},Sl=Object.values(yl).reduce(((e,t)=>e+t),0),wl=Object.values(bl).reduce(((e,t)=>e+t),0),Il=["width","height","colorSpace"],_l=(e,t)=>{const n={},r=[];let s=0,i=Array.isArray(e)?[]:{};const o=(e,i)=>{const a=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,s=e instanceof Uint8Array,i=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":s?"Uint8Array":i?"Int8Array":null})(e);if(!a){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=o(e[n],`${i}[${n}]`);return t}if("object"==typeof e){const t={},n=(e=>{const t=e instanceof Int16Array,n=e instanceof Uint16Array,r=e instanceof Int32Array,s=e instanceof Uint32Array,i=e instanceof Float32Array,o=e instanceof Float64Array,a=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":s?"Uint32Array":i?"Float32Array":o?"Float64Array":a?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${i}"`);for(const n in e)e.hasOwnProperty(n)||Il.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${i}`),t[n]=o(e[n],`${i.length?`${i}.`:""}${n}`);return t}return e}n[i]={index:s,length:e.byteLength,binaryType:a},"Buffer"===t?r.push(Buffer.from(e)):"ArrayBuffer"===a?r.push(e):r.push(e.buffer),s+=e.byteLength};i=o(e,"");let a=null;if(r.length>1)if("ArrayBuffer"===t){const e=r.reduce(((e,t)=>e+t.byteLength),0),t=new Uint8Array(e);let n=0;for(let e=0;e<r.length;e++)t.set(new Uint8Array(r[e]),n),n+=r[e].byteLength;a=t.buffer}else{a=Buffer.concat(r)}else 1===r.length&&(a=r[0]);return a?{map:n,combinedData:a,sourceCopy:i}:null},$l=(e,t,n)=>{const r=t.match(/(\[\d+\])|([^[\].]+)/g)||[];let s=e;for(let e=0;e<r.length;e++){let t=r[e];const i=t.startsWith("[")&&t.endsWith("]"),o=e===r.length-1;if(i){t=t.slice(1,-1);const i=parseInt(t,10);if(!Array.isArray(s))throw new Error(`Expected an array at key "${r.slice(0,e).join(".")}" but found an object.`);o?s[i]=n:(s[i]||(s[i]=r[e+1].startsWith("[")?[]:{}),s=s[i])}else o?s[t]=n:(s[t]||(s[t]=r[e+1].startsWith("[")?[]:{}),s=s[t])}return e},Cl=(e,t,n)=>{const r="undefined"!=typeof Buffer,s=t instanceof Uint8Array;for(const i in n)if(n.hasOwnProperty(i)){const{index:o,length:a,binaryType:c}=n[i];let l=null;if(r&&t instanceof Buffer)switch(c){case"Buffer":l=t.subarray(o,o+a);break;case"ArrayBuffer":l=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a);break;case"Uint8Array":l=new Uint8Array(t.subarray(o,o+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.subarray(o,o+a));break;case"Int8Array":l=new Int8Array(t.subarray(o,o+a))}else if(t instanceof ArrayBuffer||t instanceof Uint8Array)switch(c){case"Buffer":if(r){l=Buffer.from(t.slice(o,o+a));break}case"ArrayBuffer":l=s?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a):t.slice(o,o+a);break;case"Uint8Array":l=s?t.slice(o,o+a):new Uint8Array(t.slice(o,o+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.slice(o,o+a));break;case"Int8Array":l=new Int8Array(t.slice(o,o+a))}l&&$l(e,i,l)}return e},kl=e=>Qa(e),El="KMSG",xl="KCMD",Al=kl("klProtocol");var Nl={encode:(e,t,n)=>{const r={json:e.json},s=_l(r.json,"Buffer"),i=s?.combinedData;s&&(r.jsonBinaryMap=s.map,r.json=s.sourceCopy);const o=i?i.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),l=c.byteLength,u=yl.protocolPrefix+yl.protocolVersion+yl.jsonLength+yl.binaryLength+yl.fromServiceId+yl.toServiceId+yl.sentAt+l+o,d=Buffer.alloc(u),p=Date.now();let h=0;return d.write(El,h),h+=yl.protocolPrefix,d.writeUInt8(1,h),h+=yl.protocolVersion,d.writeUInt32LE(l,h),h+=yl.jsonLength,d.writeUInt32LE(o,h),h+=yl.binaryLength,d.writeUInt32LE(t,h),h+=yl.fromServiceId,d.writeUInt32LE(n,h),h+=yl.toServiceId,d.writeBigInt64LE(BigInt(p),h),h+=yl.sentAt,c.copy(d,h),h+=l,i&&o&&i.copy(d,h),d},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,yl.protocolPrefix);if(t+=yl.protocolPrefix,n!==El)return null;if(e.byteLength<Sl)return Al(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=yl.protocolVersion;const s=e.readUInt32LE(t);t+=yl.jsonLength;const i=e.readUInt32LE(t);t+=yl.binaryLength;const o=e.readUInt32LE(t);t+=yl.fromServiceId;const a=e.readUInt32LE(t);t+=yl.toServiceId;const c=e.readBigInt64LE(t);t+=yl.sentAt;const l=s+i,u=e.subarray(t,t+l),d=e.subarray(0,Sl);let p=null;return e.byteLength-Sl-s-i>0&&(p=e.subarray(Sl+s+i)),{header:{protocolVersion:r,jsonLength:s,binaryLength:i,fromServiceId:o,toServiceId:a,sentAt:new Date(Number(c)),packages:[u],headerPackage:d},remaining:p}},decodeFullKlMessage:e=>{const t=Buffer.concat(e.packages),n=t.subarray(0,e.jsonLength).toString(),r=t.subarray(e.jsonLength,e.jsonLength+e.binaryLength),s=ml(n);if(!s?.json)return Al("Invalid JSON in KL message"),null;s.jsonBinaryMap&&r.byteLength&&Cl(s.json,r,s.jsonBinaryMap);const i=Buffer.concat([e.headerPackage,t]);let o=i,a=null;const c=Sl+e.jsonLength+e.binaryLength;return i.byteLength>c&&(a=i.subarray(c),o=i.subarray(0,c)),{message:{json:s.json,rawMessage:o},remaining:a}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Sl)return Al("Invalid Header Size"),e;let n=0;return n+=yl.protocolPrefix,n+=yl.protocolVersion,n+=yl.jsonLength,n+=yl.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=yl.fromServiceId,void 0!==t.toServiceId&&e.writeUInt32LE(t.toServiceId,n),e},encodeCommand:e=>{let t=0;const n=Buffer.from(e),r=n.byteLength,s=wl+r,i=Buffer.alloc(s);return i.write(xl,t),t+=bl.protocolPrefix,i.writeUint32LE(r,t),t+=bl.txtLength,n.copy(i,t),i},decodeCommand:e=>{let t=0;if(e.byteLength<wl)return{command:null};const n=e.toString("utf-8",t,bl.protocolPrefix);if(t+=bl.protocolPrefix,n!==xl)return{command:null};const r=e.readUInt32LE(t);t+=bl.txtLength;const s=e.toString("utf-8",t,t+r),i=e.byteLength-wl-r;let o=null;i>0&&(o=e.subarray(wl+r));let a=0;return i<0&&(a=Math.abs(i)),{command:s,remainingData:o,missing:a}}};const Ol="KMSG",Pl="KCMD",Ll=kl("klProtocol"),Tl=new TextEncoder;var Bl={encode:(e,t,n)=>{const r={json:e.json},s=_l(e.json,"ArrayBuffer"),i=s?.combinedData;s&&(r.jsonBinaryMap=s.map,r.json=s.sourceCopy);const o=i?i.byteLength:0,a=JSON.stringify(r),c=Tl.encode(a),l=c.byteLength,u=new ArrayBuffer(yl.protocolPrefix+yl.protocolVersion+yl.jsonLength+yl.binaryLength+yl.fromServiceId+yl.toServiceId+yl.sentAt+l+o),d=new DataView(u),p=new Uint8Array(u),h=Date.now();let f=0;for(let e=0;e<4;++e)p[f++]=Ol.charCodeAt(e);return d.setUint8(f,1),f+=yl.protocolVersion,d.setUint32(f,l,!0),f+=yl.jsonLength,d.setUint32(f,o,!0),f+=yl.binaryLength,d.setUint32(f,t,!0),f+=yl.fromServiceId,d.setUint32(f,n,!0),f+=yl.toServiceId,d.setBigInt64(f,BigInt(h),!0),f+=yl.sentAt,p.set(c,f),f+=l,i&&o&&p.set(new Uint8Array(i),f),u},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<yl.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Ol)return null;if(e.byteLength<Sl)return Ll.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const s=t.getUint8(n);n+=yl.protocolVersion;const i=t.getUint32(n,!0);n+=yl.jsonLength;const o=t.getUint32(n,!0);n+=yl.binaryLength;const a=t.getUint32(n,!0);n+=yl.fromServiceId;const c=t.getUint32(n,!0);n+=yl.toServiceId;const l=t.getBigInt64(n,!0);n+=yl.sentAt;const u=i+o,d=e.slice(n,n+u),p=new Uint8Array(e,0,Sl);let h=null;if(e.byteLength-Sl-i-o>0){h=new Uint8Array(e,Sl+i+o).slice().buffer}return{header:{protocolVersion:s,jsonLength:i,binaryLength:o,fromServiceId:a,toServiceId:c,sentAt:new Date(Number(l)),packages:[d],headerPackage:p.slice().buffer},remaining:h}},decodeFullKlMessage:e=>{const t=e.packages.reduce(((e,t)=>e+t.byteLength),0),n=new Uint8Array(t);let r,s=0;for(const t of e.packages)r=new Uint8Array(t),n.set(r,s),s+=r.byteLength;const i=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),o=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=ml(i);if(!a?.json)return Ll.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&o.byteLength&&Cl(a.json,o,a.jsonBinaryMap);const c=new Uint8Array(e.headerPackage.byteLength+n.byteLength);c.set(new Uint8Array(e.headerPackage),0),c.set(n,e.headerPackage.byteLength);let l=c,u=null;const d=Sl+e.jsonLength+e.binaryLength;return c.byteLength>d&&(u=c.subarray(d),l=c.subarray(0,d)),{message:{json:a.json,...o.length?{binaryData:o.buffer}:{},rawMessage:l.buffer},remaining:u?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Sl)return Ll("Invalid Header Size"),e;let n=0;n+=yl.protocolPrefix,n+=yl.protocolVersion,n+=yl.jsonLength,n+=yl.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=yl.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=Tl.encode(e),r=n.byteLength,s=new ArrayBuffer(wl+r),i=new DataView(s),o=new Uint8Array(s);for(let e=0;e<4;++e)o[t++]=Pl.charCodeAt(e);return i.setUint32(t,r,!0),t+=bl.txtLength,o.set(n,t),s},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<wl)return{command:null};let r="";for(let e=0;e<bl.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Pl)return{command:null};const s=t.getUint32(n,!0);n+=bl.txtLength;const i=e.byteLength-wl-s,o=new Uint8Array(e,n,Math.min(s,e.byteLength-wl)),a=(new TextDecoder).decode(o);let c=null;i>0&&(c=e.slice(wl+s));let l=0;return i<0&&(l=Math.abs(i)),{command:a,remainingData:c,missing:l}}};const jl=kl("klTransmissionManager"),Dl=()=>{const e=(t,n,r,s)=>{let i=n,o=null;const a=t instanceof ArrayBuffer;if(jl(`RAW: ${t.toString()}`),!i||i.partialHeaderData){let c;if(a?(c=i?.partialHeaderData?new Uint8Array([...new Uint8Array(i.partialHeaderData),...new Uint8Array(t)]).buffer:t,o=Bl.decodeHeader(c)):(c=i?.partialHeaderData?Buffer.concat([i.partialHeaderData,t]):t,o=Nl.decodeHeader(c)),!o){const{command:t,missing:i,remainingData:o}=a?Bl.decodeCommand(c):Nl.decodeCommand(c);return t?s({command:t,complete:!0,rawMessage:c}):jl(i?`ERROR: Missing ${i} bytes to complete the command. This partial command will be aborted.`:`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${c.byteLength} bytes`),o?(jl(`${o.byteLength} bytes remain after processing command. Re-analyzing...`),e(o,n,r,s)):void 0}if(o.partialHeader)return i={firstPackageAt:Date.now(),partialHeaderData:c},r(i);if(!o.header)return jl(`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${c.byteLength} bytes`);const l=o.header;i={firstPackageAt:Date.now(),header:{...l,totalBytesReceived:l.packages[0].byteLength,totalBytesExpected:l.binaryLength+l.jsonLength,remaining:o.remaining}},r(i)}else i.header&&i.header.totalBytesReceived<i.header.totalBytesExpected&&(i.header.packages.push(t),i.header.totalBytesReceived+=t.byteLength,r(i));if(i.header&&i.header.totalBytesReceived>=i.header.totalBytesExpected){const t=Date.now()-i.header.sentAt.getTime(),n=Date.now()-i.firstPackageAt;jl(`Received ${i.header.totalBytesReceived} of ${i.header.totalBytesExpected} expected in ${t} ms, elapsed since first package: ${n}ms`);const o=a?Bl.decodeFullKlMessage(i.header):Nl.decodeFullKlMessage(i.header),c=i.header.totalBytesReceived,l=i.header.remaining;r(null),o&&s({klMessage:o.message,complete:!0,sourceServiceId:i.header.fromServiceId,targetServiceId:i.header.toServiceId,rawMessage:o.message.rawMessage});let u=l;if(o?.remaining&&(u=a?l?((e,t)=>{const n=e.byteLength+t.byteLength,r=new ArrayBuffer(n),s=new Uint8Array(e),i=new Uint8Array(t),o=new Uint8Array(r);return o.set(s),o.set(i,s.length),r})(l,o.remaining):o.remaining:l?Buffer.concat([l,o.remaining]):o.remaining),u)return jl(`${u.byteLength} bytes remaining after processing message with ${c} bytes of data. Re-analyzing...`),e(u,null,r,s)}};return e};hl.config={...hl.config,...fl};const Ul={info:ec("ipcServer:info"),data:ec("ipcServer:data")};let Ml,Fl,Rl,Wl,Gl={};const Vl=Dl(),Hl=e=>{Gl[e]&&(Ul.info(`Client disconnected [${e}]`),delete Gl[e],Fl&&Fl(e))};var zl=e=>(e?.ipcId&&(hl.config.id=e.ipcId),e?.ipcAppSpace&&(hl.config.appspace=e.ipcAppSpace),new Promise((e=>{hl.serve((()=>{Ul.info("IPC Server Initiated"),hl.server.on("data",((e,t)=>{const n=Gl[t.id];n?(Ul.data(`IPC Socket [${t.id}] data ${e.byteLength} bytes`),Vl(e,n.activeMessage,(e=>n.activeMessage=e),(e=>{if(!e.complete)return;const n=e=>{t.write(e)};if(e.command)return Ul.data(`Received command from client [${t.id}]: ${e.command}`),void(Rl&&Rl(t.id,e.command,n));e.klMessage&&Wl&&Wl({send:n,transmission:{sourceServiceId:e.sourceServiceId??-1,targetServiceId:e.targetServiceId??-1,rawMessage:e.rawMessage},json:e.klMessage.json})}))):Ul.data(`Received data from unknown client [${t.id}]. Ignoring.`)})),hl.server.on("connect",(e=>{const t=rc();Ul.info(`New client connected. Registered as "${t}"`),e.id=t,Gl[t]={socket:e,activeMessage:null,disconnectHandler:()=>Hl(t)},e.on("close",Gl[t].disconnectHandler),Ml&&Ml(t)})),hl.server.on("disconnect",(e=>{Hl(e.id)})),hl.server.on("error",(e=>{console.log(`IPC Server Error: ${e}`)})),e()})),hl.server.start()}))),ql=e=>{Ml=e},Kl=e=>{Fl=e},Jl=e=>Wl=e,Yl=(e,t)=>{const n=Gl[e];if(!n)return Ul.info(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=gl)return Ul.info("Message is too long to be a command. Use sendMessage instead."),!1;const r=Nl.encodeCommand(t);return n.socket.write(r),!0},Xl=(e,t)=>{const n=Gl[e];return!!n&&(Ul.info(`Renaming socket id [${e}] to [${t}]`),delete Gl[e],n.socket.id=t,Gl[t]=n,n.socket.removeListener("close",n.disconnectHandler),n.disconnectHandler=()=>Hl(t),n.socket.on("close",n.disconnectHandler),!0)},Zl=e=>{Rl=e};let Ql=Nl;vl&&(Ql=Bl);var eu,tu=Ql;!function(e){e.FunctionNotFound="FNC_NOT_FOUND"}(eu||(eu={}));let nu=Math.ceil(Date.now()/1e3);var ru={exports:{}};const su=["nodebuffer","arraybuffer","fragments"],iu="undefined"!=typeof Blob;iu&&su.push("blob");var ou={BINARY_TYPES:su,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:iu,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:au}=ou,cu=Buffer[Symbol.species];function lu(e,t,n,r,s){for(let i=0;i<s;i++)n[r+i]=e[i]^t[3&i]}function uu(e,t){for(let n=0;n<e.length;n++)e[n]^=t[3&n]}if(ru.exports={concat:function(e,t){if(0===e.length)return au;if(1===e.length)return e[0];const n=Buffer.allocUnsafe(t);let r=0;for(let t=0;t<e.length;t++){const s=e[t];n.set(s,r),r+=s.length}return r<t?new cu(n.buffer,n.byteOffset,r):n},mask:lu,toArrayBuffer:function(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)},toBuffer:function e(t){if(e.readOnly=!0,Buffer.isBuffer(t))return t;let n;return t instanceof ArrayBuffer?n=new cu(t):ArrayBuffer.isView(t)?n=new cu(t.buffer,t.byteOffset,t.byteLength):(n=Buffer.from(t),e.readOnly=!1),n},unmask:uu},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");ru.exports.mask=function(t,n,r,s,i){i<48?lu(t,n,r,s,i):e.mask(t,n,r,s,i)},ru.exports.unmask=function(t,n){t.length<32?uu(t,n):e.unmask(t,n)}}catch(e){}var du=ru.exports;const pu=Symbol("kDone"),hu=Symbol("kRun");const fu=B,gu=du,mu=class{constructor(e){this[pu]=()=>{this.pending--,this[hu]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[hu]()}[hu](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[pu])}}},{kStatusCode:vu}=ou,yu=Buffer[Symbol.species],bu=Buffer.from([0,0,255,255]),Su=Symbol("permessage-deflate"),wu=Symbol("total-length"),Iu=Symbol("callback"),_u=Symbol("buffers"),$u=Symbol("error");let Cu;var ku=class{constructor(e,t,n){if(this._maxPayload=0|n,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!Cu){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;Cu=new mu(e)}}static get extensionName(){return"permessage-deflate"}offer(){const e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){const e=this._deflate[Iu];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){const t=this._options,n=e.find((e=>!(!1===t.serverNoContextTakeover&&e.server_no_context_takeover||e.server_max_window_bits&&(!1===t.serverMaxWindowBits||"number"==typeof t.serverMaxWindowBits&&t.serverMaxWindowBits>e.server_max_window_bits)||"number"==typeof t.clientMaxWindowBits&&!e.client_max_window_bits)));if(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(n.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?n.client_max_window_bits=t.clientMaxWindowBits:!0!==n.client_max_window_bits&&!1!==t.clientMaxWindowBits||delete n.client_max_window_bits,n}acceptAsClient(e){const t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach((e=>{Object.keys(e).forEach((t=>{let n=e[t];if(n.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(n=n[0],"client_max_window_bits"===t){if(!0!==n){const e=+n;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${n}`)}else if("server_max_window_bits"===t){const e=+n;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else{if("client_no_context_takeover"!==t&&"server_no_context_takeover"!==t)throw new Error(`Unknown parameter "${t}"`);if(!0!==n)throw new TypeError(`Invalid value for parameter "${t}": ${n}`)}e[t]=n}))})),e}decompress(e,t,n){Cu.add((r=>{this._decompress(e,t,((e,t)=>{r(),n(e,t)}))}))}compress(e,t,n){Cu.add((r=>{this._compress(e,t,((e,t)=>{r(),n(e,t)}))}))}_decompress(e,t,n){const r=this._isServer?"client":"server";if(!this._inflate){const e=`${r}_max_window_bits`,t="number"!=typeof this.params[e]?fu.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=fu.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[Su]=this,this._inflate[wu]=0,this._inflate[_u]=[],this._inflate.on("error",Au),this._inflate.on("data",xu)}this._inflate[Iu]=n,this._inflate.write(e),t&&this._inflate.write(bu),this._inflate.flush((()=>{const e=this._inflate[$u];if(e)return this._inflate.close(),this._inflate=null,void n(e);const s=gu.concat(this._inflate[_u],this._inflate[wu]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[wu]=0,this._inflate[_u]=[],t&&this.params[`${r}_no_context_takeover`]&&this._inflate.reset()),n(null,s)}))}_compress(e,t,n){const r=this._isServer?"server":"client";if(!this._deflate){const e=`${r}_max_window_bits`,t="number"!=typeof this.params[e]?fu.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=fu.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[wu]=0,this._deflate[_u]=[],this._deflate.on("data",Eu)}this._deflate[Iu]=n,this._deflate.write(e),this._deflate.flush(fu.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=gu.concat(this._deflate[_u],this._deflate[wu]);t&&(e=new yu(e.buffer,e.byteOffset,e.length-4)),this._deflate[Iu]=null,this._deflate[wu]=0,this._deflate[_u]=[],t&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),n(null,e)}))}};function Eu(e){this[_u].push(e),this[wu]+=e.length}function xu(e){this[wu]+=e.length,this[Su]._maxPayload<1||this[wu]<=this[Su]._maxPayload?this[_u].push(e):(this[$u]=new RangeError("Max payload size exceeded"),this[$u].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[$u][vu]=1009,this.removeListener("data",xu),this.reset())}function Au(e){this[Su]._inflate=null,e[vu]=1007,this[Iu](e)}var Nu={exports:{}};const{isUtf8:Ou}=j,{hasBlob:Pu}=ou;function Lu(e){const t=e.length;let n=0;for(;n<t;)if(128&e[n])if(192==(224&e[n])){if(n+1===t||128!=(192&e[n+1])||192==(254&e[n]))return!1;n+=2}else if(224==(240&e[n])){if(n+2>=t||128!=(192&e[n+1])||128!=(192&e[n+2])||224===e[n]&&128==(224&e[n+1])||237===e[n]&&160==(224&e[n+1]))return!1;n+=3}else{if(240!=(248&e[n]))return!1;if(n+3>=t||128!=(192&e[n+1])||128!=(192&e[n+2])||128!=(192&e[n+3])||240===e[n]&&128==(240&e[n+1])||244===e[n]&&e[n+1]>143||e[n]>244)return!1;n+=4}else n++;return!0}if(Nu.exports={isBlob:function(e){return Pu&&"object"==typeof e&&"function"==typeof e.arrayBuffer&&"string"==typeof e.type&&"function"==typeof e.stream&&("Blob"===e[Symbol.toStringTag]||"File"===e[Symbol.toStringTag])},isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:Lu,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},Ou)Nu.exports.isValidUTF8=function(e){return e.length<24?Lu(e):Ou(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");Nu.exports.isValidUTF8=function(t){return t.length<32?Lu(t):e(t)}}catch(e){}var Tu=Nu.exports;const{Writable:Bu}=T,ju=ku,{BINARY_TYPES:Du,EMPTY_BUFFER:Uu,kStatusCode:Mu,kWebSocket:Fu}=ou,{concat:Ru,toArrayBuffer:Wu,unmask:Gu}=du,{isValidStatusCode:Vu,isValidUTF8:Hu}=Tu,zu=Buffer[Symbol.species];var qu=class extends Bu{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||Du[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Fu]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(8===this._opcode&&0==this._state)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){const t=this._buffers[0];return this._buffers[0]=new zu(t.buffer,t.byteOffset+e,t.length-e),new zu(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new zu(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do{switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:return void(this._loop=!1)}}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2)return void(this._loop=!1);const t=this.consume(2);if(48&t[0]){return void e(this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3"))}const n=!(64&~t[0]);if(!n||this._extensions[ju.extensionName]){if(this._fin=!(128&~t[0]),this._opcode=15&t[0],this._payloadLength=127&t[1],0===this._opcode){if(n){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(!this._fragmented){return void e(this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE"))}this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented){return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"))}this._compressed=n}else{if(!(this._opcode>7&&this._opcode<11)){return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"))}if(!this._fin){return void e(this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN"))}if(n){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength){return void e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"))}}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=!(128&~t[1]),this._isServer){if(!this._masked){return void e(this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK"))}}else if(this._masked){return void e(this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK"))}126===this._payloadLength?this._state=1:127===this._payloadLength?this._state=2:this.haveLength(e)}else{e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}}getPayloadLength16(e){this._bufferedBytes<2?this._loop=!1:(this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e))}getPayloadLength64(e){if(this._bufferedBytes<8)return void(this._loop=!1);const t=this.consume(8),n=t.readUInt32BE(0);if(n>Math.pow(2,21)-1){e(this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"))}else this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"))}else this._masked?this._state=3:this._state=4}getMask(){this._bufferedBytes<4?this._loop=!1:(this._mask=this.consume(4),this._state=4)}getData(e){let t=Uu;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength)return void(this._loop=!1);t=this.consume(this._payloadLength),this._masked&&this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3]&&Gu(t,this._mask)}if(this._opcode>7)this.controlMessage(t,e);else{if(this._compressed)return this._state=5,void this.decompress(t,e);t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}}decompress(e,t){this._extensions[ju.extensionName].decompress(e,this._fin,((e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){const e=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");return void t(e)}this._fragments.push(n)}this.dataMessage(t),0===this._state&&this.startLoop(t)}))}dataMessage(e){if(!this._fin)return void(this._state=0);const t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let r;r="nodebuffer"===this._binaryType?Ru(n,t):"arraybuffer"===this._binaryType?Wu(Ru(n,t)):"blob"===this._binaryType?new Blob(n):n,this._allowSynchronousEvents?(this.emit("message",r,!0),this._state=0):(this._state=6,setImmediate((()=>{this.emit("message",r,!0),this._state=0,this.startLoop(e)})))}else{const r=Ru(n,t);if(!this._skipUTF8Validation&&!Hu(r)){const t=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void e(t)}5===this._state||this._allowSynchronousEvents?(this.emit("message",r,!1),this._state=0):(this._state=6,setImmediate((()=>{this.emit("message",r,!1),this._state=0,this.startLoop(e)})))}}controlMessage(e,t){if(8!==this._opcode)this._allowSynchronousEvents?(this.emit(9===this._opcode?"ping":"pong",e),this._state=0):(this._state=6,setImmediate((()=>{this.emit(9===this._opcode?"ping":"pong",e),this._state=0,this.startLoop(t)})));else{if(0===e.length)this._loop=!1,this.emit("conclude",1005,Uu),this.end();else{const n=e.readUInt16BE(0);if(!Vu(n)){const e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const r=new zu(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Hu(r)){const e=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void t(e)}this._loop=!1,this.emit("conclude",n,r),this.end()}this._state=0}}createError(e,t,n,r,s){this._loop=!1,this._errored=!0;const i=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(i,this.createError),i.code=s,i[Mu]=r,i}};const{randomFillSync:Ku}=l,Ju=ku,{EMPTY_BUFFER:Yu,kWebSocket:Xu,NOOP:Zu}=ou,{isBlob:Qu,isValidStatusCode:ed}=Tu,{mask:td,toBuffer:nd}=du,rd=Symbol("kByteLength"),sd=Buffer.alloc(4),id=8192;let od,ad=id;var cd=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=Zu,this[Xu]=void 0}static frame(e,t){let n,r,s=!1,i=2,o=!1;t.mask&&(n=t.maskBuffer||sd,t.generateMask?t.generateMask(n):(ad===id&&(void 0===od&&(od=Buffer.alloc(id)),Ku(od,0,id),ad=0),n[0]=od[ad++],n[1]=od[ad++],n[2]=od[ad++],n[3]=od[ad++]),o=!(n[0]|n[1]|n[2]|n[3]),i=6),"string"==typeof e?r=t.mask&&!o||void 0===t[rd]?(e=Buffer.from(e)).length:t[rd]:(r=e.length,s=t.mask&&t.readOnly&&!o);let a=r;r>=65536?(i+=8,a=127):r>125&&(i+=2,a=126);const c=Buffer.allocUnsafe(s?r+i:i);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=a,126===a?c.writeUInt16BE(r,2):127===a&&(c[2]=c[3]=0,c.writeUIntBE(r,4,6)),t.mask?(c[1]|=128,c[i-4]=n[0],c[i-3]=n[1],c[i-2]=n[2],c[i-1]=n[3],o?[c,e]:s?(td(e,n,c,i,r),[c]):(td(e,n,e,0,r),[c,e])):[c,e]}close(t,n,r,s){let i;if(void 0===t)i=Yu;else{if("number"!=typeof t||!ed(t))throw new TypeError("First argument must be a valid error code number");if(void 0!==n&&n.length){const e=Buffer.byteLength(n);if(e>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+e),i.writeUInt16BE(t,0),"string"==typeof n?i.write(n,2):i.set(n,2)}else i=Buffer.allocUnsafe(2),i.writeUInt16BE(t,0)}const o={[rd]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(e.frame(i,o),s)}ping(t,n,r){let s,i;if("string"==typeof t?(s=Buffer.byteLength(t),i=!1):Qu(t)?(s=t.size,i=!1):(s=(t=nd(t)).length,i=nd.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[rd]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Qu(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,o,r]):this.getBlobData(t,!1,o,r):0!==this._state?this.enqueue([this.dispatch,t,!1,o,r]):this.sendFrame(e.frame(t,o),r)}pong(t,n,r){let s,i;if("string"==typeof t?(s=Buffer.byteLength(t),i=!1):Qu(t)?(s=t.size,i=!1):(s=(t=nd(t)).length,i=nd.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[rd]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Qu(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,o,r]):this.getBlobData(t,!1,o,r):0!==this._state?this.enqueue([this.dispatch,t,!1,o,r]):this.sendFrame(e.frame(t,o),r)}send(e,t,n){const r=this._extensions[Ju.extensionName];let s,i,o=t.binary?2:1,a=t.compress;"string"==typeof e?(s=Buffer.byteLength(e),i=!1):Qu(e)?(s=e.size,i=!1):(s=(e=nd(e)).length,i=nd.readOnly),this._firstFragment?(this._firstFragment=!1,a&&r&&r.params[r._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=s>=r._threshold),this._compress=a):(a=!1,o=0),t.fin&&(this._firstFragment=!0);const c={[rd]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:i,rsv1:a};Qu(e)?0!==this._state?this.enqueue([this.getBlobData,e,this._compress,c,n]):this.getBlobData(e,this._compress,c,n):0!==this._state?this.enqueue([this.dispatch,e,this._compress,c,n]):this.dispatch(e,this._compress,c,n)}getBlobData(t,n,r,s){this._bufferedBytes+=r[rd],this._state=2,t.arrayBuffer().then((t=>{if(this._socket.destroyed){const e=new Error("The socket was closed while the blob was being read");return void process.nextTick(ld,this,e,s)}this._bufferedBytes-=r[rd];const i=nd(t);n?this.dispatch(i,n,r,s):(this._state=0,this.sendFrame(e.frame(i,r),s),this.dequeue())})).catch((e=>{process.nextTick(ud,this,e,s)}))}dispatch(t,n,r,s){if(!n)return void this.sendFrame(e.frame(t,r),s);const i=this._extensions[Ju.extensionName];this._bufferedBytes+=r[rd],this._state=1,i.compress(t,r.fin,((t,n)=>{if(this._socket.destroyed){ld(this,new Error("The socket was closed while data was being compressed"),s)}else this._bufferedBytes-=r[rd],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),s),this.dequeue()}))}dequeue(){for(;0===this._state&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][rd],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][rd],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function ld(e,t,n){"function"==typeof n&&n(t);for(let n=0;n<e._queue.length;n++){const r=e._queue[n],s=r[r.length-1];"function"==typeof s&&s(t)}}function ud(e,t,n){ld(e,t,n),e.onerror(t)}const{kForOnEventAttribute:dd,kListener:pd}=ou,hd=Symbol("kCode"),fd=Symbol("kData"),gd=Symbol("kError"),md=Symbol("kMessage"),vd=Symbol("kReason"),yd=Symbol("kTarget"),bd=Symbol("kType"),Sd=Symbol("kWasClean");class wd{constructor(e){this[yd]=null,this[bd]=e}get target(){return this[yd]}get type(){return this[bd]}}Object.defineProperty(wd.prototype,"target",{enumerable:!0}),Object.defineProperty(wd.prototype,"type",{enumerable:!0});class Id extends wd{constructor(e,t={}){super(e),this[hd]=void 0===t.code?0:t.code,this[vd]=void 0===t.reason?"":t.reason,this[Sd]=void 0!==t.wasClean&&t.wasClean}get code(){return this[hd]}get reason(){return this[vd]}get wasClean(){return this[Sd]}}Object.defineProperty(Id.prototype,"code",{enumerable:!0}),Object.defineProperty(Id.prototype,"reason",{enumerable:!0}),Object.defineProperty(Id.prototype,"wasClean",{enumerable:!0});class _d extends wd{constructor(e,t={}){super(e),this[gd]=void 0===t.error?null:t.error,this[md]=void 0===t.message?"":t.message}get error(){return this[gd]}get message(){return this[md]}}Object.defineProperty(_d.prototype,"error",{enumerable:!0}),Object.defineProperty(_d.prototype,"message",{enumerable:!0});class $d extends wd{constructor(e,t={}){super(e),this[fd]=void 0===t.data?null:t.data}get data(){return this[fd]}}Object.defineProperty($d.prototype,"data",{enumerable:!0});const Cd={addEventListener(e,t,n={}){for(const r of this.listeners(e))if(!n[dd]&&r[pd]===t&&!r[dd])return;let r;if("message"===e)r=function(e,n){const r=new $d("message",{data:n?e:e.toString()});r[yd]=this,Ed(t,this,r)};else if("close"===e)r=function(e,n){const r=new Id("close",{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[yd]=this,Ed(t,this,r)};else if("error"===e)r=function(e){const n=new _d("error",{error:e,message:e.message});n[yd]=this,Ed(t,this,n)};else{if("open"!==e)return;r=function(){const e=new wd("open");e[yd]=this,Ed(t,this,e)}}r[dd]=!!n[dd],r[pd]=t,n.once?this.once(e,r):this.on(e,r)},removeEventListener(e,t){for(const n of this.listeners(e))if(n[pd]===t&&!n[dd]){this.removeListener(e,n);break}}};var kd={CloseEvent:Id,ErrorEvent:_d,Event:wd,EventTarget:Cd,MessageEvent:$d};function Ed(e,t,n){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}const{tokenChars:xd}=Tu;function Ad(e,t,n){void 0===e[t]?e[t]=[n]:e[t].push(n)}var Nd={format:function(e){return Object.keys(e).map((t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map((e=>[t].concat(Object.keys(e).map((t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map((e=>!0===e?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")},parse:function(e){const t=Object.create(null);let n,r,s=Object.create(null),i=!1,o=!1,a=!1,c=-1,l=-1,u=-1,d=0;for(;d<e.length;d++)if(l=e.charCodeAt(d),void 0===n)if(-1===u&&1===xd[l])-1===c&&(c=d);else if(0===d||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${d}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${d}`);-1===u&&(u=d);const r=e.slice(c,u);44===l?(Ad(t,r,s),s=Object.create(null)):n=r,c=u=-1}}else-1===u&&-1!==c&&(u=d);else if(void 0===r)if(-1===u&&1===xd[l])-1===c&&(c=d);else if(32===l||9===l)-1===u&&-1!==c&&(u=d);else if(59===l||44===l){if(-1===c)throw new SyntaxError(`Unexpected character at index ${d}`);-1===u&&(u=d),Ad(s,e.slice(c,u),!0),44===l&&(Ad(t,n,s),s=Object.create(null),n=void 0),c=u=-1}else{if(61!==l||-1===c||-1!==u)throw new SyntaxError(`Unexpected character at index ${d}`);r=e.slice(c,d),c=u=-1}else if(o){if(1!==xd[l])throw new SyntaxError(`Unexpected character at index ${d}`);-1===c?c=d:i||(i=!0),o=!1}else if(a)if(1===xd[l])-1===c&&(c=d);else if(34===l&&-1!==c)a=!1,u=d;else{if(92!==l)throw new SyntaxError(`Unexpected character at index ${d}`);o=!0}else if(34===l&&61===e.charCodeAt(d-1))a=!0;else if(-1===u&&1===xd[l])-1===c&&(c=d);else if(-1===c||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${d}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${d}`);-1===u&&(u=d);let o=e.slice(c,u);i&&(o=o.replace(/\\/g,""),i=!1),Ad(s,r,o),44===l&&(Ad(t,n,s),s=Object.create(null),n=void 0),r=void 0,c=u=-1}}else-1===u&&(u=d);if(-1===c||a||32===l||9===l)throw new SyntaxError("Unexpected end of input");-1===u&&(u=d);const p=e.slice(c,u);return void 0===n?Ad(t,p,s):(void 0===r?Ad(s,p,!0):Ad(s,r,i?p.replace(/\\/g,""):p),Ad(t,n,s)),t}};const Od=D,Pd=U,Ld=M,Td=A,Bd=N,{randomBytes:jd,createHash:Dd}=l,{URL:Ud}=F,Md=ku,Fd=qu,Rd=cd,{isBlob:Wd}=Tu,{BINARY_TYPES:Gd,EMPTY_BUFFER:Vd,GUID:Hd,kForOnEventAttribute:zd,kListener:qd,kStatusCode:Kd,kWebSocket:Jd,NOOP:Yd}=ou,{EventTarget:{addEventListener:Xd,removeEventListener:Zd}}=kd,{format:Qd,parse:ep}=Nd,{toBuffer:tp}=du,np=3e4,rp=Symbol("kAborted"),sp=[8,13],ip=["CONNECTING","OPEN","CLOSING","CLOSED"],op=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;let ap=class e extends Od{constructor(t,n,r){super(),this._binaryType=Gd[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Vd,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==t?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===n?n=[]:Array.isArray(n)||("object"==typeof n&&null!==n?(r=n,n=[]):n=[n]),lp(this,t,n,r)):(this._autoPong=r.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Gd.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){const s=new Fd({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Rd(t,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=t,s[Jd]=this,i[Jd]=this,t[Jd]=this,s.on("conclude",gp),s.on("drain",mp),s.on("error",vp),s.on("message",bp),s.on("ping",Sp),s.on("pong",wp),i.onerror=_p,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on("close",Cp),t.on("data",kp),t.on("end",Ep),t.on("error",xp),this._readyState=e.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=e.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[Md.extensionName]&&this._extensions[Md.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED)if(this.readyState!==e.CONNECTING)this.readyState!==e.CLOSING?(this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,(e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())})),$p(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";hp(this,this._req,e)}}pause(){this.readyState!==e.CONNECTING&&this.readyState!==e.CLOSED&&(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof t?(r=t,t=n=void 0):"function"==typeof n&&(r=n,n=void 0),"number"==typeof t&&(t=t.toString()),this.readyState===e.OPEN?(void 0===n&&(n=!this._isServer),this._sender.ping(t||Vd,n,r)):fp(this,t,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof t?(r=t,t=n=void 0):"function"==typeof n&&(r=n,n=void 0),"number"==typeof t&&(t=t.toString()),this.readyState===e.OPEN?(void 0===n&&(n=!this._isServer),this._sender.pong(t||Vd,n,r)):fp(this,t,r)}resume(){this.readyState!==e.CONNECTING&&this.readyState!==e.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof n&&(r=n,n={}),"number"==typeof t&&(t=t.toString()),this.readyState!==e.OPEN)return void fp(this,t,r);const s={binary:"string"!=typeof t,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Md.extensionName]||(s.compress=!1),this._sender.send(t||Vd,s,r)}terminate(){if(this.readyState!==e.CLOSED)if(this.readyState!==e.CONNECTING)this._socket&&(this._readyState=e.CLOSING,this._socket.destroy());else{const e="WebSocket was closed before the connection was established";hp(this,this._req,e)}}};Object.defineProperty(ap,"CONNECTING",{enumerable:!0,value:ip.indexOf("CONNECTING")}),Object.defineProperty(ap.prototype,"CONNECTING",{enumerable:!0,value:ip.indexOf("CONNECTING")}),Object.defineProperty(ap,"OPEN",{enumerable:!0,value:ip.indexOf("OPEN")}),Object.defineProperty(ap.prototype,"OPEN",{enumerable:!0,value:ip.indexOf("OPEN")}),Object.defineProperty(ap,"CLOSING",{enumerable:!0,value:ip.indexOf("CLOSING")}),Object.defineProperty(ap.prototype,"CLOSING",{enumerable:!0,value:ip.indexOf("CLOSING")}),Object.defineProperty(ap,"CLOSED",{enumerable:!0,value:ip.indexOf("CLOSED")}),Object.defineProperty(ap.prototype,"CLOSED",{enumerable:!0,value:ip.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(ap.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(ap.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[zd])return t[qd];return null},set(t){for(const t of this.listeners(e))if(t[zd]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[zd]:!0})}})})),ap.prototype.addEventListener=Xd,ap.prototype.removeEventListener=Zd;var cp=ap;function lp(e,t,n,r){const s={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:sp[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=s.autoPong,!sp.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${sp.join(", ")})`);let i;if(t instanceof Ud)i=t;else try{i=new Ud(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}"http:"===i.protocol?i.protocol="ws:":"https:"===i.protocol&&(i.protocol="wss:"),e._url=i.href;const o="wss:"===i.protocol,a="ws+unix:"===i.protocol;let c;if("ws:"===i.protocol||o||a?a&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"):c='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https", or "ws+unix:"',c){const t=new SyntaxError(c);if(0===e._redirects)throw t;return void up(e,t)}const l=o?443:80,u=jd(16).toString("base64"),d=o?Pd.request:Ld.request,p=new Set;let h,f;if(s.createConnection=s.createConnection||(o?pp:dp),s.defaultPort=s.defaultPort||l,s.port=i.port||l,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(h=new Md(!0!==s.perMessageDeflate?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=Qd({[Md.extensionName]:h.offer()})),n.length){for(const e of n){if("string"!=typeof e||!op.test(e)||p.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");p.add(e)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){const e=s.path.split(":");s.socketPath=e[0],s.path=e[1]}if(s.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=o,e._originalHostOrSocketPath=a?s.socketPath:i.host;const t=r&&r.headers;if(r={...r,headers:{}},t)for(const[e,n]of Object.entries(t))r.headers[e.toLowerCase()]=n}else if(0===e.listenerCount("redirect")){const t=a?!!e._originalIpc&&s.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&i.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,t||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),f=e._req=d(s),e._redirects&&e.emit("redirect",e.url,f)}else f=e._req=d(s);s.timeout&&f.on("timeout",(()=>{hp(e,f,"Opening handshake has timed out")})),f.on("error",(t=>{null===f||f[rp]||(f=e._req=null,up(e,t))})),f.on("response",(i=>{const o=i.headers.location,a=i.statusCode;if(o&&s.followRedirects&&a>=300&&a<400){if(++e._redirects>s.maxRedirects)return void hp(e,f,"Maximum redirects exceeded");let i;f.abort();try{i=new Ud(o,t)}catch(t){const n=new SyntaxError(`Invalid URL: ${o}`);return void up(e,n)}lp(e,i,n,r)}else e.emit("unexpected-response",f,i)||hp(e,f,`Unexpected server response: ${i.statusCode}`)})),f.on("upgrade",((t,n,r)=>{if(e.emit("upgrade",t),e.readyState!==ap.CONNECTING)return;f=e._req=null;const i=t.headers.upgrade;if(void 0===i||"websocket"!==i.toLowerCase())return void hp(e,n,"Invalid Upgrade header");const o=Dd("sha1").update(u+Hd).digest("base64");if(t.headers["sec-websocket-accept"]!==o)return void hp(e,n,"Invalid Sec-WebSocket-Accept header");const a=t.headers["sec-websocket-protocol"];let c;if(void 0!==a?p.size?p.has(a)||(c="Server sent an invalid subprotocol"):c="Server sent a subprotocol but none was requested":p.size&&(c="Server sent no subprotocol"),c)return void hp(e,n,c);a&&(e._protocol=a);const l=t.headers["sec-websocket-extensions"];if(void 0!==l){if(!h){return void hp(e,n,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=ep(l)}catch(t){return void hp(e,n,"Invalid Sec-WebSocket-Extensions header")}const r=Object.keys(t);if(1!==r.length||r[0]!==Md.extensionName){return void hp(e,n,"Server indicated an extension that was not requested")}try{h.accept(t[Md.extensionName])}catch(t){return void hp(e,n,"Invalid Sec-WebSocket-Extensions header")}e._extensions[Md.extensionName]=h}e.setSocket(n,r,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})})),s.finishRequest?s.finishRequest(f,e):f.end()}function up(e,t){e._readyState=ap.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function dp(e){return e.path=e.socketPath,Td.connect(e)}function pp(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=Td.isIP(e.host)?"":e.host),Bd.connect(e)}function hp(e,t,n){e._readyState=ap.CLOSING;const r=new Error(n);Error.captureStackTrace(r,hp),t.setHeader?(t[rp]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(up,e,r)):(t.destroy(r),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function fp(e,t,n){if(t){const n=Wd(t)?t.size:tp(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${ip[e.readyState]})`);process.nextTick(n,t)}}function gp(e,t){const n=this[Jd];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,void 0!==n._socket[Jd]&&(n._socket.removeListener("data",kp),process.nextTick(Ip,n._socket),1005===e?n.close():n.close(e,t))}function mp(){const e=this[Jd];e.isPaused||e._socket.resume()}function vp(e){const t=this[Jd];void 0!==t._socket[Jd]&&(t._socket.removeListener("data",kp),process.nextTick(Ip,t._socket),t.close(e[Kd])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function yp(){this[Jd].emitClose()}function bp(e,t){this[Jd].emit("message",e,t)}function Sp(e){const t=this[Jd];t._autoPong&&t.pong(e,!this._isServer,Yd),t.emit("ping",e)}function wp(e){this[Jd].emit("pong",e)}function Ip(e){e.resume()}function _p(e){const t=this[Jd];t.readyState!==ap.CLOSED&&(t.readyState===ap.OPEN&&(t._readyState=ap.CLOSING,$p(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function $p(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),np)}function Cp(){const e=this[Jd];let t;this.removeListener("close",Cp),this.removeListener("data",kp),this.removeListener("end",Ep),e._readyState=ap.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[Jd]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",yp),e._receiver.on("finish",yp))}function kp(e){this[Jd]._receiver.write(e)||this.pause()}function Ep(){const e=this[Jd];e._readyState=ap.CLOSING,e._receiver.end(),this.end()}function xp(){const e=this[Jd];this.removeListener("error",xp),this.on("error",Yd),e&&(e._readyState=ap.CLOSING,this.destroy())}const{tokenChars:Ap}=Tu;var Np={parse:function(e){const t=new Set;let n=-1,r=-1,s=0;for(;s<e.length;s++){const i=e.charCodeAt(s);if(-1===r&&1===Ap[i])-1===n&&(n=s);else if(0===s||32!==i&&9!==i){if(44!==i)throw new SyntaxError(`Unexpected character at index ${s}`);{if(-1===n)throw new SyntaxError(`Unexpected character at index ${s}`);-1===r&&(r=s);const i=e.slice(n,r);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);t.add(i),n=r=-1}}else-1===r&&-1!==n&&(r=s)}if(-1===n||-1!==r)throw new SyntaxError("Unexpected end of input");const i=e.slice(n,s);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return t.add(i),t}};const Op=D,Pp=M,{createHash:Lp}=l,Tp=Nd,Bp=ku,jp=Np,Dp=cp,{GUID:Up,kWebSocket:Mp}=ou,Fp=/^[+/0-9A-Za-z]{22}==$/;var Rp=class extends Op{constructor(e,t){if(super(),null==(e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Dp,...e}).port&&!e.server&&!e.noServer||null!=e.port&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=e.port?(this._server=Pp.createServer(((e,t)=>{const n=Pp.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":"text/plain"}),t.end(n)})),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){const e=this.emit.bind(this,"connection");this._removeListeners=function(e,t){for(const n of Object.keys(t))e.on(n,t[n]);return function(){for(const n of Object.keys(t))e.removeListener(n,t[n])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(2===this._state)return e&&this.once("close",(()=>{e(new Error("The server is not running"))})),void process.nextTick(Wp,this);if(e&&this.once("close",e),1!==this._state)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(Wp,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{Wp(this)}))}}shouldHandle(e){if(this.options.path){const t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on("error",Gp);const s=e.headers["sec-websocket-key"],i=e.headers.upgrade,o=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void Hp(this,e,t,405,"Invalid HTTP method")}if(void 0===i||"websocket"!==i.toLowerCase()){return void Hp(this,e,t,400,"Invalid Upgrade header")}if(void 0===s||!Fp.test(s)){return void Hp(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==o&&13!==o){return void Hp(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void Vp(t,400);const a=e.headers["sec-websocket-protocol"];let c=new Set;if(void 0!==a)try{c=jp.parse(a)}catch(n){return void Hp(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const l=e.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&void 0!==l){const n=new Bp(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=Tp.parse(l);e[Bp.extensionName]&&(n.accept(e[Bp.extensionName]),u[Bp.extensionName]=n)}catch(n){return void Hp(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const i={origin:e.headers[""+(8===o?"sec-websocket-origin":"origin")],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(i,((i,o,a,l)=>{if(!i)return Vp(t,o||401,a,l);this.completeUpgrade(u,s,c,e,t,n,r)}));if(!this.options.verifyClient(i))return Vp(t,401)}this.completeUpgrade(u,s,c,e,t,n,r)}completeUpgrade(e,t,n,r,s,i,o){if(!s.readable||!s.writable)return s.destroy();if(s[Mp])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return Vp(s,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Lp("sha1").update(t+Up).digest("base64")}`],c=new this.options.WebSocket(null,void 0,this.options);if(n.size){const e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(a.push(`Sec-WebSocket-Protocol: ${e}`),c._protocol=e)}if(e[Bp.extensionName]){const t=e[Bp.extensionName].params,n=Tp.format({[Bp.extensionName]:[t]});a.push(`Sec-WebSocket-Extensions: ${n}`),c._extensions=e}this.emit("headers",a,r),s.write(a.concat("\r\n").join("\r\n")),s.removeListener("error",Gp),c.setSocket(s,i,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(c),c.on("close",(()=>{this.clients.delete(c),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Wp,this)}))),o(c,r)}};function Wp(e){e._state=2,e.emit("close")}function Gp(){this.destroy()}function Vp(e,t,n,r){n=n||Pp.STATUS_CODES[t],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${Pp.STATUS_CODES[t]}\r\n`+Object.keys(r).map((e=>`${e}: ${r[e]}`)).join("\r\n")+"\r\n\r\n"+n)}function Hp(e,t,n,r,s){if(e.listenerCount("wsClientError")){const r=new Error(s);Error.captureStackTrace(r,Hp),e.emit("wsClientError",r,n,t)}else Vp(n,r,s)}var zp=ja(Rp);const qp=ec("websocketServer"),Kp={},Jp=Dl();let Yp,Xp,Zp,Qp,eh;const th=e=>{const t=Kp[e];t&&t.socket.close()};var nh={startServer:e=>{eh=new zp({port:e,maxPayload:104857600}),eh.on("connection",(e=>{const t=rc();qp(`New client connected. Registered as "${t}"`),e.id=t,Kp[t]={socket:e,activeMessage:null},Yp&&Yp(t),e.on("message",(t=>{if(t instanceof Buffer){const n=Kp[e.id];Jp(t,n.activeMessage,(e=>n.activeMessage=e),(t=>{if(!t.complete)return;const r=t=>{e.send(t),qp(`Writing ${t.byteLength} bytes to socket [${n.socket.id}]: ${t.toString()}`)},s=()=>{th(n.socket.id)};if(t.command)return qp(`Received command from client [${n.socket.id}]: ${t.command}`),void(Zp&&Zp(n.socket.id,t.command,r,s));t.klMessage&&Qp&&Qp({send:r,terminateWebsocket:s,websocketId:n.socket.id,transmission:{sourceServiceId:t.sourceServiceId??-1,targetServiceId:t.targetServiceId??-1,rawMessage:t.rawMessage},json:t.klMessage.json})}))}})),e.on("close",(()=>{qp(`Client disconnected: ${e.id}`),Xp&&Xp(e.id),delete Kp[e.id]})),e.on("error",(()=>{qp(`Error on client connection: ${e.id}`)}))})),console.log(`WebSocket server is running on port ${e}`)},stopServer:()=>{eh.close((()=>{console.log("WebSocket server stopped")}))},onClientConnected:e=>{Yp=e},onClientDisconnected:e=>{Xp=e},onClientCommand:e=>{Zp=e},sendCommand:(e,t)=>{const n=Kp[e];if(!n)return qp(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=gl)return qp("Message is too long to be a command. Use sendMessage instead."),!1;const r=Nl.encodeCommand(t);return n.socket.send(r),!0},onMessageReceived:e=>Qp=e,terminateConnection:th};const rh=ec("stopService"),sh=async e=>{const t=e.args[0];if(!t)return e.reply({error:"No service name provided"});const n=Lc.getAllServiceVersions(t);rh(`Stopping ${n.length} services with name: ${t}`);for(const e of n)await Lc.stopService(e.info.name,e.info.version);const r=n.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[r]})},ih=ec("removeService"),oh=async e=>{const t=e.args[0],n=e.args[1];if(!t)return e.reply({error:"No service name provided"});let r=Lc.getAllServiceVersions(t);n&&(r=r.filter((e=>e.info.version===n))),ih(`Removing ${r.length} service(s) with name: ${t}`);for(const e of r)await Lc.uninstallService(e.info.name,e.info.version);const s=r.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[s]})},ah=ec("launchService"),ch=async e=>{const t=e.args[0],n=e.args[1];if(!t)return e.reply({error:"No service name provided"});if(!n)return e.reply({error:"No service version provided"});const r=`${t}@${n}/dist`;try{const s=gc();ah(`Loading service ${t}@${n} from ${s}`);const{errorMsg:i,service:o,errorCode:a}=await Lc.loadAndLaunch(s,r,!1);if(i||"started"!==o?.status)return e.reply({error:`Failed to launch service ${t}@${n}: ${i||"error-not-provided"}`,errCode:a});const c=Date.now(),l=3e4,u=async()=>{const r=o.status;return"running"===r?(ah(`Service ${t}@${n} loaded and started`),e.reply({success:[]})):(ah(`Service ${t}@${n} not yet started, status: ${r}`),"stopped"===r||"error"===r?e.reply({error:`Error launching service: "${o.errorMsg||"failed to initiate"}"`}):Date.now()-c>l?e.reply({error:"Timeout waiting for service to start"}):(ah("Retrying in 1 second..."),void setTimeout(u,1e3)))};u()}catch(r){return ah(`Error loading service ${t}@${n}: ${r?.message||r}`),e.reply({error:r?.message||"There was an error loading the service"})}},lh=ec("getMatchingServices"),uh=async e=>{const t=e.args[0],n=[],r=[];lh(`Checking for matching services: ${t.map((e=>e.name)).join(", ")}`);for(const{name:e,version:s}of t){const t=Lc.getMatchingService(e,s);t?n.push({name:e,version:s,installationPath:Lc.getServiceRootDirectory(t)}):r.push({name:e,version:s})}lh(`Found ${n.length} available services and ${r.length} missing services.`),e.reply({success:[{available:n,missing:r}]})},dh=ec("getSecretsValues");let ph;var hh=async e=>{const t=e.args[0].services;if(!ph)throw new Error("getSecretValuesFn is not set. Please call setGetSecretValuesFunction before using this function.");dh(`Checking for secrets values for services: ${t.map((e=>`${e.name}@${e.version}`)).join(", ")}`);const n=[];for(const e of t){const t=e.secrets,r=await ph({name:e.name,version:e.version,requiredSecrets:t.reduce(((e,t)=>(e[t]={optional:!1,description:""},e)),{})});n.push({name:e.name,version:e.version,secrets:t.map((e=>({name:e,value:r[e]})))})}const r=[{services:n}];e.reply({success:r})},fh=e=>{ph=e};const gh=ec("getMappedSecrets");let mh;var vh=async e=>{const t=e.args[0].services;gh(`Getting mapped secrets for services: ${t.map((e=>`${e.name}@${e.version}`)).join(", ")}`);const n=await mh(t),r=[{services:t.map((e=>({name:e.name,version:e.version,secrets:n[e.name]||[]})))}];e.reply({success:r})},yh=e=>{mh=e};const bh=ec("getServiceContents"),Sh=({reply:e,args:t})=>{const[n]=t;bh(`Received GetServiceContents request for service ${n.serviceName} v${n.version}`);const r=Lc.getMatchingService(n.serviceName,n.version);if(r){return e({success:[{serviceName:r.info.name,serviceVersion:r.info.version,uiContent:r.info.widgetUIContents,uiContentsChecksum:r.info.uiContentChecksum}]})}bh(`Service ${n.serviceName} v${n.version} not found`),e({error:`Service ${n.serviceName} v${n.version} not found`})};let wh=null;const Ih=async e=>{const{data:t,error:n}=await(async(e,t)=>{try{const n=await fetch(e,{method:"POST",body:JSON.stringify(t)});return n.ok?{data:await n.json(),statusCode:n.status,success:!0}:{statusCode:n.status,error:await n.text(),success:!1}}catch(e){return{statusCode:500,error:e instanceof Error?e.message:"Internal server error",success:!1}}})(`${(()=>{if(!wh)throw new Error("Unknown server URL. Please call `setServerUrl` before using the APIs.");return wh})()}/v1/validate/validate_key`,{apiKey:e});return n?(console.warn(`Error validating Kemu API key: ${n}`),{valid:!1,features:{},error:n}):t?.features?{valid:!0,features:t.features,error:null}:{valid:!1,features:{},error:"No features returned from the server"}},_h={},$h=async e=>{const t=(e=>{const t=_h[e],n=Date.now()-(t?.lastCheckedAt.getTime()??0);return t&&n<3e5?t.features:null})(e);if(t)return{valid:!0,features:t,error:null};const{valid:n,features:r,error:s}=await Ih(e);return n&&(_h[e]={features:r,lastCheckedAt:new Date}),{valid:n,features:r,error:s}},Ch=ec("activeClients");let kh={},Eh={};const xh=(e,t)=>`${e}_${t}`,Ah=e=>kh[e]||null,Nh=(e,t)=>{const n=xh(e,t);return Eh[n]||[]},Oh=()=>{for(const e in kh){const t=kh[e];if(t?.transport===ya.WS){const e=Nl.encodeCommand(ga.ServicesListChanged);t.send(e)}}},Ph=async e=>{const t=[],{serviceSessionId:n,transport:r,send:s,terminateFn:i,extraInfo:o,isDevClient:a}=e,c=e=>{console.warn(e),i&&i()};if(r===ya.WS){if(!o.wsApiKey)return void c(`Attempted to register a WebSocket client without an API key. SessionId: ${n}`);const{valid:e,error:t}=await $h(o.wsApiKey);if(!e&&!t)return void c(`Attempted to register a WebSocket client with an invalid API key. SessionId: ${n}`);t&&Ch(`Unable to validate API Key, usage will be limited. SessionId: ${n}`)}kh[n]={serviceSessionId:n,transport:r,isDevClient:!!a,broadcastSubscriptions:t,send:s,extraInfo:o,terminate:()=>{i&&i()},addSubscription:e=>{if(!t.some((t=>t.targetService.serviceName===e.serviceName&&t.targetService.version===e.version))){t.push({targetService:e});const r=xh(e.serviceName,e.version);Eh[r]=Eh[r]||[];return Eh[r].some((e=>e.serviceId===n))||Eh[r].push({sendFn:s,serviceId:n}),!0}return!1},removeSubscription:e=>{const r=t.findIndex((t=>t.targetService.serviceName===e.serviceName));if(-1!==r){t.splice(r,1);const s=xh(e.serviceName,e.version),i=Eh[s]?.findIndex((e=>e.serviceId===n));if(-1!==i&&(Eh[s].splice(i,1),!Eh[s].length)){const t=Lc.getMatchingService(e.serviceName,e.version);if(t?.info.eventEmitter&&"running"===t.status){const e=Ah(t.info.sessionId);e?.extraInfo.ipcSocketId&&Yl(e?.extraInfo.ipcSocketId,ga.BroadcastEnd)}}}},removeAllSubscriptions:()=>{for(const e of t){const t=xh(e.targetService.serviceName,e.targetService.version),r=Eh[t].findIndex((e=>e.serviceId===n));-1!==r&&Eh[t].splice(r,1)}t.length=0}},r===ya.IPC&&(Oh(),Th(n))},Lh=()=>{const e=Object.values(kh);for(const t of e)if(t.transport===ya.IPC){const e=t.extraInfo.ipcSocketId,n=Lc.getServiceBySessionId(t.serviceSessionId);if(n?.info.eventEmitter){Nh(n.info.name,n.info.version).length||e&&Yl(e,ga.BroadcastEnd)}}},Th=e=>{const t=Lc.getServiceBySessionId(e);if(t?.info.eventEmitter){if(Nh(t.info.name,t.info.version).length){const t=Ah(e);t?.extraInfo.ipcSocketId&&Yl(t?.extraInfo.ipcSocketId,ga.BroadcastStart)}}},Bh=e=>{const t=kh[e];delete kh[e],t.transport===ya.IPC?Oh():(t.removeAllSubscriptions(),Lh())},jh=ec("ipc:handleIpcClientCommand"),Dh=(e,t,n)=>{const r=((e,t)=>{if(e.startsWith(ga.AcknowledgeResponse)){const n=e.split(":"),r=parseInt(n[1]),s=parseInt(n[2]);return t&&t(r,isNaN(s)?void 0:s),!0}return!1})(t,((e,t)=>{if(!e)return void jh(`Ignoring ACK response from IPC service ${e} with no service id`);jh(`Received ACK from IPC service ${e}. Marking as running.`);let r=e;t&&e&&e!==t&&(Xl(e,t),r=t);let s=!1;t&&(s=Lc.setServiceStatus(t,"running")),s?Ph({serviceSessionId:t||e,transport:ya.IPC,send:n,extraInfo:{ipcSocketId:t}}):Yl(r,ga.SendManifest)}));!r&&jh(`Received unknown command [${t}] from service ${e}`)};let Uh={};W.platform();const Mh=async e=>{const t=e.args[0];if(Uh.chooseDirectory)try{const n=await Uh.chooseDirectory(t);return e.reply({success:[String(n).trim()]})}catch(t){return console.error(t),e.reply({error:t instanceof Error?t.message:"Unknown error"})}return e.reply({error:"This hub does not support showing file dialogs",errCode:"GUI_NOT_SUPPORTED"})},Fh=async e=>{const t=e.args[0];if(Uh.chooseFile)try{const n=await Uh.chooseFile(t);return e.reply({success:[String(n).trim()]})}catch(t){return console.error(t),e.reply({error:t instanceof Error?t.message:"Unknown error"})}return e.reply({error:"This hub does not support showing file dialogs",errCode:"GUI_NOT_SUPPORTED"})},Rh=e=>{Uh=e};var Wh={},Gh={},Vh={};function Hh(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function zh(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function qh(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function Kh(e,...t){if(!qh(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function Jh(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");Hh(e.outputLen),Hh(e.blockLen)}function Yh(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Xh(e,t){Kh(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}Object.defineProperty(Vh,"__esModule",{value:!0}),Vh.output=Vh.exists=Vh.hash=Vh.bytes=Vh.bool=Vh.number=Vh.isBytes=void 0,Vh.number=Hh,Vh.bool=zh,Vh.isBytes=qh,Vh.bytes=Kh,Vh.hash=Jh,Vh.exists=Yh,Vh.output=Xh;const Zh={number:Hh,bool:zh,bytes:Kh,hash:Jh,exists:Yh,output:Xh};Vh.default=Zh;var Qh={};Object.defineProperty(Qh,"__esModule",{value:!0}),Qh.add5L=Qh.add5H=Qh.add4H=Qh.add4L=Qh.add3H=Qh.add3L=Qh.add=Qh.rotlBL=Qh.rotlBH=Qh.rotlSL=Qh.rotlSH=Qh.rotr32L=Qh.rotr32H=Qh.rotrBL=Qh.rotrBH=Qh.rotrSL=Qh.rotrSH=Qh.shrSL=Qh.shrSH=Qh.toBig=Qh.split=Qh.fromBig=void 0;const ef=BigInt(2**32-1),tf=BigInt(32);function nf(e,t=!1){return t?{h:Number(e&ef),l:Number(e>>tf&ef)}:{h:0|Number(e>>tf&ef),l:0|Number(e&ef)}}function rf(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let s=0;s<e.length;s++){const{h:i,l:o}=nf(e[s],t);[n[s],r[s]]=[i,o]}return[n,r]}Qh.fromBig=nf,Qh.split=rf;const sf=(e,t)=>BigInt(e>>>0)<<tf|BigInt(t>>>0);Qh.toBig=sf;const of=(e,t,n)=>e>>>n;Qh.shrSH=of;const af=(e,t,n)=>e<<32-n|t>>>n;Qh.shrSL=af;const cf=(e,t,n)=>e>>>n|t<<32-n;Qh.rotrSH=cf;const lf=(e,t,n)=>e<<32-n|t>>>n;Qh.rotrSL=lf;const uf=(e,t,n)=>e<<64-n|t>>>n-32;Qh.rotrBH=uf;const df=(e,t,n)=>e>>>n-32|t<<64-n;Qh.rotrBL=df;const pf=(e,t)=>t;Qh.rotr32H=pf;const hf=e=>e;Qh.rotr32L=hf;const ff=(e,t,n)=>e<<n|t>>>32-n;Qh.rotlSH=ff;const gf=(e,t,n)=>t<<n|e>>>32-n;Qh.rotlSL=gf;const mf=(e,t,n)=>t<<n-32|e>>>64-n;Qh.rotlBH=mf;const vf=(e,t,n)=>e<<n-32|t>>>64-n;function yf(e,t,n,r){const s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:0|s}}Qh.rotlBL=vf,Qh.add=yf;const bf=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0);Qh.add3L=bf;const Sf=(e,t,n,r)=>t+n+r+(e/2**32|0)|0;Qh.add3H=Sf;const wf=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0);Qh.add4L=wf;const If=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0;Qh.add4H=If;const _f=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0);Qh.add5L=_f;const $f=(e,t,n,r,s,i)=>t+n+r+s+i+(e/2**32|0)|0;Qh.add5H=$f;const Cf={fromBig:nf,split:rf,toBig:sf,shrSH:of,shrSL:af,rotrSH:cf,rotrSL:lf,rotrBH:uf,rotrBL:df,rotr32H:pf,rotr32L:hf,rotlSH:ff,rotlSL:gf,rotlBH:mf,rotlBL:vf,add:yf,add3L:bf,add3H:Sf,add4L:wf,add4H:If,add5H:$f,add5L:_f};Qh.default=Cf;var kf={},Ef={};Object.defineProperty(Ef,"__esModule",{value:!0}),Ef.crypto=void 0,Ef.crypto="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,function(e){
|
|
2
2
|
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
3
|
-
Object.defineProperty(e,"__esModule",{value:!0}),e.randomBytes=e.wrapXOFConstructorWithOpts=e.wrapConstructorWithOpts=e.wrapConstructor=e.checkOpts=e.Hash=e.concatBytes=e.toBytes=e.utf8ToBytes=e.asyncLoop=e.nextTick=e.hexToBytes=e.bytesToHex=e.byteSwap32=e.byteSwapIfBE=e.byteSwap=e.isLE=e.rotl=e.rotr=e.createView=e.u32=e.u8=e.isBytes=void 0;const t=$f,n=Rh;e.isBytes=function(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name};e.u8=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength);e.u32=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));e.createView=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);e.rotr=(e,t)=>e<<32-t|e>>>t;e.rotl=(e,t)=>e<<t|e>>>32-t>>>0,e.isLE=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0];e.byteSwap=e=>e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255,e.byteSwapIfBE=e.isLE?e=>e:t=>(0,e.byteSwap)(t),e.byteSwap32=function(t){for(let n=0;n<t.length;n++)t[n]=(0,e.byteSwap)(t[n])};const r=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));e.bytesToHex=function(e){(0,n.bytes)(e);let t="";for(let n=0;n<e.length;n++)t+=r[e[n]];return t};const s={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function i(e){return e>=s._0&&e<=s._9?e-s._0:e>=s._A&&e<=s._F?e-(s._A-10):e>=s._a&&e<=s._f?e-(s._a-10):void 0}e.hexToBytes=function(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length,n=t/2;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let t=0,s=0;t<n;t++,s+=2){const n=i(e.charCodeAt(s)),o=i(e.charCodeAt(s+1));if(void 0===n||void 0===o){const t=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+s)}r[t]=16*n+o}return r};function o(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}function a(e){return"string"==typeof e&&(e=o(e)),(0,n.bytes)(e),e}e.nextTick=async()=>{},e.asyncLoop=async function(t,n,r){let s=Date.now();for(let i=0;i<t;i++){r(i);const t=Date.now()-s;t>=0&&t<n||(await(0,e.nextTick)(),s+=t)}},e.utf8ToBytes=o,e.toBytes=a,e.concatBytes=function(...e){let t=0;for(let r=0;r<e.length;r++){const s=e[r];(0,n.bytes)(s),t+=s.length}const r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.length}return r};e.Hash=class{clone(){return this._cloneInto()}};const c={}.toString;e.checkOpts=function(e,t){if(void 0!==t&&"[object Object]"!==c.call(t))throw new Error("Options should be object or undefined");return Object.assign(e,t)},e.wrapConstructor=function(e){const t=t=>e().update(a(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t},e.wrapConstructorWithOpts=function(e){const t=(t,n)=>e(n).update(a(t)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=t=>e(t),t},e.wrapXOFConstructorWithOpts=function(e){const t=(t,n)=>e(n).update(a(t)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=t=>e(t),t},e.randomBytes=function(e=32){if(t.crypto&&"function"==typeof t.crypto.getRandomValues)return t.crypto.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}}(_f),Object.defineProperty(Fh,"__esModule",{value:!0}),Fh.shake256=Fh.shake128=Fh.keccak_512=Fh.keccak_384=Fh.keccak_256=Fh.keccak_224=Fh.sha3_512=Fh.sha3_384=Fh.sha3_256=Fh.sha3_224=Fh.Keccak=Fh.keccakP=void 0;const Cf=Rh,kf=Yh,Ef=_f,xf=[],Af=[],Nf=[],Of=BigInt(0),Lf=BigInt(1),Pf=BigInt(2),Tf=BigInt(7),Bf=BigInt(256),jf=BigInt(113);for(let e=0,t=Lf,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],xf.push(2*(5*r+n)),Af.push((e+1)*(e+2)/2%64);let s=Of;for(let e=0;e<7;e++)t=(t<<Lf^(t>>Tf)*jf)%Bf,t&Pf&&(s^=Lf<<(Lf<<BigInt(e))-Lf);Nf.push(s)}const[Df,Uf]=(0,kf.split)(Nf,!0),Mf=(e,t,n)=>n>32?(0,kf.rotlBH)(e,t,n):(0,kf.rotlSH)(e,t,n),Ff=(e,t,n)=>n>32?(0,kf.rotlBL)(e,t,n):(0,kf.rotlSL)(e,t,n);function Rf(e,t=24){const n=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let t=0;t<10;t++)n[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const r=(t+8)%10,s=(t+2)%10,i=n[s],o=n[s+1],a=Mf(i,o,1)^n[r],c=Ff(i,o,1)^n[r+1];for(let n=0;n<50;n+=10)e[t+n]^=a,e[t+n+1]^=c}let t=e[2],s=e[3];for(let n=0;n<24;n++){const r=Af[n],i=Mf(t,s,r),o=Ff(t,s,r),a=xf[n];t=e[a],s=e[a+1],e[a]=i,e[a+1]=o}for(let t=0;t<50;t+=10){for(let r=0;r<10;r++)n[r]=e[t+r];for(let r=0;r<10;r++)e[t+r]^=~n[(r+2)%10]&n[(r+4)%10]}e[0]^=Df[r],e[1]^=Uf[r]}n.fill(0)}Fh.keccakP=Rf;class Wf extends Ef.Hash{constructor(e,t,n,r=!1,s=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=r,this.rounds=s,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,(0,Cf.number)(n),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=(0,Ef.u32)(this.state)}keccak(){Ef.isLE||(0,Ef.byteSwap32)(this.state32),Rf(this.state32,this.rounds),Ef.isLE||(0,Ef.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,Cf.exists)(this);const{blockLen:t,state:n}=this,r=(e=(0,Ef.toBytes)(e)).length;for(let s=0;s<r;){const i=Math.min(t-this.pos,r-s);for(let t=0;t<i;t++)n[this.pos++]^=e[s++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:r}=this;e[n]^=t,128&t&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){(0,Cf.exists)(this,!1),(0,Cf.bytes)(e),this.finish();const t=this.state,{blockLen:n}=this;for(let r=0,s=e.length;r<s;){this.posOut>=n&&this.keccak();const i=Math.min(n-this.posOut,s-r);e.set(t.subarray(this.posOut,this.posOut+i),r),this.posOut+=i,r+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return(0,Cf.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,Cf.output)(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:r,rounds:s,enableXOF:i}=this;return e||(e=new Wf(t,n,r,i,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=n,e.outputLen=r,e.enableXOF=i,e.destroyed=this.destroyed,e}}Fh.Keccak=Wf;const Gf=(e,t,n)=>(0,Ef.wrapConstructor)((()=>new Wf(t,e,n)));Fh.sha3_224=Gf(6,144,28),Fh.sha3_256=Gf(6,136,32),Fh.sha3_384=Gf(6,104,48),Fh.sha3_512=Gf(6,72,64),Fh.keccak_224=Gf(1,144,28),Fh.keccak_256=Gf(1,136,32),Fh.keccak_384=Gf(1,104,48),Fh.keccak_512=Gf(1,72,64);const Vf=(e,t,n)=>(0,Ef.wrapXOFConstructorWithOpts)(((r={})=>new Wf(t,e,void 0===r.dkLen?n:r.dkLen,!0)));Fh.shake128=Vf(31,168,16),Fh.shake256=Vf(31,136,32);const{sha3_512:Hf}=Fh,zf=(e=4,t=Math.random)=>{let n="";for(;n.length<e;)n+=Math.floor(36*t()).toString(36);return n};function qf(e){let t=0n;for(const n of e.values()){t=(t<<8n)+BigInt(n)}return t}const Kf=(e="")=>qf(Hf(e)).toString(36).slice(1),Jf=Array.from({length:26},((e,t)=>String.fromCharCode(t+97))),Yf=({globalObj:e=(void 0!==La?La:"undefined"!=typeof window?window:{}),random:t=Math.random}={})=>{const n=Object.keys(e).toString(),r=n.length?n+zf(32,t):zf(32,t);return Kf(r).substring(0,32)},Xf=e=>()=>e++,Zf=({random:e=Math.random,counter:t=Xf(Math.floor(476782367*e())),length:n=24,fingerprint:r=Yf({random:e})}={})=>function(){const s=(e=>Jf[Math.floor(e()*Jf.length)])(e),i=Date.now().toString(36),o=t().toString(36),a=zf(n,e);return`${s+Kf(`${i+a+o+r}`).substring(1,n)}`},Qf=Zf();Mh.getConstants=()=>({defaultLength:24,bigLength:32}),Mh.init=Zf,Mh.createId=Qf,Mh.bufToBigInt=qf,Mh.createCounter=Xf,Mh.createFingerprint=Yf,Mh.isCuid=(e,{minLength:t=2,maxLength:n=32}={})=>{const r=e.length,s=/^[0-9a-z]+$/;try{if("string"==typeof e&&r>=t&&r<=n&&s.test(e))return!0}finally{}return!1};const{createId:eg,init:tg,getConstants:ng,isCuid:rg}=Mh;var sg=eg;const ig=Xa("getUniqueId"),og=({reply:e,sourceServiceId:t})=>{ig(`Generating unique id for service "${t}"`);return e({success:[sg()]})},ag=Xa("getActiveServices"),cg=async({transport:e,sourceServiceId:t,reply:n})=>{if(ag(`Received GetServices request from ${e} [${t}]`),e===ga.WS){let e=Nc.getActiveServices();const r=kh(t);if(!r)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});let s=[];if(r.transport===ga.WS){if(!r?.extraInfo.wsApiKey)return n({error:"Client does not have an API key",errCode:"CLIENT_NO_API_KEY"});const t=e.filter(Nc.isInternalKemuService),i=e.filter((e=>e.devMode&&Nc.isNotInternalKemuService(e))),o=e.filter((e=>Nc.isOfficialKemuService(e)&&Nc.isNotInternalKemuService(e)&&Nc.isNotDevService(e))).sort(((e,t)=>e.name.localeCompare(t.name))),a=await(async e=>{const{features:t}=await wh(e);return t})(r.extraInfo.wsApiKey),c=a?.hub_services??0,l=o.slice(0,c);s=o.slice(c).map((e=>({name:e.name,version:e.version,svgIcon:e.svgIcon,color:e.color,description:e.description,title:e.title,shortTitle:e.shortTitle}))),e=[...t,...i,...l]}const i=Nc.getFailedServices().map((e=>({name:e.name,version:e.version,description:e.description,title:e.title,status:e.status,errorMsg:e.errorMsg,errorCode:e.errorCode,internal:Nc.isInternalKemuService(e),svgIcon:e.svgIcon,color:e.color,shortTitle:e.shortTitle})));n({success:[{available:e.map((e=>{const{widgetUIContents:t,...n}=e;return{...n}})),failed:i,installed:s}]})}},lg=h(M(import.meta.url)),ug=Xa("hub"),dg=new function(e){const t={};let n=console.log;const r={};let s=e||String(Date.now());const i={},o=e=>!i[e],a=(e,t,n,r,s,i)=>{let a=fl?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:i.success?i.success:[i],messageId:t,type:i.success?"response":"error"}};return o(r)&&(a=Zl.encode(c,n,r)),s(a,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{n=e},processMessage:(e,s,i,o)=>{if(!o)return!1;const c=o;if(t[c.messageId]){const e=t[c.messageId];return e&&(clearTimeout(e.timer),e.fulfilled||(e.fulfilled=!0,"response"===c.type?e.resolve(c.args):"error"===c.type&&e.reject(c.args[0])),delete t[c.messageId]),!0}if("execute"!==c.type&&n&&n(`No pending execution found for message id "${c.messageId}"`),"execute"===c.type){const t=r[c.functionName];if(t){const n=e=>{a(c.functionName,c.messageId,i.targetServiceId,i.sourceServiceId,s,e)};t({transport:e,args:c.args,reply:n,messageId:c.messageId,sourceServiceId:i.sourceServiceId,send:s})}else{const e=`Function "${c.functionName}" not found.`;n&&n(e),a(c.functionName,c.messageId,i.targetServiceId,i.sourceServiceId,s,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(e,r,i,a,c,l)=>{if(!i){const e="No send buffer function provided.";throw n&&n(e),e}Ql+=1;const u=`${s}-${Ql}-exec-${e.substring(0,10)}`,d={messageId:u,functionName:e,send:i,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};d.promise=new Promise(((e,t)=>{d.resolve=e,d.reject=t}));let p=fl?new ArrayBuffer(0):Buffer.alloc(0);const h={json:{functionName:e,args:r,messageId:u,type:"execute"}};o(c)&&(p=Zl.encode(h,a,c)),t[u]=d,n&&n(`Calling remote function "${e}" with message id "${u}"`);const f="true"===process.env.NO_INVOKE_TIMEOUT;return l?.async?(d.fulfilled=!0,d.resolve([void 0]),delete t[u]):0===l?.timeout||f||(d.timer=setTimeout((()=>{n&&n(`Remote function ${u} timed out`);const r=t[u];r&&!r.fulfilled&&(r.fulfilled=!0,d.reject(`Function ${e} Timed out`)),delete t[u]}),l?.timeout||3e4)),i(p,{sourceServiceId:a,targetServiceId:c,msg:h}),d.promise},sendResponse:a,registerFunction:(e,t)=>{r[e]=t},getTransportSendFunction:e=>{const n=t[e];return n?n.send:null},setServiceName:e=>{s=e},getPendingExecutions:()=>t,rejectAllPending:e=>{Object.keys(t).forEach((n=>{const r=t[n];r&&!r.fulfilled&&(clearTimeout(r.timer),r.fulfilled=!0,r.reject(e),delete t[n])}))},broadcast:(e,t,r,i)=>{Ql+=1;const a=`${s}-${Ql}-multicast-${e.substring(0,10)}`;let c=fl?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:t,messageId:a,type:"execute"}};let u=o(r[0].serviceId);u&&(c=Zl.encode(l,i,r[0].serviceId));for(let t=0;t<r.length;t++)try{const s=r[t];n&&n(`Broadcasting function "${e}" with message id "${a}" to client [${s.serviceId}]`),0!==t&&(u=o(s.serviceId),u&&(c=Zl.patchEncodedHeader(c,{toServiceId:s.serviceId}))),s.sendFn(c,{msg:l,sourceServiceId:i,targetServiceId:s.serviceId})}catch(e){n&&n(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{i[e]=t}}}("hub");dg.setLogger(ug);const pg=(e,t)=>{const{transmission:n}=t;if(0!==n.targetServiceId){const r=kh(n.targetServiceId);if(!r)return ug(`Service [${e}] ${n.sourceServiceId} is sending data to an unknown service ["${n.targetServiceId}"]`),!0;r.transport,ga.IPC;const s=t.json?.messageId;return ug(`Forwarding message from ${n.sourceServiceId} to ${n.targetServiceId}, msgId: ${s}`),r.send(n.rawMessage,{sourceServiceId:n.sourceServiceId,targetServiceId:n.targetServiceId,msg:{json:t.json}}),!0}return!1},hg=({sourceServiceId:e,args:t})=>{const n=Nc.getServiceBySessionId(e);if(n){const r=Eh(n.info.name,n.info.version),s=Eh(n.info.name,"*");if(!r.length&&!s.length)return;const i=[...r,...s],o=t[0],a={outputs:o.outputs,variantId:o.variantId,source:{serviceName:n.info.name,serviceVersion:n.info.version,sessionId:e}};dg.broadcast(ha.BroadcastEvent,[a],i,0)}},fg=e=>{const{send:t,transmission:n,json:r}=e;ug(`Raw message Id received from WS: ${r?.messageId}`);pg(ga.WS,e)||dg.processMessage(ga.WS,t,n,r)},gg=e=>{const t=(n=e,`${pa.SocketAcknowledge}${n}`);var n;Qp.sendCommand(e,t)},mg=(e,t)=>{ug(`Received unknown command [${t}] from service ${e}`)},vg=async e=>{const{args:t,sourceServiceId:n,send:r,reply:s}=e,{apiKey:i}=t[0],o=n;await Ah({serviceSessionId:n,transport:ga.WS,send:r,terminateFn:()=>{Qp.terminateConnection(n)},extraInfo:{websocketId:o,wsApiKey:i}}),s({success:[]})},yg=e=>{ug(`WS Client ${e} disconnected`),Lh(e)},bg=async({sourceServiceId:e,args:t,transport:n,send:r})=>{if(n!==ga.IPC){var s;ug(`Received manifest from non IPC service ${e}.`)}else{const n=t[0];if(n.devMode){const t=Nc.getMatchingDevService(n.name,n.version,"stopped");if(t){ug(`Found matching previous service ${t.info.name} (${t.info.version}). Reactivating previous client with session id ${t.info.sessionId}`);const i=kh(t.info.sessionId);if(!i)return void ug(`Could not find previous client instance for ${t.info.name} (${t.info.version}). Aborting manifest injection`);i.send=r,_h[s=e]?delete _h[s]:Ih(`Could not find source client with session id ${s}`),Kl(e,t.info.sessionId);const o=await cc(n,n.path);t.info={...t.info,...o},ug(`Updating manifest for dev service ${t.info.sessionId}`),Nc.setServiceManifest(t.info.sessionId,o,"running"),ug(`Asking service ${e} to assume previous session id ${t.info.sessionId}`),ql(t.info.sessionId,(e=>`${pa.AssumeSession}${e}`)(t.info.sessionId)),(e=>{const t=_h[e];t?t.isDevClient?(t.disconnected=!1,t.transport===ga.IPC&&(xh(),Oh(e))):Ih(`Client with session id ${e} is not a dev client`):Ih(`Could not find source client with session id ${e}`)})(t.info.sessionId)}else{Nc.addDevService(e,n,"running");const t=kh(e);t?t.isDevClient=!0:Ah({serviceSessionId:e,transport:ga.IPC,send:r,extraInfo:{ipcSocketId:e},isDevClient:!0})}return}ug(`Received manifest from non dev service ${e} [${n.name}@(${n.version})]. Ignoring...`)}};var Sg=async e=>{ug("Starting Kemu Hub...");const t=e?.ipc?.appSpace||"kemu.",n=e?.ipc?.id||"widgets";if(!e.serviceUrl)throw new Error("Missing service url, please set the `apiUrl` option or the `KEMU_API_URL` environment variable.");var r;r=e.serviceUrl,yh=r,dg.registerFunction(ha.GetServiceContents,vh),dg.registerFunction(ha.GetServices,cg),dg.registerFunction(ha.ShowSecretsConfigScreen,(async({args:t,reply:n})=>{const[{name:r,version:s}]=t;e?.onShowSecretsScreen?(await e.onShowSecretsScreen(r,s),n({success:[]})):n({error:"This hub does not support showing secrets configuration screens",errCode:"GUI_NOT_SUPPORTED"})})),dg.registerFunction(ha.UnsubscribeFromService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===ga.WS){const[e]=n,s=kh(r);if(!s)return t({error:`Session id "${r}" not found`});ug(`Service ${r} unsubscribing from "${e.targetService.serviceName} (${e.targetService.version})"`),t({success:[]}),s?.removeSubscription({serviceName:e.targetService.serviceName,version:e.targetService.version})}})),dg.registerFunction(ha.SubscribeToService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===ga.WS){const[e]=n,s=kh(r),i=e.targetService;if(!s)return t({error:`Session id "${r}" not found`});if(ug(`Service ${r} subscribing to "${i.serviceName} (${i.version})"`),"hub"===i.serviceName)return s.addSubscription(i),void t({success:[]});if(!s.addSubscription(i))return ug(`Service ${r} already subscribed to "${i.serviceName} (${i.version})", ignoring request.`),t({success:[]});const o=Nc.getMatchingService(i.serviceName,i.version);if(!o)return ug(`Service ${i.serviceName} ${i.version} not active yet`),t({success:[]});if(!o.info.eventEmitter)return ug(`Service ${i.serviceName} ${i.version} does not have an event emitter, removing subscription`),s.removeSubscription(i),t({error:`Service "${i.serviceName} (${i.version})" does not produce events`});const a=kh(o.info.sessionId);return a?.extraInfo.ipcSocketId&&(ug(`Sending Broadcast START command to service ${o.info.sessionId}`),ql(a?.extraInfo.ipcSocketId,pa.BroadcastStart)),t({success:[]})}})),dg.registerFunction("stopService",th),dg.registerFunction("removeService",rh),dg.registerFunction("launchService",ih),dg.registerFunction("getMatchingServices",ah),dg.registerFunction("getSecretsValues",uh),dg.registerFunction(ha.GetMappedSecrets,fh),dg.registerFunction(ha.BroadcastEvent,hg),dg.registerFunction(ha.ServiceManifest,bg),dg.registerFunction(ha.ChooseDirectoryDialog,jh),dg.registerFunction(ha.ChooseFileDialog,Dh),dg.registerFunction(ha.GetUniqueId,og),dg.registerFunction(ha.SocketAckResponse,vg),zl((e=>{const{send:t,transmission:n,json:r}=e;ug(`Raw message Id received from IPC: ${r?.messageId}`);pg(ga.IPC,e)||dg.processMessage(ga.IPC,t,n,r)})),Qp.onMessageReceived(fg),Qp.onClientConnected(gg),Qp.onClientCommand(mg),Qp.onClientDisconnected(yg),Jl(Th),Vl((e=>{const t=(e=>`${pa.IpcAcknowledge}${e}`)(e);ql(e,t)})),Hl((e=>{ug(`IPC socket [${e}] disconnected`);const t=kh(e);if(t){ug(`Found matching service for disconnected socket. SessionId: ${t.serviceSessionId}`);const e=Nc.getServiceBySessionId(t.serviceSessionId);Nc.setServiceStatus(t.serviceSessionId,"stopped"),e?.devMode?(t.disconnected=!0,xh()):Lh(t.serviceSessionId)}})),await Gl({ipcAppSpace:t,ipcId:n}),e?.ws?.disabled||await Qp.startServer(e?.ws?.port||5368);const s=e?.defaultServicesPath||d.resolve(lg,"defaultServices"),i=process.env.DEV_SESSION_ID;Nc.setHubIpcConfig({recipePath:e?.recipeRootPath,appSpace:t,id:n}),e?.servicesInstallPath&&(e=>{uc=e})(e.servicesInstallPath),e?.testServicesInstallPath&&(e=>{dc=e})(e.testServicesInstallPath);const o=pc(),a=dc||nc,c=async({requiredSecrets:e})=>{const t=Object.keys(e).reduce(((e,t)=>({...e,[t]:process.env[t]})),{});return t.__KEMU_USER_SERVICES_PATH=o,t.__KEMU_USER_TEST_SERVICES_PATH=a,t},l=async e=>e.reduce(((e,t)=>({...e,[t.name]:[]})),{});e?.getServiceSecretsFn?(Nc.setGetSecretsFunction(e.getServiceSecretsFn),dh(e.getServiceSecretsFn)):(Nc.setGetSecretsFunction(c),dh(c)),gh(e?.getMappedSecretsFn?e.getMappedSecretsFn:l),Nc.setSpawnNodeFunction(e?.spawnFn?e.spawnFn:({args:e,options:t})=>{const n={...process.env};return R("node",e||[],{...t,env:{...n,...t?.env}})}),e?.noDefaultServices||await Nc.loadServices(s,{fixedSession:i?parseInt(i):void 0,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,internalServices:!0}),null!==e?.servicesInstallPath&&(await lc(o)||await g(o,{recursive:!0}),await Nc.loadServices(o,{internalServices:!1,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME}));const u=process.env.DEV_NO_SPAWN_LIST?.split(",");await Nc.launchServices({noSpawningList:u||[]}),ug("Kemu Hub started"),(e?.onChooseDirectory||e?.onChooseFile)&&Uh({chooseDirectory:e.onChooseDirectory,chooseFile:e.onChooseFile})},wg=e=>{if(e===ga.WS)return{handleWebsocketConnectionEvent:gg,handleWebsocketClientDisconnectionEvent:yg,handleWebsocketMessage:fg,handleWebsocketClientCommand:mg,getRemoteInvoke:()=>dg}},Ig=(e=[])=>{let t;const n=new Promise((n=>{const r=()=>{if(Nc.getAllServices().every((e=>"running"===e.status))){if(e.every((e=>"running"===Nc.getMatchingService(e.name,e.version)?.status)))return n()}t=setTimeout(r,100)};r()}));return n.abort=()=>{t&&clearTimeout(t)},n};let _g;const $g=yo("run"),Cg=ya(),kg=1e3,Eg=w(process.argv.slice(2));global.ImageData=H,Bt({createCanvas:(e,t)=>q(e,t)});const xg={createImageDataLike:(e,t,n,r="srgb")=>{let s;return s=e instanceof Uint8ClampedArray?e:new Uint8ClampedArray(e),{data:s,width:t,height:n,colorSpace:r,_kemuType:le.ImageData}},loadImageFile:async e=>{const t=await z(e),n=q(t.width,t.height).getContext("2d");n.drawImage(t,0,0,t.width,t.height);return n.getImageData(0,0,t.width,t.height)}};var Ag={start:async r=>{const s=r?.recipePath||Eg.recipePath||process.env.KEMU_EDGE_RECIPE_PATH;if(!s)throw new Error("`recipePath` not provided. Please specify it in the config object, via a command line argument [--recipePath] or as an environment variable [KEMU_EDGE_RECIPE_PATH].");if(e({path:W(G(s),".env")}),!r.apiKey)throw new Error("`apiKey` not provided. Please specify it in the config object with the `apiKey` property.");const i=s.endsWith(".json"),o=i?V(s):s,a=i?s:W(o,"recipe.json"),c=(e=>{try{return JSON.parse(e||"")}catch(e){return null}})(await t(G(a),"utf-8"));if(!c)throw new Error("Failed to parse recipe file");await Fs();const l={id:c.id||String(Date.now()),version:1,author:""};(e=>{mr=e})(console);const u=wg(ge.WS),d=(e,t)=>{if(t)u?.handleWebsocketMessage({send:h,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg?.json});else{const t=e instanceof Buffer?e.toString():e;u?.handleWebsocketClientCommand(kg,t)}},p=(so={instanceServiceId:kg,sendBuf:d,sendCmd:d,triggerOnCommand:(...e)=>io(...e),triggerOnConnected:()=>oo(),triggerOnDisconnected:()=>ao(),triggerOnMessageReceived:(...e)=>co(...e)},so);const h=(e,t)=>{if(t)p.triggerOnMessageReceived({send:d,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg.json});else{const t=e instanceof Buffer?e.toString():e;p.triggerOnCommand(t)}},f=Sa(),g=u.getRemoteInvoke();f.disableServiceEncoding(0,!0),g.disableServiceEncoding(kg,!0);const m=Object.values(c.blocks[ae].gates).filter((e=>e.type===De.hubService&&e.state.service&&!0!==e.state.service?.webOnly)),v=m.map((e=>{const t=e.state.service;return{name:t.name,version:t.version}})),y=W(o,"services"),b=await n(y).then((()=>!0)).catch((()=>!1));await Sg({recipeRootPath:o,servicesInstallPath:b?W(o,"services"):null,noDefaultServices:!0,ws:{disabled:!0},serviceUrl:process.env.KEMU_API_URL,ipc:{appSpace:"kemu-runner.",id:l.id}}),$g("Waiting for services to run"),await Ig(v),$g("All services are running"),Ni(Cg);const S=await Ei(c,"runner",l.version,l.author,mi.Desktop);return _g=S,ba(S),await ma(r.apiKey),new Promise(((e,t)=>{var n;va("acknowledged",(async()=>{await Cg.getServices();const{failed:n,sendToInputWidget:r,invokeRecipeLoadedWidgets:s}=await Ai(S);if(n.length>0){const e=`Some widgets failed to initialize: ${n.join(", ")}`;return t(e)}await s().catch((e=>{console.error("Error invoking recipe loaded widgets: ",e)})),$g("Recipe started"),e({sendToInputWidget:r})})),p.triggerOnConnected(),p.triggerOnCommand((n=kg,`${pe.SocketAcknowledge}${n}`))}))},terminate:async()=>{_g&&await xi(_g)}};void 0===typeof process.env.BLOCKS_INSTALL_DIR&&console.warn("Missing `BLOCKS_INSTALL_DIR` env var");process.env.BLOCKS_INSTALL_DIR;export{le as DataType,Ag as default,xg as utils};
|
|
3
|
+
Object.defineProperty(e,"__esModule",{value:!0}),e.randomBytes=e.wrapXOFConstructorWithOpts=e.wrapConstructorWithOpts=e.wrapConstructor=e.checkOpts=e.Hash=e.concatBytes=e.toBytes=e.utf8ToBytes=e.asyncLoop=e.nextTick=e.hexToBytes=e.bytesToHex=e.byteSwap32=e.byteSwapIfBE=e.byteSwap=e.isLE=e.rotl=e.rotr=e.createView=e.u32=e.u8=e.isBytes=void 0;const t=Ef,n=Vh;e.isBytes=function(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name};e.u8=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength);e.u32=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));e.createView=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);e.rotr=(e,t)=>e<<32-t|e>>>t;e.rotl=(e,t)=>e<<t|e>>>32-t>>>0,e.isLE=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0];e.byteSwap=e=>e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255,e.byteSwapIfBE=e.isLE?e=>e:t=>(0,e.byteSwap)(t),e.byteSwap32=function(t){for(let n=0;n<t.length;n++)t[n]=(0,e.byteSwap)(t[n])};const r=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));e.bytesToHex=function(e){(0,n.bytes)(e);let t="";for(let n=0;n<e.length;n++)t+=r[e[n]];return t};const s={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function i(e){return e>=s._0&&e<=s._9?e-s._0:e>=s._A&&e<=s._F?e-(s._A-10):e>=s._a&&e<=s._f?e-(s._a-10):void 0}e.hexToBytes=function(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length,n=t/2;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let t=0,s=0;t<n;t++,s+=2){const n=i(e.charCodeAt(s)),o=i(e.charCodeAt(s+1));if(void 0===n||void 0===o){const t=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+s)}r[t]=16*n+o}return r};function o(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}function a(e){return"string"==typeof e&&(e=o(e)),(0,n.bytes)(e),e}e.nextTick=async()=>{},e.asyncLoop=async function(t,n,r){let s=Date.now();for(let i=0;i<t;i++){r(i);const t=Date.now()-s;t>=0&&t<n||(await(0,e.nextTick)(),s+=t)}},e.utf8ToBytes=o,e.toBytes=a,e.concatBytes=function(...e){let t=0;for(let r=0;r<e.length;r++){const s=e[r];(0,n.bytes)(s),t+=s.length}const r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.length}return r};e.Hash=class{clone(){return this._cloneInto()}};const c={}.toString;e.checkOpts=function(e,t){if(void 0!==t&&"[object Object]"!==c.call(t))throw new Error("Options should be object or undefined");return Object.assign(e,t)},e.wrapConstructor=function(e){const t=t=>e().update(a(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t},e.wrapConstructorWithOpts=function(e){const t=(t,n)=>e(n).update(a(t)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=t=>e(t),t},e.wrapXOFConstructorWithOpts=function(e){const t=(t,n)=>e(n).update(a(t)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=t=>e(t),t},e.randomBytes=function(e=32){if(t.crypto&&"function"==typeof t.crypto.getRandomValues)return t.crypto.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}}(kf),Object.defineProperty(Gh,"__esModule",{value:!0}),Gh.shake256=Gh.shake128=Gh.keccak_512=Gh.keccak_384=Gh.keccak_256=Gh.keccak_224=Gh.sha3_512=Gh.sha3_384=Gh.sha3_256=Gh.sha3_224=Gh.Keccak=Gh.keccakP=void 0;const xf=Vh,Af=Qh,Nf=kf,Of=[],Pf=[],Lf=[],Tf=BigInt(0),Bf=BigInt(1),jf=BigInt(2),Df=BigInt(7),Uf=BigInt(256),Mf=BigInt(113);for(let e=0,t=Bf,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],Of.push(2*(5*r+n)),Pf.push((e+1)*(e+2)/2%64);let s=Tf;for(let e=0;e<7;e++)t=(t<<Bf^(t>>Df)*Mf)%Uf,t&jf&&(s^=Bf<<(Bf<<BigInt(e))-Bf);Lf.push(s)}const[Ff,Rf]=(0,Af.split)(Lf,!0),Wf=(e,t,n)=>n>32?(0,Af.rotlBH)(e,t,n):(0,Af.rotlSH)(e,t,n),Gf=(e,t,n)=>n>32?(0,Af.rotlBL)(e,t,n):(0,Af.rotlSL)(e,t,n);function Vf(e,t=24){const n=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let t=0;t<10;t++)n[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const r=(t+8)%10,s=(t+2)%10,i=n[s],o=n[s+1],a=Wf(i,o,1)^n[r],c=Gf(i,o,1)^n[r+1];for(let n=0;n<50;n+=10)e[t+n]^=a,e[t+n+1]^=c}let t=e[2],s=e[3];for(let n=0;n<24;n++){const r=Pf[n],i=Wf(t,s,r),o=Gf(t,s,r),a=Of[n];t=e[a],s=e[a+1],e[a]=i,e[a+1]=o}for(let t=0;t<50;t+=10){for(let r=0;r<10;r++)n[r]=e[t+r];for(let r=0;r<10;r++)e[t+r]^=~n[(r+2)%10]&n[(r+4)%10]}e[0]^=Ff[r],e[1]^=Rf[r]}n.fill(0)}Gh.keccakP=Vf;class Hf extends Nf.Hash{constructor(e,t,n,r=!1,s=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=r,this.rounds=s,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,(0,xf.number)(n),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=(0,Nf.u32)(this.state)}keccak(){Nf.isLE||(0,Nf.byteSwap32)(this.state32),Vf(this.state32,this.rounds),Nf.isLE||(0,Nf.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,xf.exists)(this);const{blockLen:t,state:n}=this,r=(e=(0,Nf.toBytes)(e)).length;for(let s=0;s<r;){const i=Math.min(t-this.pos,r-s);for(let t=0;t<i;t++)n[this.pos++]^=e[s++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:r}=this;e[n]^=t,128&t&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){(0,xf.exists)(this,!1),(0,xf.bytes)(e),this.finish();const t=this.state,{blockLen:n}=this;for(let r=0,s=e.length;r<s;){this.posOut>=n&&this.keccak();const i=Math.min(n-this.posOut,s-r);e.set(t.subarray(this.posOut,this.posOut+i),r),this.posOut+=i,r+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return(0,xf.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,xf.output)(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:r,rounds:s,enableXOF:i}=this;return e||(e=new Hf(t,n,r,i,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=n,e.outputLen=r,e.enableXOF=i,e.destroyed=this.destroyed,e}}Gh.Keccak=Hf;const zf=(e,t,n)=>(0,Nf.wrapConstructor)((()=>new Hf(t,e,n)));Gh.sha3_224=zf(6,144,28),Gh.sha3_256=zf(6,136,32),Gh.sha3_384=zf(6,104,48),Gh.sha3_512=zf(6,72,64),Gh.keccak_224=zf(1,144,28),Gh.keccak_256=zf(1,136,32),Gh.keccak_384=zf(1,104,48),Gh.keccak_512=zf(1,72,64);const qf=(e,t,n)=>(0,Nf.wrapXOFConstructorWithOpts)(((r={})=>new Hf(t,e,void 0===r.dkLen?n:r.dkLen,!0)));Gh.shake128=qf(31,168,16),Gh.shake256=qf(31,136,32);const{sha3_512:Kf}=Gh,Jf=(e=4,t=Math.random)=>{let n="";for(;n.length<e;)n+=Math.floor(36*t()).toString(36);return n};function Yf(e){let t=0n;for(const n of e.values()){t=(t<<8n)+BigInt(n)}return t}const Xf=(e="")=>Yf(Kf(e)).toString(36).slice(1),Zf=Array.from({length:26},((e,t)=>String.fromCharCode(t+97))),Qf=({globalObj:e=(void 0!==Ba?Ba:"undefined"!=typeof window?window:{}),random:t=Math.random}={})=>{const n=Object.keys(e).toString(),r=n.length?n+Jf(32,t):Jf(32,t);return Xf(r).substring(0,32)},eg=e=>()=>e++,tg=({random:e=Math.random,counter:t=eg(Math.floor(476782367*e())),length:n=24,fingerprint:r=Qf({random:e})}={})=>function(){const s=(e=>Zf[Math.floor(e()*Zf.length)])(e),i=Date.now().toString(36),o=t().toString(36),a=Jf(n,e);return`${s+Xf(`${i+a+o+r}`).substring(1,n)}`},ng=tg();Wh.getConstants=()=>({defaultLength:24,bigLength:32}),Wh.init=tg,Wh.createId=ng,Wh.bufToBigInt=Yf,Wh.createCounter=eg,Wh.createFingerprint=Qf,Wh.isCuid=(e,{minLength:t=2,maxLength:n=32}={})=>{const r=e.length,s=/^[0-9a-z]+$/;try{if("string"==typeof e&&r>=t&&r<=n&&s.test(e))return!0}finally{}return!1};const{createId:rg,init:sg,getConstants:ig,isCuid:og}=Wh;var ag=rg;const cg=ec("getUniqueId"),lg=({reply:e,sourceServiceId:t})=>{cg(`Generating unique id for service "${t}"`);return e({success:[ag()]})},ug=ec("getActiveServices"),dg=async({transport:e,sourceServiceId:t,reply:n})=>{if(ug(`Received GetServices request from ${e} [${t}]`),e===ya.WS){let e=Lc.getActiveServices();const r=Ah(t);if(!r)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});let s=[];if(r.transport===ya.WS){if(!r?.extraInfo.wsApiKey)return n({error:"Client does not have an API key",errCode:"CLIENT_NO_API_KEY"});const t=e.filter(Lc.isInternalKemuService),i=e.filter((e=>e.devMode&&Lc.isNotInternalKemuService(e))),o=e.filter((e=>Lc.isOfficialKemuService(e)&&Lc.isNotInternalKemuService(e)&&Lc.isNotDevService(e))).sort(((e,t)=>e.name.localeCompare(t.name))),a=await(async e=>{const{features:t}=await $h(e);return t})(r.extraInfo.wsApiKey),c=a?.hub_services??0,l=o.slice(0,c);s=o.slice(c).map((e=>({name:e.name,version:e.version,svgIcon:e.svgIcon,color:e.color,description:e.description,title:e.title,shortTitle:e.shortTitle}))),e=[...t,...i,...l]}const i=Lc.getFailedServices().map((e=>({name:e.name,version:e.version,description:e.description,title:e.title,status:e.status,errorMsg:e.errorMsg,errorCode:e.errorCode,internal:Lc.isInternalKemuService(e),svgIcon:e.svgIcon,color:e.color,shortTitle:e.shortTitle})));n({success:[{available:e.map((e=>{const{widgetUIContents:t,...n}=e;return{...n}})),failed:i,installed:s}]})}},pg=v(R(import.meta.url)),hg=ec("hub"),fg=new function(e){const t={};let n=console.log;const r={};let s=e||String(Date.now());const i={},o=e=>!i[e],a=(e,t,n,r,s,i)=>{let a=vl?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:i.success?i.success:[i],messageId:t,type:i.success?"response":"error"}};return o(r)&&(a=tu.encode(c,n,r)),s(a,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{n=e},processMessage:(e,s,i,o)=>{if(!o)return!1;const c=o;if(t[c.messageId]){const e=t[c.messageId];return e&&(clearTimeout(e.timer),e.fulfilled||(e.fulfilled=!0,"response"===c.type?e.resolve(c.args):"error"===c.type&&e.reject(c.args[0])),delete t[c.messageId]),!0}if("execute"!==c.type&&n&&n(`No pending execution found for message id "${c.messageId}"`),"execute"===c.type){const t=r[c.functionName];if(t){const n=e=>{a(c.functionName,c.messageId,i.targetServiceId,i.sourceServiceId,s,e)};t({transport:e,args:c.args,reply:n,messageId:c.messageId,sourceServiceId:i.sourceServiceId,send:s})}else{const e=`Function "${c.functionName}" not found.`;n&&n(e),a(c.functionName,c.messageId,i.targetServiceId,i.sourceServiceId,s,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(e,r,i,a,c,l)=>{if(!i){const e="No send buffer function provided.";throw n&&n(e),e}nu+=1;const u=`${s}-${nu}-exec-${e.substring(0,10)}`,d={messageId:u,functionName:e,send:i,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};d.promise=new Promise(((e,t)=>{d.resolve=e,d.reject=t}));let p=vl?new ArrayBuffer(0):Buffer.alloc(0);const h={json:{functionName:e,args:r,messageId:u,type:"execute"}};o(c)&&(p=tu.encode(h,a,c)),t[u]=d,n&&n(`Calling remote function "${e}" with message id "${u}"`);const f="true"===process.env.NO_INVOKE_TIMEOUT;return l?.async?(d.fulfilled=!0,d.resolve([void 0]),delete t[u]):0===l?.timeout||f||(d.timer=setTimeout((()=>{n&&n(`Remote function ${u} timed out`);const r=t[u];r&&!r.fulfilled&&(r.fulfilled=!0,d.reject(`Function ${e} Timed out`)),delete t[u]}),l?.timeout||3e4)),i(p,{sourceServiceId:a,targetServiceId:c,msg:h}),d.promise},sendResponse:a,registerFunction:(e,t)=>{r[e]=t},getTransportSendFunction:e=>{const n=t[e];return n?n.send:null},setServiceName:e=>{s=e},getPendingExecutions:()=>t,rejectAllPending:e=>{Object.keys(t).forEach((n=>{const r=t[n];r&&!r.fulfilled&&(clearTimeout(r.timer),r.fulfilled=!0,r.reject(e),delete t[n])}))},broadcast:(e,t,r,i)=>{nu+=1;const a=`${s}-${nu}-multicast-${e.substring(0,10)}`;let c=vl?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:t,messageId:a,type:"execute"}};let u=o(r[0].serviceId);u&&(c=tu.encode(l,i,r[0].serviceId));for(let t=0;t<r.length;t++)try{const s=r[t];n&&n(`Broadcasting function "${e}" with message id "${a}" to client [${s.serviceId}]`),0!==t&&(u=o(s.serviceId),u&&(c=tu.patchEncodedHeader(c,{toServiceId:s.serviceId}))),s.sendFn(c,{msg:l,sourceServiceId:i,targetServiceId:s.serviceId})}catch(e){n&&n(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{i[e]=t}}}("hub");fg.setLogger(hg);const gg=(e,t)=>{const{transmission:n}=t;if(0!==n.targetServiceId){const r=Ah(n.targetServiceId);if(!r)return hg(`Service [${e}] ${n.sourceServiceId} is sending data to an unknown service ["${n.targetServiceId}"]`),!0;r.transport,ya.IPC;const s=t.json?.messageId;return hg(`Forwarding message from ${n.sourceServiceId} to ${n.targetServiceId}, msgId: ${s}`),r.send(n.rawMessage,{sourceServiceId:n.sourceServiceId,targetServiceId:n.targetServiceId,msg:{json:t.json}}),!0}return!1},mg=({sourceServiceId:e,args:t})=>{const n=Lc.getServiceBySessionId(e);if(n){const r=Nh(n.info.name,n.info.version),s=Nh(n.info.name,"*");if(!r.length&&!s.length)return;const i=[...r,...s],o=t[0],a={outputs:o.outputs,variantId:o.variantId,source:{serviceName:n.info.name,serviceVersion:n.info.version,sessionId:e}};fg.broadcast(ma.BroadcastEvent,[a],i,0)}},vg=e=>{const{send:t,transmission:n,json:r}=e;hg(`Raw message Id received from WS: ${r?.messageId}`);gg(ya.WS,e)||fg.processMessage(ya.WS,t,n,r)},yg=e=>{const t=(n=e,`${ga.SocketAcknowledge}${n}`);var n;nh.sendCommand(e,t)},bg=(e,t)=>{hg(`Received unknown command [${t}] from service ${e}`)},Sg=async e=>{const{args:t,sourceServiceId:n,send:r,reply:s}=e,{apiKey:i}=t[0],o=n;await Ph({serviceSessionId:n,transport:ya.WS,send:r,terminateFn:()=>{nh.terminateConnection(n)},extraInfo:{websocketId:o,wsApiKey:i}}),s({success:[]})},wg=e=>{hg(`WS Client ${e} disconnected`),Bh(e)},Ig=async({sourceServiceId:e,args:t,transport:n,send:r})=>{if(n!==ya.IPC){var s;hg(`Received manifest from non IPC service ${e}.`)}else{const n=t[0];if(n.devMode){const t=Lc.getMatchingDevService(n.name,n.version,"stopped");if(t){hg(`Found matching previous service ${t.info.name} (${t.info.version}). Reactivating previous client with session id ${t.info.sessionId}`);const i=Ah(t.info.sessionId);if(!i)return void hg(`Could not find previous client instance for ${t.info.name} (${t.info.version}). Aborting manifest injection`);i.send=r,kh[s=e]?delete kh[s]:Ch(`Could not find source client with session id ${s}`),Xl(e,t.info.sessionId);const o=await dc(n,n.path);t.info={...t.info,...o},hg(`Updating manifest for dev service ${t.info.sessionId}`),Lc.setServiceManifest(t.info.sessionId,o,"running"),hg(`Asking service ${e} to assume previous session id ${t.info.sessionId}`),Yl(t.info.sessionId,(e=>`${ga.AssumeSession}${e}`)(t.info.sessionId)),(e=>{const t=kh[e];t?t.isDevClient?(t.disconnected=!1,t.transport===ya.IPC&&(Oh(),Th(e))):Ch(`Client with session id ${e} is not a dev client`):Ch(`Could not find source client with session id ${e}`)})(t.info.sessionId)}else{Lc.addDevService(e,n,"running");const t=Ah(e);t?t.isDevClient=!0:Ph({serviceSessionId:e,transport:ya.IPC,send:r,extraInfo:{ipcSocketId:e},isDevClient:!0})}return}hg(`Received manifest from non dev service ${e} [${n.name}@(${n.version})]. Ignoring...`)}};var _g=async e=>{hg("Starting Kemu Hub...");const t=e?.ipc?.appSpace||"kemu.",n=e?.ipc?.id||"widgets";if(!e.serviceUrl)throw new Error("Missing service url, please set the `apiUrl` option.");const r=e.serviceUrl;wh=r,fg.registerFunction(ma.GetServiceContents,Sh),fg.registerFunction(ma.GetServices,dg),fg.registerFunction(ma.ShowSecretsConfigScreen,(async({args:t,reply:n})=>{const[{name:r,version:s}]=t;e?.onShowSecretsScreen?(await e.onShowSecretsScreen(r,s),n({success:[]})):n({error:"This hub does not support showing secrets configuration screens",errCode:"GUI_NOT_SUPPORTED"})})),fg.registerFunction(ma.UnsubscribeFromService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===ya.WS){const[e]=n,s=Ah(r);if(!s)return t({error:`Session id "${r}" not found`});hg(`Service ${r} unsubscribing from "${e.targetService.serviceName} (${e.targetService.version})"`),t({success:[]}),s?.removeSubscription({serviceName:e.targetService.serviceName,version:e.targetService.version})}})),fg.registerFunction(ma.SubscribeToService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===ya.WS){const[e]=n,s=Ah(r),i=e.targetService;if(!s)return t({error:`Session id "${r}" not found`});if(hg(`Service ${r} subscribing to "${i.serviceName} (${i.version})"`),"hub"===i.serviceName)return s.addSubscription(i),void t({success:[]});if(!s.addSubscription(i))return hg(`Service ${r} already subscribed to "${i.serviceName} (${i.version})", ignoring request.`),t({success:[]});const o=Lc.getMatchingService(i.serviceName,i.version);if(!o)return hg(`Service ${i.serviceName} ${i.version} not active yet`),t({success:[]});if(!o.info.eventEmitter)return hg(`Service ${i.serviceName} ${i.version} does not have an event emitter, removing subscription`),s.removeSubscription(i),t({error:`Service "${i.serviceName} (${i.version})" does not produce events`});const a=Ah(o.info.sessionId);return a?.extraInfo.ipcSocketId&&(hg(`Sending Broadcast START command to service ${o.info.sessionId}`),Yl(a?.extraInfo.ipcSocketId,ga.BroadcastStart)),t({success:[]})}})),fg.registerFunction("stopService",sh),fg.registerFunction("removeService",oh),fg.registerFunction("launchService",ch),fg.registerFunction("getMatchingServices",uh),fg.registerFunction("getSecretsValues",hh),fg.registerFunction(ma.GetMappedSecrets,vh),fg.registerFunction(ma.BroadcastEvent,mg),fg.registerFunction(ma.ServiceManifest,Ig),fg.registerFunction(ma.ChooseDirectoryDialog,Mh),fg.registerFunction(ma.ChooseFileDialog,Fh),fg.registerFunction(ma.GetUniqueId,lg),fg.registerFunction(ma.SocketAckResponse,Sg),Jl((e=>{const{send:t,transmission:n,json:r}=e;hg(`Raw message Id received from IPC: ${r?.messageId}`);gg(ya.IPC,e)||fg.processMessage(ya.IPC,t,n,r)})),nh.onMessageReceived(vg),nh.onClientConnected(yg),nh.onClientCommand(bg),nh.onClientDisconnected(wg),Zl(Dh),ql((e=>{const t=(e=>`${ga.IpcAcknowledge}${e}`)(e);Yl(e,t)})),Kl((e=>{hg(`IPC socket [${e}] disconnected`);const t=Ah(e);if(t){hg(`Found matching service for disconnected socket. SessionId: ${t.serviceSessionId}`);const e=Lc.getServiceBySessionId(t.serviceSessionId);Lc.setServiceStatus(t.serviceSessionId,"stopped"),e?.devMode?(t.disconnected=!0,Oh()):Bh(t.serviceSessionId)}})),await zl({ipcAppSpace:t,ipcId:n}),e?.ws?.disabled||await nh.startServer(e?.ws?.port||5368);const s=e?.defaultServicesPath||g.resolve(pg,"defaultServices"),i=process.env.DEV_SESSION_ID;Lc.setHubIpcConfig({recipePath:e?.recipeRootPath,appSpace:t,id:n}),e?.servicesInstallPath&&(e=>{hc=e})(e.servicesInstallPath),e?.testServicesInstallPath&&(e=>{fc=e})(e.testServicesInstallPath);const o=gc(),a=fc||ic,c=async({requiredSecrets:e})=>{const t=Object.keys(e).reduce(((e,t)=>({...e,[t]:process.env[t]})),{});return t.__KEMU_USER_SERVICES_PATH=o,t.__KEMU_USER_TEST_SERVICES_PATH=a,t.__KEMU_SERVICE_URL=r,t},l=async e=>e.reduce(((e,t)=>({...e,[t.name]:[]})),{});e?.getServiceSecretsFn?(Lc.setGetSecretsFunction(e.getServiceSecretsFn),fh(e.getServiceSecretsFn)):(Lc.setGetSecretsFunction(c),fh(c)),yh(e?.getMappedSecretsFn?e.getMappedSecretsFn:l),Lc.setSpawnNodeFunction(e?.spawnFn?e.spawnFn:({args:e,options:t})=>{const n={...process.env};return G("node",e||[],{...t,env:{...n,...t?.env}})}),e?.noDefaultServices||await Lc.loadServices(s,{fixedSession:i?parseInt(i):void 0,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,internalServices:!0}),null!==e?.servicesInstallPath&&(await pc(o)||await b(o,{recursive:!0}),await Lc.loadServices(o,{internalServices:!1,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME}));const u=process.env.DEV_NO_SPAWN_LIST?.split(",");await Lc.launchServices({noSpawningList:u||[]}),hg("Kemu Hub started"),(e?.onChooseDirectory||e?.onChooseFile)&&Rh({chooseDirectory:e.onChooseDirectory,chooseFile:e.onChooseFile})},$g=e=>{if(e===ya.WS)return{handleWebsocketConnectionEvent:yg,handleWebsocketClientDisconnectionEvent:wg,handleWebsocketMessage:vg,handleWebsocketClientCommand:bg,getRemoteInvoke:()=>fg}},Cg=(e=[])=>{let t;const n=new Promise((n=>{const r=()=>{if(Lc.getAllServices().every((e=>"running"===e.status))){if(e.every((e=>"running"===Lc.getMatchingService(e.name,e.version)?.status)))return n()}t=setTimeout(r,100)};r()}));return n.abort=()=>{t&&clearTimeout(t)},n};let kg;const Eg=wo("run"),xg=wa(),Ag=1e3,Ng=C(process.argv.slice(2));global.ImageData=q,Dt({createCanvas:(e,t)=>J(e,t)});const Og={createImageDataLike:(e,t,n,r="srgb")=>{let s;return s=e instanceof Uint8ClampedArray?e:new Uint8ClampedArray(e),{data:s,width:t,height:n,colorSpace:r,_kemuType:de.ImageData}},loadImageFile:async e=>{const t=await K(e),n=J(t.width,t.height).getContext("2d");n.drawImage(t,0,0,t.width,t.height);return n.getImageData(0,0,t.width,t.height)}};var Pg={start:async r=>{r=r||{};const s=r?.recipePath||Ng.recipePath||process.env.KEMU_EDGE_RECIPE_PATH||process.cwd();if(!s)throw new Error("`recipePath` not provided. Please specify it in the config object, via a command line argument [--recipePath] or as an environment variable [KEMU_EDGE_RECIPE_PATH].");e({path:V(H(s),".env")});const i=r.apiKey||process.env.KEMU_API_KEY;if(!i)throw new Error("Missing API key. Please provide it via config.apiKey or KEMU_API_KEY environment variable.");const o=s.endsWith(".json"),a=o?z(s):s,c=o?s:V(a,"recipe.json"),l=(e=>{try{return JSON.parse(e||"")}catch(e){return null}})(await t(H(c),"utf-8"));if(!l)throw new Error("Failed to parse recipe file");const{serviceUrl:u,apiKey:d}=((e,t)=>{const n=ji(e,t),r=Buffer.from(n,"base64").toString("utf8"),[s,i]=r.split("<@>");if(!s||!i)throw new Error("Invalid API key.");return{serviceUrl:s,apiKey:i}})(l,i);await Ws();const p={id:l.id||String(Date.now()),version:1,author:""};(e=>{yr=e})(console);const h=$g(ve.WS),f=(e,t)=>{if(t)h?.handleWebsocketMessage({send:m,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg?.json});else{const t=e instanceof Buffer?e.toString():e;h?.handleWebsocketClientCommand(Ag,t)}},g=(ao={instanceServiceId:Ag,sendBuf:f,sendCmd:f,triggerOnCommand:(...e)=>co(...e),triggerOnConnected:()=>lo(),triggerOnDisconnected:()=>uo(),triggerOnMessageReceived:(...e)=>po(...e)},ao);const m=(e,t)=>{if(t)g.triggerOnMessageReceived({send:f,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg.json});else{const t=e instanceof Buffer?e.toString():e;g.triggerOnCommand(t)}},v=_a(),y=h.getRemoteInvoke();v.disableServiceEncoding(0,!0),y.disableServiceEncoding(Ag,!0);const b=Object.values(l.blocks[le].gates).filter((e=>e.type===Me.hubService&&e.state.service&&!0!==e.state.service?.webOnly)),S=b.map((e=>{const t=e.state.service;return{name:t.name,version:t.version}})),w=V(a,"services"),I=await n(w).then((()=>!0)).catch((()=>!1));await _g({recipeRootPath:a,servicesInstallPath:I?V(a,"services"):null,noDefaultServices:!0,ws:{disabled:!0},serviceUrl:u,ipc:{appSpace:"kemu-runner.",id:p.id}}),Eg("Waiting for services to run"),await Cg(S),Eg("All services are running"),Pi(xg);const _=await Ai(l,"runner",p.version,p.author,yi.Desktop);return kg=_,Ia(_),await ba(d),new Promise(((e,t)=>{var n;Sa("acknowledged",(async()=>{await xg.getServices();const{failed:n,sendToInputWidget:r,invokeRecipeLoadedWidgets:s}=await Oi(_);if(n.length>0){const e=`Some widgets failed to initialize: ${n.join(", ")}`;return t(e)}await s().catch((e=>{console.error("Error invoking recipe loaded widgets: ",e)})),Eg("Recipe started"),e({sendToInputWidget:r})})),g.triggerOnConnected(),g.triggerOnCommand((n=Ag,`${fe.SocketAcknowledge}${n}`))}))},terminate:async()=>{kg&&await Ni(kg)}};void 0===typeof process.env.BLOCKS_INSTALL_DIR&&console.warn("Missing `BLOCKS_INSTALL_DIR` env var");process.env.BLOCKS_INSTALL_DIR;export{de as DataType,Pg as default,Og as utils};
|