@kemu-io/edge-runtime 1.2.5 → 1.3.0
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 +3 -1
- package/runner.js +11 -2
package/runner.js
CHANGED
|
@@ -1,3 +1,12 @@
|
|
|
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 i from"jsonp";import s from"crypto-js";import o from"emittery";import"axios";import a from"jszip";import c from"util";import l from"mustache";import d,{scryptSync as u,createDecipheriv as p,createHash as g}from"crypto";import{satisfies as h}from"compare-versions";import f from"debug";import m,{join as y,dirname as v,resolve as b}from"path";import"node-ipc";import{mkdir as S,readFile as w,access as I,constants as _,readdir as $,rm as C}from"fs/promises";import k from"minimist";import E from"tty";import x,{homedir as A}from"os";import N from"net";import P from"tls";import O,{promises as T}from"fs";import L from"dgram";import B from"stream";import D from"zlib";import j from"buffer";import U from"events";import R from"https";import F from"http";import M,{fileURLToPath as W}from"url";import G from"node:os";import{spawn as V}from"child_process";import{join as H,resolve as z,dirname as q}from"node:path";import{ImageData as K,loadImage as J,createCanvas as Y}from"@napi-rs/canvas";var X;!function(e){e.STARTING="STARTING",e.PENDING="PENDING",e.RUNNING="RUNNING",e.PAUSED="PAUSED",e.DRAINING="DRAINING",e.STOPPED="STOPPED",e.ERROR="ERROR"}(X=X||(X={}));const Z="undefined"!=typeof window&&void 0!==window.document&&void 0!==typeof window.document.createElement,Q="object"==typeof self&&self.constructor&&"DedicatedWorkerGlobalScope"===self.constructor.name,ee="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node,te={};let ne=0,re="";const ie=e=>te[e]?te[e]:null,se=(e,t)=>{const n=ie(e);if(!n)return n;return n.blocks[t]||null},oe=(e,t,n)=>{const r=se(e,t);if(!r)return r;return r.gates[n]},ae=(e,t)=>{let n=r(4);for(;te[n];)n=r(4);const i=(s=e,JSON.parse(JSON.stringify(s)));var s;return i.logs="",i.addLog=e=>{i.logs+=`${(()=>{const e=Date.now();if(e!==ne){const t=new Date;ne=e,re=t.toJSON()}return re})()}:: ${e}\n`},i.dbInfo={...t},te[n]=i,n},ce="interrupt_port",le="main.js",de="state.json",ue="{#}",pe="UI:",ge="default";var he,fe,me,ye,ve,be,Se,we;let Ie;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(he||(he={})),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"}(fe||(fe={})),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"}(me||(me={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(ye||(ye={})),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:"}(ve||(ve={})),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.GetSystemInfo="getSystemInfo",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.UninstallService="uninstallService",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.GetUniqueId="getUniqueId",e.RebootToInstallUpdate="rebootToInstallUpdate",e.GetFileContentFromCacheId="getFileContentFromCacheId",e.GetDecryptedEdgeApiKey="getDecryptedEdgeApiKey"}(be||(be={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(Se||(Se={})),function(e){e.IPC="ipc",e.WS="ws"}(we||(we={}));const _e=()=>{if(!Ie)throw new Error("CanvasManager not set");return Ie},$e=e=>{Ie=e},Ce=(e,t)=>_e().createCanvas(e,t),ke=e=>Z?e.getContext("2d",{willReadFrequently:!0}):e.getContext("2d"),Ee=e=>_e().loadImage(e),xe="-",Ae=`inner${xe}`,Ne=`outer${xe}`,Pe=`${Ne}input${xe}`,Oe=`${Ne}output${xe}`,Te=`${Ae}input${xe}`,Le=`${Ae}output${xe}`,Be=e=>(new TextEncoder).encode(e),De=e=>e===ce,je=e=>e&&void 0!==e.width&&void 0!==e.height&&void 0!==e.data&&e.data.constructor&&"Uint8ClampedArray"===e.data.constructor.name,Ue=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,Re=e=>e&&"number"==typeof e.x&&"number"==typeof e.y,Fe=e=>"number"==typeof e?fe.Number:"string"==typeof e?fe.String:"boolean"==typeof e?fe.Boolean:Array.isArray(e)?fe.Array:je(e)?fe.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?fe.AudioBuffer:e&&void 0!==e.byteLength?fe.ArrayBuffer:Ue(e)?fe.Rect:e&&void 0!==e.x&&void 0!==e.y&&"number"==typeof e.x&&"number"==typeof e.y?fe.Point:(e=>e&&"string"==typeof e.format&&e.data&&e.data instanceof ArrayBuffer)(e)?fe.BinaryFile:fe.JsonObj,Me=e=>{const t={};let n;n=Array.isArray(e)?e[0]:e;for(const e in n){const r=Fe(n[e]);t[e]=r}return t},We=(e,t,n)=>"inner"===e?"input"===t?`${Te}${n}`:`${Le}${n}`:"input"===t?`${Pe}${n}`:`${Oe}${n}`,Ge=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]}},Ve=async e=>{try{return new ImageData(e.data,e.width,e.height,{colorSpace:e.colorSpace})}catch(t){console.warn("Failed to create ImageData from info, assuming raw image data",t);return await Ee(e.data)}};var He,ze;!function(e){e.Action="action",e.CustomInput="customInput"}(He=He||(He={})),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",e.note="note",e.stringify="stringify",e.templateString="templateString",e.expressionEval="expressionEval",e.rescue="rescue",e.objectCombine="objectCombine",e.loop="loop"}(ze=ze||(ze={}));const qe={};let Ke;const Je=async e=>{const t=qe[e],n={name:ce,type:fe.Boolean};if(t){const r={name:t.portName},i=t.data||{type:fe.Boolean,value:!0};Ke?(await Ke(!0,t.targetWidgetId,t.thingId,t.recipePoolId,n.name,r,{...i,timestamp:Date.now()},[n]),"timeout"===t.type&&Ye(e)):console.warn("Interrupt service has not been initialized")}},Ye=e=>{const t=qe[e];return!!t&&(t.timerRef&&("interval"===t.type?clearInterval(t.timerRef):"timeout"===t.type&&clearTimeout(t.timerRef)),delete qe[e],!0)};var Xe={interruptHandler:Je,createInterrupt:(e,t,n,i,s,o,a,c)=>{if(c&&qe[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(qe[l]={data:a,portName:s,recipePoolId:t,targetWidgetId:i,thingId:n,type:e},"interval"===e)qe[l].timerRef=setInterval((async()=>await Je(l)),o.interval);else{if("timeout"!==e)throw new Error(`Invalid interrupt type '${e}'`);qe[l].timerRef=setTimeout((async()=>await Je(l)),o.timeout)}return l},destroyInterrupt:Ye,destroyAllInterrupts:()=>{Object.keys(qe).forEach(Ye)},setInvokeChildGateCb:e=>{Ke=e}};const Ze=[10001,"Invalid `sourcePort` parameter"],Qe=[10002,"The gate [%s] does not exist. Have you called `loadWidgets` yet?"],et=[10110,"No storage medium has been loaded, call `loadMedium()` first"],tt=(e,...t)=>JSON.stringify({code:e[0],message:t[0]?c.format(e[1],...t):e[1].replace(/ \[%s\]/g,"")}),nt=()=>({inputName:"",dataType:fe.Anything}),rt="output",it={processEvent:async(e,t)=>{const n=t.getState(),r={...nt(),...n};if(e.type===r.dataType||r.dataType===fe.Anything)return t.nextWidget(rt,{type:e.type,value:e.value});console.error(`Invalid data type: ${e.type} for input: ${r.inputName}. Expected: ${r.dataType}`)},getOutputNames:e=>{const t={...nt(),...e};return[{name:rt,type:t.dataType}]},getInputNames:()=>[]},st=Object.freeze({in:"in",reset:"reset",increment:"increment"}),ot="output";var at={onParentEvent:async(e,t,n,r)=>{if(!e)throw new Error(tt(Ze));const i={currentValue:0,increment:1,...r.getState()};let s=i.increment,o=i.currentValue;const a=await r.getParentAtPort(st.increment);if(t.name===st.increment)return void(n.data.type===fe.Number&&r.setState({...i,increment:Number(n.data.value)}));if(a){const e=a.getValue();null!==e&&(s=e)}if(t.name===st.reset)return r.setState({...i,currentValue:0});o+=s,r.setState({currentValue:o,increment:s});const c={type:fe.Number,value:o};return r.nextGate(ot,c)},getInputNames:()=>[{name:st.in,type:fe.Anything},{name:st.reset,type:fe.Anything},{name:st.increment,type:fe.Number}],getOutputNames:()=>[{name:ot,type:fe.Number}]};const ct=Object.freeze({in:"in",reset:"reset"}),lt="output";var dt={onParentEvent:async(e,t,n,r)=>{const i={updatedAt:0,elapsed:0,...r.getState()},s=Date.now(),o=s-(i.updatedAt||s);return t.name===ct.reset?r.setState({...i,updatedAt:s,elapsed:0}):(r.setState({updatedAt:s,elapsed:o}),r.nextGate(lt,{type:fe.Number,value:o}))},getInputNames:()=>[{name:ct.in,type:fe.Anything},{name:ct.reset,type:fe.Anything}],getOutputNames:()=>[{name:lt,type:fe.Number}]};const ut=Object.freeze({data:"data",evaluation:"evaluation"}),pt="then",gt="else";var ht={onParentEvent:async(e,t,n,r)=>{const i={value:5,condition:"Equal",useDataPort:!1,...r.getState()},s=n.data.value,o=!isNaN(Number(s)),a="string"==typeof s;if(!i.useDataPort&&(n.data.type===fe.Number||n.data.type===fe.String||n.data.type===fe.Boolean||n.data.type===fe.Anything&&o||n.data.type===fe.Anything&&a)){let e=!1;return("Equal"===i.condition&&(n.data.value==i.value||n.data.type===fe.Boolean&&n.data.value.toString()===i.value.toString())||"Not Equal"===i.condition&&(n.data.value!==i.value||n.data.type===fe.Boolean&&n.data.value!==i.value.toString())||"Greater"===i.condition&&n.data.type===fe.Number&&n.data.value>Number(i.value)||"Less"===i.condition&&n.data.type===fe.Number&&n.data.value<Number(i.value)||"Starts With"===i.condition&&String(n.data.value).startsWith(String(i.value))||"Ends With"===i.condition&&String(n.data.value).endsWith(String(i.value))||"Includes"===i.condition&&String(n.data.value).includes(String(i.value))||"Matches"===i.condition&&String(n.data.value).match(String(i.value)))&&(e=!0),e?r.nextGate(pt,n.data):r.nextGate(gt,n.data)}if(t.name===ut.evaluation&&(n.data.type===fe.Number||n.data.type===fe.String||n.data.type===fe.Boolean||n.data.type===fe.Anything&&(o||a))&&(i.$lastValue=n.data.value,i.$lastInputDataType=n.data.type,r.setState({...i})),t.name===ut.data){let e=!1;return("Equal"===i.condition&&(i.$lastValue==i.value||i.$lastInputDataType===fe.Boolean&&i.$lastValue?.toString()===i.value.toString())||"Not Equal"===i.condition&&(i.$lastValue!==i.value||i.$lastInputDataType===fe.Boolean&&i.$lastValue!==i.value.toString())||"Greater"===i.condition&&i.$lastInputDataType===fe.Number&&Number(i.$lastValue)>Number(i.value)||"Less"===i.condition&&i.$lastInputDataType===fe.Number&&Number(i.$lastValue)<Number(i.value)||"Starts With"===i.condition&&String(i.$lastValue).startsWith(String(i.value))||"Ends With"===i.condition&&String(i.$lastValue).endsWith(String(i.value))||"Includes"===i.condition&&String(i.$lastValue).includes(String(i.value))||"Matches"===i.condition&&String(i.$lastValue).match(String(i.value)))&&(e=!0),r.setState({...i,$lastValue:void 0,$lastInputDataType:void 0}),e?r.nextGate(pt,n.data):r.nextGate(gt,n.data)}},getInputNames:e=>e.useDataPort?[{name:ut.data,type:fe.Anything,triggerPort:!0},{name:ut.evaluation,type:[fe.Number,fe.String,fe.Boolean]}]:[{name:"in",type:[fe.Number,fe.String,fe.Boolean]}],getOutputNames:e=>e.$lastOutputDataType?[{name:pt,type:e.$lastOutputDataType},{name:gt,type:e.$lastOutputDataType}]:[{name:pt,type:[fe.Number,fe.String]},{name:gt,type:[fe.Number,fe.String]}]};const ft=Object.freeze({in:"in",reset:"reset"}),mt="out";var yt={onParentEvent:async(e,t,n,r)=>{const i={totalCalls:0,callsLimit:1,...r.getState()};return t.name===ft.reset?r.setState({...i,totalCalls:0}):(i.totalCalls=i.totalCalls+1,i.totalCalls>i.callsLimit?(i.totalCalls=0,r.setState(i),r.nextGate(mt,n.data)):void r.setState(i))},getInputNames:()=>[{name:ft.in,type:fe.Anything},{name:ft.reset,type:fe.Anything}],getOutputNames:()=>[{name:mt,type:fe.Anything}]};const vt=Object.freeze({in:"in"}),bt="then",St="else";var wt={onParentEvent:async(e,t,n,r)=>{const i={min:1,max:10,...r.getState()};if(n.data.type===fe.Number)return n.data.value>=i.min&&n.data.value<=i.max?r.nextGate(bt,n.data):r.nextGate(St,n.data)},getInputNames:()=>[{name:vt.in,type:fe.Number}],getOutputNames:()=>[{name:bt,type:fe.Number},{name:St,type:fe.Number}]};const It=Object.freeze({in:"in"}),_t="out";var $t={onParentEvent:async(e,t,n,r)=>{const i={clamp:!0,...r.getState()},s=Number(n.data.value);if(void 0!==i.fromMax&&void 0!==i.fromMin&&void 0!==i.toMax&&void 0!==i.toMin&&""!==i.fromMax&&""!==i.fromMin&&""!==i.toMax&&""!==i.toMin&&(n.data.type===fe.Number||n.data.type===fe.Anything&&!isNaN(Number(s)))){let e=((e,t,n,r,i)=>(e-t)*(i-r)/(n-t)+r)(s,Number(i.fromMin),Number(i.fromMax),Number(i.toMin),Number(i.toMax));if(isNaN(e))return;return i.clamp&&(e<Number(i.toMin)&&(e=Number(i.toMin)),e>Number(i.toMax)&&(e=Number(i.toMax))),r.nextGate(_t,{type:fe.Number,value:Number(e)})}},getInputNames:()=>[{name:It.in,type:fe.Number}],getOutputNames:()=>[{name:_t,type:fe.Number}]};const Ct=Object.freeze({in:"in"}),kt="out";var Et={onParentEvent:async(e,t,n,r)=>{const i={convertTo:"Integer",floatPlaces:2,...r.getState()};let s=n.data.value;if(n.data.type===fe.Number||n.data.type===fe.Anything||n.data.type===fe.String){if((!isNaN(Number(s))||"string"==typeof s)&&!Array.isArray(s))return"Integer"===i.convertTo?s=parseInt(s):"Decimal"===i.convertTo?s=parseFloat(Number(s).toFixed(i.floatPlaces)):"String"===i.convertTo?s=String(s):"Abs"===i.convertTo?s=Math.abs(Number(s)):"Round"===i.convertTo&&(s=Math.round(Number(s))),r.nextGate(kt,{type:"String"===i.convertTo?fe.String:fe.Number,value:s})}},getInputNames:()=>[{name:Ct.in,type:fe.Number}],getOutputNames:e=>{const t="String"===e?.convertTo?fe.String:fe.Number;return[{name:kt,type:t}]}};const xt=Object.freeze({in:"in"}),At="out";var Nt={onParentEvent:async(e,t,n,r)=>{const i={currentValue:50,min:0,max:100,...r.getState()};let s=!1;return i.currentValue<i.min&&(i.currentValue=i.min,s=!0),i.currentValue>i.max&&(i.currentValue=i.max,s=!0),s&&r.setState(i),r.nextWidget(At,{type:fe.Number,value:i.currentValue})},getInputNames:()=>[{name:xt.in,type:fe.Anything}],getOutputNames:()=>[{name:At,type:fe.Number}]};const Pt=Object.freeze({in:"in",reset:"reset"}),Ot="out";var Tt={onParentEvent:async(e,t,n,r)=>{const i={lastCalledAt:0,delayMs:500},s={lastCalledAt:0,delayMs:500,...r.getState()};if(t.name===Pt.reset)return r.setState({...s,lastCalledAt:0});const o=Date.now(),a=o-s.lastCalledAt;return s.lastCalledAt===i.lastCalledAt||a>=s.delayMs&&s.delayMs>0?(s.lastCalledAt=o,r.setState(s),r.nextGate(Ot,n.data)):void 0},getInputNames:()=>[{name:Pt.in,type:fe.Anything},{name:Pt.reset,type:fe.Anything}],getOutputNames:()=>[{name:Ot,type:fe.Anything}]};const Lt="in";var Bt={onParentEvent:async()=>{},getInputNames:()=>[{name:Lt,type:[fe.ImageData,fe.Number]}],getOutputNames:()=>[]};const Dt=()=>({properties:[{label:"property1",name:"property1"}],detectedProperties:{}}),jt=(e,t)=>t.split(".").reduce(((e,t)=>null!=e?e[t]:e),e);var Ut={onParentEvent:async(e,t,n,r)=>{const i={properties:[{label:"property1",name:"property1"}],detectedProperties:{},...r.getState()},s=n?.data?.value,o=Array.isArray(s);if(n.data.type===fe.JsonObj||n.data.type===fe.Rect||n.data.type===fe.Point||n.data.type===fe.BinaryFile||n.data.type===fe.Anything||o){let e=!1;for(const t in s){const n=Fe(s[t]),r=!!i.detectedProperties[t],o=i.detectedProperties[t]?.type!==n;if(!r||o){const r=n===fe.JsonObj||n===fe.Rect||n===fe.Point||n===fe.Array;i.detectedProperties[t]={type:n,...r?{shape:Me(s[t])}:void 0},e=!0}}if(o&&void 0===i.detectedProperties.length&&(i.detectedProperties.length={type:fe.Number}),e&&r.setState(i),s){const e=[];for(const t of i.properties||[]){const n=jt(s,t.label),o=t.label.includes(".");if(void 0!==n){const s=o?Fe(n):void 0!==i.detectedProperties[t.label]?.type?i.detectedProperties[t.label].type:fe.Anything;e.push(r.nextGate(t.name,{type:s,value:n}))}}await Promise.allSettled(e)}}},getInputNames:()=>[{name:"in",type:fe.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:fe.Anything,r=t.detectedProperties[e.label]?.shape||void 0,i="string"==typeof e;return{name:i?e:e.name,label:i?e:e.label,type:n,jsonShape:r}}))},getDefaultState:Dt};const Rt="output",Ft="noItem";var Mt={onParentEvent:async(e,t,n,r)=>{const i={index:0,...r.getState()};let s=i.index;const o=n.data.value,a="string"==typeof n.data.value,c=Array.isArray(n.data.value);if(n.data.type===fe.Anything&&(c||a)||n.data.type===fe.String&&a||n.data.type===fe.Array&&c){s<0&&(s=o.length+s);const e=a?fe.String:Fe(o[s]);return e!==i.$$lastDetectedType&&r.setState({...i,$$lastDetectedType:e}),void 0!==o[s]?r.nextGate(Rt,{value:o[s],type:e}):r.nextGate(Ft,{value:!0,type:fe.Boolean})}},getInputNames:()=>[{name:"in",type:[fe.Array,fe.String]}],getOutputNames:e=>[{name:Rt,type:e.$$lastDetectedType??fe.Anything},{name:Ft,type:fe.Boolean}]};const Wt={},Gt=e=>(Wt[e]||(Wt[e]={canvasFrom:Ce(320,240),canvasTo:Ce(320,240)}),Wt[e]),Vt=Object.freeze({image:"image",rect:"rect"}),Ht="image";var zt={onParentEvent:async(e,t,n,r)=>{const i=Gt(r.id),s={offset:{height:0,left:0,top:0,width:0},...r.getState()},o=[fe.Anything,fe.Rect,fe.JsonObj];if(t.name===Vt.rect&&Ue(n.data.value)&&o.includes(n.data.type)&&(s.rect=n.data.value,r.setState({...s})),t.name===Vt.image){if(!((n.data.type===fe.ImageData||n.data.type===fe.Anything)&&je(n.data.value)))throw new Error("Invalid image data. Expected a valid ImageData type");i.lastImage=n.data.value}if(i.lastImage&&s.rect){const e=((e,t,n,r,i)=>{if(r&&r.getContext){const s=r.getContext("2d"),o=n.getContext("2d");if(s&&o){n.width=e.width,n.height=e.height,o.putImageData(e,0,0);const a={...i};i&&(a.height=Number(i.height),a.width=Number(i.width),a.left=Number(i.left),a.top=Number(i.top));const c={top:0,width:0,left:0,height:0,...a};return i&&(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,s.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),s.getImageData(0,0,r.width||1,r.height||1)}}return e})(i.lastImage,s.rect,i.canvasFrom,i.canvasTo,s.offset);r.setState({...s,rect:null}),i.lastImage=void 0,await r.nextWidget(Ht,{type:fe.ImageData,value:e})}},getInputNames:()=>[{name:Vt.image,type:fe.ImageData},{name:Vt.rect,type:[fe.Rect,fe.JsonObj]}],getOutputNames:()=>[{name:Ht,type:fe.ImageData}],initialize:async e=>{Gt(e.widgetId)},terminate:async e=>{delete Wt[e.widgetId]}};const qt=(e,t)=>{const n=Math.round(Math.sqrt(t.length)),r=Math.floor(n/2),i=e.data,s=e.width,o=e.height,a=s,c=o,l=((e,t,n)=>{if(Z)return new ImageData(t,n);return console.warn("Node environment detected. Aborting new ImageData creation"),e})(e,a,c),d=l.data;for(let e=0;e<c;e++)for(let c=0;c<a;c++){const l=e,u=c,p=4*(e*a+c);let g=0,h=0,f=0,m=0;for(let e=0;e<n;e++)for(let a=0;a<n;a++){const c=l+e-r,d=u+a-r;if(c>=0&&c<o&&d>=0&&d<s){const r=4*(c*s+d),o=t[e*n+a];g+=i[r]*o,h+=i[r+1]*o,f+=i[r+2]*o,m+=i[r+3]*o}}d[p]=g,d[p+1]=h,d[p+2]=f,d[p+3]=m+1*(255-m)}return l},Kt=[-1,0,1,-2,0,2,1,0,1],Jt=Object.freeze({image:"image"}),Yt="image";var Xt={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={matrix:[...Kt],...i};if(n.data.type===fe.ImageData||n.data.type===fe.Anything&&je(n.data.value)){const e=qt(n.data.value,s.matrix);return r.nextGate(Yt,{type:fe.ImageData,value:e})}},getInputNames:()=>[{name:Jt.image,type:fe.ImageData}],getOutputNames:()=>[{name:Yt,type:fe.ImageData}]};const Zt=Object.freeze({output:"output",aborted:"aborted"}),Qt=()=>({inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0}),en=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:fe.Anything})));return n.push({name:"reset",type:fe.Anything}),n};var tn={onParentEvent:async(e,t,n,r)=>{const i={inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0,...r.getState()};if("reset"===t.name)return r.setState({...i,triggeredAt:0});const s=Date.now(),o=s-i.triggeredAt;if(i.triggeredAt&&!(o>=i.delayMs&&i.delayMs>0)&&i.delayMs)return r.nextGate(Zt.aborted,n.data);{i.triggeredAt=s;const e=en(i,(r.recipePoolId,r.recipeType,r.thingRecipeId,r.id)).findIndex((e=>e.name===t.name));-1!==e&&(i.lastInputIndex=e),i.matchingOutputs?-1!==e&&await r.nextGate(`output${e+1}`,n.data):await r.nextGate(Zt.output,n.data),r.setState(i)}},getInputNames:en,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:fe.Anything})));return e.push({name:Zt.aborted,type:fe.Anything}),e}return[{name:Zt.output,type:fe.Anything},{name:Zt.aborted,type:fe.Anything}]},getDefaultState:Qt};const nn=(e,t,n,r,i,s)=>{if(i){const o=e.measureText(i),a=o.fontBoundingBoxAscent+o.fontBoundingBoxDescent;e.fillStyle=r,e.fillRect(t,n-s,1.1*o.width,a),e.font=`${s}px Arial`,e.fillStyle="black",e.fillText(i,t,n)}},rn=(e,t,n,r,i,s,o)=>{e.fillStyle=i,e.fillRect(t,n,r,r),nn(e,t,n,i,s,o)},sn=(e,t,n,r,i,s)=>{e.beginPath(),e.strokeStyle=r,e.lineWidth=n,e.rect(t.left,t.top,t.width,t.height),e.stroke();const o=n/2;nn(e,t.left-o,t.top-o,r,i,s)},on={},an=e=>(on[e]||(on[e]={memCanvas:Ce(320,240),lastFrame:void 0,pixels:void 0}),on[e]),cn=Object.freeze({image:"image",pixels:"pixels"}),ln="image";var dn={onParentEvent:async(e,t,n,r)=>{const i=an(r.id),s={fontSize:12,color:"#00ff00",size:2,...r.getState()},o=(n.data.type===fe.ImageData||n.data.type===fe.Anything)&&je(n.data.value);if(t.name===cn.pixels){const e=(e=>Re(e)||Ue(e)||Array.isArray(e)&&e[0]&&(Re(e[0])||Ue(e[0])))(n.data.value);if(!e)return;i.pixels=n.data.value}if(t.name===cn.image&&o){const e=n.data.value;i.lastFrame=e}if(i.lastFrame&&i.pixels&&i.memCanvas){const e=(e=>{const{sourceImage:t,pixels:n,memCanvas:r,size:i,color:s,labelProp:o,fontSize:a}=e;if(r){const e=ke(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]:"";Ue(n)?sn(e,n,i,s,r,a):Re(n)&&rn(e,n.x,n.y,i,s,r,a)}return e.getImageData(0,0,r.width,r.height)}}return t})({sourceImage:i.lastFrame,pixels:i.pixels||[],memCanvas:i.memCanvas,size:s.size,color:s.color,labelProp:s.labelProp,fontSize:s.fontSize});return i.lastFrame=void 0,i.pixels=void 0,r.setState({...s}),r.nextWidget(ln,{type:fe.ImageData,value:e})}r.setState(s)},getInputNames:()=>[{name:cn.image,type:fe.ImageData},{name:cn.pixels,type:[fe.Rect,fe.Point,fe.Array,fe.JsonObj]}],getOutputNames:()=>[{name:ln,type:fe.ImageData}],initialize:async e=>{an(e.widgetId)},terminate:async e=>{delete on[e.widgetId]}};const un=Object.freeze({in:"in"}),pn="output",gn=e=>{const t=String(e).split(".");return t.length<2?0:t[1].length};var hn={onParentEvent:async(e,t,n,r)=>{const i={min:1,max:100,...r.getState()},s=!Number.isInteger(i.min),o=!Number.isInteger(i.max),a=s||o;let c=(l=i.min,d=i.max,Math.random()*(d-l)+l);var l,d;if(a){let e=0;if(s&&(e=gn(i.min)),o){const t=gn(i.max);t>e&&(e=t)}c=Number(c.toFixed(e))}else c=Math.floor(c);return r.nextGate(pn,{type:fe.Number,value:c})},getInputNames:()=>[{name:un.in,type:fe.Anything}],getOutputNames:()=>[{name:pn,type:fe.Number}]};const fn=Object.freeze({output:"output",totalItems:"totalItems"}),mn=Object.freeze({trigger:"trigger",clear:"clear"}),yn=()=>({$$$time:0,totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1}),vn=async(e,t)=>t.nextGate(fn.totalItems,{type:fe.Number,value:e});var bn={onParentEvent:async(e,t,n,r)=>{const i={$$$time:0,totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...r.getState()};if(t.name===mn.clear)return i.$$list=[],i.properties?.autoFilled&&delete i.properties,r.setState(i),vn(i.$$list.length,r);const s=t.name===mn.trigger;if(!s)if(Array.isArray(n.data.value))n.data.type!==fe.Array&&n.data.type!==fe.Anything||(i.$$outputShape={...i.$$outputShape,...e?.jsonShape},i.$$list=i.$$list.concat(n.data.value),r.setState({...i}),await vn(i.$$list.length,r));else{const t=`$$primitive_${Object.keys(i.$$outputShape).length}`;n.data.type===fe.JsonObj?i.$$outputShape={...i.$$outputShape,...e?.jsonShape?e.jsonShape:void 0}:i.$$outputShape={...i.$$outputShape,[t]:n.data.type},i.$$list.push(n.data.value),r.setState({...i}),await vn(i.$$list.length,r)}if(s){Object.keys(i.$$outputShape).length&&(i.properties={autoFilled:!0,jsonShape:{...i.$$outputShape}});const e=i.$$list.length,t=[...i.$$list];return i.$$list=[],r.setState({...i}),await vn(e,r),r.nextGate(fn.output,{type:fe.Array,value:t})}},getInputNames:e=>{const t={$$$time:0,totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...e},n=Array(t.totalInputs||1).fill(0).map(((e,t)=>({name:`input${t+1}`,type:fe.Anything})));return n.push({name:mn.clear,type:fe.Anything},{name:mn.trigger,type:fe.Anything}),n},getOutputNames:e=>[{name:fn.output,type:fe.Array,...e.properties?{jsonShape:e.properties?.jsonShape}:void 0},{name:fn.totalItems,label:"Total Items",type:fe.Number}],getDefaultState:yn};const Sn=Object.freeze({start:"start",stop:"stop"}),wn="output",In="clock_interrupt";var _n={onParentEvent:async(e,t,n,r)=>{const i={enabled:!1,interval:1e3,intervalMode:"ms",...r.getState()};if(De(e?.name||"")&&t.name===In)return r.nextGate(wn,{type:fe.Boolean,value:!0});if(t.name===Sn.stop&&i.enabled&&i.$$interruptId){r.cancelInterrupt(i.$$interruptId)?(i.enabled=!1,i.$$interruptId=void 0,r.setState(i)):console.warn(`Failed to cancel interrupt [${i.$$interruptId}]`)}else t.name!==Sn.start||i.enabled||i.$$interruptId||(i.$$interruptId=r.registerInterrupt("interval",In,{interval:i.interval}),i.enabled=!0,r.setState(i))},getInputNames:()=>[{name:Sn.start,type:fe.Anything},{name:Sn.stop,type:fe.Anything}],getOutputNames:()=>[{name:wn,type:fe.Boolean}],initialize:async e=>{const t=e.getState();if(t.enabled&&!t.$$interruptId){const n=e.registerInterrupt("interval",In,{interval:t.interval});e.setState({...t,$$interruptId:n})}}};const $n=Object.freeze({in:"in"}),Cn="output",kn=(e,t,n)=>"number"==typeof e?Number((e*t).toFixed(n)):e;var En={onParentEvent:async(e,t,n,r)=>{const i={userProperties:[],factor:2,decimalPoints:2,...r.getState()},s=n.data.type;let o=n.data.value,a=!1;return e?.jsonShape&&(i.detectedInputJson={...i.detectedInputJson,...e?.jsonShape},a=!0),i.detectedInputType||(i.detectedInputType=s,a=!0),n.data.type===fe.Array&&("number"==typeof n.data.value?.[0]?o=((e,t,n)=>{const r=(e||[]).map((e=>kn(e,t,n)));return r})(n.data.value,i.factor,i.decimalPoints):"object"==typeof n.data.value?.[0]&&(o=((e,t,n,r)=>{const i=(e||[]).map((e=>{const i={...e};return Object.keys(i).forEach((e=>{r?.length&&!r?.includes(e)||(i[e]=kn(i[e],t,n))})),i}));return i})(n.data.value,i.factor,i.decimalPoints,i.userProperties))),n.data.type===fe.Number&&(o=kn(n.data.value,i.factor,i.decimalPoints)),a&&r.setState(i),r.nextGate(Cn,{type:s,value:o})},getInputNames:()=>[{name:$n.in,type:[fe.Array,fe.Number]}],getOutputNames:e=>[{name:Cn,type:e.detectedInputType||fe.Number,jsonShape:e.detectedInputJson}]};const xn={},An=Object.freeze({output:"output"}),Nn=Object.freeze({trigger:"trigger"}),Pn=e=>e===fe.ArrayBuffer||e===fe.AudioBuffer||e===fe.BinaryFile||e===fe.ImageData||e===fe.ImageBitmap||e===fe.Array||e===fe.JsonObj,On=()=>({useTriggerPort:!0,properties:[{name:"x",label:"x",type:fe.Number,value:10},{name:"y",label:"y",type:fe.Number,value:20}]}),Tn=e=>{const t={};for(let n=0;n<e.properties.length;n++)t[e.properties[n].label]=e.properties[n].type;return t},Ln=(e,t)=>{const n={};for(let r=0;r<e.properties.length;r++){let i=e.properties[r].value;const s=e.properties[r].type;Pn(s)&&(i=xn[t][e.properties[r].name]),s===fe.Number?i=Number(i):s===fe.String&&(i=String(i)),n[e.properties[r].label]=i}return n};var Bn={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s=structuredClone(i),o={...On(),...s};if(t.name===Nn.trigger){const e=Ln(o,r.id);return r.nextWidget(An.output,{type:fe.JsonObj,value:e})}const a=o.properties.findIndex((e=>e.name===t.name));if(-1!==a){const e=o.properties[a];let t=n.data.type===e.type;if(!t&&n.data.type===fe.Anything){t=Fe(n.data.type)===e.type}if(t){const t=Pn(n.data.type);xn[r.id]=xn[r.id]||{},t?(xn[r.id][e.name]=n.data.value,o.properties[a].value=void 0):o.properties[a].value=n.data.value,o.properties[a].$$invalidInputType=!1}else o.properties[a].$$invalidInputType=!0;if(r.setState(o),!o.useTriggerPort){const e=Ln(o,r.id);return r.nextWidget(An.output,{type:fe.JsonObj,value:e})}}},getInputNames:e=>{const t={...On(),...e},n=t.properties.map((e=>({name:e.name,label:e.label,type:e.type})));return t.useTriggerPort&&n.push({name:Nn.trigger,label:Nn.trigger,type:fe.Anything}),n},getOutputNames:e=>[{name:An.output,label:An.output,type:fe.JsonObj,jsonShape:Tn(e)}],getDefaultState:On,initialize:async e=>{xn[e.widgetId]={}},terminate:async e=>{delete xn[e.widgetId]}};const Dn=async e=>{const t=(e,t)=>e.split(t)[1];if(e.startsWith(Pe)){const n=t(e,Pe);return We("inner","input",n)}if(e.startsWith(Le)){const n=t(e,Le);return We("outer","output",n)}return null},jn=()=>({canvasPosition:{x:0,y:0},canvasZoom:1,inputs:[{name:"input",type:[fe.Anything],index:0}],outputs:[{name:"output",type:[fe.Anything],index:0}],name:"Custom Widget 1",description:"",type:"custom"}),Un=e=>{const t={...jn(),...e},n=t.inputs.map(((e,t)=>({name:We("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:We("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 Rn={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...jn(),...i},o=Un(s,(r.recipePoolId,r.recipeType,r.thingRecipeId,r.id));for(let e=0;e<o.length;e++){const i=o[e];if(t.name===i.name&&(i.type.includes(fe.Anything)||i.type.includes(n.data.type))){const e=await Dn(t.name);e&&await r.nextWidget(e,{type:n.data.type,value:n.data.value})}}},getInputNames:Un,getOutputNames:e=>{const t={...jn(),...e},n=t.outputs.map(((e,t)=>({name:We("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:We("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:jn};const Fn=(e,t,n,r,i)=>{const s=4*(t*n.width+e),o=n.data[s],a=n.data[s+1],c=n.data[s+2];return Math.abs(o-r.r)<=i&&Math.abs(a-r.g)<=i&&Math.abs(c-r.b)<=i};var Mn={getPixelValueAtIndex:(e,t)=>{const n=e.data,r=n[t]||0,i=n[t+1]||0,s=n[t+2]||0;return{avr:(r+i+s)/3,r:r,g:i,b:s}},getBoundingBox:(e,t,n)=>{const r=e.width,i=e.height,s=new Set,o=Number(n.threshold||0),a=isNaN(o)?10:o,c=(n,o)=>{const c=[[n,o]];let l=n,d=n,u=o,p=o;for(;c.length>0;){const n=c.shift();if(!n)continue;const[o,g]=n;o<0||g<0||o>=r||g>=i||s.has(`${o},${g}`)||!Fn(o,g,e,t,a||0)||(s.add(`${o},${g}`),l=Math.min(l,o),d=Math.max(d,o),u=Math.min(u,g),p=Math.max(p,g),c.push([o+1,g],[o-1,g],[o,g+1],[o,g-1]))}return{minX:l,maxX:d,minY:u,maxY:p}},l=[];for(let o=0;o<i;o+=4)for(let i=0;i<r;i+=4)if(!s.has(`${i},${o}`)&&Fn(i,o,e,t,a)){const{minX:e,maxX:t,minY:r,maxY:s}=c(i,o),a=t-e,d=s-r;if(a>=(n.minWidth||1)&&d>=(n.minHeight||1)&&l.push({left:e,top:r,width:a,height:d}),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,i="object"==typeof n,s=i?n.r:n,o=i?n.g:n,a=i?n.b:n;r[t]=s,r[t+1]=o,r[t+2]=a,r[t+3]=255}};const Wn=e=>Fe(e);var Gn,Vn,Hn,zn,qn,Kn,Jn,Yn,Xn,Zn;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(Gn||(Gn={})),function(e){e.Bundle="bundle",e.Group="group"}(Vn||(Vn={})),function(e){e.Hardware="hardware",e.Virtual="virtual"}(Hn||(Hn={})),function(e){e.Cloud="cloud",e.Web="web"}(zn||(zn={})),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"}(qn||(qn={})),function(e){e.Gateway="gateway",e.Timer="timer"}(Kn||(Kn={})),(Jn||(Jn={})).InstallInProgress="installation-in-progress",function(e){e.InstallDependencies="install-dependencies",e.GetInstalledDependencies="get-installed-dep"}(Yn||(Yn={})),function(e){e.Success="success",e.Error="error",e.Pending="pending"}(Xn||(Xn={})),function(e){e.NotFound="not-found",e.BadRequest="bad-request",e.Forbidden="forbidden",e.InternalError="internal-error"}(Zn||(Zn={}));let Qn=null;var er=()=>{if(!Qn)throw new Error("Required function is not set");return Qn};class tr extends Error{targetWidgetId;targetPortName;sourcePortName;sourceWidgetId;targetWidgetType;sourceWidgetType;constructor(e,t){super(e),this.name="ChildWidgetError",t.stack&&(this.stack=t.stack),this.targetWidgetId=t.targetWidgetId,this.targetPortName=t.targetPortName,this.sourcePortName=t.sourcePortName,this.sourceWidgetId=t.sourceWidgetId,this.targetWidgetType=t.targetWidgetType,this.sourceWidgetType=t.sourceWidgetType}}class nr extends Error{constructor(e,t){super(e),this.name="UserCodeError",t&&(this.stack=t)}}const rr=(e,t)=>`\n\t\tfunction _user_code_(){\n\t\t\t${t===Gn.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\tdecodeDataType: this.decodeDataType,\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===Gn.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`,ir=(e,t,n,r)=>{const o=rr(e,n),a={...t,document:{},__errorTracer:e=>{if(e instanceof tr)throw e;throw new nr(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:Mn,...n===Gn.Cloud?{require:er(),kemuProcess:process.env.KEMU_PROCESS?process.env.KEMU_PROCESS:{}}:{},jsonp:i,CryptoJS:s,decodeDataType:Wn,window:{addEventListener:t?.addEventListener,removeEventListener:t?.removeEventListener}};try{const e="browser"===(()=>{if(Z)return"browser";if(ee)return"node";if(Q)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}}}},sr="main",or="My Script",ar="This is a test script.",cr=`\n/**\n * Name: ${or}\n * Description: ${ar}\n */\n\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`.trim(),lr=()=>({pauseExecution:!1,autoPauseOnError:!0,$$eventListeners:{},version:2,metadata:{name:or,description:ar},pages:{[sr]:{code:cr,language:"javascript",name:"My First Script"}}}),dr=(e,t)=>{const n={message:"Unknown Error"};if(e?.stack){const r=e?.stack?.split(":")[0].trim();n.type=r;const i=(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);i&&(n.line=i.line-(e=>{const t="___user_code_section___";return rr(t,e).split(t)[0].split("\n").length+2})(t),n.column=i.column)}return e.message&&(n.message=e.message),n},ur=(e,t)=>{const n={...{...lr(),...t.getState()},$$error:e||void 0};e&&console.error(e.message),t.setState(n)},pr=new o;let gr,hr,fr={},mr={};const yr=e=>{const t=oe(gr,hr,e);if(!t)throw new Error(`Widget ${e} not found in thing ${hr}`);return t},vr=(e,t)=>`${e}:${t}`,br=e=>`${yr(e.createdByWidgetId).id}::${e.variableName}`,Sr=e=>`${pe}${e}`;var wr=e=>{const t=yr(e.createdByWidgetId),n=br({variableName:e.variableName,createdByWidgetId:e.createdByWidgetId});mr[n]={type:e.type,subscriberWidgetId:t.id,subscriberWidgetType:t.type}},Ir=e=>{const t=br({variableName:e.variableName,createdByWidgetId:e.createdByWidgetId});delete mr[t]},_r=async e=>{const t=yr(e.setByWidgetId);if(!t)throw new Error(`Widget ${e.setByWidgetId} not found in thing ${hr} in recipe ${gr}`);const n=e.variableName.startsWith(pe)?br({variableName:e.variableName,createdByWidgetId:e.setByWidgetId}):e.variableName;fr[n]={value:e.value,type:e.type};const r={value:e.value,type:e.type,varName:e.variableName,isUIElement:e.variableName.startsWith(pe),setByWidgetType:t.type,setByWidgetId:e.setByWidgetId};await pr.emit(vr(e.variableName,e.type),r),e.type!==fe.Anything&&await pr.emit(vr(e.variableName,fe.Anything),r)},$r=e=>{const{readerWidgetId:t,variableName:n}=e;if(!yr(t))throw new Error(`Widget ${t} not found in thing ${hr} in recipe ${gr}`);const r=n.startsWith(pe)?br({variableName:e.variableName,createdByWidgetId:e.readerWidgetId}):n,i=fr[r];if(i)return{type:i.type,value:i.value}},Cr=e=>{const{widgetId:t,variableName:n,type:r}=e;if(!yr(t))throw new Error(`Widget ${t} not found in thing ${hr} in recipe ${gr}`);const i=vr(n,r);let s;return s=pr.on(i,(async r=>{oe(gr,hr,t)?await e.onValueChange(r):(console.warn(`Zombie widget ${t} detected, unsubscribing from variable events "${n}"`),s?.())})),s},kr=(e,t)=>{const n=vr(e,fe.Anything);return pr.on(n,(async e=>{const{isUIElement:n,...r}=e;await t(r)}))},Er=e=>{mr={},fr={},gr=e.recipePoolId,hr=e.thingId};const xr="setTimeout",Ar="variableChanged",Nr=e=>{const{recipePoolId:t,thingId:n,scriptWidgetId:r}=e,i=oe(t,n,r);if(!i)throw new Error(`Widget "${r}" not found in recipe "${t}"`);const s=(e,t)=>{const n=$r({readerWidgetId:r,variableName:e});if(n||t)return void 0===n?{value:t?.value??t,type:t?.type??Fe(t)}:{value:n.value,type:n.type}},o=(t,n,s)=>{if(!e.setState)return void console.warn("Cannot subscribe to variable changes without a setState function");const o={...lr(),...e.getState()},a=Cr({variableName:t,type:fe.Anything,widgetId:r,onValueChange:async e=>{n?e.setByWidgetType===ze.widgetGroup&&e.setByWidgetId===i.groupId&&await s(e):s(e)}});delete o.$$eventListeners[t],o.$$eventListeners[t]={handler:s,abort:async()=>{a()},name:Ar},e.setState(o)};return{get:s,set:async(e,t,n)=>{await _r({variableName:e,type:n||Fe(t),setByWidgetId:r,value:t})},onValueChange:(e,t)=>{o(e,!1,t)},onUIValueChange:(e,t)=>{const n=Sr(e);o(n,!0,t)},getUIValue:e=>{const r=Sr(e),o=s(r);if(o)return{value:o.value,type:o.type};const a=i.groupId;if(!a)throw new Error("You can only read UI variables from inside a widgetGroup");const c=oe(t,n,a);if(!c)throw new Error(`Widget "${a}" not found in recipe "${t}"`);const l=c.state,d=(l.settings||[]).find((t=>t.variableName===e));if(!d)throw new Error(`Field "${e}" not found in widgetGroup "${l.name}"`);const u=d.config.defaultValue;if(!u)throw new Error(`Field "${e}" in widgetGroup "${l.name}" has no default value`);return{value:u,type:Fe(u)}}}},Pr="__command-compile__";let Or;const Tr=()=>{throw new Error("Method not implemented")},Lr=(e,t,n)=>{const i=(e,...n)=>{const r={...lr(),...t.getState()}.$$eventListeners[e];r&&r.handler(n)},s={};return Object.keys(fe).forEach((e=>{s[e]=fe[e]})),{dataTypesEnum:s,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?Nr({recipePoolId:n.recipePoolId,scriptWidgetId:n.widgetId,thingId:n.thingId,getState:t.getState,setState:t.setState}):{get:Tr,set:async()=>Tr(),onValueChange:Tr,onUIValueChange:Tr,getUIValue:Tr},setTimeout:(n,i,s)=>{if(e.withTimers&&t&&t.setState&&t.registerInterrupt){const e=r(),o={...lr(),...t.getState()};o.$$eventListeners[e]={handler:n,rejectHandler:s,name:xr},t.setState(o),t.registerInterrupt("timeout",e,{timeout:i},void 0,e)}},addEventListener:(e,n)=>{if(t.setState){const s=r(),o={...lr(),...t.getState()};o.$$eventListeners[s]={handler:n,name:e},t.setState(o),window.addEventListener(e,i.bind(s))}else console.warn(`Cannot remove event listener '${e}' because the widget context is not available.`)},removeEventListener:(e,n)=>{if(t.setState){const r={...lr(),...t.getState()},i=Object.keys(r.$$eventListeners).find((t=>r.$$eventListeners[t].name===e&&r.$$eventListeners[t].handler===n));t.setState(r),i&&removeEventListener(r.$$eventListeners[i].name,r.$$eventListeners[i].handler)}else console.warn(`Cannot remove event listener '${e}' because the widget context is not available.`)}}},Br=(e,t,n,r)=>{const i={...lr(),...n.getState()},s=i.pages[sr].$$compiledCode;if(s)return{compiledModule:s};{const s=Lr(e,n,t);return ir(i.pages[sr].code,s,n.recipeType,r)}},Dr=e=>e.map((e=>({...e,name:e.name.replace("_","")}))),jr=async(e,t)=>{const n={...e};for(const r in e){if(e[r].name===xr){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},Ur=async e=>{const t={...e};for(const n in e){if(e[n].name===Ar){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},Rr=async(e,t,n)=>{let r={...lr(),...e.getState()};if(void 0!==n){r.pages[sr]?.$$compiledCode?.onTerminate&&await(r.pages[sr].$$compiledCode?.onTerminate());let t=await jr(r.$$eventListeners,e);t=await Ur(t),r.$$eventListeners=t,r.pages[sr].$$compiledCode=void 0,r.pages[sr].code=n,e.setState({...r})}const i=!r.pages[sr].$$compiledCode,{compiledModule:s,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=dr(o,e.recipeType);return ur(t,e),null}if(s){const n=(()=>{const e=(e,...t)=>{if(Or)try{return Or[e](...t)}catch(e){return void console.log("Error in custom logger: ",e)}console[e](...t)};return{log:(...t)=>{e("log",...t)},error:(...t)=>{e("error",...t)},warn:(...t)=>{e("warn",...t)},info:(...t)=>{e("info",...t)}}})();let o;r={...e.getState()},r.pages[sr].$$compiledCode=s;const a=Mr(r.pages[sr].code);a?.name===r.metadata?.name&&a?.description===r.metadata?.description||(r.metadata=a||void 0);const c=e.nextWidget||e.nextGate;if(c&&s.setSendToPortFun(c),t)try{await s.recipeInit({setState:e.setState,getState:e.getState},n)}catch(t){o=dr(t,e.recipeType)}if(c&&i)try{await s.main(c,n)}catch(t){o=dr(t,e.recipeType)}r.$$lastInputs=s.getWidgetInputs?s.getWidgetInputs():[],r.$$lastOutputs=s.getWidgetOutputs?s.getWidgetOutputs():[],e.setState(r),ur(o,e)}};var Fr={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...lr(),...i};if(!s.pages[sr])return console.warn("Missing default page");if(De(e?.name||""))return s.$$eventListeners[t.name]?(await s.$$eventListeners[t.name].handler(),s.$$eventListeners[t.name].name===xr&&delete s.$$eventListeners[t.name],void r.setState({...s})):void console.log(`Unknown interrupt id [${t.name}] `);const o=t.name===Pr;await Rr(r,!1,o?n.data.value:void 0);const a=s.pages[sr].$$compiledCode;if(e&&e.name!==Pr&&a)try{await a.asyncProcessEvent(t,e,n)}catch(e){if("UserCodeError"===e.name){const t=dr(e,r.recipeType);throw ur(t,r),t}throw e}},getInputNames:(e,t)=>{const n={...lr(),...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 Dr(e)}return e.$$lastInputs||[]},getOutputNames:(e,t)=>{const n={...lr(),...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 Dr(e)}return e.$$lastOutputs||[]},getDefaultState:lr,initialize:async e=>{const t=e.getState(),n={...lr(),...t};n.pages[sr].code&&await Rr({getState:e.getState,id:e.widgetId,recipePoolId:e.recipePoolId,recipeType:e.recipeType,registerInterrupt:e.registerInterrupt,setState:e.setState,nextWidget:e.nextWidget,thingRecipeId:e.thingRecipeId,cancelInterrupt:()=>!0},!0,n.pages[sr].code)},terminate:async e=>{try{const t=e.getState();t.pages[sr].$$compiledCode?.onTerminate&&await t.pages[sr].$$compiledCode.onTerminate();const n=e=>Xe.destroyInterrupt(e),r=await jr(t.$$eventListeners,{cancelInterrupt:n});await Ur(r)}catch(t){console.warn(`Error terminating script widget ${e.widgetId}: `,t)}}};const Mr=e=>{const t=e.trimStart().match(/^(?:\/\*\*(?:[^*]|\*(?!\/))*\*\/|\/\*(?:[^*]|\*(?!\/))*\*\/)/);if(!t)return null;const n=t[0].replace(/^\/\*\*?/,"").replace(/\*\/$/,"").split("\n").map((e=>e.replace(/^\s*\*?\s?/,"").trim())).join("\n"),r=n.match(/Name\s*:\s*([^]*?)(?=\n\s*[A-Za-z]+\s*:|$)/i),i=n.match(/Description\s*:\s*([^]*?)(?=\n\s*[A-Za-z]+\s*:|$)/i),s={};return r&&r[1]&&(s.name=r[1].trim()),i&&i[1]&&(s.description=i[1].trim()),Object.keys(s).length>0?s:null},Wr=async(e,t,n,r)=>{e.startsWith("data:image/")||(e=`data:image/png;base64,${e}`);const i=await Gr(e);return((e,t,n,r)=>{const i=r.getContext("2d");if(!i)throw new Error("Failed to get canvas context");const s=e.width,o=e.height;return r.width=t,r.height=n,i.drawImage(e,0,0,s,o,0,0,t,n),i.getImageData(0,0,t,n)})(i,n||i.naturalWidth,r||i.naturalHeight,t)},Gr=e=>new Promise(((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=e=>n(e),r.src=e})),Vr=Object.freeze({image:"image"}),Hr=Object.freeze({base64:"base64"}),zr=()=>({});var qr={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};if(t.name===Hr.base64){if("string"!=typeof n.data.value)return;if(n.data.type!==fe.String&&n.data.type!==fe.Anything)return;const e=n.data.value;Z&&(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ce(320,240)));try{const t=await Wr(e,i.$$memCanvas,i.resize?.width,i.resize?.height);return r.setState(i),r.nextGate(Vr.image,{type:fe.ImageData,value:t})}catch(e){console.log("[base64ToImageData] Error: ",e)}}},getInputNames:()=>[{name:Hr.base64,type:fe.String}],getOutputNames:()=>[{name:Vr.image,type:fe.ImageData}],getDefaultState:zr};const Kr=Object.freeze({object:"object",error:"error"}),Jr=Object.freeze({string:"string"}),Yr=()=>({outputIsArray:!1});var Xr={onParentEvent:async(e,t,n,r)=>{const i={outputIsArray:!1,...r.getState()};if((n.data.type===fe.String||n.data.type===fe.Anything)&&"string"==typeof n.data.value)try{const e=JSON.parse(n.data.value),t=Array.isArray(e);return t&&!i.outputIsArray?r.setState({...i,outputIsArray:!0}):!t&&i.outputIsArray&&r.setState({...i,outputIsArray:!1}),r.nextGate("object",{type:t?fe.Array:fe.JsonObj,value:e})}catch(e){return r.nextGate("error",{type:fe.Boolean,value:!0})}},getInputNames:()=>[{name:Jr.string,type:fe.String}],getOutputNames:e=>[{name:Kr.object,type:[fe.JsonObj,fe.Array],label:e.outputIsArray?"array":Kr.object},{name:Kr.error,type:fe.Boolean}],getDefaultState:Yr};const Zr=Object.freeze({string:"string",length:"length"}),Qr=Object.freeze({trigger:"trigger",setText:"setText"}),ei=()=>({text:"",dispatchOnSet:!1});var ti={onParentEvent:async(e,t,n,r)=>{const i={text:"",dispatchOnSet:!1,...r.getState()};if(t.name===Qr.setText){if(!((n.data.type===fe.String||n.data.type===fe.Anything)&&"string"==typeof n.data.value))return;if("string"==typeof n.data.value&&(i.text=n.data.value,r.setState(i)),!i.dispatchOnSet)return}const s=r.nextGate(Zr.length,{type:fe.Number,value:i.text.length}),o=r.nextGate(Zr.string,{type:fe.String,value:i.text});await Promise.all([s,o])},getInputNames:e=>{const t=[{name:Qr.setText,type:fe.String}];return e.dispatchOnSet||t.push({name:Qr.trigger,type:fe.Anything}),t},getOutputNames:()=>[{name:Zr.string,type:fe.String},{name:Zr.length,type:fe.Number}],getDefaultState:ei};const ni=Object.freeze({image:"image"}),ri=Object.freeze({image:"image",x:"x",y:"y",width:"width",height:"height"}),ii=()=>({showInputPorts:!1});var si={onParentEvent:async(e,t,n,r)=>{const i={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===ri.x&&(i.cropX=n.data.value),t.name===ri.y&&(i.cropY=n.data.value),t.name===ri.width&&(i.cropWidth=n.data.value),t.name===ri.height&&(i.cropHeight=n.data.value),void r.setState(i);if(t.name===ri.image){if(n.data.type!==fe.ImageData&&n.data.type!==fe.Anything)return;if(!je(n.data.value))return;const e=n.data.value;if(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ce(320,240),i.$$memCanvasContext=ke(i.$$memCanvas),r.setState(i)),!i.$$memCanvas||!i.$$memCanvasContext)return void console.error("Failed to get canvas or context");let t=e;return i.$$memCanvas.width=e.width,i.$$memCanvas.height=e.height,(i.cropX||i.cropY||i.cropWidth||i.cropHeight)&&(t=((e,t,n,r)=>{if(!n)return e;const i=Math.max(r.x||0,0),s=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,i,s,c,l,0,0,c,l),n.getImageData(0,0,c,l)})(e,i.$$memCanvas,i.$$memCanvasContext,{x:i.cropX,y:i.cropY,width:i.cropWidth,height:i.cropHeight})),r.nextGate(ni.image,{type:fe.ImageData,value:t})}},getInputNames:e=>{const t=[{name:ri.image,type:[fe.ImageData]}];return e.showInputPorts&&(t.push({name:ri.x,type:fe.Number}),t.push({name:ri.y,type:fe.Number}),t.push({name:ri.width,type:fe.Number}),t.push({name:ri.height,type:fe.Number})),t},getOutputNames:()=>[{name:ni.image,type:fe.ImageData}],getDefaultState:ii};const oi=Object.freeze({image:"image"}),ai=Object.freeze({image:"image",width:"width",height:"height"}),ci=()=>({showInputPorts:!1});var li={onParentEvent:async(e,t,n,r)=>{const i={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===ai.width&&(i.width=n.data.value),t.name===ai.height&&(i.height=n.data.value),void r.setState(i);if(t.name===ai.image){if(n.data.type!==fe.ImageData&&n.data.type!==fe.Anything)return;if(!je(n.data.value))return;const e=n.data.value;if(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ce(320,240),i.$$tempCanvas=Ce(320,240),r.setState(i)),!i.$$memCanvas||!i.$$tempCanvas)return;let t=e;return(i.width||i.height)&&(t=((e,t,n,r,i)=>{if(!r&&!i)return e;r&&!i?i=r*(e.height/e.width):!r&&i&&(r=i*(e.width/e.height));const s=Math.max(1,r||e.width),o=Math.max(1,i||e.height);n.width===e.width&&n.height===e.height||(n.width=e.width,n.height=e.height),t.width=s,t.height=o;const a=ke(t),c=ke(n);if(!a||!c)throw new Error("Failed to get canvas context");return c.putImageData(e,0,0),a.drawImage(n,0,0,e.width,e.height,0,0,s,o),a.getImageData(0,0,s,o)})(e,i.$$memCanvas,i.$$tempCanvas,i.width,i.height)),r.nextGate(oi.image,{type:fe.ImageData,value:t})}},getInputNames:e=>{const t=[{name:ai.image,type:fe.ImageData}];return e.showInputPorts&&(t.push({name:ai.width,type:fe.Number}),t.push({name:ai.height,type:fe.Number})),t},getOutputNames:()=>[{name:oi.image,type:fe.ImageData}],getDefaultState:ci};const di=Object.freeze({value:"value"}),ui=Object.freeze({trigger:"trigger",setValue:"setValue"}),pi=()=>({value:0,dispatchOnSet:!1});var gi={onParentEvent:async(e,t,n,r)=>{const i={value:0,dispatchOnSet:!1,...r.getState()};if(t.name===ui.setValue){const e=n.data.type===fe.Number||n.data.type===fe.Anything||n.data.type===fe.String,t=!isNaN(Number(n.data.value))&&!Array.isArray(n.data.value);if(!e||!t)return;if(i.value=Number(n.data.value),r.setState(i),!i.dispatchOnSet)return}return r.nextGate(di.value,{type:fe.Number,value:i.value})},getInputNames:e=>{const t=[{name:ui.setValue,type:fe.Number}];return e.dispatchOnSet||t.push({name:ui.trigger,type:fe.Anything}),t},getOutputNames:()=>[{name:di.value,type:fe.Number}],getDefaultState:pi};const hi=Object.freeze({image:"image"}),fi=Object.freeze({image:"image"}),mi=()=>({anchors:[],vertices:[],matrix:[]}),yi={onParentEvent:async(e,t,n,r)=>{const i={anchors:[],vertices:[],matrix:[],...r.getState()},s=window,o=n.data.type===fe.ImageData;if(s.Speedy&&o){const e=s.Speedy,t=n.data.value;let o,d,u,p=i.$$private?.canvas,g=i.$$private?.context,h={...i};const f=4===i.anchors.length;if(i.$$private?.pipeline)o=i.$$private?.pipeline,d=i.$$private?.source;else{o=e.Pipeline(),d=e.Image.Source();const n=e.Image.Sink();u=e.Transform.PerspectiveWarp(),p?p.width===t.width&&p.height===t.height||(p.width=t.width,p.height=t.height,g=p.getContext("2d")):(c=t.width,l=t.height,p=Ce(c,l),g=p.getContext("2d")),d.output().connectTo(u.input()),u.output().connectTo(n.input()),o.init(d,n,u);let r=e.Matrix(3,3,[1,0,0,0,1,0,0,0,1]);if(4===i.anchors.length){const t=e.Matrix(2,4,[(a=i.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,i.vertices.reduce(((e,t)=>e.concat([t.x,t.y])),[])),s=e.Matrix.Zeros(3,3);await e.Matrix.perspective(s,t,n);const o=s.read();r=e.Matrix(3,3,o)}u.transform=r,h={...h,$$private:{...h.$$private,canvas:p,context:g,perspective:u,pipeline:o,source:d}}}let m=t;if(f){const e=await(async(e,t)=>{const n=window,r=e.$$private?.source,i=e.$$private?.pipeline;if(n.Speedy&&r&&i){const e=n.Speedy,s=await createImageBitmap(t),o=await e.load(s);return r.media=o,(await i.run()).image.source}return null})(h,m);e&&(p&&g&&(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,g)),h.$$private&&r.setState({...h,$$private:{...h.$$private,lastInputImage:t}}))}else h.$$private&&r.setState({...h,$$private:{...h.$$private,lastInputImage:t}});return r.nextGate(hi.image,{type:fe.ImageData,value:m})}var a,c,l;console.log("Environment not supported")},getInputNames:()=>[{name:fi.image,type:fe.ImageData}],getOutputNames:()=>[{name:hi.image,type:fe.ImageData}],getDefaultState:mi,terminate:async e=>{const t=e.getState();t.$$private?.pipeline.release()}},vi=()=>({name:"Default widget bundle",description:"",inputs:[{dataType:[fe.Anything],name:"input"}],outputs:[{dataType:[fe.Anything],name:"output"}]});let bi;const Si=()=>{if(!bi)throw new Error(tt(et));return bi};const wi=async e=>{const t=new a,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},Ii={};var _i=e=>Ii[e]||null;const $i=async(e,t,n)=>{try{const r=Si(),i=n?r.loadBlobAsString:r.loadBlob;return await i(e,t)}catch(e){return null}},Ci=async e=>{const t=le;try{const n=await $i(e,t,!0);if(!n)return null;return Function(n)()}catch(e){return null}},ki=async e=>{const t=de;try{const n=await $i(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}},Ei=(e,t)=>`${e.replace(ue,"")}_${t}`,xi=(e,t)=>`widget/${e.replace(ue,"")}/v/${t}`,Ai=async(e,t)=>{const n=Si(),[r]=await Promise.all([wi(e),n.createLocation(t)]);for(const e in r)e.startsWith("__MACOSX")||await n.saveBlob(t,e,r[e])},Ni=(e,t)=>{const n=Ei(e,t),r=_i(n);return r?{...r}:null},Pi=(e,t,n)=>{const r=`${`widget/${e.replace(ue,"")}/tmp`}/${t}`;if(n){return Si().getCacheLocation(r)}return r};var Oi=Ni,Ti=async(e,t,n)=>{const r=Pi(t,n);await Ai(e,r);const i=Ci(r),s=ki(r),o=Si(),a=o.getCacheLocation(r),[c,l]=await Promise.all([i,s]);if(!c)return null;let d=l;if(!l){const e=vi(),t=JSON.stringify(e);await o.saveBlob(r,de,Be(t)),d=e}return{cachePath:a,processor:c,storedState:Object.freeze(d)}},Li=(e,t,n)=>{if(n.isTempStorage)return Pi(e,t,n.fullStorageRoot);const r=Si(),i=xi(e,t);return n.fullStorageRoot?r.getCacheLocation(i):i};const Bi=()=>vi();var Di={onParentEvent:async(e,t,n,r)=>{const i=r.getState();return i.$$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={...Bi(),...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={...Bi(),...e};return n.$$processor?.getOutputNames?n.$$processor.getOutputNames(e,t):n.outputs.map((e=>({name:e.name,type:e.dataType})))},getDefaultState:Bi,initialize:async(e,t)=>{console.log("Widget bundle initialize",e);let n={...e.getState()},r=n.$$cacheInfo?.widgetThingId||n.collectionInfo?.widgetId||e.widgetId;const i=n.$$cacheInfo?.version.toString()||n.collectionInfo?.version.toString()||1;if(n.$$cacheInfo={...n.$$cacheInfo,version:Number(i),widgetThingId:r},!r||!i)throw new Error("Widget bundle state is missing cache id or version");console.log("Loading state from cache");const s=Oi(r,i);let o=!s;if(!n.$$processor)if(n.storageUnitId&&!s){const t=await e.getStorageData(n.storageUnitId);if(t){r=e.widgetId;const s=await Ti(t,r,i);o=!0,s&&(n={...n,$$processor:s.processor,$$cacheInfo:{...n.$$cacheInfo,widgetThingId:r,version:Number(i)}},e.setState(n))}}else if(s){o=!1;const r=n.collectionInfo?{...n.collectionInfo}:void 0;n={...n,...!t.keepCurrentState&&s.storedState?{...s.storedState,...r?{collectionInfo:r}:{}}:{},$$processor:s.processor},e.setState(n)}const a=Li(r,i,{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 ji=Object.freeze({event:"event"}),Ui="1",Ri="2",Fi="3";var Mi={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};r.setState({...i,$$lastEventType:n.data.type}),await r.nextGate(Ui,n.data),await r.nextGate(Ri,n.data),await r.nextGate(Fi,n.data)},getInputNames:()=>[{name:ji.event,type:fe.Anything}],getOutputNames:e=>{const t={type:{...e}.$$lastEventType??fe.Anything};return[{name:Ui,...t},{name:Ri,...t},{name:Fi,...t}]}};const Wi=()=>({name:"myVar",type:fe.Anything,reactive:!0,defaultValue:""}),Gi=Object.freeze({set:"set",read:"read"}),Vi="value";var Hi={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...Wi(),...i};if(t.name!==Gi.set){if(t.name===Gi.read){const e=$r({variableName:s.name,readerWidgetId:r.id}),t=e?e.value:s.defaultValue;await r.nextWidget(Vi,{type:s.type,value:t})}}else{if(n.data.type!==s.type&&s.type!==fe.Anything)return;await _r({variableName:s.name,value:n.data.value,setByWidgetId:r.id,type:s.type})}},getInputNames:e=>{const t={...e};return[{name:Gi.set,type:t.type||fe.Anything},{name:Gi.read,type:fe.Anything}]},getOutputNames:e=>{const t={...e};return[{name:Vi,type:t.type||fe.Anything}]},initialize:async e=>{const t=e.getState(),n={...Wi(),...t};if(n.$$abortListener)try{n.$$abortListener()}catch(t){console.warn(`Error aborting variable listener for widget ${e.widgetId}: `,t)}wr({variableName:n.name,type:n.type,createdByWidgetId:e.widgetId});const r=Cr({variableName:n.name,type:n.type,widgetId:e.widgetId,onValueChange:async t=>{const n=e.getState();void 0!==t.value&&(n.type!==fe.Anything&&t.type!==n.type||n.reactive&&await e.nextWidget(Vi,{type:t.type,value:t.value}))}});e.setState({...n,$$abortListener:r})},terminate:async e=>{const t=e.getState(),n={...Wi(),...t};n.$$abortListener&&n.$$abortListener(),Ir({variableName:n.name,createdByWidgetId:e.widgetId})}};let zi;var qi=e=>{zi=e},Ki=()=>{if(!zi)throw new Error("Hub Connector not set");return zi};const Ji=e=>{const t=ie(e);return t?.name||""},Yi=async(e,t=!1)=>{const n=Ki();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 Xi={onParentEvent:async(e,t,n,r)=>{const i={dynamicInputs:{},dynamicOutputs:{},customState:{},...r.getState()};if(!e)return;const s=Ki();let o=i.$$$serviceId;if(!o){const e=s.getCachedServices().available.find((e=>e.name===i.service?.name&&e.version===i.service?.version));if(!e)return;o=e.sessionId,i.$$$serviceId=o,r.setState(i)}const a=i.service?.variants?.find((e=>e.id===i.variantId)),c=a?i.dynamicInputs[a.id]||a?.inputs||[]:i.service?.inputs||[];if(!c?.length)return;if(!a&&i.service?.ignoreParentEvents)return;const l=i.service?.processingTimeoutSec,d=i.service?.name&&r.eventContext?.[i.service?.name];return s.onParentEvent({recipeId:r.recipePoolId,recipeName:Ji(r.recipePoolId),data:n.data,targetServiceSessionId:o,currentState:i.customState,targetVariantId:i.variantId,target:{portName:t.name,widgetId:r.id,widgetType:r.type},source:e,config:{timeout:l?1e3*l:0,async:i.service?.asyncParentEvents},eventContext:d})},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=ie(e.recipePoolId),r=n?.name||"",i=Ki(),s=await Yi(t);if(s)try{return await i.initializeServiceInstance({recipeId:e.recipePoolId,sessionId:s,recipeName:r,widgetId:e.widgetId,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.widgetId}] 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=Ki(),r=await Yi(t,!0);if(r)return n.terminateServiceInstance(r,e.widgetId,e.recipePoolId,t.variantId)}};const Zi=Object.freeze({Image:"image"}),Qi=Object.freeze({Image:"image"}),es=()=>({filters:[{name:"grayscale",value:"0.5",id:"d-1"}]});var ts={onParentEvent:async(e,t,n,r)=>{const i={filters:[{name:"grayscale",value:"0.5",id:"d-1"}],...r.getState()};if(t.name===Zi.Image&&n.data.type===fe.ImageData){if(!je(n.data.value))return void console.log("ImageFilter: Invalid image data type, aborting process");const e=n.data.value;i.$$memCanvas?.getContext||(i.$$memCanvas=Ce(e.width,e.height)),i.$$context?.drawImage||(i.$$context=i.$$memCanvas.getContext("2d")),i.$$memCanvas.width!==e.width&&(i.$$memCanvas.width=e.width),i.$$memCanvas.height!==e.height&&(i.$$memCanvas.height=e.height),r.setState(i),i.$$context.putImageData(e,0,0),i.filters.length?i.$$context.filter=i.filters.map((e=>{let t="";return"blur"===e.name?t="px":"hue-rotate"===e.name&&(t="deg"),`${e.name}(${parseFloat(e.value)}${t})`})).join(" "):i.$$context.filter="none",i.$$context.drawImage(i.$$memCanvas,0,0);const t=i.$$context.getImageData(0,0,e.width,e.height);return r.nextWidget(Qi.Image,{type:fe.ImageData,value:t})}},getInputNames:()=>[{name:Zi.Image,type:fe.ImageData}],getOutputNames:()=>[{name:Qi.Image,type:fe.ImageData}],getDefaultState:es};const ns="loaded";var rs={onParentEvent:async(e,t,n,r)=>r.nextWidget(ns,{value:!0,type:fe.Boolean}),getInputNames:()=>[],getOutputNames:()=>[{name:ns,type:fe.Boolean,description:"Triggered when the recipe is fully loaded"}]};var is={onParentEvent:async()=>{},getInputNames:()=>[],getOutputNames:()=>[],getDefaultState:()=>({text:"",color:"#eac43e",size:{width:300,height:200}})};var ss={onParentEvent:async(e,t,n,r)=>{try{const e=((e,t)=>{switch(t){case fe.Number:case fe.Boolean:case fe.String:return String(e);case fe.Array:case fe.JsonObj:case fe.Rect:case fe.Point:return JSON.stringify(e,((e,t)=>"bigint"==typeof t?t.toString():t));case fe.ArrayBuffer:if(e instanceof ArrayBuffer){if(ee)return Buffer.from(e).toString("base64");{const t=new Uint8Array(e),n=t.length,r=new Array(n);for(let e=0;e<n;e++)r[e]=String.fromCharCode(t[e]);return btoa(r.join(""))}}throw new Error("Type is ArrayBuffer but value is not an ArrayBuffer");case fe.ImageData:{if(!je(e))throw new Error("Expected ImageData");const t=e,n=Ce(t.width,t.height),r=ke(n);if(!r)throw new Error("Failed to get canvas context");r.putImageData(t,0,0);const i=n.toDataURL("image/png");if(!i)throw new Error("Failed to convert canvas to data URL");return i.split(",")[1]}default:return String(e)}})(n.data.value,n.data.type);return r.nextWidget("text",{type:fe.String,value:e})}catch(e){return r.nextWidget("error",{type:fe.String,value:e instanceof Error?e.message:"Failed to stringify object"})}},getInputNames:()=>[{name:"object",type:[fe.Number,fe.String,fe.ArrayBuffer,fe.Array,fe.Boolean,fe.JsonObj,fe.Rect,fe.Point,fe.ImageData]}],getOutputNames:()=>[{name:"text",type:fe.String},{name:"error",type:fe.String}],getDefaultState:()=>({})};const os=e=>{if(Array.isArray(e))return e.map(((e,t,n)=>null===e||"object"!=typeof e?{value:e,"@index":t,"@indexPlus1":t+1,"@isFirst":0===t,"@isLast":t===n.length-1}:{...os(e),"@index":t,"@indexPlus1":t+1,"@isFirst":0===t,"@isLast":t===n.length-1}));if("object"==typeof e&&null!==e){const t={};for(const n in e){const r=e[n];t[n]=os(r)}return t}return e},as=(e,t)=>{const n=(e=>{const t=new Date;return{input:"object"==typeof e&&null!==e?os(e):{value:e},date:{year:t.getFullYear(),month:t.getMonth()+1,day:t.getDate(),hours:t.getHours(),minutes:t.getMinutes(),seconds:t.getSeconds(),milliseconds:t.getMilliseconds(),time:t.getTime(),dayOfWeek:t.getDay(),dayName:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][t.getDay()],shortDayName:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][t.getDay()],date:t.getDate(),fullYear:t.getFullYear(),timezoneOffset:t.getTimezoneOffset(),UTCDate:t.getUTCDate(),UTCDay:t.getUTCDay(),UTCFullYear:t.getUTCFullYear(),UTCHours:t.getUTCHours(),UTCMilliseconds:t.getUTCMilliseconds(),UTCMonth:t.getUTCMonth()+1,UTCMinutes:t.getUTCMinutes(),UTCSeconds:t.getUTCSeconds(),isoString:t.toISOString(),localeString:t.toLocaleString()}}})(t);return l.render(e,n)},cs=()=>({text:"",format:"Text"});var ls={onParentEvent:async(e,t,n,r)=>{const i={text:"",format:"Text",...r.getState()},s=as(i.text,n.data.value);return r.nextWidget("text",{type:fe.String,value:s})},getInputNames:()=>[{name:"input",type:fe.Anything}],getOutputNames:()=>[{name:"text",type:fe.String}],getDefaultState:cs};const ds=()=>({expression:""});var us={onParentEvent:async(e,t,n,r)=>{const i={expression:"",...r.getState()},s=((e,t)=>{const n=Symbol("error"),r=`\n // 'data' is an argument to this function, passed by new Function call.\n // 'SError' is also an argument, providing the error symbol.\n // 'this' inside this function (created by new Function) is the global object.\n\n\t\t// Shadow eval and Function in this non-strict scope.\n\t\tvar eval = undefined;\n\t\tvar Function = undefined;\n\n // Define the sandbox environment\n const sandboxEnvironment = {\n // Make input 'data' accessible\n data: data,\n \n // Safe console (bind methods to the original console)\n console: undefined,\n\n // Mocked/disabled globals\n process: undefined,\n document: undefined,\n navigator: undefined,\n \n require: undefined,\n // eval and Function are shadowed by var declarations above\n \n // Allowed safe globals (pointing to the real ones, accessed via 'this')\n Math: this.Math,\n Date: this.Date,\n JSON: this.JSON,\n Array: this.Array,\n Object: this.Object,\n String: this.String,\n Number: this.Number,\n Boolean: this.Boolean,\n RegExp: this.RegExp,\n // Error: this.Error, // Not Allow Error constructor\n Symbol: this.Symbol, // Allow Symbol constructor\n Map: this.Map,\n Set: this.Set,\n Promise: this.Promise, // Allow Promise if async expressions are intended\n // setTimeout, setInterval, fetch, etc., are deliberately omitted\n };\n\n // Assign the sandboxEnvironment to act as the 'global' context variables\n const global = sandboxEnvironment;\n const window = sandboxEnvironment;\n const globalThis = sandboxEnvironment;\n\n // Shadow top-level variables that might be accessed directly,\n // ensuring they use the sandboxed versions.\n const process = sandboxEnvironment.process;\n const document = sandboxEnvironment.document;\n const navigator = sandboxEnvironment.navigator;\n const console = sandboxEnvironment.console; // Use the sandboxed console for the expression\n const require = sandboxEnvironment.require;\n // 'eval' and 'Function' are already shadowed by var declarations\n\n // The expression will be evaluated in this scope.\n // 'data' is available as it's an argument to the outer function.\n // 'global.xxx' will resolve to 'sandboxEnvironment.xxx'.\n // 'process.yyy' will resolve to 'sandboxEnvironment.process.yyy'.\n \n return () => {\n "use strict"; // Apply strict mode only to the expression evaluation scope\n const abort = Symbol('abort'); // Local symbol for the expression's optional special return value\n\n let result;\n try {\n // Strict mode can add a layer of security and prevent some common errors.\n // It also changes 'this' binding within the expression if it uses 'this'.\n // If the expression uses 'this', under strict mode it would be undefined unless explicitly set.\n // For expressions not using 'this', strict mode is generally safer.\n result = (() => { return ${t}; })();\n } catch(e) {\n // Log the error using the sandboxed console\n // Use 'instanceof Error' to ensure 'e' has a message property.\n const errorMessage = e instanceof Error ? e.message : String(e);\n return {\n\t\t\t\t\terror: 'Error during expression execution: ' + errorMessage, \n\t\t\t\t\tvalue: null\n\t\t\t\t}; // Return the SError symbol passed into this function's scope\n }\n \n\t\t\t// allows ternary expressions that return 'abort' to cancel the evaluation\n if (result !== abort) {\n // Original logic: if result is strictly true, and expression wasn't literally "true", return original data.\n if (result === true && String(expression).trim() !== 'true') {\n return {value: data, error: null}; \n } else {\n return {value: result, error: null};\n }\n }\n \n // If the expression explicitly returned the 'abort' symbol\n return {value: abort, error: null}; \n }\n // End of functionBody template literal\n `;try{return new Function("data","SError",r)(e,n).call({})}catch(e){return{error:e.message,value:null}}})(n.data.value,i.expression);if("symbol"==typeof s.value)return;if(s.error)throw new Error(s.error);if(Number.isNaN(s.value))throw new Error("Expression resulted in NaN");if(void 0===s.value||null===s.value)return;const o=Fe(s.value);return o!==i.$$lastResultType&&r.setState({...i,$$lastResultType:o}),r.nextWidget("result",{type:o,value:s.value})},getInputNames:()=>[{name:"data",type:fe.Anything}],getOutputNames:e=>[{name:"result",type:e.$$lastResultType||fe.Anything}],getDefaultState:ds};var ps={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};r.setState({...i,$$lastEventType:n.data.type});try{await r.nextWidget("event",n.data)}catch(e){const t=e;await r.nextWidget("error",{type:fe.JsonObj,value:{error:{message:e.message,targetWidgetId:t.targetWidgetId,targetPortName:t.targetPortName,sourcePortName:t.sourcePortName,sourceWidgetId:t.sourceWidgetId,targetWidgetType:t.targetWidgetType,sourceWidgetType:t.sourceWidgetType,stack:e.stack},inputEvent:{type:n.data.type,data:n.data.value}}})}},getInputNames:()=>[{name:"event",type:fe.Anything}],getOutputNames:e=>[{name:"event",type:{...e}.$$lastEventType??fe.Anything},{name:"error",type:fe.JsonObj,jsonShape:{error:fe.JsonObj,inputEvent:fe.JsonObj}}]};const gs={},hs=Object.freeze({output:"output"}),fs=Object.freeze({read:"read",clear:"clear"}),ms=()=>({$$$time:0,totalInputs:1});var ys={onParentEvent:async(e,t,n,r)=>{const i={$$$time:0,totalInputs:1,...r.getState()};if(gs[r.id]||(gs[r.id]={}),t.name===fs.clear)return gs[r.id]={},void r.setState(i);const s=t.name===fs.read;if(!(s||n.data.type!==fe.JsonObj&&n.data.type!==fe.Anything&&n.data.type!==fe.Rect||"object"!=typeof n.data.value||null===n.data.value||Array.isArray(n.data.value))){const e=gs[r.id]||{};gs[r.id]={...e,...n.data.value}}if(s){const e={...gs[r.id]};return gs[r.id]={},r.setState({...i}),r.nextWidget(hs.output,{type:fe.JsonObj,value:e})}},getInputNames:e=>{const t={$$$time:0,totalInputs:1,...e},n=Array(t.totalInputs||1).fill(0).map(((e,t)=>({name:`input${t+1}`,type:fe.Anything})));return n.push({name:fs.clear,type:fe.Anything},{name:fs.read,type:fe.Anything,triggerPort:!0}),n},getOutputNames:()=>[{name:hs.output,type:fe.JsonObj}],getDefaultState:ms,initialize:async e=>{gs[e.widgetId]={}},terminate:async e=>{delete gs[e.widgetId]}};const vs={},bs=Object.freeze({output:"output",index:"index",finish:"finish"}),Ss=Object.freeze({array:"array",next:"next",clear:"clear"}),ws=()=>({autoLoop:!1,autoClear:!1,$$outputType:fe.Anything,totalItems:0,currentIndex:0});const Is={input:it,counter:at,elapsed:dt,ifGate:ht,skipEvent:yt,between:wt,map:$t,parser:Et,slider:Nt,suspend:Tt,display:Bt,json:Ut,arrayItem:Mt,extractImage:zt,imageConvolution:Xt,firstEvent:tn,pixelDraw:dn,randomBetween:hn,arrayCombine:bn,clock:_n,multiplication:En,object:Bn,widgetGroup:Rn,script:Fr,base64ToImageData:qr,jsonParse:Xr,text:ti,imageCrop:si,imageResize:li,value:gi,imageWarp:yi,widgetBundle:Di,sequence:Mi,variable:Hi,hubService:Xi,imageFilter:ts,recipeLoad:rs,note:is,stringify:ss,templateString:ls,expressionEval:us,rescue:ps,objectCombine:ys,loop:{onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...ws(),...i};if(t.name===Ss.clear)return delete vs[r.id],void r.setState({...ws(),autoLoop:s.autoLoop,autoClear:s.autoClear});if(t.name!==Ss.array)t.name===Ss.next&&await(async e=>{const t=e.id,n=vs[t],r={...ws(),...e.getState()};if(n&&n.index<n.list.length){const i=n.index,s=n.list[i];await e.nextWidget(bs.index,{type:fe.Number,value:i}),await e.nextWidget(bs.output,{type:r.$$outputType,value:s}),n.index++,e.setState({...r,currentIndex:n.index}),n.index===n.list.length&&(await e.nextWidget(bs.finish,{type:fe.Boolean,value:!0}),r.autoClear?(delete vs[t],e.setState({...ws()})):(n.index=0,e.setState({...r,currentIndex:0})))}})(r);else if((n.data.type===fe.Array||n.data.type===fe.Anything)&&Array.isArray(n.data.value)){const e=n.data.value,t=e[0],i=void 0!==t?Fe(t):fe.Anything,o={list:e,index:0};vs[r.id]=o;const a={...s,$$outputType:i,totalItems:e.length,currentIndex:0};if(r.setState(a),a.autoLoop&&e.length>0){for(const t of e){const e=o.index;r.setState({...a,currentIndex:e}),await r.nextWidget(bs.index,{type:fe.Number,value:e}),await r.nextWidget(bs.output,{type:a.$$outputType,value:t}),o.index++}await r.nextWidget(bs.finish,{type:fe.Boolean,value:!0}),a.autoClear?(delete vs[r.id],r.setState({...a,$$outputType:fe.Anything,totalItems:0,currentIndex:0})):(o.index=0,r.setState({...a,currentIndex:0}))}}},getInputNames:()=>[{name:Ss.array,type:fe.Array},{name:Ss.next,type:fe.Anything},{name:Ss.clear,type:fe.Anything}],getOutputNames:e=>{const t={...ws(),...e};return[{name:bs.index,type:fe.Number},{name:bs.output,type:t.$$outputType},{name:bs.finish,type:fe.Anything}]},getDefaultState:ws,initialize:async e=>{const t={...ws(),...e.getState()};vs[e.widgetId]={list:[],index:0},e.setState({...t,currentIndex:0,totalItems:0})},terminate:async e=>{delete vs[e.widgetId]}},play:{getInputNames:()=>[],onParentEvent:()=>Promise.resolve(),getOutputNames:()=>[{name:"out",type:fe.Boolean}]}},_s={},$s=async()=>{if(!Object.keys(_s).length)for(const e in Is){const t=Is[e];_s[e]=Object.freeze({...t})}};var Cs=e=>{if(_s[e])return _s[e];throw new Error(tt(Qe,e))},ks=$s;const Es=new o,xs="invoked";let As={},Ns={},Ps={},Os={};const Ts=(e,t,n)=>`${e}-${t}${n?`-${n}`:""}`;var Ls=(e,t,n,r,i)=>{const s=Ts(e,t,n),o=Ts(e,t),a=Ts(e,t,"produced"),c=Ps[o],l=Date.now();Os[o]=l,As[s]={data:r,sourcePortName:n,...i?{target:{widgetId:i.widgetId,portName:i.portName}}:{}},Es.emit(a,{currentTime:l,prevTime:c,...i?{targetPort:i?.portName}:{}})},Bs=(e,t,n,r,i)=>{const s=Ts(e,t,n),o=Ts(e,t),a=Ts(e,t,xs),c=Ps[o],l=Date.now();Ps[o]=l,Ns[s]={data:r,sourcePortName:n,...i?{source:{widgetId:i.widgetId,portName:i.portName}}:{}},Es.emit(a,{prevTime:c,currentTime:l,targetPort:n,sourceInfo:i})},Ds=()=>{As={},Ns={},Ps={},Os={},Es.clearListeners()};const js={};let Us={};const Rs=new o;let Fs=!1,Ms=!1,Ws=!1,Gs=null,Vs=null;const Hs="processing-state-change",zs="error-event",qs={abortRequested:!1,isPaused:!1,pausePromise:null,pausePromiseResolve:null,lastPausedWidgetId:null},Ks=e=>(Vs=e,Rs.emit(Hs,e)),Js=(e,t)=>`${e}-${t}`,Ys=(e,t)=>`state-change:${Js(e,t)}`,Xs=e=>{const{thingId:t,widgetId:n}=e,r=Js(t,n);return js[r]||{isProcessing:!1}},Zs=()=>{qs.abortRequested=!1,qs.isPaused=!1},Qs=e=>(qs.pausePromise||(qs.isPaused=!0,qs.pausePromise=new Promise((e=>{qs.pausePromiseResolve=e})),e&&(qs.lastPausedWidgetId=e),Ks({isProcessing:!0,isPaused:!0,...e?{pauseTrapWidgetId:e}:{}})),qs.pausePromise);var eo,to,no=async e=>{const{thingId:t,widgetId:n}=e,r=Js(t,n),i=Ys(t,n),s=Xs({thingId:t,widgetId:n});if(s.isProcessing)return;const o={isProcessing:!0,isPaused:!1,startTime:Date.now()};js[r]=o,Fs||(Fs=!0,Gs=null,await Ks({isProcessing:!0,isPaused:!1})),await Rs.emit(i,{thingId:t,widgetId:n,prevState:s,newState:o})},ro=async e=>{const{thingId:t,widgetId:n,error:r}=e,i=Js(t,n),s=Ys(t,n),o=Xs({thingId:t,widgetId:n}),a={isProcessing:!1,isPaused:!1,startTime:o.startTime,endTime:Date.now(),error:r};js[i]=a,await Rs.emit(s,{thingId:t,widgetId:n,prevState:o,newState:a}),r&&(Gs=r,await Rs.emit(zs,r)),Fs&&0===Object.values(js).filter((e=>e.isProcessing)).length&&(Fs=!1,Ms=!1,Zs(),await Ks({isProcessing:!1,isPaused:!1}))},io=()=>{Fs=!1;for(const e in js)delete js[e];qs.abortRequested=!1,qs.isPaused=!1,qs.pausePromise=null,qs.pausePromiseResolve=null,qs.lastPausedWidgetId=null,Rs.clearListeners()},so=()=>qs.abortRequested,oo=e=>{qs.lastPausedWidgetId=e,qs.isPaused=!0,Ks({isProcessing:!0,isPaused:!0,pauseTrapWidgetId:e})},ao=()=>Ms||Ws?null:qs.pausePromise,co=e=>Ws?null:Us[e]??null,lo=()=>Ms,uo=e=>Qs(e);!function(e){e.ServiceCreationLog="service-creation-log"}(eo=eo||(eo={})),function(e){e.Service="service",e.ServiceUI="serviceUI"}(to=to||(to={}));let po={},go={},ho=null;const fo=(e,t)=>{const n=(()=>{if(null===ho)throw new Error("Recipe execution type not set, please set the execution type using `setRecipeExecutionType`");return ho===Gn.Desktop})();let r=n?go[e]:void 0;return r||(r=(e=>{const{widgets:t,targetId:n,allowedTypes:r}=e;if(!t[n])return[];const i=new Set;Object.values(t).forEach((e=>{e.children?.forEach((e=>i.add(e.childId)))}));const s=Object.keys(t).filter((e=>!i.has(e))),o=s.length>0?s:Object.keys(t),a=[],c=(e,i,s)=>{if(s.has(e))return;s.add(e);const o=t[e],l=!r||r.includes(o.type),d=[...i];l&&d.push(e),e===n?a.push(d.join("/")):o.children?.forEach((e=>c(e.childId,d,s))),s.delete(e)};return o.forEach((e=>c(e,[],new Set))),[...new Set(a)]})({widgets:t,targetId:e,allowedTypes:[ze.hubService]}),n&&(go[e]=r)),r},mo=(e,t,n)=>{fo(t,n).forEach((n=>{po[n]={eventContext:e,widgetId:t}}))},yo=(e,t)=>{const n=t[e].state,r=n.service?.name;if(!r)return[];const i=fo(e,t),s=new Map;for(const e of i){const n=e.split("/");let i="";for(let e=0;e<n.length-1;e++){i=0===e?n[e]:`${i}/${n[e]}`;const o=po[i];if(o&&!s.has(o.widgetId)){const e=t[o.widgetId].state;e.service?.name===r&&s.set(o.widgetId,{path:i,data:o,pathSegments:i.split("/").length})}}}return Array.from(s.values())},vo=()=>{po={}},bo=e=>{ho=e},So=()=>{po={},go={}};let wo,Io,_o,$o=!1,Co=0;const ko=async e=>{const{widgetId:t,thingId:n,recipeId:r,targetPortName:i,data:s}=e,o=se(r,n);if(!o)return;const a=o.gates[t];if(!a||a.disabled)return;const c={...s,timestamp:Date.now()},l=Cs(a.type),d=Po({gateId:t,originalEvent:c,blockRecipeId:o.recipeId,blockDbId:o.id,blockVersion:o.version,recipeId:r});if(d&&l.onParentEvent){const e={name:i};return wo&&await wo({recipeId:r,blockId:o.recipeId,gateId:t,targetPort:e.name,data:s}),l.onParentEvent(null,e,{originalEvent:c,data:{...c}},d)}},Eo=async e=>{const{interruptDriven:t,childGateId:n,recipeId:r,sourcePortName:i,targetPort:s,data:o,sourceOutputNames:a,sourceGateId:c}=e;let{originalEvent:l,block:d}=e;if(!t&&!c)throw new Error("Missing parameter ['sourceGateId']");if(!t&&!l)throw new Error("Missing parameter ['originalEvent']");t&&(l={timestamp:Date.now(),type:fe.Boolean,value:!0});const u=l;if("string"==typeof d){const e=se(r,d);if(!e)return;d=e}const p=d.gates[n];if(!p||p.disabled)return;const g=a.findIndex((e=>e.name===i)),h=Cs(p.type),f=Po({gateId:n,originalEvent:u,blockRecipeId:d.recipeId,blockDbId:d.id,blockVersion:d.version,recipeId:r});if(f&&h.onParentEvent&&-1!==g){wo&&await wo({recipeId:r,blockId:d.recipeId,gateId:n,targetPort:s.name,data:o,sourceGate:t?"interrupt_widget":c,sourcePort:t?ce:i});const e={name:a[g].name,type:a[g].type,...a[g].jsonShape?{jsonShape:a[g].jsonShape}:void 0};return Bs(d.recipeId,n,s.name,o,c?{widgetId:c,portName:i}:void 0),h.onParentEvent(e,s,{originalEvent:u,data:o},f)}},xo=async e=>{const{portName:t,originalEvent:n,data:r,currentGateId:i,blockRecipeId:s,thingDbId:o,thingVersion:a,recipeId:c,eventContext:l}=e,d=ie(c);if(!d)throw new Error(`Failed to find recipe "${c}" in cache`);const u=d.dbInfo.recipeType,p=oe(c,s,i);if(!p)return;const g={...r,timestamp:n.timestamp},h=Cs(p.type);let f;f=p.type===ze.input?h.getOutputNames(p.state,{thingRecipeId:s,thingDbId:o,thingVersion:a,id:i,recipeId:c,recipeType:u,recipePoolId:c}):await h.getOutputNames(p.state,{recipePoolId:c,recipeType:u,thingRecipeId:s,widgetId:i});const m=f.findIndex((e=>e.name===t));if(-1!==m){const e=se(c,s);if(!e)return;Ls(s,i,t,g);let r=null;const o=p.children.length;if(p.type===ze.hubService&&l){const t=p.state,n=t.service?.name;n&&mo(l,p.id,e.gates)}try{for(let a=0;a<o;a++){const o=e.gates[p.children[a].childId];if(o?.disabled)continue;const l=Ge(p.children[a]?.sourcePort),d=Ge(p.children[a]?.targetPort);if(l.portName===t&&o&&!o.disabled){if($o&&ao()&&(oo(o.id),await ao()),co(o.id)&&!lo()&&"innerInput"!==d?.portType){const e=uo(o.id);await e}if($o&&so())break;const a=Cs(o.type);let l;const h={recipePoolId:c,recipeType:u,thingRecipeId:s,widgetId:i};l=o.type===ze.hubService?await a.getInputNames(o.state,h):a.getInputNames(o.state,h);const m=l.find((e=>e.name===d.portName));if(m){$o&&await no({thingId:s,widgetId:o.id}),Co++;if(!await Eo({interruptDriven:!1,childGateId:o.id,block:e,recipeId:c,sourcePortName:t,targetPort:{name:m.name},data:p.returnOriginalEvent?n:g,sourceOutputNames:f,sourceGateId:p.id,originalEvent:n}).then((()=>!0)).catch((e=>{const n=o.type===ze.hubService&&"CHILD_WIDGET_ERROR"===e.errCode;if(e instanceof tr)throw e;if(n&&e.errData){const t=e.errData;throw new tr(e.error||e.message||("string"==typeof e?e:JSON.stringify(e)),{targetWidgetId:t.targetWidgetId,targetPortName:t.targetPortName,sourcePortName:t.sourcePortName,sourceWidgetId:t.sourceWidgetId,targetWidgetType:t.targetWidgetType,sourceWidgetType:t.sourceWidgetType})}if(!r){const n="string"==typeof e?e:e.message||JSON.stringify(e);r={targetWidgetId:o.id,targetPortName:m.name,sourcePortName:t,error:n}}throw new tr(e.message||("string"==typeof e?e:JSON.stringify(e)),{stack:e.stack,targetWidgetId:o.id,targetPortName:m.name,sourcePortName:t,sourceWidgetId:p.id,targetWidgetType:o.type,sourceWidgetType:p.type})})).finally((()=>{if(Co--,$o)return ro({thingId:s,widgetId:o.id,error:r})})))break}}}}catch(e){if(e instanceof tr)throw e;console.error(`Error processing next widget [${i}]: ${e}`)}finally{Co<0&&(console.warn("Active execution counter is negative, this should never happen"),Co=0),0===Co&&vo()}}},Ao=async(e,t,n,r)=>{const i=ie(r);if(!i)return null;const s=se(r,n);if(!s)return s;const o=s.gates,a=s.gates[t],c=Cs(a.type),l=await c.getInputNames(a.state,{recipePoolId:r,recipeType:i.dbInfo.recipeType,thingRecipeId:n,widgetId:t}),d=l.findIndex((t=>t.name===e));if(-1!==d){const e=((e,t,n)=>{for(const r in n){const i=n[r],s=i.children.length;for(let n=0;n<s;n++){const r=i.children[n],s=Ge(r.targetPort);if(r.childId===e&&s.portName===t)return i}}return null})(t,l[d].name,o);if(e){const t=Cs(e.type);return{getValue:()=>"function"==typeof t.getValue?t.getValue():null}}}return null},No=e=>{const{gateId:t,originalEvent:n,thingRecipeId:r,thingDbId:i,thingVersion:s,recipeId:o}=e;if(!ie(o))throw new Error(`Failed to find recipe "${o}" in cache`);if(!oe(o,r,t))throw console.warn(`Gate ${t} not found in block ${r} for recipe ${o}`),new Error(`Gate ${t} not found in block ${r} for recipe ${o}`);return async(e,a)=>xo({portName:e,originalEvent:n||{timestamp:Date.now(),type:a.type,value:a.value},data:a,currentGateId:t,blockRecipeId:r,thingDbId:i,thingVersion:s,recipeId:o})},Po=e=>{const{gateId:t,originalEvent:n,blockRecipeId:r,blockDbId:i,blockVersion:s,recipeId:o}=e,a=ie(o);if(!a)throw new Error(`Failed to find recipe "${o}" in cache`);const c=oe(o,r,t);if(!c)return console.warn(`Gate ${t} not found in block ${r} for recipe ${o}`),null;const l=No({gateId:t,originalEvent:n,thingRecipeId:r,thingDbId:i,thingVersion:s,recipeId:o}),d=c.type===ze.hubService,u=d?yo(t,a.blocks[r].gates):[],p=u.reduce(((e,t)=>e.pathSegments>t.pathSegments?e:t),u[0]),g={id:t,type:c.type,recipePoolId:o,thingRecipeId:r,recipeType:a.dbInfo.recipeType,returnOriginalEvent:!!c.returnOriginalEvent,registerInterrupt:(e,n,i,s,a)=>Xe.createInterrupt(e,o,r,t,n,i,s,a),cancelInterrupt:e=>Xe.destroyInterrupt(e),nextWidget:l,nextGate:l,getParentAtPort:e=>Ao(e,t,r,o),getState:()=>Object.freeze({...c.state,...c.type===ze.input&&{customInputs:[]}}),setState:e=>{if("object"!=typeof e)return void console.warn(`Invalid state type [${typeof e}]. Expected an 'object'`);const n={...e,...c.type===ze.input&&!e.customInputs&&{customInputs:[]}},i={...c.state};c.state=n,Io&&Io({blockId:r,gateId:t,prevState:i,newState:{...n},recipeId:o})},...d&&p&&{eventContext:p.data.eventContext}};return g};Xe.setInvokeChildGateCb((async(e,t,n,r,i,s,o,a,c,l)=>Eo({interruptDriven:e,childGateId:t,block:n,recipeId:r,sourcePortName:i,targetPort:s,data:o,sourceOutputNames:a,sourceGateId:c,originalEvent:l})));const Oo=(e,t,n,r,i)=>{const s=oe(e,n,r);if(!s)return console.warn(`Gate ${r} not found in block ${n} for recipe ${e}`),null;const o=(t,i,s,o)=>Xe.createInterrupt(t,e,n,r,i,s,o),a=()=>Object.freeze({...s.state,...s.type===ze.input&&{customInputs:[]}}),c=e=>{if("object"!=typeof e)return void console.warn(`Invalid state type [${typeof e}]. Expected an 'object'`);const t={...e,...s.type===ze.input&&!e.customInputs&&{customInputs:[]}};s.state=t},l=async t=>{const r=((e,t,n)=>{const r=ie(e);if(!r)throw new Error(`Recipe [${e} does not exist]`);if(!r.storage)return null;const i=se(e,t);if(!i)throw new Error(`The Thing "${t}" does not exist in recipe ${e}`);if(!(i.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};if(i){return{getState:a,setState:c,registerInterrupt:o,getStorageData:l,nextWidget:No({gateId:r,thingRecipeId:n,thingDbId:s.id,thingVersion:"default",recipeId:e}),recipePoolId:e,recipeType:t,thingRecipeId:n,widgetId:r}}return{getState:a,setState:c,recipePoolId:e,widgetId:r}},To=new o,Lo="invoked",Bo="state",Do=()=>{Xe.destroyAllInterrupts()},jo=async(e,t,n)=>{const r=ie(e),i=oe(e,t,n);if(i&&r){const s=Cs(i.type);if(s&&"function"==typeof s.terminate){const i=((e,t,n,r)=>Oo(e,t,n,r))(e,r.dbInfo.recipeType,t,n);if(i)try{await s.terminate(i)}catch(e){console.warn(`Error terminating widget "${n}" in thing "${t}". Failing silently: `,e)}}}},Uo=async e=>{const{recipePoolId:t,thingRecipeId:n,widgetRecipeId:r,options:i}=e,s=ie(t),o=oe(t,n,r);if(o&&s){const e=Cs(o.type);if(e&&"function"==typeof e.initialize){const a=((e,t,n,r)=>Oo(e,t,n,r,!0))(t,s.dbInfo.recipeType,n,r);if(a){const t=e.initialize;try{(e=>{if(e.type===ze.script){const t=e.state;if((t.version||0)<2){const n=Object.keys(e.variablesListener||{});for(const t of n)if(e.variablesListener){const n=Sr(t);e.variablesListener[n]=e.variablesListener[t],delete e.variablesListener[t],delete e.variables}t.version=2}}})(o),await t(a,i||{})}catch(e){throw console.warn(`Error initializing widget "${r}" in thing "${n}": `,e),e}}}}},Ro=(e,t)=>{const n=ie(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},Fo=(e,t="",n="")=>`block:${t}:gate:${n||""}:${e}`,Mo=e=>{To.emit(Fo(Bo),e),To.emit(Fo(Bo,e.blockId,e.gateId),e)};wo=async e=>{await To.emit(Fo(Lo),e),await To.emit(Fo(Lo,e.blockId,e.gateId),e)},(e=>{Io=e})(Mo);var Wo,Go,Vo,Ho,zo,qo,Ko,Jo,Yo,Xo,Zo,Qo,ea,ta=async(e,t,n,r,i)=>{const s=ae(e,{id:t,authorId:r,version:n,recipeType:i});Ds(),So(),bo(i);const o=ie(s);return o&&(o.startedAt=Date.now(),o.retryAttempts=0,o.execCounter=0,o.status=X.STARTING,o.addLog("recipe registered")),s},na=async e=>{const t=ie(e);var n;if(!t)return null;t.addLog("terminating recipe"),Do(),io();for(const n in t.blocks){const r=t.blocks[n];for(const t in r.gates)await jo(e,n,t)}te[n=e]&&delete te[n]},ra=async(e,t)=>{const n=ie(e),r=[],i=[];if(n){Er({recipePoolId:e,thingId:ge});for(const s in n.blocks){const o=n.blocks[s];if(!t||!Array.isArray(t)||t.includes(s))for(const t in o.gates)try{if(n.dbInfo?.recipeType===Gn.Desktop){const e=o.gates[t];if(e.type===ze.hubService){const r=e.state;if(r?.service?.webOnly){n?.addLog(`skipping initialization of web-only widget "${t}"`);continue}}e.type===ze.recipeLoad&&i.push(e)}await Uo({recipePoolId:e,thingRecipeId:s,widgetRecipeId:t,options:{keepCurrentState:!0}})}catch(e){r.push({widgetId:t,error:e.message})}}}return{failed:r,sendToInputWidget:(t,n,r=ge)=>(async(e,t,n,r)=>{const i=ie(n),s=se(n,r),o=Date.now();if(s&&i)for(const i in s.gates){const a=s.gates[i];if(a.type===ze.input&&!a.disabled){const c=a.state.inputName||"";if(c===e){const e=Cs(a.type),l={...t,timestamp:o},d=Po({gateId:i,originalEvent:l,blockRecipeId:r,blockDbId:s.id,blockVersion:s.version,recipeId:n});if(d&&e.processEvent){const s={...d,getState:d.getState};wo&&await wo({recipeId:n,blockId:r,gateId:i,targetPort:rt,data:t}),_o?await _o(r,n,c,t):await e.processEvent(l,s)}}}}})(t,n,e,r),invokeRecipeLoadedWidgets:async()=>{for(const t of i)await ko({widgetId:t.id,thingId:ge,recipeId:e,targetPortName:ns,data:{type:fe.Boolean,value:!0}})}}},ia=e=>{qi(e)},sa=(e,t,n,r=!1)=>{const i=Ro(t,e);if(i){const{widget:s,thing:o}=i,a={...s.state};s.state=n,r&&Mo({blockId:o.recipeId,gateId:t,recipeId:e,newState:{...n},prevState:a})}},oa=(e,t)=>{const n=Ro(t,e);return n?n.widget.state:null},aa=async e=>{const{recipePoolId:t,currentGateId:n,sourcePortName:r,originalEvent:i,data:s,eventContext:o}=e,a=Ro(n,t);if(a)return xo({portName:r,originalEvent:i,data:s,currentGateId:n,blockRecipeId:a.thing.recipeId,thingDbId:a.thing.id,thingVersion:a.thing.version,recipeId:t,eventContext:o})};!function(e){e.Seats="seats",e.RecipeInvocations="recipe_invocations",e.HubServices="hub_services",e.RecipeExports="recipe_exports"}(Wo||(Wo={})),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"}(Go||(Go={})),function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(Vo||(Vo={})),function(e){e.Bundle="bundle",e.Group="group"}(Ho||(Ho={})),function(e){e.Hardware="hardware",e.Virtual="virtual"}(zo||(zo={})),function(e){e.Cloud="cloud",e.Web="web"}(qo||(qo={})),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"}(Ko||(Ko={})),function(e){e.Gateway="gateway",e.Timer="timer"}(Jo||(Jo={})),function(e){e.InstallInProgress="installation-in-progress"}(Yo||(Yo={})),function(e){e.InstallDependencies="install-dependencies",e.GetInstalledDependencies="get-installed-dep"}(Xo||(Xo={})),function(e){e.Success="success",e.Error="error",e.Pending="pending"}(Zo||(Zo={})),function(e){e.NotFound="not-found",e.BadRequest="bad-request",e.Forbidden="forbidden",e.InternalError="internal-error"}(Qo||(Qo={})),function(e){e.KeyCreated="key_created",e.ValidateKey="validate_key",e.ExecuteRecipe="execute_recipe",e.InstallHubService="install_hub_service",e.UninstallHubService="uninstall_hub_service",e.ExportRecipe="export_recipe"}(ea||(ea={}));const ca=(e,t)=>((e,t,n)=>{const r=Buffer.from(n,"base64"),i=r.subarray(0,16),s=r.subarray(16).toString("base64"),o=u(e,t,32),a=p("aes-256-cbc",o,i);let c=a.update(s,"base64","utf8");return c+=a.final("utf8"),c})(e.id||"recipe.kemu","kemu",t);var la,da,ua,pa,ga,ha,fa,ma;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(la||(la={})),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"}(da||(da={})),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"}(pa||(pa={})),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.GetSystemInfo="getSystemInfo",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.UninstallService="uninstallService",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.GetUniqueId="getUniqueId",e.RebootToInstallUpdate="rebootToInstallUpdate",e.GetFileContentFromCacheId="getFileContentFromCacheId",e.GetDecryptedEdgeApiKey="getDecryptedEdgeApiKey"}(ha||(ha={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(fa||(fa={})),function(e){e.IPC="ipc",e.WS="ws"}(ma||(ma={}));const ya=e=>{try{return JSON.parse(e)}catch(e){return null}},va="undefined"!=typeof window,ba={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},Sa={protocolPrefix:4,txtLength:4},wa=Object.values(ba).reduce(((e,t)=>e+t),0),Ia=Object.values(Sa).reduce(((e,t)=>e+t),0),_a=["width","height","colorSpace"],$a=(e,t)=>{const n={},r=[];let i=0,s=Array.isArray(e)?[]:{};const o=(e,s)=>{const a=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,i=e instanceof Uint8Array,s=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":i?"Uint8Array":s?"Int8Array":null})(e);if(!a){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=o(e[n],`${s}[${n}]`);return t}if("object"==typeof e){const t={},n=(e=>{const t=e instanceof Int16Array,n=e instanceof Uint16Array,r=e instanceof Int32Array,i=e instanceof Uint32Array,s=e instanceof Float32Array,o=e instanceof Float64Array,a=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":i?"Uint32Array":s?"Float32Array":o?"Float64Array":a?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${s}"`);for(const n in e)Object.hasOwn(e,n)||_a.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${s}`),t[n]=o(e[n],`${s.length?`${s}.`:""}${n}`);return t}return e}n[s]={index:i,length:e.byteLength,binaryType:a},"Buffer"===t?r.push(Buffer.from(e)):"ArrayBuffer"===a?r.push(e):r.push(e.buffer),i+=e.byteLength};s=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:s}:null},Ca=(e,t,n)=>{const r=t.match(/(\[\d+\])|([^[\].]+)/g)||[];let i=e;for(let e=0;e<r.length;e++){let t=r[e];const s=t.startsWith("[")&&t.endsWith("]"),o=e===r.length-1;if(s){t=t.slice(1,-1);const s=parseInt(t,10);if(!Array.isArray(i))throw new Error(`Expected an array at key "${r.slice(0,e).join(".")}" but found an object.`);o?i[s]=n:(i[s]||(i[s]=r[e+1].startsWith("[")?[]:{}),i=i[s])}else o?i[t]=n:(i[t]||(i[t]=r[e+1].startsWith("[")?[]:{}),i=i[t])}return e},ka=(e,t,n)=>{const r="undefined"!=typeof Buffer,i=t instanceof Uint8Array;for(const s in n)if(Object.hasOwn(n,s)){const{index:o,length:a,binaryType:c}=n[s];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=i?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a):t.slice(o,o+a);break;case"Uint8Array":l=i?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&&Ca(e,s,l)}return e},Ea=e=>f(e),xa="KMSG",Aa="KCMD",Na=Ea("klProtocol");var Pa={encode:(e,t,n)=>{const r={json:e.json},i=$a(r.json,"Buffer"),s=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const o=s?s.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),l=c.byteLength,d=ba.protocolPrefix+ba.protocolVersion+ba.jsonLength+ba.binaryLength+ba.fromServiceId+ba.toServiceId+ba.sentAt+l+o,u=Buffer.alloc(d),p=Date.now();let g=0;return u.write(xa,g),g+=ba.protocolPrefix,u.writeUInt8(1,g),g+=ba.protocolVersion,u.writeUInt32LE(l,g),g+=ba.jsonLength,u.writeUInt32LE(o,g),g+=ba.binaryLength,u.writeUInt32LE(t,g),g+=ba.fromServiceId,u.writeUInt32LE(n,g),g+=ba.toServiceId,u.writeBigInt64LE(BigInt(p),g),g+=ba.sentAt,c.copy(u,g),g+=l,s&&o&&s.copy(u,g),u},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,ba.protocolPrefix);if(t+=ba.protocolPrefix,n!==xa)return null;if(e.byteLength<wa)return Na(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=ba.protocolVersion;const i=e.readUInt32LE(t);t+=ba.jsonLength;const s=e.readUInt32LE(t);t+=ba.binaryLength;const o=e.readUInt32LE(t);t+=ba.fromServiceId;const a=e.readUInt32LE(t);t+=ba.toServiceId;const c=e.readBigInt64LE(t);t+=ba.sentAt;const l=i+s,d=e.subarray(t,t+l),u=e.subarray(0,wa);let p=null;return e.byteLength-wa-i-s>0&&(p=e.subarray(wa+i+s)),{header:{protocolVersion:r,jsonLength:i,binaryLength:s,fromServiceId:o,toServiceId:a,sentAt:new Date(Number(c)),packages:[d],headerPackage:u},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),i=ya(n);if(!i?.json)return Na("Invalid JSON in KL message"),null;i.jsonBinaryMap&&r.byteLength&&ka(i.json,r,i.jsonBinaryMap);const s=Buffer.concat([e.headerPackage,t]);let o=s,a=null;const c=wa+e.jsonLength+e.binaryLength;return s.byteLength>c&&(a=s.subarray(c),o=s.subarray(0,c)),{message:{json:i.json,rawMessage:o},remaining:a}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<wa)return Na("Invalid Header Size"),e;let n=0;return n+=ba.protocolPrefix,n+=ba.protocolVersion,n+=ba.jsonLength,n+=ba.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=ba.fromServiceId,void 0!==t.toServiceId&&e.writeUInt32LE(t.toServiceId,n),e},encodeCommand:e=>{let t=0;const n=Buffer.from(e),r=n.byteLength,i=Ia+r,s=Buffer.alloc(i);return s.write(Aa,t),t+=Sa.protocolPrefix,s.writeUint32LE(r,t),t+=Sa.txtLength,n.copy(s,t),s},decodeCommand:e=>{let t=0;if(e.byteLength<Ia)return{command:null};const n=e.toString("utf-8",t,Sa.protocolPrefix);if(t+=Sa.protocolPrefix,n!==Aa)return{command:null};const r=e.readUInt32LE(t);t+=Sa.txtLength;const i=e.toString("utf-8",t,t+r),s=e.byteLength-Ia-r;let o=null;s>0&&(o=e.subarray(Ia+r));let a=0;return s<0&&(a=Math.abs(s)),{command:i,remainingData:o,missing:a}}};const Oa="KMSG",Ta="KCMD",La=Ea("klProtocol"),Ba=new TextEncoder;var Da={encode:(e,t,n)=>{const r={json:e.json},i=$a(e.json,"ArrayBuffer"),s=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const o=s?s.byteLength:0,a=JSON.stringify(r),c=Ba.encode(a),l=c.byteLength,d=new ArrayBuffer(ba.protocolPrefix+ba.protocolVersion+ba.jsonLength+ba.binaryLength+ba.fromServiceId+ba.toServiceId+ba.sentAt+l+o),u=new DataView(d),p=new Uint8Array(d),g=Date.now();let h=0;for(let e=0;e<4;++e)p[h++]=Oa.charCodeAt(e);return u.setUint8(h,1),h+=ba.protocolVersion,u.setUint32(h,l,!0),h+=ba.jsonLength,u.setUint32(h,o,!0),h+=ba.binaryLength,u.setUint32(h,t,!0),h+=ba.fromServiceId,u.setUint32(h,n,!0),h+=ba.toServiceId,u.setBigInt64(h,BigInt(g),!0),h+=ba.sentAt,p.set(c,h),h+=l,s&&o&&p.set(new Uint8Array(s),h),d},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<ba.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Oa)return null;if(e.byteLength<wa)return La.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const i=t.getUint8(n);n+=ba.protocolVersion;const s=t.getUint32(n,!0);n+=ba.jsonLength;const o=t.getUint32(n,!0);n+=ba.binaryLength;const a=t.getUint32(n,!0);n+=ba.fromServiceId;const c=t.getUint32(n,!0);n+=ba.toServiceId;const l=t.getBigInt64(n,!0);n+=ba.sentAt;const d=s+o,u=e.slice(n,n+d),p=new Uint8Array(e,0,wa);let g=null;if(e.byteLength-wa-s-o>0){g=new Uint8Array(e,wa+s+o).slice().buffer}return{header:{protocolVersion:i,jsonLength:s,binaryLength:o,fromServiceId:a,toServiceId:c,sentAt:new Date(Number(l)),packages:[u],headerPackage:p.slice().buffer},remaining:g}},decodeFullKlMessage:e=>{const t=e.packages.reduce(((e,t)=>e+t.byteLength),0),n=new Uint8Array(t);let r,i=0;for(const t of e.packages)r=new Uint8Array(t),n.set(r,i),i+=r.byteLength;const s=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),o=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=ya(s);if(!a?.json)return La.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&o.byteLength&&ka(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,d=null;const u=wa+e.jsonLength+e.binaryLength;return c.byteLength>u&&(d=c.subarray(u),l=c.subarray(0,u)),{message:{json:a.json,...o.length?{binaryData:o.buffer}:{},rawMessage:l.buffer},remaining:d?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<wa)return La("Invalid Header Size"),e;let n=0;n+=ba.protocolPrefix,n+=ba.protocolVersion,n+=ba.jsonLength,n+=ba.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=ba.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=Ba.encode(e),r=n.byteLength,i=new ArrayBuffer(Ia+r),s=new DataView(i),o=new Uint8Array(i);for(let e=0;e<4;++e)o[t++]=Ta.charCodeAt(e);return s.setUint32(t,r,!0),t+=Sa.txtLength,o.set(n,t),i},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<Ia)return{command:null};let r="";for(let e=0;e<Sa.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Ta)return{command:null};const i=t.getUint32(n,!0);n+=Sa.txtLength;const s=e.byteLength-Ia-i,o=new Uint8Array(e,n,Math.min(i,e.byteLength-Ia)),a=(new TextDecoder).decode(o);let c=null;s>0&&(c=e.slice(Ia+i));let l=0;return s<0&&(l=Math.abs(s)),{command:a,remainingData:c,missing:l}}};let ja=Pa;va&&(ja=Da);var Ua,Ra=ja;!function(e){e.FunctionNotFound="FNC_NOT_FOUND",e.ParentEventCallbackError="PARENT_EVENT_CALLBACK_ERROR"}(Ua||(Ua={}));let Fa=Math.ceil(Date.now()/1e3);let Ma,Wa,Ga,Va,Ha,za=!1;var qa=()=>{za=!0},Ka=(e,t)=>{if(!Ma)throw new Error("Memory connection not set.");Ma.sendBuf(e,t)},Ja=e=>Wa=e,Ya=e=>Ha=e,Xa=e=>Ga=e,Za=e=>Va=e;const Qa=async(e,t=2)=>{const n=async(e,r)=>{if(Array.isArray(e))for(let i=0;i<e.length;i++){const s=e[i];if(s&&"object"==typeof s)if(Array.isArray(s))await n(s,r+1);else{const o=s._kemuType;void 0!==o?o===fe.ImageData&&(e[i]=await Ve(s)):r<t&&await n(s,r+1)}}else if("object"==typeof e&&null!==e){const i=Object.keys(e);for(const s of i){const i=e[s];if(i&&"object"==typeof i){const o=i._kemuType;void 0!==o?o===fe.ImageData&&(e[s]=await Ve(i)):r<t&&await n(i,r+1)}}}};return await n(e,1),e};Ea("klTransmissionManager"),Ea("ipcClient");Ea("kemuWidgetService"),k(process.argv.slice(2));const ec=e=>f(`runner:${e}`),tc=ec("connectionManager"),nc=ec("remoteInvoke"),rc=new function(e){const t={};let n=console.log;const r={};let i=e||String(Date.now());const s={},o=e=>!s[e],a=(e,t,n,r,i,s)=>{let a=va?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:s.success?s.success:[s],messageId:t,type:s.success?"response":"error"}};return o(r)&&(a=Ra.encode(c,n,r)),i(a,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{n=e},processMessage:(e,i,s,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,s.targetServiceId,s.sourceServiceId,i,e)};t({transport:e,args:c.args,reply:n,messageId:c.messageId,sourceServiceId:s.sourceServiceId,send:i})}else{const e=`Function "${c.functionName}" not found.`;n&&n(e),a(c.functionName,c.messageId,s.targetServiceId,s.sourceServiceId,i,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(e,r,s,a,c,l)=>{if(!s){const e="No send buffer function provided.";throw n&&n(e),e}Fa+=1;const d=`${i}-${Fa}-exec-${e.substring(0,10)}`,u={messageId:d,functionName:e,send:s,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};u.promise=new Promise(((e,t)=>{u.resolve=e,u.reject=t}));let p=va?new ArrayBuffer(0):Buffer.alloc(0);const g={json:{functionName:e,args:r,messageId:d,type:"execute"}};o(c)&&(p=Ra.encode(g,a,c)),t[d]=u,n&&n(`Calling remote function "${e}" with message id "${d}"`);const h="true"===process.env.NO_INVOKE_TIMEOUT;return l?.async?(u.fulfilled=!0,u.resolve([void 0]),delete t[d]):0===l?.timeout||h||(u.timer=setTimeout((()=>{n&&n(`Remote function ${d} timed out`);const r=t[d];r&&!r.fulfilled&&(r.fulfilled=!0,u.reject(`Function ${e} Timed out`)),delete t[d]}),l?.timeout||3e4)),s(p,{sourceServiceId:a,targetServiceId:c,msg:g}),u.promise},sendResponse:a,registerFunction:(e,t)=>{r[e]=t},getTransportSendFunction:e=>{const n=t[e];return n?n.send:null},setServiceName:e=>{i=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,s)=>{Fa+=1;const a=`${i}-${Fa}-multicast-${e.substring(0,10)}`;let c=va?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:t,messageId:a,type:"execute"}};let d=o(r[0].serviceId);d&&(c=Ra.encode(l,s,r[0].serviceId));for(let t=0;t<r.length;t++)try{const i=r[t];n&&n(`Broadcasting function "${e}" with message id "${a}" to client [${i.serviceId}]`),0!==t&&(d=o(i.serviceId),d&&(c=Ra.patchEncodedHeader(c,{toServiceId:i.serviceId}))),i.sendFn(c,{msg:l,sourceServiceId:s,targetServiceId:i.serviceId})}catch(e){n&&n(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{s[e]=t}}}("kweb");rc.setLogger(nc);const ic=new o,sc=new o;let oc,ac=null,cc=null,lc=null,dc=null;const uc={},pc=()=>{if(!lc)throw new Error("API key is required to interact with the hub");return lc},gc=(e,t,n)=>{const r=`${e}_${t}`,i={contents:n,lastRequestedAt:Date.now(),contentsChecksum:""};return uc[r]=i,i},hc=(e,t)=>uc[`${e}_${t}`]||null,fc=async(e,t)=>{if(!ac)return tc("Hub Link has not been acknowledged. Cannot get services."),null;const n=[{serviceName:e,version:t}];return(await rc.execute(be.GetServiceContents,n,yc,ac,0))[0]},mc=async(e,t,n=!1)=>{if(!e||!t)return null;const r=hc(e,t);if(!r||n){const n=r||gc(e,t);try{const r=await fc(e,t);return r&&(n.contents=r.uiContent,n.contentsChecksum=r.uiContentsChecksum||""),n.contents||null}catch(n){tc(`Failed to fetch service contents for ${e} v${t}`,n)}}return r?.contents||null},yc=Ka,vc=()=>{tc("Disconnected from the server"),ac=null,dc=null,rc.rejectAllPending("Disconnected from the server"),ic.emit("disconnected")},bc=()=>{tc("Connected to the server"),ic.emit("connected")},Sc=()=>cc,wc=(e,t,n,r)=>`${e}_${t}_${n}_${r}`,Ic=async()=>{const e=Sc();if(e){const t=ie(e)?.blocks;if(t){const n={};for(const r in t){const i=t[r];for(const t in i.gates){const r=i.gates[t];if(r.type===ze.hubService){const t=r.state;if(t.service?.eventEmitter){const r=`${t.service.name}_${t.service.version}`;if(!n[r])try{tc(`Re-issuing subscription for service ${t.service.name} (${t.service.version})`),n[r]=!0,await jc({listener:{recipeId:e},targetService:{serviceName:t.service.name,version:t.service.version}})}catch(e){tc(`Failed to re-issue subscription for service ${t.service.name} (${t.service.version})`,e)}}}}}}}},_c=async e=>{if(!e)return void tc("Hub sent ACK request without service id");const t={apiKey:pc(),ackSessionId:e};await rc.execute(be.SocketAckResponse,[t],yc,e,0),tc("Hub Link acknowledged"),ac=e,ic.emit("acknowledged"),Ic()},$c=async e=>{const t=e.args[0],n=wc("broadcast",`hub_${t.type}`,(0).toString(),"");await sc.emit(n,t)},Cc=async e=>{const t=e.args[0];for(const e of t.outputs||[])e.type===fe.ImageData&&je(e.value)&&(e.value=await Ve(e.value));const n=Sc();if(n){const r=ie(n);if(r){const i=async e=>{const n=wc("broadcast",t.source.serviceName,t.source.serviceVersion,e);try{await sc.emit(n,t)}catch(t){tc(`Failed to emit broadcast event for target ${e}`,t)}};await i("app");for(const s in r.blocks){const o=r.blocks[s];for(const r in o.gates){const s=o.gates[r];if(s.disabled)continue;const a=s.state;if(s.type===ze.hubService&&a.service?.name===t.source.serviceName&&a.service?.version===t.source.serviceVersion&&a.variantId===t.variantId){await i(r);const s=a?.service?.name&&t.eventContext?{[a.service.name]:t.eventContext}:void 0;for(const i of t.outputs||[])if(null!==i.value&&void 0!==i.value){const t={type:i.type,value:i.value,timestamp:Date.now()};tc(`Sending data to output ${i.name} requested by messageId ${e.messageId}`),await aa({recipePoolId:n,currentGateId:r,sourcePortName:i.name,originalEvent:t,data:t,eventContext:s})}}}}}}},kc=async e=>{const t=e.args[0],{finalState:n,recipeId:r,widgetId:i}=t,s=oa(r,i);let o=s;if(n&&o&&s&&(o={...s,customState:n},sa(r,i,o,!0)),o?.service)try{const e=wc("setOutputs",o.service.name,o.service.version,i);await sc.emit(e,t.outputs)}catch(e){tc(`Failed to emit setOutputs event for widget ${i}`,e)}let a=null;for(const n of t.outputs)if(null!==n.value&&void 0!==n.value){if(n.type===fe.ImageData){if(!je(n.value)){tc(`Invalid ImageData value received for output ${n.name}. Expected an ImageData-like object`);continue}n.value=await Ve(n.value)}else n.type!==fe.JsonObj&&n.type!==fe.Array||await Qa(n.value);const s={type:n.type,value:n.value,timestamp:Date.now()};tc(`Sending data to output ${n.name} requested by messageId ${e.messageId}`);const c=o?.service?.name&&t.eventContext?{[o.service.name]:t.eventContext}:void 0;try{await aa({recipePoolId:r,currentGateId:i,sourcePortName:n.name,originalEvent:s,data:s,eventContext:c})}catch(e){tc(`Failed to trigger next global widget for output ${n.name}`,e),a=e;break}}if(a){const t=a instanceof tr,n=a;e.reply({error:a.message,errCode:t?"CHILD_WIDGET_ERROR":"INVOKING_ERROR",errData:{targetWidgetId:n.targetWidgetId,targetPortName:n.targetPortName,sourcePortName:n.sourcePortName,sourceWidgetId:n.sourceWidgetId,targetWidgetType:n.targetWidgetType,sourceWidgetType:n.sourceWidgetType}})}else e.reply({success:[]})},Ec=async e=>{const t=e.args[0],{newState:n,recipeId:r,widgetId:i}=t,s=oa(r,i);if(s){const t={...s,customState:{...s.customState,...n}};return sa(r,i,t,!0),e.reply({success:[]})}},xc=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:i,path:s,key:o}=n;tc(`Received request to set a dependency path for "${o}" on widget "${i}" in recipe "${r}"`);const a=oa(r,i);if(a){const e={...a};e.dependencies=e.dependencies||{},e.dependencies[o]={path:s},sa(r,i,e,!0)}return t({success:[]})},Ac=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:i,key:s}=n;tc(`Received request to get a dependency path for "${s}" on widget "${i}" in recipe "${r}"`);const o=oa(r,i);if(o){const e=o.dependencies?.[s]?.path;return tc(`Returning dependency path for "${s}" on widget "${i}": "${e}"`),t({success:[e||null]})}return t({error:"Widget not found",errCode:"WIDGET_NOT_FOUND"})},Nc=async()=>{if(tc(`Requesting services on ${(new Date).toISOString()}`),!ac)return tc("Hub Link has not been acknowledged. Cannot get services."),{available:[],installed:[],failed:[]};const[e]=await rc.execute(be.GetServices,[],yc,ac,0);oc=e;for(const t of e.available){if(t.internal)continue;const e=hc(t.name,t.version);if(!e||e?.contentsChecksum!==t.uiContentChecksum)try{const n=e||gc(t.name,t.version);tc(`Service ${t.name} v${t.version} contents have changed, fetching new contents`);const r=await fc(t.name,t.version);r&&(n.contents=r.uiContent,n.contentsChecksum=t.uiContentChecksum||"")}catch(e){tc(`Failed to update service contents for ${t.name} v${t.version}`,e)}}return e},Pc=()=>oc||{available:[],installed:[],failed:[]},Oc=()=>!!oc,Tc=async e=>{const{targetServiceSessionId:t}=e;if(!ac)return void tc("No target service session id provided");tc(`Forwarding "onParentEvent" to service ${t}`);return await rc.execute(be.OnParentEvent,[e],yc,ac,t,e.config).catch((e=>{throw tc(`Error invoking onParentEvent callback: ${e}`),e.errCode===Ua.ParentEventCallbackError?e.error:e}))},Lc=async e=>{if(!ac)return tc("Hub Link has not been acknowledged. Cannot get services."),{};const[t]=await rc.execute(be.GetDefaultState,[],yc,ac,e);return t},Bc=async(e,t,n,r)=>{if(!ac)return tc("Hub Link has not been acknowledged. Cannot get services."),null;const[i]=await rc.execute(be.UIEvent,[t,n],yc,ac,e,r);return i},Dc=(e,t)=>{const n=()=>{t()};return ic.on(e,n),()=>ic.off(e,n)},jc=async e=>{if(ac)return rc.execute(be.SubscribeToService,[e],yc,ac,0);tc("Hub Link has not been acknowledged. Cannot subscribe to services.")},Uc=async e=>{if(ac)return rc.execute(be.UnsubscribeFromService,[e],yc,ac,0);tc("Hub Link has not been acknowledged. Cannot subscribe to services.")},Rc=(e,t,n,r)=>{const i=wc("broadcast",t,n,e);return sc.on(i,r)},Fc=(e,t,n,r)=>{const i=wc("setOutputs",t,n,e);return sc.on(i,r)},Mc=async(e,t,n)=>ac?rc.execute(e,t,yc,ac,0,n):(tc("Hub Link has not been acknowledged. Cannot execute function."),null),Wc=async e=>{if(!ac)return void tc("Hub Link has not been acknowledged. Cannot execute function.");const t=oa(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,recipeName:e.recipeName,currentDependencies:n}],[i]=await rc.execute(be.InitializeInstance,r,yc,ac,e.sessionId);if(i){const t=oa(e.recipeId,e.widgetId);if(t){const n={...t,customState:i};sa(e.recipeId,e.widgetId,n,!0)}}},Gc=async(e,t,n,r)=>{if(!ac)return void tc("Hub Link has not been acknowledged. Cannot execute function.");const i=oa(n,t);if(!i)throw new Error("Widget or recipe pool not found. Cannot initialize service instance.");const s=[{currentState:i.customState,recipeId:n,widgetId:t,variantId:r}];await rc.execute(be.TerminateInstance,s,yc,ac,e)},Vc=async(e,t,n="^",r)=>{const i=["^","~",">=",">","<=","<","="];if(!i.includes(n))throw new Error(`Invalid compare mode "${n}". Must be one of ${i.join(", ")}`);const s=Oc(),o=r||!s?await Nc():Pc();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},Hc=async()=>{if(!ac)return tc("Hub Link has not been acknowledged. Cannot get services."),null;if(dc)return dc;const[e]=await rc.execute(be.GetSystemInfo,[],yc,ac,0).catch((e=>(tc("Failed to get system info",e),[null])));return dc=e,e};var zc,qc,Kc,Jc,Yc,Xc,Zc,Qc,el=async e=>{Xa(bc),Za(vc),lc=e,Ya((({json:e,transmission:t})=>{rc.processMessage("websocket",yc,t,e)})),rc.registerFunction(be.SetState,Ec),rc.registerFunction(be.SetOutputs,kc),rc.registerFunction(be.BroadcastEvent,Cc),rc.registerFunction(be.HubBroadcastEvent,$c),rc.registerFunction(Se.SetDependencyPath,xc),rc.registerFunction(Se.GetDependencyPath,Ac),Ja((e=>{((e,t)=>{const n=ve.SocketAcknowledge,r=ve.IpcAcknowledge,i=e.startsWith(n);if(e===r)return t&&t(),0;if(i){const s=e.split(i?n:r),o=parseInt(s[1]);return t&&t(o),o}})(e,_c),((e,t)=>{e===ve.ServicesListChanged&&(t&&t())})(e,(()=>{tc("Services list changed"),ic.emit("services-changed")}))})),await qa()},tl=(e,t)=>{ic.on(e,t)},nl=()=>({getServices:Nc,getServiceContents:mc,onParentEvent:Tc,onCommand:Dc,getDefaultState:Lc,getCachedServices:Pc,areServicesCached:Oc,subscribeToServiceEvents:jc,unsubscribeFromServiceEvents:Uc,callProcessorHandler:Bc,onBroadcastEvent:Rc,onSetOutputsEvent:Fc,executeHubFunction:Mc,initializeServiceInstance:Wc,terminateServiceInstance:Gc,getCompatibleService:Vc,getHubSystemInfo:Hc}),rl=e=>{cc=e},il=()=>rc;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(zc||(zc={})),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"}(qc||(qc={})),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"}(Kc||(Kc={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(Jc||(Jc={})),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:"}(Yc||(Yc={})),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.GetSystemInfo="getSystemInfo",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.UninstallService="uninstallService",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.GetUniqueId="getUniqueId",e.RebootToInstallUpdate="rebootToInstallUpdate",e.GetFileContentFromCacheId="getFileContentFromCacheId",e.GetDecryptedEdgeApiKey="getDecryptedEdgeApiKey"}(Xc||(Xc={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(Zc||(Zc={})),function(e){e.IPC="ipc",e.WS="ws"}(Qc||(Qc={}));const sl=e=>{try{return JSON.parse(e)}catch(e){return null}},ol=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,al=e=>{if("string"!=typeof e)throw new TypeError("Invalid argument expected string");const t=e.match(ol);if(!t)throw new Error(`Invalid argument not valid semver ('${e}' received)`);return t.shift(),t},cl=e=>"*"===e||"x"===e||"X"===e,ll=e=>{const t=parseInt(e,10);return isNaN(t)?e:t},dl=(e,t)=>{if(cl(e)||cl(t))return 0;const[n,r]=((e,t)=>typeof e!=typeof t?[String(e),String(t)]:[e,t])(ll(e),ll(t));return n>r?1:n<r?-1:0},ul=(e,t)=>{for(let n=0;n<Math.max(e.length,t.length);n++){const r=dl(e[n]||"0",t[n]||"0");if(0!==r)return r}return 0},pl=(e,t,n)=>{fl(n);const r=((e,t)=>{const n=al(e),r=al(t),i=n.pop(),s=r.pop(),o=ul(n,r);return 0!==o?o:i&&s?ul(i.split("."),s.split(".")):i||s?i?-1:1:0})(e,t);return gl[n].includes(r)},gl={">":[1],">=":[0,1],"=":[0],"<=":[-1,0],"<":[-1],"!=":[-1,1]},hl=Object.keys(gl),fl=e=>{if(-1===hl.indexOf(e))throw new Error(`Invalid operator, expected one of ${hl.join("|")}`)};var ml="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function yl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var vl,bl,Sl,wl,Il,_l={exports:{}},$l={exports:{}};function Cl(){if(bl)return vl;bl=1;var e=1e3,t=60*e,n=60*t,r=24*n,i=7*r,s=365.25*r;function o(e,t,n,r){var i=t>=1.5*n;return Math.round(e/n)+" "+r+(i?"s":"")}return vl=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*s;case"weeks":case"week":case"w":return c*i;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(i){var s=Math.abs(i);if(s>=r)return o(i,s,r,"day");if(s>=n)return o(i,s,n,"hour");if(s>=t)return o(i,s,t,"minute");if(s>=e)return o(i,s,e,"second");return i+" ms"}(a):function(i){var s=Math.abs(i);if(s>=r)return Math.round(i/r)+"d";if(s>=n)return Math.round(i/n)+"h";if(s>=t)return Math.round(i/t)+"m";if(s>=e)return Math.round(i/e)+"s";return i+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))}}function kl(){if(wl)return Sl;return wl=1,Sl=function(e){function t(e){let r,i,s,o=null;function a(...e){if(!a.enabled)return;const n=a,i=Number(new Date),s=i-(r||i);n.diff=s,n.prev=r,n.curr=i,r=i,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,i)=>{if("%%"===r)return"%";o++;const s=t.formatters[i];if("function"==typeof s){const t=e[o];r=s.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:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),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,]+/),i=r.length;for(n=0;n<i;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=Cl(),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},Sl}var El,xl,Al,Nl,Pl,Ol={exports:{}};function Tl(){return xl||(xl=1,El=(e,t=process.argv)=>{const n=e.startsWith("-")?"":1===e.length?"-":"--",r=t.indexOf(n+e),i=t.indexOf("--");return-1!==r&&(-1===i||r<i)}),El}"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?_l.exports=(Il||(Il=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,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(i=r))})),t.splice(i,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=kl()(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}($l,$l.exports)),$l.exports):_l.exports=(Pl||(Pl=1,function(e,t){const n=E,r=c;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:i}=this;if(i){const t=this.color,i="[3"+(t<8?t:"8;5;"+t),s=` ${i};1m${r} [0m`;n[0]=s+n[0].split("\n").join("\n"+s),n.push(i+"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(Nl)return Al;Nl=1;const e=x,t=E,n=Tl(),{env:r}=process;let i;function s(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function o(t,s){if(0===i)return 0;if(n("color=16m")||n("color=full")||n("color=truecolor"))return 3;if(n("color=256"))return 2;if(t&&!s&&void 0===i)return 0;const o=i||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")?i=0:(n("color")||n("colors")||n("color=true")||n("color=always"))&&(i=1),"FORCE_COLOR"in r&&(i="true"===r.FORCE_COLOR?1:"false"===r.FORCE_COLOR?0:0===r.FORCE_COLOR.length?1:Math.min(parseInt(r.FORCE_COLOR,10),3)),Al={supportsColor:function(e){return s(o(e,e&&e.isTTY))},stdout:s(o(!0,t.isatty(1))),stderr:s(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=kl()(t);const{formatters:i}=e.exports;i.o=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts).split("\n").map((e=>e.trim())).join(" ")},i.O=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts)}}(Ol,Ol.exports)),Ol.exports);var Ll=yl(_l.exports);const Bl=e=>Ll(e),Dl=Date.now();let jl=Math.ceil(Dl/1e3);var Ul=()=>jl+=1;const Rl=y(A(),"kemu-user-services"),Fl=y(A(),"kemu-test-services"),Ml="KMU-CB-v1",Wl=process.env.HUB_PKG_VERSION||'"1.3.5"';var Gl;!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"}(Gl||(Gl={}));const Vl=e=>({...e,type:Array.isArray(e.type)?e.type.map((e=>qc[e])):qc[e.type]}),Hl=async e=>{try{return await w(e,"utf-8")}catch(e){return null}},zl=e=>{if(e&&e.startsWith(Ml)){const t=e.slice(9),n=decodeURI(t);return sl(n)}return null},ql=async(e,t,n)=>{let r=[];e.variants?.length&&(r=e.variants.map((e=>({...e,...e.inputs?{inputs:e.inputs.map(Vl)}:{},...e.outputs?{outputs:e.outputs.map(Vl)}:{}}))));const i={...e,path:t,customWidgets:[],...e.inputs?{inputs:e.inputs.map(Vl)}:{inputs:[]},...e.outputs?{outputs:e.outputs.map(Vl)}:{outputs:[]},variants:r,...e.widgetUI&&n?.widgetUIContents?{widgetUIContents:n.widgetUIContents}:{}},s=await(async(e,t,n=console.log)=>{const r=[];if(t.customWidgets?.length)for(const i of t.customWidgets){const t=await Hl(y(e,i));if(!t){n(`Error loading custom widget file ${i}`);continue}const s=t.startsWith(Ml)?t:`${Ml}${t}`,o=zl(s);if(!o){n(`Custom widget file "${i}" is not a valid Kemu Clipboard item`);continue}const a=Object.values(o).filter((e=>e.type===Gl.widgetGroup&&!e.groupId));if(a.length>1){n(`Custom widget file "${i}" contains more than one top level widgetGroup`);continue}const c=a[0];if(!c){n(`Custom widget file "${i}" does not contain a top level widgetGroup`);continue}const l=c.state,d={name:l.name,color:l.color,description:l.description,contents:s,rootGroupId:c.id,icon:l.icon,protocolVersion:l.protocolVersion||"2"};r.push(d)}return r})(t,e,n?.log);if(s.length?i.customWidgets=s:delete i.customWidgets,i.variants?.length)for(const e of i.variants)if(e.svgIcon)try{const n=await w(y(t,e.svgIcon),"utf-8");e.svgIcon=n}catch(t){n?.log&&n?.log(`Error loading svgIcon for variant ${e.id}: ${t}`)}return i},Kl=async e=>{try{return await I(e,_.F_OK),!0}catch{return!1}};let Jl=null,Yl=null;const Xl=()=>Jl||Rl,Zl=Bl("servicesManager"),Ql={};let ed=null,td=null,nd=null;class rd extends Error{code;originalError;constructor(e,t,n){super(e),this.code=t,this.originalError=n,this.name="ServiceError"}}const id=async e=>{try{return await I(e),!0}catch{return!1}},sd=async e=>{if(!ed)throw new Error('IPC config not set, call "setHubIpcConfig" first.');try{if(e.processor===Jc.Javascript){Zl(`Spawning service ${e.name} with sessionId ${e.sessionId}`);const t=m.join(e.path,"processor.js"),n=m.join(e.path,"processor.mjs"),r=await id(t)?t:n,i=[`--sessionId=${e.sessionId.toString()}`,`--ipcSpace=${ed.appSpace}`,`--ipcId=${ed?.id}`,`--recipePath=${ed.recipePath||""}`];if(e.internal&&i.push("--internal=true"),!nd)throw new Error('Get secrets function not set, call "setGetSecretsFunction" first.');const s=await nd({name:e.name,version:e.version,requiredSecrets:e.requiredSecrets||{}}),o=Object.entries(e.requiredSecrets||{}).filter((([e,t])=>{const n=s[e];return null==n&&!t.optional})).map((([e])=>e));if(o?.length)throw new rd(`Missing required environment variables: ${o.join(", ")}`,"MISSING_REQUIRED_SECRETS");return new Promise(((t,n)=>{if(!td)throw new Error('Spawn function not set, call "setSpawnNodeFunction" first.');const o=td({args:[r,...i],serviceInfo:{name:e.name,version:e.version},options:{env:s}});o.stdout.on("data",(t=>{Zl(`[${e.name}] - stdout: ${t}`)})),o.stderr.on("data",(t=>{Zl(`[${e.name}] - stderr: ${t}`)})),o.on("exit",(t=>{Zl(`[${e.name}] exited with code ${t}`)})),o.on("spawn",(()=>{Zl(`[${e.name}] spawned with PID ${o.pid}`),t(o)})),o.on("error",(t=>{Zl(`[${e.name}] error: ${t}`),n(new rd(`Error spawning service ${e.name}: ${t}`,"SPAWN_ERROR"))}))}))}throw`Unsupported processor type ${e.processor}`}catch(t){if(t instanceof rd)throw t;throw`Error spawning service ${e.name}: ${t}`}},od=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[Jc.Javascript,Jc.Executable,Jc.Python].includes(e?.processor)?null:"Invalid processor"},ad=async(e,t)=>{const n=m.join(e,"manifest.json");if(!await id(n)){const t=`Missing manifest for service ${e}. Aborting.`;return Zl(t),{error:t}}const r=await w(n,"utf-8"),i=sl(r),s=od(i);if(!i||s){const t=`Invalid service manifest [${e}]: ${s}. Aborting.`;return Zl(t),{error:t}}let o;if(delete i.internal,t?.singleServiceName&&i.name!==t.singleServiceName){return{error:`Skipping service ${i.name} as it does not match the singleServiceName option`}}await Promise.all([(async()=>{if(i.widgetUI)try{o=await w(m.join(e,"widgetUI.js"))}catch(e){const t=`Error loading widgetUI file ${i.name}: ${e}`;return Zl(t),{error:t}}})(),(async()=>{if(i.svgIcon){const t=await Hl(m.join(e,i.svgIcon));if(!t){return{error:`Error loading icon for service ${i.name}`}}i.svgIcon=t}})(),(async()=>{if(i.subServices?.length)for(const t of i.subServices){const n=m.join(e,t),{error:r,service:s}=await ad(n);r?Zl(`Error loading sub-service ${t}: ${r}`):s&&(s.info.parentService={name:i.name,version:i.version})}delete i.subServices})(),(async()=>{if(i.variants?.length)for(const t of i.variants)if(t.svgIcon)try{const n=await w(m.join(e,t.svgIcon),"utf-8");t.svgIcon=n}catch(e){Zl(`Error loading svgIcon for variant ${t.id}: ${e}`)}})()]);const a=Ul(),c=t?.fixedSession||a;Zl(`Loaded service ${i.name} with sessionId ${c}`);const l=await ql(i,e,{widgetUIContents:o});return cd(l),Ql[c]={info:{...l,path:e,sessionId:c},status:"loaded",childProcess:null},{service:Ql[c]}},cd=e=>{e.widgetUIContents?e.uiContentChecksum=(e=>{const t=g("sha256");return t.update(e),t.digest("hex")})(e.widgetUIContents):e.uiContentChecksum=void 0},ld=async e=>{try{return e.childProcess=await sd(e.info),e.status="started",e.errorMsg=void 0,e.errorCode=void 0,!0}catch(t){return Zl(`Service [${e.info.name}] error: ${t}`),e.status="error",t instanceof rd?(e.errorMsg=t.message,e.errorCode=t.code):(e.errorMsg="string"==typeof t?t:JSON.stringify(t),e.errorCode="UNKNOWN_ERROR"),!1}},dd=e=>{const{path:t,...n}=e.info;return{...n}},ud=()=>Object.values(Ql).filter((e=>"running"===e.status)).map(dd),pd=e=>{const{serviceName:t,version:n,force:r}=e,i=Object.values(Ql).find((t=>t.info.name===e.serviceName&&t.info.version===e.version));if(!i)return null;if(i.info.internal&&!r)throw`Cannot stop internal service ${t}`;if(i.childProcess){Zl(`Stopping service "${t} (v${n})"`);i.childProcess.kill("SIGINT")||Zl(`Failed to stop service ${t}`)}return i.status="stopped",Zl(`Service ${t} stopped`),i},gd=e=>e.info.internal?e.info.path:m.join(e.info.path,".."),hd=e=>!!e.internal;var fd={isOfficialKemuService:e=>e.name.startsWith("kemu.io"),loadServices:async(e,t)=>{if(!await Kl(e))return void Zl(`Failed to load services from "${e}". Directory does not exist.`);const n=(await $(e,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name));Zl(`Found ${n.length} services in "${e}"`);for(let r=0;r<n.length;r++){const i=n[r],s=m.join(e,i),{error:o,service:a}=await ad(`${s}${t?.internalServices?"":"/dist"}`,t);o&&Zl(`Failed to load service ${s}. Please check logs`),a&&t?.internalServices&&(a.info.internal=!0)}},launchServices:async e=>{if(Zl("Initializing services"),!ed)throw new Error('IPC config not set, call "setHubIpcConfig" first.');for(const t in Ql){const n=Ql[t];e.noSpawningList&&e.noSpawningList.includes(n.info.name)?Zl(`Service ${n.info.name} is in the noSpawningList. Skipping.`):ld(n)}Zl("Services initialized")},setServiceStatus:(e,t)=>{const n=Ql[e];return n?(n.status=t,!0):(Zl(`Service with serviceId ${e} not found`),!1)},getActiveServices:ud,getMatchingService:(e,t)=>{const n=Object.values(Ql).filter((e=>"running"===e.status));for(const r of n)if(r.info.name===e){if(r.info.version===t)return r;if(pl(r.info.version,t,">="))return r}return null},getServiceBySessionId:e=>Ql[e]||null,killAllServices:()=>{for(const e in Ql){const t=Ql[e];if(t.childProcess)try{Zl(`Killing service ${t.info.name} with PID ${t.childProcess.pid}`),t.childProcess.kill()}catch(e){Zl(`Error killing service ${t.info.name}: ${e}`)}}},addDevService:async(e,t,n)=>{const r={info:{...await ql(t,t.path),sessionId:e},status:n,startedAt:new Date,devMode:!0,childProcess:null};Ql[e]=r,cd(Ql[e].info)},setServiceManifest:(e,t,n)=>{const r=Ql[e];if(!r)return Zl(`Service with sessionId ${e} not found`),!1;const i=od(t);if(i)return Zl(`Invalid manifest for service ${r.info.name}: ${i}`),!1;cd(t),r.info={...r.info,...t},n&&(r.status=n)},getMatchingDevService:(e,t,n)=>{const r=Object.values(Ql).filter((e=>e.devMode));for(const i of r)if(i.info.name===e&&i.status===n&&i.info.version===t)return i;return null},getInternalServices:()=>ud().filter((e=>e.internal)),getAllServices:()=>Object.values(Ql),stopService:pd,uninstallService:async(e,t)=>{Zl(`Uninstalling service ${e} v${t}`);const n=pd({serviceName:e,version:t});if(!n)return!1;Zl(`Service ${e} stopped. Removing from disk...`);const r=gd(n),i=Xl();return r.startsWith(i)?(await C(r,{recursive:!0,force:!0}),Zl(`Service ${e} successfully removed from disk`),(e=>{const t=Ql[e];delete Ql[e]})(n.info.sessionId),!0):(Zl(`Service ${e} is not installed in the user services directory. Aborting.`),!1)},getAllServiceVersions:e=>Object.values(Ql).filter((t=>t.info.name===e)),setHubIpcConfig:e=>{ed={...e}},loadAndLaunch:async(e,t,n)=>{const r=b(e,t),{error:i,service:s}=await ad(r);if(i||!s)return{errorMsg:i};try{s.info.internal=!!n,s.childProcess=await sd(s.info),s.status="started"}catch(e){s.status="error",e instanceof rd?(Zl(`Service spawning error: ${e.message} (${e.code})`),s.errorMsg=e.message,s.errorCode=e.code):(Zl(`Error launching service ${s.info.name}: ${e}`),s.errorMsg="string"==typeof e?e:JSON.stringify(e))}return{service:s,errorCode:s.errorCode,errorMsg:s.errorMsg}},getServiceRootDirectory:gd,setSpawnNodeFunction:e=>{td=e},setGetSecretsFunction:e=>{nd=e},restartService:async(e,t)=>{Zl(`Restarting service ${e} v${t}`);const n=pd({serviceName:e,version:t,force:!0});return!!n&&ld(n)},getFailedServices:()=>Object.values(Ql).filter((e=>"error"===e.status)).map((e=>({...dd(e),errorMsg:e.errorMsg||"",errorCode:e.errorCode,status:e.status}))),isInternalKemuService:hd,isNotInternalKemuService:e=>!hd(e),isNotDevService:e=>!e.devMode};class md{constructor(){}appspace="app.";socketRoot="/tmp/";id=x.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=x.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 yd{constructor(e){e||(e=new md),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 vd=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={}},bd=yl(vd);var Sd=yl((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 wd{}class Id{}const _d=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 wd,t=Id){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 wd}}())}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 $d{constructor(){}on(e,t,n=!1){return _d.string(e),_d.function(t),_d.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(_d.string(e),e!=this.#e.toString()&&"*"!=e||(e=this.#e),!this.#t[e])return this;if("*"==t)return delete this.#t[e],this;_d.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){_d.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)=>{_d.string(e),_d.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 Cd=new yd;class kd extends $d{constructor(e,t){super(),this.config=e,this.log=t,this.publish=super.emit,e.maxRetries&&(this.retriesRemaining=e.maxRetries),Cd=new yd(this.config)}Client=kd;queue=new Sd;socket=!1;connect=Ad;emit=Ed;retriesRemaining=0;explicitlyDisconnected=!1}function Ed(e,t){this.log("dispatching event to ",this.id,this.path," : ",e,",",t);let n=new bd;n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Cd.format(n),this.config.sync?this.queue.add(xd.bind(this,n)):this.socket.write(n)}function xd(e){this.log("dispatching event to ",this.id,this.path," : ",e),this.socket.write(e)}function Ad(){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=P.connect(e.config.tls)}else e.log("Connecting client via TCP to",t),e.socket=N.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=N.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)!=Cd.delimiter||-1==t.indexOf(Cd.delimiter))return void e.log("Messages are large, You may want to consider smaller messages.");this.ipcBuffer="";const n=Cd.parse(t),r=n.length;for(let t=0;t<r;t++){let r=new bd;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 Nd=new yd;class Pd extends $d{constructor(e,t,n,r){super(),this.config=t,this.path=e,this.port=r,this.log=n,this.publish=super.emit,Nd=new yd(this.config),this.on("close",Ld.bind(this))}udp4=!1;udp6=!1;server=!1;sockets=[];emit=Od;broadcast=Td;onStart(e){this.publish("start",e)}stop(){this.server.close()}start(){this.path?this.config.unlink?O.unlink(this.path,Ud.bind(this)):Ud.bind(this)():this.log("Socket Server Path not specified, refusing to start")}}function Od(e,t,n){this.log("dispatching event to socket"," : ",t,n);let r=new bd;if(r.type=t,r.data=n,this.config.rawBuffer?(this.log(this.config.encoding),r=Buffer.from(t,this.config.encoding)):r=Nd.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 Td(e,t){this.log("broadcasting event to all known sockets listening to ",this.path," : ",this.port?this.port:"",e,t);let n=new bd;if(n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Nd.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 Ld(){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 Bd(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)==Nd.delimiter&&-1!=t.indexOf(Nd.delimiter))for(r.ipcBuffer="",t=Nd.parse(t);t.length>0;){let e=new bd;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 Dd(e){this.publish("close",e)}function jd(e){this.sockets.push(e),e.setEncoding&&e.setEncoding(this.config.encoding),this.log("## socket connection to server detected ##"),e.on("close",Dd.bind(this)),e.on("error",function(e){this.log("server socket error",e),this.publish("error",e)}.bind(this)),e.on("data",Bd.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 Ud(){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=Fd.bind(this),this.server.on("listening",function(){jd.bind(this)(this.server)}.bind(this))):(this.log("starting TLS server",this.config.tls),this.config.tls?Rd.bind(this)():this.server=N.createServer(jd.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 Rd(){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=P.createServer(this.config.tls,jd.bind(this))}function Fd(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 Md{constructor(){}config=new md;of={};server=!1;get connectTo(){return qd}get connectToNet(){return Kd}get disconnect(){return Gd}get serve(){return Vd}get serveNet(){return zd}get log(){return Wd}set connectTo(e){return qd}set connectToNet(e){return Kd}set disconnect(e){return Gd}set serve(e){return Vd}set serveNet(e){return zd}set log(e){return Wd}}function Wd(...e){if(!this.config.silent){for(let t=0,n=e.length;t<n;t++)"object"==typeof e[t]&&(e[t]=c.inspect(e[t],{depth:this.config.logDepth,colors:this.config.logInColor}));this.config.logger(e.join(" "))}}function Gd(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 Vd(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=Hd),this.server=new Pd(e,this.config,Wd),this.server.on("start",t)}function Hd(){}function zd(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=Hd),this.server=new Pd(e,this.config,Wd,t),n&&(this.server[n]=!0,"udp4"===n&&"::1"===e&&(this.server.path="127.0.0.1")),this.server.on("start",r)}function qd(e,t,n){if("function"==typeof t&&(n=t,t=!1),n||(n=Hd),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 kd(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 Kd(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=Hd),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 kd(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 Jd=new class extends Md{constructor(){super()}IPC=Md};var Yd={id:"widgets",retry:1500,silent:!0,rawBuffer:!0,appspace:"kemu.",encoding:"hex"};const Xd=Object.values({protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8}).reduce(((e,t)=>e+t),0),Zd=e=>{try{return JSON.parse(e)}catch(e){return null}},Qd="undefined"!=typeof window,eu={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},tu={protocolPrefix:4,txtLength:4},nu=Object.values(eu).reduce(((e,t)=>e+t),0),ru=Object.values(tu).reduce(((e,t)=>e+t),0),iu=["width","height","colorSpace"],su=(e,t)=>{const n={},r=[];let i=0,s=Array.isArray(e)?[]:{};const o=(e,s)=>{const a=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,i=e instanceof Uint8Array,s=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":i?"Uint8Array":s?"Int8Array":null})(e);if(!a){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=o(e[n],`${s}[${n}]`);return t}if("object"==typeof e){const t={},n=(e=>{const t=e instanceof Int16Array,n=e instanceof Uint16Array,r=e instanceof Int32Array,i=e instanceof Uint32Array,s=e instanceof Float32Array,o=e instanceof Float64Array,a=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":i?"Uint32Array":s?"Float32Array":o?"Float64Array":a?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${s}"`);for(const n in e)e.hasOwnProperty(n)||iu.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${s}`),t[n]=o(e[n],`${s.length?`${s}.`:""}${n}`);return t}return e}n[s]={index:i,length:e.byteLength,binaryType:a},"Buffer"===t?r.push(Buffer.from(e)):"ArrayBuffer"===a?r.push(e):r.push(e.buffer),i+=e.byteLength};s=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:s}:null},ou=(e,t,n)=>{const r=t.match(/(\[\d+\])|([^[\].]+)/g)||[];let i=e;for(let e=0;e<r.length;e++){let t=r[e];const s=t.startsWith("[")&&t.endsWith("]"),o=e===r.length-1;if(s){t=t.slice(1,-1);const s=parseInt(t,10);if(!Array.isArray(i))throw new Error(`Expected an array at key "${r.slice(0,e).join(".")}" but found an object.`);o?i[s]=n:(i[s]||(i[s]=r[e+1].startsWith("[")?[]:{}),i=i[s])}else o?i[t]=n:(i[t]||(i[t]=r[e+1].startsWith("[")?[]:{}),i=i[t])}return e},au=(e,t,n)=>{const r="undefined"!=typeof Buffer,i=t instanceof Uint8Array;for(const s in n)if(n.hasOwnProperty(s)){const{index:o,length:a,binaryType:c}=n[s];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=i?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a):t.slice(o,o+a);break;case"Uint8Array":l=i?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&&ou(e,s,l)}return e},cu=e=>Ll(e),lu="KMSG",du="KCMD",uu=cu("klProtocol");var pu={encode:(e,t,n)=>{const r={json:e.json},i=su(r.json,"Buffer"),s=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const o=s?s.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),l=c.byteLength,d=eu.protocolPrefix+eu.protocolVersion+eu.jsonLength+eu.binaryLength+eu.fromServiceId+eu.toServiceId+eu.sentAt+l+o,u=Buffer.alloc(d),p=Date.now();let g=0;return u.write(lu,g),g+=eu.protocolPrefix,u.writeUInt8(1,g),g+=eu.protocolVersion,u.writeUInt32LE(l,g),g+=eu.jsonLength,u.writeUInt32LE(o,g),g+=eu.binaryLength,u.writeUInt32LE(t,g),g+=eu.fromServiceId,u.writeUInt32LE(n,g),g+=eu.toServiceId,u.writeBigInt64LE(BigInt(p),g),g+=eu.sentAt,c.copy(u,g),g+=l,s&&o&&s.copy(u,g),u},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,eu.protocolPrefix);if(t+=eu.protocolPrefix,n!==lu)return null;if(e.byteLength<nu)return uu(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=eu.protocolVersion;const i=e.readUInt32LE(t);t+=eu.jsonLength;const s=e.readUInt32LE(t);t+=eu.binaryLength;const o=e.readUInt32LE(t);t+=eu.fromServiceId;const a=e.readUInt32LE(t);t+=eu.toServiceId;const c=e.readBigInt64LE(t);t+=eu.sentAt;const l=i+s,d=e.subarray(t,t+l),u=e.subarray(0,nu);let p=null;return e.byteLength-nu-i-s>0&&(p=e.subarray(nu+i+s)),{header:{protocolVersion:r,jsonLength:i,binaryLength:s,fromServiceId:o,toServiceId:a,sentAt:new Date(Number(c)),packages:[d],headerPackage:u},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),i=Zd(n);if(!i?.json)return uu("Invalid JSON in KL message"),null;i.jsonBinaryMap&&r.byteLength&&au(i.json,r,i.jsonBinaryMap);const s=Buffer.concat([e.headerPackage,t]);let o=s,a=null;const c=nu+e.jsonLength+e.binaryLength;return s.byteLength>c&&(a=s.subarray(c),o=s.subarray(0,c)),{message:{json:i.json,rawMessage:o},remaining:a}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<nu)return uu("Invalid Header Size"),e;let n=0;return n+=eu.protocolPrefix,n+=eu.protocolVersion,n+=eu.jsonLength,n+=eu.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=eu.fromServiceId,void 0!==t.toServiceId&&e.writeUInt32LE(t.toServiceId,n),e},encodeCommand:e=>{let t=0;const n=Buffer.from(e),r=n.byteLength,i=ru+r,s=Buffer.alloc(i);return s.write(du,t),t+=tu.protocolPrefix,s.writeUint32LE(r,t),t+=tu.txtLength,n.copy(s,t),s},decodeCommand:e=>{let t=0;if(e.byteLength<ru)return{command:null};const n=e.toString("utf-8",t,tu.protocolPrefix);if(t+=tu.protocolPrefix,n!==du)return{command:null};const r=e.readUInt32LE(t);t+=tu.txtLength;const i=e.toString("utf-8",t,t+r),s=e.byteLength-ru-r;let o=null;s>0&&(o=e.subarray(ru+r));let a=0;return s<0&&(a=Math.abs(s)),{command:i,remainingData:o,missing:a}}};const gu="KMSG",hu="KCMD",fu=cu("klProtocol"),mu=new TextEncoder;var yu={encode:(e,t,n)=>{const r={json:e.json},i=su(e.json,"ArrayBuffer"),s=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const o=s?s.byteLength:0,a=JSON.stringify(r),c=mu.encode(a),l=c.byteLength,d=new ArrayBuffer(eu.protocolPrefix+eu.protocolVersion+eu.jsonLength+eu.binaryLength+eu.fromServiceId+eu.toServiceId+eu.sentAt+l+o),u=new DataView(d),p=new Uint8Array(d),g=Date.now();let h=0;for(let e=0;e<4;++e)p[h++]=gu.charCodeAt(e);return u.setUint8(h,1),h+=eu.protocolVersion,u.setUint32(h,l,!0),h+=eu.jsonLength,u.setUint32(h,o,!0),h+=eu.binaryLength,u.setUint32(h,t,!0),h+=eu.fromServiceId,u.setUint32(h,n,!0),h+=eu.toServiceId,u.setBigInt64(h,BigInt(g),!0),h+=eu.sentAt,p.set(c,h),h+=l,s&&o&&p.set(new Uint8Array(s),h),d},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<eu.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==gu)return null;if(e.byteLength<nu)return fu.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const i=t.getUint8(n);n+=eu.protocolVersion;const s=t.getUint32(n,!0);n+=eu.jsonLength;const o=t.getUint32(n,!0);n+=eu.binaryLength;const a=t.getUint32(n,!0);n+=eu.fromServiceId;const c=t.getUint32(n,!0);n+=eu.toServiceId;const l=t.getBigInt64(n,!0);n+=eu.sentAt;const d=s+o,u=e.slice(n,n+d),p=new Uint8Array(e,0,nu);let g=null;if(e.byteLength-nu-s-o>0){g=new Uint8Array(e,nu+s+o).slice().buffer}return{header:{protocolVersion:i,jsonLength:s,binaryLength:o,fromServiceId:a,toServiceId:c,sentAt:new Date(Number(l)),packages:[u],headerPackage:p.slice().buffer},remaining:g}},decodeFullKlMessage:e=>{const t=e.packages.reduce(((e,t)=>e+t.byteLength),0),n=new Uint8Array(t);let r,i=0;for(const t of e.packages)r=new Uint8Array(t),n.set(r,i),i+=r.byteLength;const s=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),o=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=Zd(s);if(!a?.json)return fu.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&o.byteLength&&au(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,d=null;const u=nu+e.jsonLength+e.binaryLength;return c.byteLength>u&&(d=c.subarray(u),l=c.subarray(0,u)),{message:{json:a.json,...o.length?{binaryData:o.buffer}:{},rawMessage:l.buffer},remaining:d?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<nu)return fu("Invalid Header Size"),e;let n=0;n+=eu.protocolPrefix,n+=eu.protocolVersion,n+=eu.jsonLength,n+=eu.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=eu.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=mu.encode(e),r=n.byteLength,i=new ArrayBuffer(ru+r),s=new DataView(i),o=new Uint8Array(i);for(let e=0;e<4;++e)o[t++]=hu.charCodeAt(e);return s.setUint32(t,r,!0),t+=tu.txtLength,o.set(n,t),i},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<ru)return{command:null};let r="";for(let e=0;e<tu.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==hu)return{command:null};const i=t.getUint32(n,!0);n+=tu.txtLength;const s=e.byteLength-ru-i,o=new Uint8Array(e,n,Math.min(i,e.byteLength-ru)),a=(new TextDecoder).decode(o);let c=null;s>0&&(c=e.slice(ru+i));let l=0;return s<0&&(l=Math.abs(s)),{command:a,remainingData:c,missing:l}}};const vu=cu("klTransmissionManager"),bu=()=>{const e=(t,n,r,i)=>{let s=n,o=null;const a=t instanceof ArrayBuffer;if(vu(`RAW: ${t.toString()}`),!s||s.partialHeaderData){let c;if(a?(c=s?.partialHeaderData?new Uint8Array([...new Uint8Array(s.partialHeaderData),...new Uint8Array(t)]).buffer:t,o=yu.decodeHeader(c)):(c=s?.partialHeaderData?Buffer.concat([s.partialHeaderData,t]):t,o=pu.decodeHeader(c)),!o){const{command:t,missing:s,remainingData:o}=a?yu.decodeCommand(c):pu.decodeCommand(c);return t?i({command:t,complete:!0,rawMessage:c}):vu(s?`ERROR: Missing ${s} 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?(vu(`${o.byteLength} bytes remain after processing command. Re-analyzing...`),e(o,n,r,i)):void 0}if(o.partialHeader)return s={firstPackageAt:Date.now(),partialHeaderData:c},r(s);if(!o.header)return vu(`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${c.byteLength} bytes`);const l=o.header;s={firstPackageAt:Date.now(),header:{...l,totalBytesReceived:l.packages[0].byteLength,totalBytesExpected:l.binaryLength+l.jsonLength,remaining:o.remaining}},r(s)}else s.header&&s.header.totalBytesReceived<s.header.totalBytesExpected&&(s.header.packages.push(t),s.header.totalBytesReceived+=t.byteLength,r(s));if(s.header&&s.header.totalBytesReceived>=s.header.totalBytesExpected){const t=Date.now()-s.header.sentAt.getTime(),n=Date.now()-s.firstPackageAt;vu(`Received ${s.header.totalBytesReceived} of ${s.header.totalBytesExpected} expected in ${t} ms, elapsed since first package: ${n}ms`);const o=a?yu.decodeFullKlMessage(s.header):pu.decodeFullKlMessage(s.header),c=s.header.totalBytesReceived,l=s.header.remaining;r(null),o&&i({klMessage:o.message,complete:!0,sourceServiceId:s.header.fromServiceId,targetServiceId:s.header.toServiceId,rawMessage:o.message.rawMessage});let d=l;if(o?.remaining&&(d=a?l?((e,t)=>{const n=e.byteLength+t.byteLength,r=new ArrayBuffer(n),i=new Uint8Array(e),s=new Uint8Array(t),o=new Uint8Array(r);return o.set(i),o.set(s,i.length),r})(l,o.remaining):o.remaining:l?Buffer.concat([l,o.remaining]):o.remaining),d)return vu(`${d.byteLength} bytes remaining after processing message with ${c} bytes of data. Re-analyzing...`),e(d,null,r,i)}};return e};Jd.config={...Jd.config,...Yd};const Su={info:Bl("ipcServer:info"),data:Bl("ipcServer:data")};let wu,Iu,_u,$u,Cu={};const ku=bu(),Eu=e=>{Cu[e]&&(Su.info(`Client disconnected [${e}]`),delete Cu[e],Iu&&Iu(e))};var xu=e=>(e?.ipcId&&(Jd.config.id=e.ipcId),e?.ipcAppSpace&&(Jd.config.appspace=e.ipcAppSpace),new Promise((e=>{Jd.serve((()=>{Su.info("IPC Server Initiated"),Jd.server.on("data",((e,t)=>{const n=Cu[t.id];n?(Su.data(`IPC Socket [${t.id}] data ${e.byteLength} bytes`),ku(e,n.activeMessage,(e=>n.activeMessage=e),(e=>{if(!e.complete)return;const n=e=>{t.write(e)};if(e.command)return Su.data(`Received command from client [${t.id}]: ${e.command}`),void(_u&&_u(t.id,e.command,n));e.klMessage&&$u&&$u({send:n,transmission:{sourceServiceId:e.sourceServiceId??-1,targetServiceId:e.targetServiceId??-1,rawMessage:e.rawMessage},json:e.klMessage.json})}))):Su.data(`Received data from unknown client [${t.id}]. Ignoring.`)})),Jd.server.on("connect",(e=>{const t=Ul();Su.info(`New client connected. Registered as "${t}"`),e.id=t,Cu[t]={socket:e,activeMessage:null,disconnectHandler:()=>Eu(t)},e.on("close",Cu[t].disconnectHandler),wu&&wu(t)})),Jd.server.on("disconnect",(e=>{Eu(e.id)})),Jd.server.on("error",(e=>{console.log(`IPC Server Error: ${e}`)})),e()})),Jd.server.start()}))),Au=e=>{wu=e},Nu=e=>{Iu=e},Pu=e=>$u=e,Ou=(e,t)=>{const n=Cu[e];if(!n)return Su.info(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=Xd)return Su.info("Message is too long to be a command. Use sendMessage instead."),!1;const r=pu.encodeCommand(t);return n.socket.write(r),!0},Tu=(e,t)=>{const n=Cu[e];return!!n&&(Su.info(`Renaming socket id [${e}] to [${t}]`),delete Cu[e],n.socket.id=t,Cu[t]=n,n.socket.removeListener("close",n.disconnectHandler),n.disconnectHandler=()=>Eu(t),n.socket.on("close",n.disconnectHandler),!0)},Lu=e=>{_u=e};let Bu=pu;Qd&&(Bu=yu);var Du,ju=Bu;!function(e){e.FunctionNotFound="FNC_NOT_FOUND",e.ParentEventCallbackError="PARENT_EVENT_CALLBACK_ERROR"}(Du||(Du={}));let Uu=Math.ceil(Date.now()/1e3);var Ru={exports:{}};const Fu=["nodebuffer","arraybuffer","fragments"],Mu="undefined"!=typeof Blob;Mu&&Fu.push("blob");var Wu={BINARY_TYPES:Fu,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Mu,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:Gu}=Wu,Vu=Buffer[Symbol.species];function Hu(e,t,n,r,i){for(let s=0;s<i;s++)n[r+s]=e[s]^t[3&s]}function zu(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 Gu;if(1===e.length)return e[0];const n=Buffer.allocUnsafe(t);let r=0;for(let t=0;t<e.length;t++){const i=e[t];n.set(i,r),r+=i.length}return r<t?new Vu(n.buffer,n.byteOffset,r):n},mask:Hu,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 Vu(t):ArrayBuffer.isView(t)?n=new Vu(t.buffer,t.byteOffset,t.byteLength):(n=Buffer.from(t),e.readOnly=!1),n},unmask:zu},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");Ru.exports.mask=function(t,n,r,i,s){s<48?Hu(t,n,r,i,s):e.mask(t,n,r,i,s)},Ru.exports.unmask=function(t,n){t.length<32?zu(t,n):e.unmask(t,n)}}catch(e){}var qu=Ru.exports;const Ku=Symbol("kDone"),Ju=Symbol("kRun");const Yu=D,Xu=qu,Zu=class{constructor(e){this[Ku]=()=>{this.pending--,this[Ju]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ju]()}[Ju](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[Ku])}}},{kStatusCode:Qu}=Wu,ep=Buffer[Symbol.species],tp=Buffer.from([0,0,255,255]),np=Symbol("permessage-deflate"),rp=Symbol("total-length"),ip=Symbol("callback"),sp=Symbol("buffers"),op=Symbol("error");let ap;var cp=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,!ap){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;ap=new Zu(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[ip];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){ap.add((r=>{this._decompress(e,t,((e,t)=>{r(),n(e,t)}))}))}compress(e,t,n){ap.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]?Yu.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=Yu.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[np]=this,this._inflate[rp]=0,this._inflate[sp]=[],this._inflate.on("error",up),this._inflate.on("data",dp)}this._inflate[ip]=n,this._inflate.write(e),t&&this._inflate.write(tp),this._inflate.flush((()=>{const e=this._inflate[op];if(e)return this._inflate.close(),this._inflate=null,void n(e);const i=Xu.concat(this._inflate[sp],this._inflate[rp]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[rp]=0,this._inflate[sp]=[],t&&this.params[`${r}_no_context_takeover`]&&this._inflate.reset()),n(null,i)}))}_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]?Yu.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=Yu.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[rp]=0,this._deflate[sp]=[],this._deflate.on("data",lp)}this._deflate[ip]=n,this._deflate.write(e),this._deflate.flush(Yu.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=Xu.concat(this._deflate[sp],this._deflate[rp]);t&&(e=new ep(e.buffer,e.byteOffset,e.length-4)),this._deflate[ip]=null,this._deflate[rp]=0,this._deflate[sp]=[],t&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),n(null,e)}))}};function lp(e){this[sp].push(e),this[rp]+=e.length}function dp(e){this[rp]+=e.length,this[np]._maxPayload<1||this[rp]<=this[np]._maxPayload?this[sp].push(e):(this[op]=new RangeError("Max payload size exceeded"),this[op].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[op][Qu]=1009,this.removeListener("data",dp),this.reset())}function up(e){this[np]._inflate=null,e[Qu]=1007,this[ip](e)}var pp={exports:{}};const{isUtf8:gp}=j,{hasBlob:hp}=Wu;function fp(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(pp.exports={isBlob:function(e){return hp&&"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:fp,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]},gp)pp.exports.isValidUTF8=function(e){return e.length<24?fp(e):gp(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");pp.exports.isValidUTF8=function(t){return t.length<32?fp(t):e(t)}}catch(e){}var mp=pp.exports;const{Writable:yp}=B,vp=cp,{BINARY_TYPES:bp,EMPTY_BUFFER:Sp,kStatusCode:wp,kWebSocket:Ip}=Wu,{concat:_p,toArrayBuffer:$p,unmask:Cp}=qu,{isValidStatusCode:kp,isValidUTF8:Ep}=mp,xp=Buffer[Symbol.species];var Ap=class extends yp{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||bp[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Ip]=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 xp(t.buffer,t.byteOffset+e,t.length-e),new xp(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 xp(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[vp.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=Sp;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]&&Cp(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[vp.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?_p(n,t):"arraybuffer"===this._binaryType?$p(_p(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=_p(n,t);if(!this._skipUTF8Validation&&!Ep(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,Sp),this.end();else{const n=e.readUInt16BE(0);if(!kp(n)){const e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const r=new xp(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ep(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,i){this._loop=!1,this._errored=!0;const s=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(s,this.createError),s.code=i,s[wp]=r,s}};const{randomFillSync:Np}=d,Pp=cp,{EMPTY_BUFFER:Op,kWebSocket:Tp,NOOP:Lp}=Wu,{isBlob:Bp,isValidStatusCode:Dp}=mp,{mask:jp,toBuffer:Up}=qu,Rp=Symbol("kByteLength"),Fp=Buffer.alloc(4),Mp=8192;let Wp,Gp=Mp;var Vp=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=Lp,this[Tp]=void 0}static frame(e,t){let n,r,i=!1,s=2,o=!1;t.mask&&(n=t.maskBuffer||Fp,t.generateMask?t.generateMask(n):(Gp===Mp&&(void 0===Wp&&(Wp=Buffer.alloc(Mp)),Np(Wp,0,Mp),Gp=0),n[0]=Wp[Gp++],n[1]=Wp[Gp++],n[2]=Wp[Gp++],n[3]=Wp[Gp++]),o=!(n[0]|n[1]|n[2]|n[3]),s=6),"string"==typeof e?r=t.mask&&!o||void 0===t[Rp]?(e=Buffer.from(e)).length:t[Rp]:(r=e.length,i=t.mask&&t.readOnly&&!o);let a=r;r>=65536?(s+=8,a=127):r>125&&(s+=2,a=126);const c=Buffer.allocUnsafe(i?r+s:s);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[s-4]=n[0],c[s-3]=n[1],c[s-2]=n[2],c[s-1]=n[3],o?[c,e]:i?(jp(e,n,c,s,r),[c]):(jp(e,n,e,0,r),[c,e])):[c,e]}close(t,n,r,i){let s;if(void 0===t)s=Op;else{if("number"!=typeof t||!Dp(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");s=Buffer.allocUnsafe(2+e),s.writeUInt16BE(t,0),"string"==typeof n?s.write(n,2):s.set(n,2)}else s=Buffer.allocUnsafe(2),s.writeUInt16BE(t,0)}const o={[Rp]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,s,!1,o,i]):this.sendFrame(e.frame(s,o),i)}ping(t,n,r){let i,s;if("string"==typeof t?(i=Buffer.byteLength(t),s=!1):Bp(t)?(i=t.size,s=!1):(i=(t=Up(t)).length,s=Up.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[Rp]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};Bp(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 i,s;if("string"==typeof t?(i=Buffer.byteLength(t),s=!1):Bp(t)?(i=t.size,s=!1):(i=(t=Up(t)).length,s=Up.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[Rp]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};Bp(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[Pp.extensionName];let i,s,o=t.binary?2:1,a=t.compress;"string"==typeof e?(i=Buffer.byteLength(e),s=!1):Bp(e)?(i=e.size,s=!1):(i=(e=Up(e)).length,s=Up.readOnly),this._firstFragment?(this._firstFragment=!1,a&&r&&r.params[r._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=i>=r._threshold),this._compress=a):(a=!1,o=0),t.fin&&(this._firstFragment=!0);const c={[Rp]:i,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:s,rsv1:a};Bp(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,i){this._bufferedBytes+=r[Rp],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(Hp,this,e,i)}this._bufferedBytes-=r[Rp];const s=Up(t);n?this.dispatch(s,n,r,i):(this._state=0,this.sendFrame(e.frame(s,r),i),this.dequeue())})).catch((e=>{process.nextTick(zp,this,e,i)}))}dispatch(t,n,r,i){if(!n)return void this.sendFrame(e.frame(t,r),i);const s=this._extensions[Pp.extensionName];this._bufferedBytes+=r[Rp],this._state=1,s.compress(t,r.fin,((t,n)=>{if(this._socket.destroyed){Hp(this,new Error("The socket was closed while data was being compressed"),i)}else this._bufferedBytes-=r[Rp],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),i),this.dequeue()}))}dequeue(){for(;0===this._state&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][Rp],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Rp],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 Hp(e,t,n){"function"==typeof n&&n(t);for(let n=0;n<e._queue.length;n++){const r=e._queue[n],i=r[r.length-1];"function"==typeof i&&i(t)}}function zp(e,t,n){Hp(e,t,n),e.onerror(t)}const{kForOnEventAttribute:qp,kListener:Kp}=Wu,Jp=Symbol("kCode"),Yp=Symbol("kData"),Xp=Symbol("kError"),Zp=Symbol("kMessage"),Qp=Symbol("kReason"),eg=Symbol("kTarget"),tg=Symbol("kType"),ng=Symbol("kWasClean");class rg{constructor(e){this[eg]=null,this[tg]=e}get target(){return this[eg]}get type(){return this[tg]}}Object.defineProperty(rg.prototype,"target",{enumerable:!0}),Object.defineProperty(rg.prototype,"type",{enumerable:!0});class ig extends rg{constructor(e,t={}){super(e),this[Jp]=void 0===t.code?0:t.code,this[Qp]=void 0===t.reason?"":t.reason,this[ng]=void 0!==t.wasClean&&t.wasClean}get code(){return this[Jp]}get reason(){return this[Qp]}get wasClean(){return this[ng]}}Object.defineProperty(ig.prototype,"code",{enumerable:!0}),Object.defineProperty(ig.prototype,"reason",{enumerable:!0}),Object.defineProperty(ig.prototype,"wasClean",{enumerable:!0});class sg extends rg{constructor(e,t={}){super(e),this[Xp]=void 0===t.error?null:t.error,this[Zp]=void 0===t.message?"":t.message}get error(){return this[Xp]}get message(){return this[Zp]}}Object.defineProperty(sg.prototype,"error",{enumerable:!0}),Object.defineProperty(sg.prototype,"message",{enumerable:!0});class og extends rg{constructor(e,t={}){super(e),this[Yp]=void 0===t.data?null:t.data}get data(){return this[Yp]}}Object.defineProperty(og.prototype,"data",{enumerable:!0});const ag={addEventListener(e,t,n={}){for(const r of this.listeners(e))if(!n[qp]&&r[Kp]===t&&!r[qp])return;let r;if("message"===e)r=function(e,n){const r=new og("message",{data:n?e:e.toString()});r[eg]=this,lg(t,this,r)};else if("close"===e)r=function(e,n){const r=new ig("close",{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[eg]=this,lg(t,this,r)};else if("error"===e)r=function(e){const n=new sg("error",{error:e,message:e.message});n[eg]=this,lg(t,this,n)};else{if("open"!==e)return;r=function(){const e=new rg("open");e[eg]=this,lg(t,this,e)}}r[qp]=!!n[qp],r[Kp]=t,n.once?this.once(e,r):this.on(e,r)},removeEventListener(e,t){for(const n of this.listeners(e))if(n[Kp]===t&&!n[qp]){this.removeListener(e,n);break}}};var cg={CloseEvent:ig,ErrorEvent:sg,Event:rg,EventTarget:ag,MessageEvent:og};function lg(e,t,n){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}const{tokenChars:dg}=mp;function ug(e,t,n){void 0===e[t]?e[t]=[n]:e[t].push(n)}var pg={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,i=Object.create(null),s=!1,o=!1,a=!1,c=-1,l=-1,d=-1,u=0;for(;u<e.length;u++)if(l=e.charCodeAt(u),void 0===n)if(-1===d&&1===dg[l])-1===c&&(c=u);else if(0===u||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${u}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${u}`);-1===d&&(d=u);const r=e.slice(c,d);44===l?(ug(t,r,i),i=Object.create(null)):n=r,c=d=-1}}else-1===d&&-1!==c&&(d=u);else if(void 0===r)if(-1===d&&1===dg[l])-1===c&&(c=u);else if(32===l||9===l)-1===d&&-1!==c&&(d=u);else if(59===l||44===l){if(-1===c)throw new SyntaxError(`Unexpected character at index ${u}`);-1===d&&(d=u),ug(i,e.slice(c,d),!0),44===l&&(ug(t,n,i),i=Object.create(null),n=void 0),c=d=-1}else{if(61!==l||-1===c||-1!==d)throw new SyntaxError(`Unexpected character at index ${u}`);r=e.slice(c,u),c=d=-1}else if(o){if(1!==dg[l])throw new SyntaxError(`Unexpected character at index ${u}`);-1===c?c=u:s||(s=!0),o=!1}else if(a)if(1===dg[l])-1===c&&(c=u);else if(34===l&&-1!==c)a=!1,d=u;else{if(92!==l)throw new SyntaxError(`Unexpected character at index ${u}`);o=!0}else if(34===l&&61===e.charCodeAt(u-1))a=!0;else if(-1===d&&1===dg[l])-1===c&&(c=u);else if(-1===c||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${u}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${u}`);-1===d&&(d=u);let o=e.slice(c,d);s&&(o=o.replace(/\\/g,""),s=!1),ug(i,r,o),44===l&&(ug(t,n,i),i=Object.create(null),n=void 0),r=void 0,c=d=-1}}else-1===d&&(d=u);if(-1===c||a||32===l||9===l)throw new SyntaxError("Unexpected end of input");-1===d&&(d=u);const p=e.slice(c,d);return void 0===n?ug(t,p,i):(void 0===r?ug(i,p,!0):ug(i,r,s?p.replace(/\\/g,""):p),ug(t,n,i)),t}};const gg=U,hg=R,fg=F,mg=N,yg=P,{randomBytes:vg,createHash:bg}=d,{URL:Sg}=M,wg=cp,Ig=Ap,_g=Vp,{isBlob:$g}=mp,{BINARY_TYPES:Cg,EMPTY_BUFFER:kg,GUID:Eg,kForOnEventAttribute:xg,kListener:Ag,kStatusCode:Ng,kWebSocket:Pg,NOOP:Og}=Wu,{EventTarget:{addEventListener:Tg,removeEventListener:Lg}}=cg,{format:Bg,parse:Dg}=pg,{toBuffer:jg}=qu,Ug=3e4,Rg=Symbol("kAborted"),Fg=[8,13],Mg=["CONNECTING","OPEN","CLOSING","CLOSED"],Wg=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;let Gg=class e extends gg{constructor(t,n,r){super(),this._binaryType=Cg[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=kg,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]),Hg(this,t,n,r)):(this._autoPong=r.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Cg.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 i=new Ig({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),s=new _g(t,this._extensions,r.generateMask);this._receiver=i,this._sender=s,this._socket=t,i[Pg]=this,s[Pg]=this,t[Pg]=this,i.on("conclude",Xg),i.on("drain",Zg),i.on("error",Qg),i.on("message",th),i.on("ping",nh),i.on("pong",rh),s.onerror=sh,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on("close",ah),t.on("data",ch),t.on("end",lh),t.on("error",dh),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[wg.extensionName]&&this._extensions[wg.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())})),oh(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";Jg(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||kg,n,r)):Yg(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||kg,n,r)):Yg(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 Yg(this,t,r);const i={binary:"string"!=typeof t,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[wg.extensionName]||(i.compress=!1),this._sender.send(t||kg,i,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";Jg(this,this._req,e)}}};Object.defineProperty(Gg,"CONNECTING",{enumerable:!0,value:Mg.indexOf("CONNECTING")}),Object.defineProperty(Gg.prototype,"CONNECTING",{enumerable:!0,value:Mg.indexOf("CONNECTING")}),Object.defineProperty(Gg,"OPEN",{enumerable:!0,value:Mg.indexOf("OPEN")}),Object.defineProperty(Gg.prototype,"OPEN",{enumerable:!0,value:Mg.indexOf("OPEN")}),Object.defineProperty(Gg,"CLOSING",{enumerable:!0,value:Mg.indexOf("CLOSING")}),Object.defineProperty(Gg.prototype,"CLOSING",{enumerable:!0,value:Mg.indexOf("CLOSING")}),Object.defineProperty(Gg,"CLOSED",{enumerable:!0,value:Mg.indexOf("CLOSED")}),Object.defineProperty(Gg.prototype,"CLOSED",{enumerable:!0,value:Mg.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(Gg.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(Gg.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[xg])return t[Ag];return null},set(t){for(const t of this.listeners(e))if(t[xg]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[xg]:!0})}})})),Gg.prototype.addEventListener=Tg,Gg.prototype.removeEventListener=Lg;var Vg=Gg;function Hg(e,t,n,r){const i={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:Fg[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=i.autoPong,!Fg.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${Fg.join(", ")})`);let s;if(t instanceof Sg)s=t;else try{s=new Sg(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}"http:"===s.protocol?s.protocol="ws:":"https:"===s.protocol&&(s.protocol="wss:"),e._url=s.href;const o="wss:"===s.protocol,a="ws+unix:"===s.protocol;let c;if("ws:"===s.protocol||o||a?a&&!s.pathname?c="The URL's pathname is empty":s.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 zg(e,t)}const l=o?443:80,d=vg(16).toString("base64"),u=o?hg.request:fg.request,p=new Set;let g,h;if(i.createConnection=i.createConnection||(o?Kg:qg),i.defaultPort=i.defaultPort||l,i.port=s.port||l,i.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},i.path=s.pathname+s.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(g=new wg(!0!==i.perMessageDeflate?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=Bg({[wg.extensionName]:g.offer()})),n.length){for(const e of n){if("string"!=typeof e||!Wg.test(e)||p.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");p.add(e)}i.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(s.username||s.password)&&(i.auth=`${s.username}:${s.password}`),a){const e=i.path.split(":");i.socketPath=e[0],i.path=e[1]}if(i.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=o,e._originalHostOrSocketPath=a?i.socketPath:s.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&&i.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&s.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!o)&&(delete i.headers.authorization,delete i.headers.cookie,t||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),h=e._req=u(i),e._redirects&&e.emit("redirect",e.url,h)}else h=e._req=u(i);i.timeout&&h.on("timeout",(()=>{Jg(e,h,"Opening handshake has timed out")})),h.on("error",(t=>{null===h||h[Rg]||(h=e._req=null,zg(e,t))})),h.on("response",(s=>{const o=s.headers.location,a=s.statusCode;if(o&&i.followRedirects&&a>=300&&a<400){if(++e._redirects>i.maxRedirects)return void Jg(e,h,"Maximum redirects exceeded");let s;h.abort();try{s=new Sg(o,t)}catch(t){const n=new SyntaxError(`Invalid URL: ${o}`);return void zg(e,n)}Hg(e,s,n,r)}else e.emit("unexpected-response",h,s)||Jg(e,h,`Unexpected server response: ${s.statusCode}`)})),h.on("upgrade",((t,n,r)=>{if(e.emit("upgrade",t),e.readyState!==Gg.CONNECTING)return;h=e._req=null;const s=t.headers.upgrade;if(void 0===s||"websocket"!==s.toLowerCase())return void Jg(e,n,"Invalid Upgrade header");const o=bg("sha1").update(d+Eg).digest("base64");if(t.headers["sec-websocket-accept"]!==o)return void Jg(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 Jg(e,n,c);a&&(e._protocol=a);const l=t.headers["sec-websocket-extensions"];if(void 0!==l){if(!g){return void Jg(e,n,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=Dg(l)}catch(t){return void Jg(e,n,"Invalid Sec-WebSocket-Extensions header")}const r=Object.keys(t);if(1!==r.length||r[0]!==wg.extensionName){return void Jg(e,n,"Server indicated an extension that was not requested")}try{g.accept(t[wg.extensionName])}catch(t){return void Jg(e,n,"Invalid Sec-WebSocket-Extensions header")}e._extensions[wg.extensionName]=g}e.setSocket(n,r,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})})),i.finishRequest?i.finishRequest(h,e):h.end()}function zg(e,t){e._readyState=Gg.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function qg(e){return e.path=e.socketPath,mg.connect(e)}function Kg(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=mg.isIP(e.host)?"":e.host),yg.connect(e)}function Jg(e,t,n){e._readyState=Gg.CLOSING;const r=new Error(n);Error.captureStackTrace(r,Jg),t.setHeader?(t[Rg]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(zg,e,r)):(t.destroy(r),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function Yg(e,t,n){if(t){const n=$g(t)?t.size:jg(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${Mg[e.readyState]})`);process.nextTick(n,t)}}function Xg(e,t){const n=this[Pg];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,void 0!==n._socket[Pg]&&(n._socket.removeListener("data",ch),process.nextTick(ih,n._socket),1005===e?n.close():n.close(e,t))}function Zg(){const e=this[Pg];e.isPaused||e._socket.resume()}function Qg(e){const t=this[Pg];void 0!==t._socket[Pg]&&(t._socket.removeListener("data",ch),process.nextTick(ih,t._socket),t.close(e[Ng])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function eh(){this[Pg].emitClose()}function th(e,t){this[Pg].emit("message",e,t)}function nh(e){const t=this[Pg];t._autoPong&&t.pong(e,!this._isServer,Og),t.emit("ping",e)}function rh(e){this[Pg].emit("pong",e)}function ih(e){e.resume()}function sh(e){const t=this[Pg];t.readyState!==Gg.CLOSED&&(t.readyState===Gg.OPEN&&(t._readyState=Gg.CLOSING,oh(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function oh(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),Ug)}function ah(){const e=this[Pg];let t;this.removeListener("close",ah),this.removeListener("data",ch),this.removeListener("end",lh),e._readyState=Gg.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[Pg]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",eh),e._receiver.on("finish",eh))}function ch(e){this[Pg]._receiver.write(e)||this.pause()}function lh(){const e=this[Pg];e._readyState=Gg.CLOSING,e._receiver.end(),this.end()}function dh(){const e=this[Pg];this.removeListener("error",dh),this.on("error",Og),e&&(e._readyState=Gg.CLOSING,this.destroy())}const{tokenChars:uh}=mp;var ph={parse:function(e){const t=new Set;let n=-1,r=-1,i=0;for(;i<e.length;i++){const s=e.charCodeAt(i);if(-1===r&&1===uh[s])-1===n&&(n=i);else if(0===i||32!==s&&9!==s){if(44!==s)throw new SyntaxError(`Unexpected character at index ${i}`);{if(-1===n)throw new SyntaxError(`Unexpected character at index ${i}`);-1===r&&(r=i);const s=e.slice(n,r);if(t.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);t.add(s),n=r=-1}}else-1===r&&-1!==n&&(r=i)}if(-1===n||-1!==r)throw new SyntaxError("Unexpected end of input");const s=e.slice(n,i);if(t.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return t.add(s),t}};const gh=U,hh=F,{createHash:fh}=d,mh=pg,yh=cp,vh=ph,bh=Vg,{GUID:Sh,kWebSocket:wh}=Wu,Ih=/^[+/0-9A-Za-z]{22}==$/;var _h=class extends gh{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:bh,...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=hh.createServer(((e,t)=>{const n=hh.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($h,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($h,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{$h(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",Ch);const i=e.headers["sec-websocket-key"],s=e.headers.upgrade,o=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void Eh(this,e,t,405,"Invalid HTTP method")}if(void 0===s||"websocket"!==s.toLowerCase()){return void Eh(this,e,t,400,"Invalid Upgrade header")}if(void 0===i||!Ih.test(i)){return void Eh(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==o&&13!==o){return void Eh(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void kh(t,400);const a=e.headers["sec-websocket-protocol"];let c=new Set;if(void 0!==a)try{c=vh.parse(a)}catch(n){return void Eh(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const l=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&void 0!==l){const n=new yh(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=mh.parse(l);e[yh.extensionName]&&(n.accept(e[yh.extensionName]),d[yh.extensionName]=n)}catch(n){return void Eh(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const s={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(s,((s,o,a,l)=>{if(!s)return kh(t,o||401,a,l);this.completeUpgrade(d,i,c,e,t,n,r)}));if(!this.options.verifyClient(s))return kh(t,401)}this.completeUpgrade(d,i,c,e,t,n,r)}completeUpgrade(e,t,n,r,i,s,o){if(!i.readable||!i.writable)return i.destroy();if(i[wh])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return kh(i,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${fh("sha1").update(t+Sh).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[yh.extensionName]){const t=e[yh.extensionName].params,n=mh.format({[yh.extensionName]:[t]});a.push(`Sec-WebSocket-Extensions: ${n}`),c._extensions=e}this.emit("headers",a,r),i.write(a.concat("\r\n").join("\r\n")),i.removeListener("error",Ch),c.setSocket(i,s,{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($h,this)}))),o(c,r)}};function $h(e){e._state=2,e.emit("close")}function Ch(){this.destroy()}function kh(e,t,n,r){n=n||hh.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} ${hh.STATUS_CODES[t]}\r\n`+Object.keys(r).map((e=>`${e}: ${r[e]}`)).join("\r\n")+"\r\n\r\n"+n)}function Eh(e,t,n,r,i){if(e.listenerCount("wsClientError")){const r=new Error(i);Error.captureStackTrace(r,Eh),e.emit("wsClientError",r,n,t)}else kh(n,r,i)}var xh=yl(_h);const Ah=Bl("websocketServer"),Nh={},Ph=bu();let Oh,Th,Lh,Bh,Dh;const jh=e=>{const t=Nh[e];t&&t.socket.close()};var Uh={startServer:e=>{Dh=new xh({port:e,maxPayload:1048576e3}),Dh.on("connection",(e=>{const t=Ul();Ah(`New client connected. Registered as "${t}"`),e.id=t,Nh[t]={socket:e,activeMessage:null},Oh&&Oh(t),e.on("message",(t=>{if(t instanceof Buffer){const n=Nh[e.id];Ph(t,n.activeMessage,(e=>n.activeMessage=e),(t=>{if(!t.complete)return;const r=t=>{e.send(t),Ah(`Writing ${t.byteLength} bytes to socket [${n.socket.id}]: ${t.toString()}`)},i=()=>{jh(n.socket.id)};if(t.command)return Ah(`Received command from client [${n.socket.id}]: ${t.command}`),void(Lh&&Lh(n.socket.id,t.command,r,i));t.klMessage&&Bh&&Bh({send:r,terminateWebsocket:i,websocketId:n.socket.id,transmission:{sourceServiceId:t.sourceServiceId??-1,targetServiceId:t.targetServiceId??-1,rawMessage:t.rawMessage},json:t.klMessage.json})}))}})),e.on("close",(()=>{Ah(`Client disconnected: ${e.id}`),Th&&Th(e.id),delete Nh[e.id]})),e.on("error",(()=>{Ah(`Error on client connection: ${e.id}`)}))})),console.log(`WebSocket server is running on port ${e}`)},stopServer:()=>{Dh.close((()=>{console.log("WebSocket server stopped")}))},onClientConnected:e=>{Oh=e},onClientDisconnected:e=>{Th=e},onClientCommand:e=>{Lh=e},sendCommand:(e,t)=>{const n=Nh[e];if(!n)return Ah(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=Xd)return Ah("Message is too long to be a command. Use sendMessage instead."),!1;const r=pu.encodeCommand(t);return n.socket.send(r),!0},onMessageReceived:e=>Bh=e,terminateConnection:jh};const Rh=Bl("stopService"),Fh=async e=>{const t=e.args[0];if(!t)return e.reply({error:"No service name provided"});const n=fd.getAllServiceVersions(t);Rh(`Stopping ${n.length} services with name: ${t}`);for(const e of n)await fd.stopService({serviceName:e.info.name,version:e.info.version});const r=n.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[r]})},Mh=Bl("removeService"),Wh=async e=>{const t=e.args[0],n=e.args[1];if(!t)return e.reply({error:"No service name provided"});let r=fd.getAllServiceVersions(t);n&&(r=r.filter((e=>e.info.version===n))),Mh(`Removing ${r.length} service(s) with name: ${t}`);for(const e of r)await fd.uninstallService(e.info.name,e.info.version);const i=r.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[i]})},Gh=Bl("launchService"),Vh=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 i=Xl();Gh(`Loading service ${t}@${n} from ${i}`);const{errorMsg:s,service:o,errorCode:a}=await fd.loadAndLaunch(i,r,!1);if(s||"started"!==o?.status)return e.reply({error:`Failed to launch service ${t}@${n}: ${s||"error-not-provided"}`,errCode:a});const c=Date.now(),l=3e4,d=async()=>{const r=o.status;return"running"===r?(Gh(`Service ${t}@${n} loaded and started`),e.reply({success:[]})):(Gh(`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"}):(Gh("Retrying in 1 second..."),void setTimeout(d,1e3)))};d()}catch(r){return Gh(`Error loading service ${t}@${n}: ${r?.message||r}`),e.reply({error:r?.message||"There was an error loading the service"})}},Hh=Bl("getMatchingServices"),zh=async e=>{const t=e.args[0],n=[],r=[];Hh(`Checking for matching services: ${t.map((e=>e.name)).join(", ")}`);for(const{name:e,version:i}of t){const t=fd.getMatchingService(e,i);t?n.push({name:e,version:i,installationPath:fd.getServiceRootDirectory(t)}):r.push({name:e,version:i})}Hh(`Found ${n.length} available services and ${r.length} missing services.`),e.reply({success:[{available:n,missing:r}]})},qh=Bl("getSecretsValues");let Kh;var Jh=async e=>{const t=e.args[0].services;if(!Kh)throw new Error("getSecretValuesFn is not set. Please call setGetSecretValuesFunction before using this function.");qh(`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 Kh({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})},Yh=e=>{Kh=e};const Xh=Bl("getMappedSecrets");let Zh;var Qh=async e=>{const t=e.args[0].services;Xh(`Getting mapped secrets for services: ${t.map((e=>`${e.name}@${e.version}`)).join(", ")}`);const n=await Zh(t),r=[{services:t.map((e=>({name:e.name,version:e.version,secrets:n[e.name]||[]})))}];e.reply({success:r})},ef=e=>{Zh=e};const tf=Bl("getServiceContents"),nf=({reply:e,args:t})=>{const[n]=t;tf(`Received GetServiceContents request for service ${n.serviceName} v${n.version}`);const r=fd.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}]})}tf(`Service ${n.serviceName} v${n.version} not found`),e({error:`Service ${n.serviceName} v${n.version} not found`})};let rf={globalApiKey:void 0};const sf=()=>({...rf}),of=()=>{const e=sf();if(!e.serviceUrl)throw new Error("Unknown server URL. Please call `edgeConfig.setEdgeConfig` before using the APIs.");return e.serviceUrl},af=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}}},cf={},lf=async e=>{const t=(e=>{const t=cf[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:i}=await(async e=>{const{data:t,error:n}=await af(`${of()}/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"}})(e);return n&&(cf[e]={features:r,lastCheckedAt:new Date}),{valid:n,features:r,error:i}},df=Bl("activeClients");let uf={},pf={};const gf=(e,t)=>`${e}_${t}`,hf=e=>uf[e]||null,ff=(e,t)=>{const n=gf(e,t);return pf[n]||[]},mf=()=>{for(const e in uf){const t=uf[e];if(t?.transport===Qc.WS){const e=pu.encodeCommand(Yc.ServicesListChanged);t.send(e)}}},yf=async e=>{const t=[],{serviceSessionId:n,transport:r,send:i,terminateFn:s,extraInfo:o,isDevClient:a}=e,c=e=>{console.warn(e),s&&s()};if(r===Qc.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 lf(o.wsApiKey);if(!e&&!t)return void c(`Attempted to register a WebSocket client with an invalid API key. SessionId: ${n}`);t&&df(`Unable to validate API Key, usage will be limited. SessionId: ${n}`)}uf[n]={serviceSessionId:n,transport:r,isDevClient:!!a,broadcastSubscriptions:t,send:i,extraInfo:o,terminate:()=>{s&&s()},addSubscription:e=>{if(!t.some((t=>t.targetService.serviceName===e.serviceName&&t.targetService.version===e.version))){t.push({targetService:e});const r=gf(e.serviceName,e.version);pf[r]=pf[r]||[];return pf[r].some((e=>e.serviceId===n))||pf[r].push({sendFn:i,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 i=gf(e.serviceName,e.version),s=pf[i]?.findIndex((e=>e.serviceId===n));if(-1!==s&&(pf[i]?.splice(s,1),!pf[i]?.length)){const t=fd.getMatchingService(e.serviceName,e.version);if(t?.info.eventEmitter&&"running"===t.status){const e=hf(t.info.sessionId);e?.extraInfo.ipcSocketId&&Ou(e?.extraInfo.ipcSocketId,Yc.BroadcastEnd)}}}},removeAllSubscriptions:()=>{for(const e of t){const t=gf(e.targetService.serviceName,e.targetService.version),r=pf[t]?.findIndex((e=>e.serviceId===n));-1!==r&&pf[t]?.splice(r,1)}t.length=0}},r===Qc.IPC&&(mf(),bf(n))},vf=()=>{const e=Object.values(uf);for(const t of e)if(t.transport===Qc.IPC){const e=t.extraInfo.ipcSocketId,n=fd.getServiceBySessionId(t.serviceSessionId);if(n?.info.eventEmitter){ff(n.info.name,n.info.version).length||e&&Ou(e,Yc.BroadcastEnd)}}},bf=e=>{const t=fd.getServiceBySessionId(e);if(t?.info.eventEmitter){if(ff(t.info.name,t.info.version).length){const t=hf(e);t?.extraInfo.ipcSocketId&&Ou(t?.extraInfo.ipcSocketId,Yc.BroadcastStart)}}},Sf=e=>{const t=uf[e];delete uf[e],t?.transport===Qc.IPC?mf():(t?.removeAllSubscriptions(),vf())},wf=Bl("ipc:handleIpcClientCommand"),If=(e,t,n)=>{const r=((e,t)=>{if(e.startsWith(Yc.AcknowledgeResponse)){const n=e.split(":"),r=parseInt(n[1]),i=parseInt(n[2]);return t&&t(r,isNaN(i)?void 0:i),!0}return!1})(t,((e,t)=>{if(!e)return void wf(`Ignoring ACK response from IPC service ${e} with no service id`);wf(`Received ACK from IPC service ${e}. Marking as running.`);let r=e;t&&e&&e!==t&&(Tu(e,t),r=t);let i=!1;t&&(i=fd.setServiceStatus(t,"running")),i?yf({serviceSessionId:t||e,transport:Qc.IPC,send:n,extraInfo:{ipcSocketId:t}}):Ou(r,Yc.SendManifest)}));!r&&wf(`Received unknown command [${t}] from service ${e}`)};let _f={};G.platform();const $f=async e=>{const t=e.args[0];if(_f.chooseDirectory)try{const n=await _f.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"})},Cf=async e=>{const t=e.args[0];if(_f.chooseFile)try{const n=await _f.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"})},kf=e=>{_f=e};var Ef={},xf={},Af={};function Nf(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function Pf(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function Of(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function Tf(e,...t){if(!Of(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 Lf(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");Nf(e.outputLen),Nf(e.blockLen)}function Bf(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 Df(e,t){Tf(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}Object.defineProperty(Af,"__esModule",{value:!0}),Af.output=Af.exists=Af.hash=Af.bytes=Af.bool=Af.number=Af.isBytes=void 0,Af.number=Nf,Af.bool=Pf,Af.isBytes=Of,Af.bytes=Tf,Af.hash=Lf,Af.exists=Bf,Af.output=Df;const jf={number:Nf,bool:Pf,bytes:Tf,hash:Lf,exists:Bf,output:Df};Af.default=jf;var Uf={};Object.defineProperty(Uf,"__esModule",{value:!0}),Uf.add5L=Uf.add5H=Uf.add4H=Uf.add4L=Uf.add3H=Uf.add3L=Uf.add=Uf.rotlBL=Uf.rotlBH=Uf.rotlSL=Uf.rotlSH=Uf.rotr32L=Uf.rotr32H=Uf.rotrBL=Uf.rotrBH=Uf.rotrSL=Uf.rotrSH=Uf.shrSL=Uf.shrSH=Uf.toBig=Uf.split=Uf.fromBig=void 0;const Rf=BigInt(2**32-1),Ff=BigInt(32);function Mf(e,t=!1){return t?{h:Number(e&Rf),l:Number(e>>Ff&Rf)}:{h:0|Number(e>>Ff&Rf),l:0|Number(e&Rf)}}function Wf(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let i=0;i<e.length;i++){const{h:s,l:o}=Mf(e[i],t);[n[i],r[i]]=[s,o]}return[n,r]}Uf.fromBig=Mf,Uf.split=Wf;const Gf=(e,t)=>BigInt(e>>>0)<<Ff|BigInt(t>>>0);Uf.toBig=Gf;const Vf=(e,t,n)=>e>>>n;Uf.shrSH=Vf;const Hf=(e,t,n)=>e<<32-n|t>>>n;Uf.shrSL=Hf;const zf=(e,t,n)=>e>>>n|t<<32-n;Uf.rotrSH=zf;const qf=(e,t,n)=>e<<32-n|t>>>n;Uf.rotrSL=qf;const Kf=(e,t,n)=>e<<64-n|t>>>n-32;Uf.rotrBH=Kf;const Jf=(e,t,n)=>e>>>n-32|t<<64-n;Uf.rotrBL=Jf;const Yf=(e,t)=>t;Uf.rotr32H=Yf;const Xf=e=>e;Uf.rotr32L=Xf;const Zf=(e,t,n)=>e<<n|t>>>32-n;Uf.rotlSH=Zf;const Qf=(e,t,n)=>t<<n|e>>>32-n;Uf.rotlSL=Qf;const em=(e,t,n)=>t<<n-32|e>>>64-n;Uf.rotlBH=em;const tm=(e,t,n)=>e<<n-32|t>>>64-n;function nm(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:0|i}}Uf.rotlBL=tm,Uf.add=nm;const rm=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0);Uf.add3L=rm;const im=(e,t,n,r)=>t+n+r+(e/2**32|0)|0;Uf.add3H=im;const sm=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0);Uf.add4L=sm;const om=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0;Uf.add4H=om;const am=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0);Uf.add5L=am;const cm=(e,t,n,r,i,s)=>t+n+r+i+s+(e/2**32|0)|0;Uf.add5H=cm;const lm={fromBig:Mf,split:Wf,toBig:Gf,shrSH:Vf,shrSL:Hf,rotrSH:zf,rotrSL:qf,rotrBH:Kf,rotrBL:Jf,rotr32H:Yf,rotr32L:Xf,rotlSH:Zf,rotlSL:Qf,rotlBH:em,rotlBL:tm,add:nm,add3L:rm,add3H:im,add4L:sm,add4H:om,add5H:cm,add5L:am};Uf.default=lm;var dm={},um={};Object.defineProperty(um,"__esModule",{value:!0}),um.crypto=void 0,um.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 i from"jsonp";import s from"crypto-js";import o from"emittery";import"axios";import a from"jszip";import c from"util";import l from"mustache";import u,{scryptSync as d,createDecipheriv as h,createHash as f}from"crypto";import{satisfies as p}from"compare-versions";import g from"debug";import m,{join as y,dirname as v,resolve as b}from"path";import"node-ipc";import w,{mkdir as S,readFile as _,access as I,constants as x,readdir as k,rm as E}from"fs/promises";import C from"minimist";import O from"tty";import $,{homedir as M}from"os";import N from"stream";import T from"buffer";import A from"events";import P,{promises as D}from"fs";import L from"zlib";import j from"string_decoder";import R from"http";import F from"https";import B from"net";import U from"tls";import W from"dgram";import Y,{fileURLToPath as G}from"url";import H from"node:os";import{spawn as V}from"child_process";import{join as z,resolve as q,dirname as J}from"node:path";import{ImageData as K,loadImage as Z,createCanvas as X}from"@napi-rs/canvas";var Q;!function(e){e.STARTING="STARTING",e.PENDING="PENDING",e.RUNNING="RUNNING",e.PAUSED="PAUSED",e.DRAINING="DRAINING",e.STOPPED="STOPPED",e.ERROR="ERROR"}(Q=Q||(Q={}));const ee="undefined"!=typeof window&&void 0!==window.document&&void 0!==typeof window.document.createElement,te="object"==typeof self&&self.constructor&&"DedicatedWorkerGlobalScope"===self.constructor.name,ne="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node,re={};let ie=0,se="";const oe=e=>re[e]?re[e]:null,ae=(e,t)=>{const n=oe(e);if(!n)return n;return n.blocks[t]||null},ce=(e,t,n)=>{const r=ae(e,t);if(!r)return r;return r.gates[n]},le=(e,t)=>{let n=r(4);for(;re[n];)n=r(4);const i=(s=e,JSON.parse(JSON.stringify(s)));var s;return i.logs="",i.addLog=e=>{i.logs+=`${(()=>{const e=Date.now();if(e!==ie){const t=new Date;ie=e,se=t.toJSON()}return se})()}:: ${e}\n`},i.dbInfo={...t},re[n]=i,n},ue="interrupt_port",de="main.js",he="state.json",fe="{#}",pe="UI:",ge="default";var me,ye,ve,be,we,Se,_e,Ie;let xe;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(me||(me={})),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"}(ye||(ye={})),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"}(ve||(ve={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(be||(be={})),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:"}(we||(we={})),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.GetSystemInfo="getSystemInfo",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.UninstallService="uninstallService",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.GetUniqueId="getUniqueId",e.RebootToInstallUpdate="rebootToInstallUpdate",e.GetFileContentFromCacheId="getFileContentFromCacheId",e.GetDecryptedEdgeApiKey="getDecryptedEdgeApiKey"}(Se||(Se={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(_e||(_e={})),function(e){e.IPC="ipc",e.WS="ws"}(Ie||(Ie={}));const ke=()=>{if(!xe)throw new Error("CanvasManager not set");return xe},Ee=e=>{xe=e},Ce=(e,t)=>ke().createCanvas(e,t),Oe=e=>ee?e.getContext("2d",{willReadFrequently:!0}):e.getContext("2d"),$e=e=>ke().loadImage(e),Me="-",Ne=`inner${Me}`,Te=`outer${Me}`,Ae=`${Te}input${Me}`,Pe=`${Te}output${Me}`,De=`${Ne}input${Me}`,Le=`${Ne}output${Me}`,je=e=>(new TextEncoder).encode(e),Re=e=>e===ue,Fe=e=>e&&void 0!==e.width&&void 0!==e.height&&void 0!==e.data&&e.data.constructor&&"Uint8ClampedArray"===e.data.constructor.name,Be=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,Ue=e=>e&&"number"==typeof e.x&&"number"==typeof e.y,We=e=>"number"==typeof e?ye.Number:"string"==typeof e?ye.String:"boolean"==typeof e?ye.Boolean:Array.isArray(e)?ye.Array:Fe(e)?ye.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?ye.AudioBuffer:e&&void 0!==e.byteLength?ye.ArrayBuffer:Be(e)?ye.Rect:e&&void 0!==e.x&&void 0!==e.y&&"number"==typeof e.x&&"number"==typeof e.y?ye.Point:(e=>e&&"string"==typeof e.format&&e.data&&e.data instanceof ArrayBuffer)(e)?ye.BinaryFile:ye.JsonObj,Ye=e=>{const t={};let n;n=Array.isArray(e)?e[0]:e;for(const e in n){const r=We(n[e]);t[e]=r}return t},Ge=(e,t,n)=>"inner"===e?"input"===t?`${De}${n}`:`${Le}${n}`:"input"===t?`${Ae}${n}`:`${Pe}${n}`,He=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]}},Ve=async e=>{try{return new ImageData(e.data,e.width,e.height,{colorSpace:e.colorSpace})}catch(t){console.warn("Failed to create ImageData from info, assuming raw image data",t);return await $e(e.data)}};var ze,qe;!function(e){e.Action="action",e.CustomInput="customInput"}(ze=ze||(ze={})),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",e.note="note",e.stringify="stringify",e.templateString="templateString",e.expressionEval="expressionEval",e.rescue="rescue",e.objectCombine="objectCombine",e.loop="loop"}(qe=qe||(qe={}));const Je={};let Ke;const Ze=async e=>{const t=Je[e],n={name:ue,type:ye.Boolean};if(t){const r={name:t.portName},i=t.data||{type:ye.Boolean,value:!0};Ke?(await Ke(!0,t.targetWidgetId,t.thingId,t.recipePoolId,n.name,r,{...i,timestamp:Date.now()},[n]),"timeout"===t.type&&Xe(e)):console.warn("Interrupt service has not been initialized")}},Xe=e=>{const t=Je[e];return!!t&&(t.timerRef&&("interval"===t.type?clearInterval(t.timerRef):"timeout"===t.type&&clearTimeout(t.timerRef)),delete Je[e],!0)};var Qe={interruptHandler:Ze,createInterrupt:(e,t,n,i,s,o,a,c)=>{if(c&&Je[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(Je[l]={data:a,portName:s,recipePoolId:t,targetWidgetId:i,thingId:n,type:e},"interval"===e)Je[l].timerRef=setInterval((async()=>await Ze(l)),o.interval);else{if("timeout"!==e)throw new Error(`Invalid interrupt type '${e}'`);Je[l].timerRef=setTimeout((async()=>await Ze(l)),o.timeout)}return l},destroyInterrupt:Xe,destroyAllInterrupts:()=>{Object.keys(Je).forEach(Xe)},setInvokeChildGateCb:e=>{Ke=e}};const et=[10001,"Invalid `sourcePort` parameter"],tt=[10002,"The gate [%s] does not exist. Have you called `loadWidgets` yet?"],nt=[10110,"No storage medium has been loaded, call `loadMedium()` first"],rt=(e,...t)=>JSON.stringify({code:e[0],message:t[0]?c.format(e[1],...t):e[1].replace(/ \[%s\]/g,"")}),it=()=>({inputName:"",dataType:ye.Anything}),st="output",ot={processEvent:async(e,t)=>{const n=t.getState(),r={...it(),...n};if(e.type===r.dataType||r.dataType===ye.Anything)return t.nextWidget(st,{type:e.type,value:e.value});console.error(`Invalid data type: ${e.type} for input: ${r.inputName}. Expected: ${r.dataType}`)},getOutputNames:e=>{const t={...it(),...e};return[{name:st,type:t.dataType}]},getInputNames:()=>[]},at=Object.freeze({in:"in",reset:"reset",increment:"increment"}),ct="output";var lt={onParentEvent:async(e,t,n,r)=>{if(!e)throw new Error(rt(et));const i={currentValue:0,increment:1,...r.getState()};let s=i.increment,o=i.currentValue;const a=await r.getParentAtPort(at.increment);if(t.name===at.increment)return void(n.data.type===ye.Number&&r.setState({...i,increment:Number(n.data.value)}));if(a){const e=a.getValue();null!==e&&(s=e)}if(t.name===at.reset)return r.setState({...i,currentValue:0});o+=s,r.setState({currentValue:o,increment:s});const c={type:ye.Number,value:o};return r.nextGate(ct,c)},getInputNames:()=>[{name:at.in,type:ye.Anything},{name:at.reset,type:ye.Anything},{name:at.increment,type:ye.Number}],getOutputNames:()=>[{name:ct,type:ye.Number}]};const ut=Object.freeze({in:"in",reset:"reset"}),dt="output";var ht={onParentEvent:async(e,t,n,r)=>{const i={updatedAt:0,elapsed:0,...r.getState()},s=Date.now(),o=s-(i.updatedAt||s);return t.name===ut.reset?r.setState({...i,updatedAt:s,elapsed:0}):(r.setState({updatedAt:s,elapsed:o}),r.nextGate(dt,{type:ye.Number,value:o}))},getInputNames:()=>[{name:ut.in,type:ye.Anything},{name:ut.reset,type:ye.Anything}],getOutputNames:()=>[{name:dt,type:ye.Number}]};const ft=Object.freeze({data:"data",evaluation:"evaluation"}),pt="then",gt="else";var mt={onParentEvent:async(e,t,n,r)=>{const i={value:5,condition:"Equal",useDataPort:!1,...r.getState()},s=n.data.value,o=!isNaN(Number(s)),a="string"==typeof s;if(!i.useDataPort&&(n.data.type===ye.Number||n.data.type===ye.String||n.data.type===ye.Boolean||n.data.type===ye.Anything&&o||n.data.type===ye.Anything&&a)){let e=!1;return("Equal"===i.condition&&(n.data.value==i.value||n.data.type===ye.Boolean&&n.data.value.toString()===i.value.toString())||"Not Equal"===i.condition&&(n.data.value!==i.value||n.data.type===ye.Boolean&&n.data.value!==i.value.toString())||"Greater"===i.condition&&n.data.type===ye.Number&&n.data.value>Number(i.value)||"Less"===i.condition&&n.data.type===ye.Number&&n.data.value<Number(i.value)||"Starts With"===i.condition&&String(n.data.value).startsWith(String(i.value))||"Ends With"===i.condition&&String(n.data.value).endsWith(String(i.value))||"Includes"===i.condition&&String(n.data.value).includes(String(i.value))||"Matches"===i.condition&&String(n.data.value).match(String(i.value)))&&(e=!0),e?r.nextGate(pt,n.data):r.nextGate(gt,n.data)}if(t.name===ft.evaluation&&(n.data.type===ye.Number||n.data.type===ye.String||n.data.type===ye.Boolean||n.data.type===ye.Anything&&(o||a))&&(i.$lastValue=n.data.value,i.$lastInputDataType=n.data.type,r.setState({...i})),t.name===ft.data){let e=!1;return("Equal"===i.condition&&(i.$lastValue==i.value||i.$lastInputDataType===ye.Boolean&&i.$lastValue?.toString()===i.value.toString())||"Not Equal"===i.condition&&(i.$lastValue!==i.value||i.$lastInputDataType===ye.Boolean&&i.$lastValue!==i.value.toString())||"Greater"===i.condition&&i.$lastInputDataType===ye.Number&&Number(i.$lastValue)>Number(i.value)||"Less"===i.condition&&i.$lastInputDataType===ye.Number&&Number(i.$lastValue)<Number(i.value)||"Starts With"===i.condition&&String(i.$lastValue).startsWith(String(i.value))||"Ends With"===i.condition&&String(i.$lastValue).endsWith(String(i.value))||"Includes"===i.condition&&String(i.$lastValue).includes(String(i.value))||"Matches"===i.condition&&String(i.$lastValue).match(String(i.value)))&&(e=!0),r.setState({...i,$lastValue:void 0,$lastInputDataType:void 0}),e?r.nextGate(pt,n.data):r.nextGate(gt,n.data)}},getInputNames:e=>e.useDataPort?[{name:ft.data,type:ye.Anything,triggerPort:!0},{name:ft.evaluation,type:[ye.Number,ye.String,ye.Boolean]}]:[{name:"in",type:[ye.Number,ye.String,ye.Boolean]}],getOutputNames:e=>e.$lastOutputDataType?[{name:pt,type:e.$lastOutputDataType},{name:gt,type:e.$lastOutputDataType}]:[{name:pt,type:[ye.Number,ye.String]},{name:gt,type:[ye.Number,ye.String]}]};const yt=Object.freeze({in:"in",reset:"reset"}),vt="out";var bt={onParentEvent:async(e,t,n,r)=>{const i={totalCalls:0,callsLimit:1,...r.getState()};return t.name===yt.reset?r.setState({...i,totalCalls:0}):(i.totalCalls=i.totalCalls+1,i.totalCalls>i.callsLimit?(i.totalCalls=0,r.setState(i),r.nextGate(vt,n.data)):void r.setState(i))},getInputNames:()=>[{name:yt.in,type:ye.Anything},{name:yt.reset,type:ye.Anything}],getOutputNames:()=>[{name:vt,type:ye.Anything}]};const wt=Object.freeze({in:"in"}),St="then",_t="else";var It={onParentEvent:async(e,t,n,r)=>{const i={min:1,max:10,...r.getState()};if(n.data.type===ye.Number)return n.data.value>=i.min&&n.data.value<=i.max?r.nextGate(St,n.data):r.nextGate(_t,n.data)},getInputNames:()=>[{name:wt.in,type:ye.Number}],getOutputNames:()=>[{name:St,type:ye.Number},{name:_t,type:ye.Number}]};const xt=Object.freeze({in:"in"}),kt="out";var Et={onParentEvent:async(e,t,n,r)=>{const i={clamp:!0,...r.getState()},s=Number(n.data.value);if(void 0!==i.fromMax&&void 0!==i.fromMin&&void 0!==i.toMax&&void 0!==i.toMin&&""!==i.fromMax&&""!==i.fromMin&&""!==i.toMax&&""!==i.toMin&&(n.data.type===ye.Number||n.data.type===ye.Anything&&!isNaN(Number(s)))){let e=((e,t,n,r,i)=>(e-t)*(i-r)/(n-t)+r)(s,Number(i.fromMin),Number(i.fromMax),Number(i.toMin),Number(i.toMax));if(isNaN(e))return;return i.clamp&&(e<Number(i.toMin)&&(e=Number(i.toMin)),e>Number(i.toMax)&&(e=Number(i.toMax))),r.nextGate(kt,{type:ye.Number,value:Number(e)})}},getInputNames:()=>[{name:xt.in,type:ye.Number}],getOutputNames:()=>[{name:kt,type:ye.Number}]};const Ct=Object.freeze({in:"in"}),Ot="out";var $t={onParentEvent:async(e,t,n,r)=>{const i={convertTo:"Integer",floatPlaces:2,...r.getState()};let s=n.data.value;if(n.data.type===ye.Number||n.data.type===ye.Anything||n.data.type===ye.String){if((!isNaN(Number(s))||"string"==typeof s)&&!Array.isArray(s))return"Integer"===i.convertTo?s=parseInt(s):"Decimal"===i.convertTo?s=parseFloat(Number(s).toFixed(i.floatPlaces)):"String"===i.convertTo?s=String(s):"Abs"===i.convertTo?s=Math.abs(Number(s)):"Round"===i.convertTo&&(s=Math.round(Number(s))),r.nextGate(Ot,{type:"String"===i.convertTo?ye.String:ye.Number,value:s})}},getInputNames:()=>[{name:Ct.in,type:ye.Number}],getOutputNames:e=>{const t="String"===e?.convertTo?ye.String:ye.Number;return[{name:Ot,type:t}]}};const Mt=Object.freeze({in:"in"}),Nt="out";var Tt={onParentEvent:async(e,t,n,r)=>{const i={currentValue:50,min:0,max:100,...r.getState()};let s=!1;return i.currentValue<i.min&&(i.currentValue=i.min,s=!0),i.currentValue>i.max&&(i.currentValue=i.max,s=!0),s&&r.setState(i),r.nextWidget(Nt,{type:ye.Number,value:i.currentValue})},getInputNames:()=>[{name:Mt.in,type:ye.Anything}],getOutputNames:()=>[{name:Nt,type:ye.Number}]};const At=Object.freeze({in:"in",reset:"reset"}),Pt="out";var Dt={onParentEvent:async(e,t,n,r)=>{const i={lastCalledAt:0,delayMs:500},s={lastCalledAt:0,delayMs:500,...r.getState()};if(t.name===At.reset)return r.setState({...s,lastCalledAt:0});const o=Date.now(),a=o-s.lastCalledAt;return s.lastCalledAt===i.lastCalledAt||a>=s.delayMs&&s.delayMs>0?(s.lastCalledAt=o,r.setState(s),r.nextGate(Pt,n.data)):void 0},getInputNames:()=>[{name:At.in,type:ye.Anything},{name:At.reset,type:ye.Anything}],getOutputNames:()=>[{name:Pt,type:ye.Anything}]};const Lt="in";var jt={onParentEvent:async()=>{},getInputNames:()=>[{name:Lt,type:[ye.ImageData,ye.Number]}],getOutputNames:()=>[]};const Rt=()=>({properties:[{label:"property1",name:"property1"}],detectedProperties:{}}),Ft=(e,t)=>t.split(".").reduce(((e,t)=>null!=e?e[t]:e),e);var Bt={onParentEvent:async(e,t,n,r)=>{const i={properties:[{label:"property1",name:"property1"}],detectedProperties:{},...r.getState()},s=n?.data?.value,o=Array.isArray(s);if(n.data.type===ye.JsonObj||n.data.type===ye.Rect||n.data.type===ye.Point||n.data.type===ye.BinaryFile||n.data.type===ye.Anything||o){let e=!1;for(const t in s){const n=We(s[t]),r=!!i.detectedProperties[t],o=i.detectedProperties[t]?.type!==n;if(!r||o){const r=n===ye.JsonObj||n===ye.Rect||n===ye.Point||n===ye.Array;i.detectedProperties[t]={type:n,...r?{shape:Ye(s[t])}:void 0},e=!0}}if(o&&void 0===i.detectedProperties.length&&(i.detectedProperties.length={type:ye.Number}),e&&r.setState(i),s){const e=[];for(const t of i.properties||[]){const n=Ft(s,t.label),o=t.label.includes(".");if(void 0!==n){const s=o?We(n):void 0!==i.detectedProperties[t.label]?.type?i.detectedProperties[t.label].type:ye.Anything;e.push(r.nextGate(t.name,{type:s,value:n}))}}await Promise.allSettled(e)}}},getInputNames:()=>[{name:"in",type:ye.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:ye.Anything,r=t.detectedProperties[e.label]?.shape||void 0,i="string"==typeof e;return{name:i?e:e.name,label:i?e:e.label,type:n,jsonShape:r}}))},getDefaultState:Rt};const Ut="output",Wt="noItem";var Yt={onParentEvent:async(e,t,n,r)=>{const i={index:0,...r.getState()};let s=i.index;const o=n.data.value,a="string"==typeof n.data.value,c=Array.isArray(n.data.value);if(n.data.type===ye.Anything&&(c||a)||n.data.type===ye.String&&a||n.data.type===ye.Array&&c){s<0&&(s=o.length+s);const e=a?ye.String:We(o[s]);return e!==i.$$lastDetectedType&&r.setState({...i,$$lastDetectedType:e}),void 0!==o[s]?r.nextGate(Ut,{value:o[s],type:e}):r.nextGate(Wt,{value:!0,type:ye.Boolean})}},getInputNames:()=>[{name:"in",type:[ye.Array,ye.String]}],getOutputNames:e=>[{name:Ut,type:e.$$lastDetectedType??ye.Anything},{name:Wt,type:ye.Boolean}]};const Gt={},Ht=e=>(Gt[e]||(Gt[e]={canvasFrom:Ce(320,240),canvasTo:Ce(320,240)}),Gt[e]),Vt=Object.freeze({image:"image",rect:"rect"}),zt="image";var qt={onParentEvent:async(e,t,n,r)=>{const i=Ht(r.id),s={offset:{height:0,left:0,top:0,width:0},...r.getState()},o=[ye.Anything,ye.Rect,ye.JsonObj];if(t.name===Vt.rect&&Be(n.data.value)&&o.includes(n.data.type)&&(s.rect=n.data.value,r.setState({...s})),t.name===Vt.image){if(!((n.data.type===ye.ImageData||n.data.type===ye.Anything)&&Fe(n.data.value)))throw new Error("Invalid image data. Expected a valid ImageData type");i.lastImage=n.data.value}if(i.lastImage&&s.rect){const e=((e,t,n,r,i)=>{if(r&&r.getContext){const s=r.getContext("2d"),o=n.getContext("2d");if(s&&o){n.width=e.width,n.height=e.height,o.putImageData(e,0,0);const a={...i};i&&(a.height=Number(i.height),a.width=Number(i.width),a.left=Number(i.left),a.top=Number(i.top));const c={top:0,width:0,left:0,height:0,...a};return i&&(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,s.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),s.getImageData(0,0,r.width||1,r.height||1)}}return e})(i.lastImage,s.rect,i.canvasFrom,i.canvasTo,s.offset);r.setState({...s,rect:null}),i.lastImage=void 0,await r.nextWidget(zt,{type:ye.ImageData,value:e})}},getInputNames:()=>[{name:Vt.image,type:ye.ImageData},{name:Vt.rect,type:[ye.Rect,ye.JsonObj]}],getOutputNames:()=>[{name:zt,type:ye.ImageData}],initialize:async e=>{Ht(e.widgetId)},terminate:async e=>{delete Gt[e.widgetId]}};const Jt=(e,t)=>{const n=Math.round(Math.sqrt(t.length)),r=Math.floor(n/2),i=e.data,s=e.width,o=e.height,a=s,c=o,l=((e,t,n)=>{if(ee)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,h=4*(e*a+c);let f=0,p=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<s){const r=4*(c*s+u),o=t[e*n+a];f+=i[r]*o,p+=i[r+1]*o,g+=i[r+2]*o,m+=i[r+3]*o}}u[h]=f,u[h+1]=p,u[h+2]=g,u[h+3]=m+1*(255-m)}return l},Kt=[-1,0,1,-2,0,2,1,0,1],Zt=Object.freeze({image:"image"}),Xt="image";var Qt={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={matrix:[...Kt],...i};if(n.data.type===ye.ImageData||n.data.type===ye.Anything&&Fe(n.data.value)){const e=Jt(n.data.value,s.matrix);return r.nextGate(Xt,{type:ye.ImageData,value:e})}},getInputNames:()=>[{name:Zt.image,type:ye.ImageData}],getOutputNames:()=>[{name:Xt,type:ye.ImageData}]};const en=Object.freeze({output:"output",aborted:"aborted"}),tn=()=>({inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0}),nn=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:ye.Anything})));return n.push({name:"reset",type:ye.Anything}),n};var rn={onParentEvent:async(e,t,n,r)=>{const i={inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0,...r.getState()};if("reset"===t.name)return r.setState({...i,triggeredAt:0});const s=Date.now(),o=s-i.triggeredAt;if(i.triggeredAt&&!(o>=i.delayMs&&i.delayMs>0)&&i.delayMs)return r.nextGate(en.aborted,n.data);{i.triggeredAt=s;const e=nn(i,(r.recipePoolId,r.recipeType,r.thingRecipeId,r.id)).findIndex((e=>e.name===t.name));-1!==e&&(i.lastInputIndex=e),i.matchingOutputs?-1!==e&&await r.nextGate(`output${e+1}`,n.data):await r.nextGate(en.output,n.data),r.setState(i)}},getInputNames:nn,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:ye.Anything})));return e.push({name:en.aborted,type:ye.Anything}),e}return[{name:en.output,type:ye.Anything},{name:en.aborted,type:ye.Anything}]},getDefaultState:tn};const sn=(e,t,n,r,i,s)=>{if(i){const o=e.measureText(i),a=o.fontBoundingBoxAscent+o.fontBoundingBoxDescent;e.fillStyle=r,e.fillRect(t,n-s,1.1*o.width,a),e.font=`${s}px Arial`,e.fillStyle="black",e.fillText(i,t,n)}},on=(e,t,n,r,i,s,o)=>{e.fillStyle=i,e.fillRect(t,n,r,r),sn(e,t,n,i,s,o)},an=(e,t,n,r,i,s)=>{e.beginPath(),e.strokeStyle=r,e.lineWidth=n,e.rect(t.left,t.top,t.width,t.height),e.stroke();const o=n/2;sn(e,t.left-o,t.top-o,r,i,s)},cn={},ln=e=>(cn[e]||(cn[e]={memCanvas:Ce(320,240),lastFrame:void 0,pixels:void 0}),cn[e]),un=Object.freeze({image:"image",pixels:"pixels"}),dn="image";var hn={onParentEvent:async(e,t,n,r)=>{const i=ln(r.id),s={fontSize:12,color:"#00ff00",size:2,...r.getState()},o=(n.data.type===ye.ImageData||n.data.type===ye.Anything)&&Fe(n.data.value);if(t.name===un.pixels){const e=(e=>Ue(e)||Be(e)||Array.isArray(e)&&e[0]&&(Ue(e[0])||Be(e[0])))(n.data.value);if(!e)return;i.pixels=n.data.value}if(t.name===un.image&&o){const e=n.data.value;i.lastFrame=e}if(i.lastFrame&&i.pixels&&i.memCanvas){const e=(e=>{const{sourceImage:t,pixels:n,memCanvas:r,size:i,color:s,labelProp:o,fontSize:a}=e;if(r){const e=Oe(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]:"";Be(n)?an(e,n,i,s,r,a):Ue(n)&&on(e,n.x,n.y,i,s,r,a)}return e.getImageData(0,0,r.width,r.height)}}return t})({sourceImage:i.lastFrame,pixels:i.pixels||[],memCanvas:i.memCanvas,size:s.size,color:s.color,labelProp:s.labelProp,fontSize:s.fontSize});return i.lastFrame=void 0,i.pixels=void 0,r.setState({...s}),r.nextWidget(dn,{type:ye.ImageData,value:e})}r.setState(s)},getInputNames:()=>[{name:un.image,type:ye.ImageData},{name:un.pixels,type:[ye.Rect,ye.Point,ye.Array,ye.JsonObj]}],getOutputNames:()=>[{name:dn,type:ye.ImageData}],initialize:async e=>{ln(e.widgetId)},terminate:async e=>{delete cn[e.widgetId]}};const fn=Object.freeze({in:"in"}),pn="output",gn=e=>{const t=String(e).split(".");return t.length<2?0:t[1].length};var mn={onParentEvent:async(e,t,n,r)=>{const i={min:1,max:100,...r.getState()},s=!Number.isInteger(i.min),o=!Number.isInteger(i.max),a=s||o;let c=(l=i.min,u=i.max,Math.random()*(u-l)+l);var l,u;if(a){let e=0;if(s&&(e=gn(i.min)),o){const t=gn(i.max);t>e&&(e=t)}c=Number(c.toFixed(e))}else c=Math.floor(c);return r.nextGate(pn,{type:ye.Number,value:c})},getInputNames:()=>[{name:fn.in,type:ye.Anything}],getOutputNames:()=>[{name:pn,type:ye.Number}]};const yn=Object.freeze({output:"output",totalItems:"totalItems"}),vn=Object.freeze({trigger:"trigger",clear:"clear"}),bn=()=>({$$$time:0,totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1}),wn=async(e,t)=>t.nextGate(yn.totalItems,{type:ye.Number,value:e});var Sn={onParentEvent:async(e,t,n,r)=>{const i={$$$time:0,totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...r.getState()};if(t.name===vn.clear)return i.$$list=[],i.properties?.autoFilled&&delete i.properties,r.setState(i),wn(i.$$list.length,r);const s=t.name===vn.trigger;if(!s)if(Array.isArray(n.data.value))n.data.type!==ye.Array&&n.data.type!==ye.Anything||(i.$$outputShape={...i.$$outputShape,...e?.jsonShape},i.$$list=i.$$list.concat(n.data.value),r.setState({...i}),await wn(i.$$list.length,r));else{const t=`$$primitive_${Object.keys(i.$$outputShape).length}`;n.data.type===ye.JsonObj?i.$$outputShape={...i.$$outputShape,...e?.jsonShape?e.jsonShape:void 0}:i.$$outputShape={...i.$$outputShape,[t]:n.data.type},i.$$list.push(n.data.value),r.setState({...i}),await wn(i.$$list.length,r)}if(s){Object.keys(i.$$outputShape).length&&(i.properties={autoFilled:!0,jsonShape:{...i.$$outputShape}});const e=i.$$list.length,t=[...i.$$list];return i.$$list=[],r.setState({...i}),await wn(e,r),r.nextGate(yn.output,{type:ye.Array,value:t})}},getInputNames:e=>{const t={$$$time:0,totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...e},n=Array(t.totalInputs||1).fill(0).map(((e,t)=>({name:`input${t+1}`,type:ye.Anything})));return n.push({name:vn.clear,type:ye.Anything},{name:vn.trigger,type:ye.Anything}),n},getOutputNames:e=>[{name:yn.output,type:ye.Array,...e.properties?{jsonShape:e.properties?.jsonShape}:void 0},{name:yn.totalItems,label:"Total Items",type:ye.Number}],getDefaultState:bn};const _n=Object.freeze({start:"start",stop:"stop"}),In="output",xn="clock_interrupt";var kn={onParentEvent:async(e,t,n,r)=>{const i={enabled:!1,interval:1e3,intervalMode:"ms",...r.getState()};if(Re(e?.name||"")&&t.name===xn)return r.nextGate(In,{type:ye.Boolean,value:!0});if(t.name===_n.stop&&i.enabled&&i.$$interruptId){r.cancelInterrupt(i.$$interruptId)?(i.enabled=!1,i.$$interruptId=void 0,r.setState(i)):console.warn(`Failed to cancel interrupt [${i.$$interruptId}]`)}else t.name!==_n.start||i.enabled||i.$$interruptId||(i.$$interruptId=r.registerInterrupt("interval",xn,{interval:i.interval}),i.enabled=!0,r.setState(i))},getInputNames:()=>[{name:_n.start,type:ye.Anything},{name:_n.stop,type:ye.Anything}],getOutputNames:()=>[{name:In,type:ye.Boolean}],initialize:async e=>{const t=e.getState();if(t.enabled&&!t.$$interruptId){const n=e.registerInterrupt("interval",xn,{interval:t.interval});e.setState({...t,$$interruptId:n})}}};const En=Object.freeze({in:"in"}),Cn="output",On=(e,t,n)=>"number"==typeof e?Number((e*t).toFixed(n)):e;var $n={onParentEvent:async(e,t,n,r)=>{const i={userProperties:[],factor:2,decimalPoints:2,...r.getState()},s=n.data.type;let o=n.data.value,a=!1;return e?.jsonShape&&(i.detectedInputJson={...i.detectedInputJson,...e?.jsonShape},a=!0),i.detectedInputType||(i.detectedInputType=s,a=!0),n.data.type===ye.Array&&("number"==typeof n.data.value?.[0]?o=((e,t,n)=>{const r=(e||[]).map((e=>On(e,t,n)));return r})(n.data.value,i.factor,i.decimalPoints):"object"==typeof n.data.value?.[0]&&(o=((e,t,n,r)=>{const i=(e||[]).map((e=>{const i={...e};return Object.keys(i).forEach((e=>{r?.length&&!r?.includes(e)||(i[e]=On(i[e],t,n))})),i}));return i})(n.data.value,i.factor,i.decimalPoints,i.userProperties))),n.data.type===ye.Number&&(o=On(n.data.value,i.factor,i.decimalPoints)),a&&r.setState(i),r.nextGate(Cn,{type:s,value:o})},getInputNames:()=>[{name:En.in,type:[ye.Array,ye.Number]}],getOutputNames:e=>[{name:Cn,type:e.detectedInputType||ye.Number,jsonShape:e.detectedInputJson}]};const Mn={},Nn=Object.freeze({output:"output"}),Tn=Object.freeze({trigger:"trigger"}),An=e=>e===ye.ArrayBuffer||e===ye.AudioBuffer||e===ye.BinaryFile||e===ye.ImageData||e===ye.ImageBitmap||e===ye.Array||e===ye.JsonObj,Pn=()=>({useTriggerPort:!0,properties:[{name:"x",label:"x",type:ye.Number,value:10},{name:"y",label:"y",type:ye.Number,value:20}]}),Dn=e=>{const t={};for(let n=0;n<e.properties.length;n++)t[e.properties[n].label]=e.properties[n].type;return t},Ln=(e,t)=>{const n={};for(let r=0;r<e.properties.length;r++){let i=e.properties[r].value;const s=e.properties[r].type;An(s)&&(i=Mn[t][e.properties[r].name]),s===ye.Number?i=Number(i):s===ye.String&&(i=String(i)),n[e.properties[r].label]=i}return n};var jn={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s=structuredClone(i),o={...Pn(),...s};if(t.name===Tn.trigger){const e=Ln(o,r.id);return r.nextWidget(Nn.output,{type:ye.JsonObj,value:e})}const a=o.properties.findIndex((e=>e.name===t.name));if(-1!==a){const e=o.properties[a];let t=n.data.type===e.type;if(!t&&n.data.type===ye.Anything){t=We(n.data.type)===e.type}if(t){const t=An(n.data.type);Mn[r.id]=Mn[r.id]||{},t?(Mn[r.id][e.name]=n.data.value,o.properties[a].value=void 0):o.properties[a].value=n.data.value,o.properties[a].$$invalidInputType=!1}else o.properties[a].$$invalidInputType=!0;if(r.setState(o),!o.useTriggerPort){const e=Ln(o,r.id);return r.nextWidget(Nn.output,{type:ye.JsonObj,value:e})}}},getInputNames:e=>{const t={...Pn(),...e},n=t.properties.map((e=>({name:e.name,label:e.label,type:e.type})));return t.useTriggerPort&&n.push({name:Tn.trigger,label:Tn.trigger,type:ye.Anything}),n},getOutputNames:e=>[{name:Nn.output,label:Nn.output,type:ye.JsonObj,jsonShape:Dn(e)}],getDefaultState:Pn,initialize:async e=>{Mn[e.widgetId]={}},terminate:async e=>{delete Mn[e.widgetId]}};const Rn=async e=>{const t=(e,t)=>e.split(t)[1];if(e.startsWith(Ae)){const n=t(e,Ae);return Ge("inner","input",n)}if(e.startsWith(Le)){const n=t(e,Le);return Ge("outer","output",n)}return null},Fn=()=>({canvasPosition:{x:0,y:0},canvasZoom:1,inputs:[{name:"input",type:[ye.Anything],index:0}],outputs:[{name:"output",type:[ye.Anything],index:0}],name:"Custom Widget 1",description:"",type:"custom"}),Bn=e=>{const t={...Fn(),...e},n=t.inputs.map(((e,t)=>({name:Ge("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:Ge("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 Un={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...Fn(),...i},o=Bn(s,(r.recipePoolId,r.recipeType,r.thingRecipeId,r.id));for(let e=0;e<o.length;e++){const i=o[e];if(t.name===i.name&&(i.type.includes(ye.Anything)||i.type.includes(n.data.type))){const e=await Rn(t.name);e&&await r.nextWidget(e,{type:n.data.type,value:n.data.value})}}},getInputNames:Bn,getOutputNames:e=>{const t={...Fn(),...e},n=t.outputs.map(((e,t)=>({name:Ge("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:Ge("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:Fn};const Wn=(e,t,n,r,i)=>{const s=4*(t*n.width+e),o=n.data[s],a=n.data[s+1],c=n.data[s+2];return Math.abs(o-r.r)<=i&&Math.abs(a-r.g)<=i&&Math.abs(c-r.b)<=i};var Yn={getPixelValueAtIndex:(e,t)=>{const n=e.data,r=n[t]||0,i=n[t+1]||0,s=n[t+2]||0;return{avr:(r+i+s)/3,r:r,g:i,b:s}},getBoundingBox:(e,t,n)=>{const r=e.width,i=e.height,s=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,h=o;for(;c.length>0;){const n=c.shift();if(!n)continue;const[o,f]=n;o<0||f<0||o>=r||f>=i||s.has(`${o},${f}`)||!Wn(o,f,e,t,a||0)||(s.add(`${o},${f}`),l=Math.min(l,o),u=Math.max(u,o),d=Math.min(d,f),h=Math.max(h,f),c.push([o+1,f],[o-1,f],[o,f+1],[o,f-1]))}return{minX:l,maxX:u,minY:d,maxY:h}},l=[];for(let o=0;o<i;o+=4)for(let i=0;i<r;i+=4)if(!s.has(`${i},${o}`)&&Wn(i,o,e,t,a)){const{minX:e,maxX:t,minY:r,maxY:s}=c(i,o),a=t-e,u=s-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,i="object"==typeof n,s=i?n.r:n,o=i?n.g:n,a=i?n.b:n;r[t]=s,r[t+1]=o,r[t+2]=a,r[t+3]=255}};const Gn=e=>We(e);var Hn,Vn,zn,qn,Jn,Kn,Zn,Xn,Qn,er;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(Hn||(Hn={})),function(e){e.Bundle="bundle",e.Group="group"}(Vn||(Vn={})),function(e){e.Hardware="hardware",e.Virtual="virtual"}(zn||(zn={})),function(e){e.Cloud="cloud",e.Web="web"}(qn||(qn={})),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"}(Jn||(Jn={})),function(e){e.Gateway="gateway",e.Timer="timer"}(Kn||(Kn={})),(Zn||(Zn={})).InstallInProgress="installation-in-progress",function(e){e.InstallDependencies="install-dependencies",e.GetInstalledDependencies="get-installed-dep"}(Xn||(Xn={})),function(e){e.Success="success",e.Error="error",e.Pending="pending"}(Qn||(Qn={})),function(e){e.NotFound="not-found",e.BadRequest="bad-request",e.Forbidden="forbidden",e.InternalError="internal-error"}(er||(er={}));let tr=null;var nr=()=>{if(!tr)throw new Error("Required function is not set");return tr};class rr extends Error{targetWidgetId;targetPortName;sourcePortName;sourceWidgetId;targetWidgetType;sourceWidgetType;constructor(e,t){super(e),this.name="ChildWidgetError",t.stack&&(this.stack=t.stack),this.targetWidgetId=t.targetWidgetId,this.targetPortName=t.targetPortName,this.sourcePortName=t.sourcePortName,this.sourceWidgetId=t.sourceWidgetId,this.targetWidgetType=t.targetWidgetType,this.sourceWidgetType=t.sourceWidgetType}}class ir extends Error{constructor(e,t){super(e),this.name="UserCodeError",t&&(this.stack=t)}}const sr=(e,t)=>`\n\t\tfunction _user_code_(){\n\t\t\t${t===Hn.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 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\t\t\t\n\t\t\tvar console = this.console;\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\tdecodeDataType: this.decodeDataType,\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) => {\n\t\t\t\ttry {\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) => {\n\t\t\t\ttry{\n\t\t\t\t\tsetSendToPort(sendNextFun);\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`,or=(e,t,n,r)=>{const o=sr(e,n),a={...t,document:{},__errorTracer:e=>{if(e instanceof rr)throw e;throw new ir(e.message,e.stack)},__jest:void 0===globalThis.__jest?void 0:globalThis.__jest,___notSupportedMethod:()=>r?.error("This method is not supported."),console:{...t.logger},setInterval:()=>r?.error("'setInterval' is not supported. Please use a \"Timer\" widget instead."),setTimeout:t?.setTimeout,imageHelpers:Yn,...n===Hn.Cloud?{require:nr(),kemuProcess:process.env.KEMU_PROCESS?process.env.KEMU_PROCESS:{}}:{},jsonp:i,CryptoJS:s,decodeDataType:Gn,window:{addEventListener:t?.addEventListener,removeEventListener:t?.removeEventListener}};try{const e="browser"===(()=>{if(ee)return"browser";if(ne)return"node";if(te)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}}}},ar="main",cr="My Script",lr="This is a test script.",ur=`\n/**\n * Name: ${cr}\n * Description: ${lr}\n */\n\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`.trim(),dr=()=>({pauseExecution:!1,autoPauseOnError:!0,$$eventListeners:{},version:2,metadata:{name:cr,description:lr},pages:{[ar]:{code:ur,language:"javascript",name:"My First Script"}}}),hr=(e,t)=>{const n={message:"Unknown Error"};if(e?.stack){const r=e?.stack?.split(":")[0].trim();n.type=r;const i=(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);i&&(n.line=i.line-(e=>{const t="___user_code_section___";return sr(t,e).split(t)[0].split("\n").length+2})(t),n.column=i.column)}return e.message&&(n.message=e.message),n},fr=(e,t)=>{const n={...{...dr(),...t.getState()},$$error:e||void 0};e&&console.error(e.message),t.setState(n)},pr=new o;let gr,mr,yr={},vr={};const br=e=>{const t=ce(gr,mr,e);if(!t)throw new Error(`Widget ${e} not found in thing ${mr}`);return t},wr=(e,t)=>`${e}:${t}`,Sr=e=>`${br(e.createdByWidgetId).id}::${e.variableName}`,_r=e=>`${pe}${e}`;var Ir=e=>{const t=br(e.createdByWidgetId),n=Sr({variableName:e.variableName,createdByWidgetId:e.createdByWidgetId});vr[n]={type:e.type,subscriberWidgetId:t.id,subscriberWidgetType:t.type}},xr=e=>{const t=Sr({variableName:e.variableName,createdByWidgetId:e.createdByWidgetId});delete vr[t]},kr=async e=>{const t=br(e.setByWidgetId);if(!t)throw new Error(`Widget ${e.setByWidgetId} not found in thing ${mr} in recipe ${gr}`);const n=e.variableName.startsWith(pe)?Sr({variableName:e.variableName,createdByWidgetId:e.setByWidgetId}):e.variableName;yr[n]={value:e.value,type:e.type};const r={value:e.value,type:e.type,varName:e.variableName,isUIElement:e.variableName.startsWith(pe),setByWidgetType:t.type,setByWidgetId:e.setByWidgetId};await pr.emit(wr(e.variableName,e.type),r),e.type!==ye.Anything&&await pr.emit(wr(e.variableName,ye.Anything),r)},Er=e=>{const{readerWidgetId:t,variableName:n}=e;if(!br(t))throw new Error(`Widget ${t} not found in thing ${mr} in recipe ${gr}`);const r=n.startsWith(pe)?Sr({variableName:e.variableName,createdByWidgetId:e.readerWidgetId}):n,i=yr[r];if(i)return{type:i.type,value:i.value}},Cr=e=>{const{widgetId:t,variableName:n,type:r}=e;if(!br(t))throw new Error(`Widget ${t} not found in thing ${mr} in recipe ${gr}`);const i=wr(n,r);let s;return s=pr.on(i,(async r=>{ce(gr,mr,t)?await e.onValueChange(r):(console.warn(`Zombie widget ${t} detected, unsubscribing from variable events "${n}"`),s?.())})),s},Or=(e,t)=>{const n=wr(e,ye.Anything);return pr.on(n,(async e=>{const{isUIElement:n,...r}=e;await t(r)}))},$r=e=>{vr={},yr={},gr=e.recipePoolId,mr=e.thingId};const Mr="setTimeout",Nr="variableChanged",Tr=e=>{const{recipePoolId:t,thingId:n,scriptWidgetId:r}=e,i=ce(t,n,r);if(!i)throw new Error(`Widget "${r}" not found in recipe "${t}"`);const s=(e,t)=>{const n=Er({readerWidgetId:r,variableName:e});if(n||t)return void 0===n?{value:t?.value??t,type:t?.type??We(t)}:{value:n.value,type:n.type}},o=(t,n,s)=>{if(!e.setState)return void console.warn("Cannot subscribe to variable changes without a setState function");const o={...dr(),...e.getState()},a=Cr({variableName:t,type:ye.Anything,widgetId:r,onValueChange:async e=>{n?e.setByWidgetType===qe.widgetGroup&&e.setByWidgetId===i.groupId&&await s(e):s(e)}});delete o.$$eventListeners[t],o.$$eventListeners[t]={handler:s,abort:async()=>{a()},name:Nr},e.setState(o)};return{get:s,set:async(e,t,n)=>{await kr({variableName:e,type:n||We(t),setByWidgetId:r,value:t})},onValueChange:(e,t)=>{o(e,!1,t)},onUIValueChange:(e,t)=>{const n=_r(e);o(n,!0,t)},getUIValue:e=>{const r=_r(e),o=s(r);if(o)return{value:o.value,type:o.type};const a=i.groupId;if(!a)throw new Error("You can only read UI variables from inside a widgetGroup");const c=ce(t,n,a);if(!c)throw new Error(`Widget "${a}" not found in recipe "${t}"`);const l=c.state,u=(l.settings||[]).find((t=>t.variableName===e));if(!u)throw new Error(`Field "${e}" not found in widgetGroup "${l.name}"`);const d=u.config.defaultValue;if(!d)throw new Error(`Field "${e}" in widgetGroup "${l.name}" has no default value`);return{value:d,type:We(d)}}}},Ar="__command-compile__";let Pr;const Dr=()=>{throw new Error("Method not implemented")},Lr=(e,t,n)=>{const i=(e,...n)=>{const r={...dr(),...t.getState()}.$$eventListeners[e];r&&r.handler(n)},s={};return Object.keys(ye).forEach((e=>{s[e]=ye[e]})),{logger:Fr(),dataTypesEnum:s,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?Tr({recipePoolId:n.recipePoolId,scriptWidgetId:n.widgetId,thingId:n.thingId,getState:t.getState,setState:t.setState}):{get:Dr,set:async()=>Dr(),onValueChange:Dr,onUIValueChange:Dr,getUIValue:Dr},setTimeout:(n,i,s)=>{if(e.withTimers&&t&&t.setState&&t.registerInterrupt){const e=r(),o={...dr(),...t.getState()};o.$$eventListeners[e]={handler:n,rejectHandler:s,name:Mr},t.setState(o),t.registerInterrupt("timeout",e,{timeout:i},void 0,e)}},addEventListener:(e,n)=>{if(t.setState){const s=r(),o={...dr(),...t.getState()};o.$$eventListeners[s]={handler:n,name:e},t.setState(o),window.addEventListener(e,i.bind(s))}else console.warn(`Cannot remove event listener '${e}' because the widget context is not available.`)},removeEventListener:(e,n)=>{if(t.setState){const r={...dr(),...t.getState()},i=Object.keys(r.$$eventListeners).find((t=>r.$$eventListeners[t].name===e&&r.$$eventListeners[t].handler===n));t.setState(r),i&&removeEventListener(r.$$eventListeners[i].name,r.$$eventListeners[i].handler)}else console.warn(`Cannot remove event listener '${e}' because the widget context is not available.`)}}},jr=(e,t,n)=>{const r={...dr(),...n.getState()},i=r.pages[ar].$$compiledCode;if(i)return{compiledModule:i};{const i=Lr(e,n,t);return or(r.pages[ar].code,i,n.recipeType)}},Rr=e=>e.map((e=>({...e,name:e.name.replace("_","")}))),Fr=()=>{const e=(e,...t)=>{if(Pr)try{return Pr[e](...t)}catch(e){return void console.log("Error in custom logger: ",e)}console[e](...t)};return{log:(...t)=>{e("log",...t)},error:(...t)=>{e("error",...t)},warn:(...t)=>{e("warn",...t)},info:(...t)=>{e("info",...t)}}},Br=async(e,t)=>{const n={...e};for(const r in e){if(e[r].name===Mr){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},Ur=async e=>{const t={...e};for(const n in e){if(e[n].name===Nr){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},Wr=async(e,t,n)=>{let r={...dr(),...e.getState()};if(void 0!==n){r.pages[ar]?.$$compiledCode?.onTerminate&&await(r.pages[ar].$$compiledCode?.onTerminate());let t=await Br(r.$$eventListeners,e);t=await Ur(t),r.$$eventListeners=t,r.pages[ar].$$compiledCode=void 0,r.pages[ar].code=n,e.setState({...r})}const i=!r.pages[ar].$$compiledCode,{compiledModule:s,error:o}=jr({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=hr(o,e.recipeType);return fr(t,e),null}if(s){let n;r={...e.getState()},r.pages[ar].$$compiledCode=s;const o=Gr(r.pages[ar].code);o?.name===r.metadata?.name&&o?.description===r.metadata?.description||(r.metadata=o||void 0);const a=e.nextWidget||e.nextGate;if(a&&s.setSendToPortFun(a),t)try{await s.recipeInit({setState:e.setState,getState:e.getState})}catch(t){n=hr(t,e.recipeType)}if(a&&i)try{await s.main(a)}catch(t){n=hr(t,e.recipeType)}r.$$lastInputs=s.getWidgetInputs?s.getWidgetInputs():[],r.$$lastOutputs=s.getWidgetOutputs?s.getWidgetOutputs():[],e.setState(r),fr(n,e)}};var Yr={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...dr(),...i};if(!s.pages[ar])return console.warn("Missing default page");if(Re(e?.name||""))return s.$$eventListeners[t.name]?(await s.$$eventListeners[t.name].handler(),s.$$eventListeners[t.name].name===Mr&&delete s.$$eventListeners[t.name],void r.setState({...s})):void console.log(`Unknown interrupt id [${t.name}] `);const o=t.name===Ar;await Wr(r,!1,o?n.data.value:void 0);const a=s.pages[ar].$$compiledCode;if(e&&e.name!==Ar&&a)try{await a.asyncProcessEvent(t,e,n)}catch(e){if("UserCodeError"===e.name){const t=hr(e,r.recipeType);throw fr(t,r),t}throw e}},getInputNames:(e,t)=>{const n={...dr(),...e},{compiledModule:r}=jr({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetInputs){const e=r.getWidgetInputs();return Rr(e)}return e.$$lastInputs||[]},getOutputNames:(e,t)=>{const n={...dr(),...e},{compiledModule:r}=jr({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetOutputs){const e=r.getWidgetOutputs();return Rr(e)}return e.$$lastOutputs||[]},getDefaultState:dr,initialize:async e=>{const t=e.getState(),n={...dr(),...t};n.pages[ar].code&&await Wr({getState:e.getState,id:e.widgetId,recipePoolId:e.recipePoolId,recipeType:e.recipeType,registerInterrupt:e.registerInterrupt,setState:e.setState,nextWidget:e.nextWidget,thingRecipeId:e.thingRecipeId,cancelInterrupt:()=>!0},!0,n.pages[ar].code)},terminate:async e=>{try{const t=e.getState();t.pages[ar].$$compiledCode?.onTerminate&&await t.pages[ar].$$compiledCode.onTerminate();const n=e=>Qe.destroyInterrupt(e),r=await Br(t.$$eventListeners,{cancelInterrupt:n});await Ur(r)}catch(t){console.warn(`Error terminating script widget ${e.widgetId}: `,t)}}};const Gr=e=>{const t=e.trimStart().match(/^(?:\/\*\*(?:[^*]|\*(?!\/))*\*\/|\/\*(?:[^*]|\*(?!\/))*\*\/)/);if(!t)return null;const n=t[0].replace(/^\/\*\*?/,"").replace(/\*\/$/,"").split("\n").map((e=>e.replace(/^\s*\*?\s?/,"").trim())).join("\n"),r=n.match(/Name\s*:\s*([^]*?)(?=\n\s*[A-Za-z]+\s*:|$)/i),i=n.match(/Description\s*:\s*([^]*?)(?=\n\s*[A-Za-z]+\s*:|$)/i),s={};return r&&r[1]&&(s.name=r[1].trim()),i&&i[1]&&(s.description=i[1].trim()),Object.keys(s).length>0?s:null},Hr=async(e,t,n,r)=>{e.startsWith("data:image/")||(e=`data:image/png;base64,${e}`);const i=await Vr(e);return((e,t,n,r)=>{const i=r.getContext("2d");if(!i)throw new Error("Failed to get canvas context");const s=e.width,o=e.height;return r.width=t,r.height=n,i.drawImage(e,0,0,s,o,0,0,t,n),i.getImageData(0,0,t,n)})(i,n||i.naturalWidth,r||i.naturalHeight,t)},Vr=e=>new Promise(((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=e=>n(e),r.src=e})),zr=Object.freeze({image:"image"}),qr=Object.freeze({base64:"base64"}),Jr=()=>({});var Kr={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};if(t.name===qr.base64){if("string"!=typeof n.data.value)return;if(n.data.type!==ye.String&&n.data.type!==ye.Anything)return;const e=n.data.value;ee&&(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ce(320,240)));try{const t=await Hr(e,i.$$memCanvas,i.resize?.width,i.resize?.height);return r.setState(i),r.nextGate(zr.image,{type:ye.ImageData,value:t})}catch(e){console.log("[base64ToImageData] Error: ",e)}}},getInputNames:()=>[{name:qr.base64,type:ye.String}],getOutputNames:()=>[{name:zr.image,type:ye.ImageData}],getDefaultState:Jr};const Zr=Object.freeze({object:"object",error:"error"}),Xr=Object.freeze({string:"string"}),Qr=()=>({outputIsArray:!1});var ei={onParentEvent:async(e,t,n,r)=>{const i={outputIsArray:!1,...r.getState()};if((n.data.type===ye.String||n.data.type===ye.Anything)&&"string"==typeof n.data.value)try{const e=JSON.parse(n.data.value),t=Array.isArray(e);return t&&!i.outputIsArray?r.setState({...i,outputIsArray:!0}):!t&&i.outputIsArray&&r.setState({...i,outputIsArray:!1}),r.nextGate("object",{type:t?ye.Array:ye.JsonObj,value:e})}catch(e){return r.nextGate("error",{type:ye.Boolean,value:!0})}},getInputNames:()=>[{name:Xr.string,type:ye.String}],getOutputNames:e=>[{name:Zr.object,type:[ye.JsonObj,ye.Array],label:e.outputIsArray?"array":Zr.object},{name:Zr.error,type:ye.Boolean}],getDefaultState:Qr};const ti=Object.freeze({string:"string",length:"length"}),ni=Object.freeze({trigger:"trigger",setText:"setText"}),ri=()=>({text:"",dispatchOnSet:!1});var ii={onParentEvent:async(e,t,n,r)=>{const i={text:"",dispatchOnSet:!1,...r.getState()};if(t.name===ni.setText){if(!((n.data.type===ye.String||n.data.type===ye.Anything)&&"string"==typeof n.data.value))return;if("string"==typeof n.data.value&&(i.text=n.data.value,r.setState(i)),!i.dispatchOnSet)return}const s=r.nextGate(ti.length,{type:ye.Number,value:i.text.length}),o=r.nextGate(ti.string,{type:ye.String,value:i.text});await Promise.all([s,o])},getInputNames:e=>{const t=[{name:ni.setText,type:ye.String}];return e.dispatchOnSet||t.push({name:ni.trigger,type:ye.Anything}),t},getOutputNames:()=>[{name:ti.string,type:ye.String},{name:ti.length,type:ye.Number}],getDefaultState:ri};const si=Object.freeze({image:"image"}),oi=Object.freeze({image:"image",x:"x",y:"y",width:"width",height:"height"}),ai=()=>({showInputPorts:!1});var ci={onParentEvent:async(e,t,n,r)=>{const i={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===oi.x&&(i.cropX=n.data.value),t.name===oi.y&&(i.cropY=n.data.value),t.name===oi.width&&(i.cropWidth=n.data.value),t.name===oi.height&&(i.cropHeight=n.data.value),void r.setState(i);if(t.name===oi.image){if(n.data.type!==ye.ImageData&&n.data.type!==ye.Anything)return;if(!Fe(n.data.value))return;const e=n.data.value;if(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ce(320,240),i.$$memCanvasContext=Oe(i.$$memCanvas),r.setState(i)),!i.$$memCanvas||!i.$$memCanvasContext)return void console.error("Failed to get canvas or context");let t=e;return i.$$memCanvas.width=e.width,i.$$memCanvas.height=e.height,(i.cropX||i.cropY||i.cropWidth||i.cropHeight)&&(t=((e,t,n,r)=>{if(!n)return e;const i=Math.max(r.x||0,0),s=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,i,s,c,l,0,0,c,l),n.getImageData(0,0,c,l)})(e,i.$$memCanvas,i.$$memCanvasContext,{x:i.cropX,y:i.cropY,width:i.cropWidth,height:i.cropHeight})),r.nextGate(si.image,{type:ye.ImageData,value:t})}},getInputNames:e=>{const t=[{name:oi.image,type:[ye.ImageData]}];return e.showInputPorts&&(t.push({name:oi.x,type:ye.Number}),t.push({name:oi.y,type:ye.Number}),t.push({name:oi.width,type:ye.Number}),t.push({name:oi.height,type:ye.Number})),t},getOutputNames:()=>[{name:si.image,type:ye.ImageData}],getDefaultState:ai};const li=Object.freeze({image:"image"}),ui=Object.freeze({image:"image",width:"width",height:"height"}),di=()=>({showInputPorts:!1});var hi={onParentEvent:async(e,t,n,r)=>{const i={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===ui.width&&(i.width=n.data.value),t.name===ui.height&&(i.height=n.data.value),void r.setState(i);if(t.name===ui.image){if(n.data.type!==ye.ImageData&&n.data.type!==ye.Anything)return;if(!Fe(n.data.value))return;const e=n.data.value;if(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ce(320,240),i.$$tempCanvas=Ce(320,240),r.setState(i)),!i.$$memCanvas||!i.$$tempCanvas)return;let t=e;return(i.width||i.height)&&(t=((e,t,n,r,i)=>{if(!r&&!i)return e;r&&!i?i=r*(e.height/e.width):!r&&i&&(r=i*(e.width/e.height));const s=Math.max(1,r||e.width),o=Math.max(1,i||e.height);n.width===e.width&&n.height===e.height||(n.width=e.width,n.height=e.height),t.width=s,t.height=o;const a=Oe(t),c=Oe(n);if(!a||!c)throw new Error("Failed to get canvas context");return c.putImageData(e,0,0),a.drawImage(n,0,0,e.width,e.height,0,0,s,o),a.getImageData(0,0,s,o)})(e,i.$$memCanvas,i.$$tempCanvas,i.width,i.height)),r.nextGate(li.image,{type:ye.ImageData,value:t})}},getInputNames:e=>{const t=[{name:ui.image,type:ye.ImageData}];return e.showInputPorts&&(t.push({name:ui.width,type:ye.Number}),t.push({name:ui.height,type:ye.Number})),t},getOutputNames:()=>[{name:li.image,type:ye.ImageData}],getDefaultState:di};const fi=Object.freeze({value:"value"}),pi=Object.freeze({trigger:"trigger",setValue:"setValue"}),gi=()=>({value:0,dispatchOnSet:!1});var mi={onParentEvent:async(e,t,n,r)=>{const i={value:0,dispatchOnSet:!1,...r.getState()};if(t.name===pi.setValue){const e=n.data.type===ye.Number||n.data.type===ye.Anything||n.data.type===ye.String,t=!isNaN(Number(n.data.value))&&!Array.isArray(n.data.value);if(!e||!t)return;if(i.value=Number(n.data.value),r.setState(i),!i.dispatchOnSet)return}return r.nextGate(fi.value,{type:ye.Number,value:i.value})},getInputNames:e=>{const t=[{name:pi.setValue,type:ye.Number}];return e.dispatchOnSet||t.push({name:pi.trigger,type:ye.Anything}),t},getOutputNames:()=>[{name:fi.value,type:ye.Number}],getDefaultState:gi};const yi=Object.freeze({image:"image"}),vi=Object.freeze({image:"image"}),bi=()=>({anchors:[],vertices:[],matrix:[]}),wi={onParentEvent:async(e,t,n,r)=>{const i={anchors:[],vertices:[],matrix:[],...r.getState()},s=window,o=n.data.type===ye.ImageData;if(s.Speedy&&o){const e=s.Speedy,t=n.data.value;let o,u,d,h=i.$$private?.canvas,f=i.$$private?.context,p={...i};const g=4===i.anchors.length;if(i.$$private?.pipeline)o=i.$$private?.pipeline,u=i.$$private?.source;else{o=e.Pipeline(),u=e.Image.Source();const n=e.Image.Sink();d=e.Transform.PerspectiveWarp(),h?h.width===t.width&&h.height===t.height||(h.width=t.width,h.height=t.height,f=h.getContext("2d")):(c=t.width,l=t.height,h=Ce(c,l),f=h.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===i.anchors.length){const t=e.Matrix(2,4,[(a=i.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,i.vertices.reduce(((e,t)=>e.concat([t.x,t.y])),[])),s=e.Matrix.Zeros(3,3);await e.Matrix.perspective(s,t,n);const o=s.read();r=e.Matrix(3,3,o)}d.transform=r,p={...p,$$private:{...p.$$private,canvas:h,context:f,perspective:d,pipeline:o,source:u}}}let m=t;if(g){const e=await(async(e,t)=>{const n=window,r=e.$$private?.source,i=e.$$private?.pipeline;if(n.Speedy&&r&&i){const e=n.Speedy,s=await createImageBitmap(t),o=await e.load(s);return r.media=o,(await i.run()).image.source}return null})(p,m);e&&(h&&f&&(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,h,f)),p.$$private&&r.setState({...p,$$private:{...p.$$private,lastInputImage:t}}))}else p.$$private&&r.setState({...p,$$private:{...p.$$private,lastInputImage:t}});return r.nextGate(yi.image,{type:ye.ImageData,value:m})}var a,c,l;console.log("Environment not supported")},getInputNames:()=>[{name:vi.image,type:ye.ImageData}],getOutputNames:()=>[{name:yi.image,type:ye.ImageData}],getDefaultState:bi,terminate:async e=>{const t=e.getState();t.$$private?.pipeline.release()}},Si=()=>({name:"Default widget bundle",description:"",inputs:[{dataType:[ye.Anything],name:"input"}],outputs:[{dataType:[ye.Anything],name:"output"}]});let _i;const Ii=()=>{if(!_i)throw new Error(rt(nt));return _i};const xi=async e=>{const t=new a,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},ki={};var Ei=e=>ki[e]||null;const Ci=async(e,t,n)=>{try{const r=Ii(),i=n?r.loadBlobAsString:r.loadBlob;return await i(e,t)}catch(e){return null}},Oi=async e=>{const t=de;try{const n=await Ci(e,t,!0);if(!n)return null;return Function(n)()}catch(e){return null}},$i=async e=>{const t=he;try{const n=await Ci(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}},Mi=(e,t)=>`${e.replace(fe,"")}_${t}`,Ni=(e,t)=>`widget/${e.replace(fe,"")}/v/${t}`,Ti=async(e,t)=>{const n=Ii(),[r]=await Promise.all([xi(e),n.createLocation(t)]);for(const e in r)e.startsWith("__MACOSX")||await n.saveBlob(t,e,r[e])},Ai=(e,t)=>{const n=Mi(e,t),r=Ei(n);return r?{...r}:null},Pi=(e,t,n)=>{const r=`${`widget/${e.replace(fe,"")}/tmp`}/${t}`;if(n){return Ii().getCacheLocation(r)}return r};var Di=Ai,Li=async(e,t,n)=>{const r=Pi(t,n);await Ti(e,r);const i=Oi(r),s=$i(r),o=Ii(),a=o.getCacheLocation(r),[c,l]=await Promise.all([i,s]);if(!c)return null;let u=l;if(!l){const e=Si(),t=JSON.stringify(e);await o.saveBlob(r,he,je(t)),u=e}return{cachePath:a,processor:c,storedState:Object.freeze(u)}},ji=(e,t,n)=>{if(n.isTempStorage)return Pi(e,t,n.fullStorageRoot);const r=Ii(),i=Ni(e,t);return n.fullStorageRoot?r.getCacheLocation(i):i};const Ri=()=>Si();var Fi={onParentEvent:async(e,t,n,r)=>{const i=r.getState();return i.$$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={...Ri(),...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={...Ri(),...e};return n.$$processor?.getOutputNames?n.$$processor.getOutputNames(e,t):n.outputs.map((e=>({name:e.name,type:e.dataType})))},getDefaultState:Ri,initialize:async(e,t)=>{console.log("Widget bundle initialize",e);let n={...e.getState()},r=n.$$cacheInfo?.widgetThingId||n.collectionInfo?.widgetId||e.widgetId;const i=n.$$cacheInfo?.version.toString()||n.collectionInfo?.version.toString()||1;if(n.$$cacheInfo={...n.$$cacheInfo,version:Number(i),widgetThingId:r},!r||!i)throw new Error("Widget bundle state is missing cache id or version");console.log("Loading state from cache");const s=Di(r,i);let o=!s;if(!n.$$processor)if(n.storageUnitId&&!s){const t=await e.getStorageData(n.storageUnitId);if(t){r=e.widgetId;const s=await Li(t,r,i);o=!0,s&&(n={...n,$$processor:s.processor,$$cacheInfo:{...n.$$cacheInfo,widgetThingId:r,version:Number(i)}},e.setState(n))}}else if(s){o=!1;const r=n.collectionInfo?{...n.collectionInfo}:void 0;n={...n,...!t.keepCurrentState&&s.storedState?{...s.storedState,...r?{collectionInfo:r}:{}}:{},$$processor:s.processor},e.setState(n)}const a=ji(r,i,{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 Bi=Object.freeze({event:"event"}),Ui="1",Wi="2",Yi="3";var Gi={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};r.setState({...i,$$lastEventType:n.data.type}),await r.nextGate(Ui,n.data),await r.nextGate(Wi,n.data),await r.nextGate(Yi,n.data)},getInputNames:()=>[{name:Bi.event,type:ye.Anything}],getOutputNames:e=>{const t={type:{...e}.$$lastEventType??ye.Anything};return[{name:Ui,...t},{name:Wi,...t},{name:Yi,...t}]}};const Hi=()=>({name:"myVar",type:ye.Anything,reactive:!0,defaultValue:""}),Vi=Object.freeze({set:"set",read:"read"}),zi="value";var qi={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...Hi(),...i};if(t.name!==Vi.set){if(t.name===Vi.read){const e=Er({variableName:s.name,readerWidgetId:r.id}),t=e?e.value:s.defaultValue;await r.nextWidget(zi,{type:s.type,value:t})}}else{if(n.data.type!==s.type&&s.type!==ye.Anything)return;await kr({variableName:s.name,value:n.data.value,setByWidgetId:r.id,type:s.type})}},getInputNames:e=>{const t={...e};return[{name:Vi.set,type:t.type||ye.Anything},{name:Vi.read,type:ye.Anything}]},getOutputNames:e=>{const t={...e};return[{name:zi,type:t.type||ye.Anything}]},initialize:async e=>{const t=e.getState(),n={...Hi(),...t};if(n.$$abortListener)try{n.$$abortListener()}catch(t){console.warn(`Error aborting variable listener for widget ${e.widgetId}: `,t)}Ir({variableName:n.name,type:n.type,createdByWidgetId:e.widgetId});const r=Cr({variableName:n.name,type:n.type,widgetId:e.widgetId,onValueChange:async t=>{const n=e.getState();void 0!==t.value&&(n.type!==ye.Anything&&t.type!==n.type||n.reactive&&await e.nextWidget(zi,{type:t.type,value:t.value}))}});e.setState({...n,$$abortListener:r})},terminate:async e=>{const t=e.getState(),n={...Hi(),...t};n.$$abortListener&&n.$$abortListener(),xr({variableName:n.name,createdByWidgetId:e.widgetId})}};let Ji;var Ki=e=>{Ji=e},Zi=()=>{if(!Ji)throw new Error("Hub Connector not set");return Ji};const Xi=e=>{const t=oe(e);return t?.name||""},Qi=async(e,t=!1)=>{const n=Zi();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 es={onParentEvent:async(e,t,n,r)=>{const i={dynamicInputs:{},dynamicOutputs:{},customState:{},...r.getState()};if(!e)return;const s=Zi();let o=i.$$$serviceId;if(!o){const e=s.getCachedServices().available.find((e=>e.name===i.service?.name&&e.version===i.service?.version));if(!e)return;o=e.sessionId,i.$$$serviceId=o,r.setState(i)}const a=i.service?.variants?.find((e=>e.id===i.variantId)),c=a?i.dynamicInputs[a.id]||a?.inputs||[]:i.service?.inputs||[];if(!c?.length)return;if(!a&&i.service?.ignoreParentEvents)return;const l=i.service?.processingTimeoutSec,u=i.service?.name&&r.eventContext?.[i.service?.name];return s.onParentEvent({recipeId:r.recipePoolId,recipeName:Xi(r.recipePoolId),data:n.data,targetServiceSessionId:o,currentState:i.customState,targetVariantId:i.variantId,target:{portName:t.name,widgetId:r.id,widgetType:r.type},source:e,config:{timeout:l?1e3*l:0,async:i.service?.asyncParentEvents},eventContext:u})},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=oe(e.recipePoolId),r=n?.name||"",i=Zi(),s=await Qi(t);if(s)try{return await i.initializeServiceInstance({recipeId:e.recipePoolId,sessionId:s,recipeName:r,widgetId:e.widgetId,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.widgetId}] 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=Zi(),r=await Qi(t,!0);if(r)return n.terminateServiceInstance(r,e.widgetId,e.recipePoolId,t.variantId)}};const ts=Object.freeze({Image:"image"}),ns=Object.freeze({Image:"image"}),rs=()=>({filters:[{name:"grayscale",value:"0.5",id:"d-1"}]});var is={onParentEvent:async(e,t,n,r)=>{const i={filters:[{name:"grayscale",value:"0.5",id:"d-1"}],...r.getState()};if(t.name===ts.Image&&n.data.type===ye.ImageData){if(!Fe(n.data.value))return void console.log("ImageFilter: Invalid image data type, aborting process");const e=n.data.value;i.$$memCanvas?.getContext||(i.$$memCanvas=Ce(e.width,e.height)),i.$$context?.drawImage||(i.$$context=i.$$memCanvas.getContext("2d")),i.$$memCanvas.width!==e.width&&(i.$$memCanvas.width=e.width),i.$$memCanvas.height!==e.height&&(i.$$memCanvas.height=e.height),r.setState(i),i.$$context.putImageData(e,0,0),i.filters.length?i.$$context.filter=i.filters.map((e=>{let t="";return"blur"===e.name?t="px":"hue-rotate"===e.name&&(t="deg"),`${e.name}(${parseFloat(e.value)}${t})`})).join(" "):i.$$context.filter="none",i.$$context.drawImage(i.$$memCanvas,0,0);const t=i.$$context.getImageData(0,0,e.width,e.height);return r.nextWidget(ns.Image,{type:ye.ImageData,value:t})}},getInputNames:()=>[{name:ts.Image,type:ye.ImageData}],getOutputNames:()=>[{name:ns.Image,type:ye.ImageData}],getDefaultState:rs};const ss="loaded";var os={onParentEvent:async(e,t,n,r)=>r.nextWidget(ss,{value:!0,type:ye.Boolean}),getInputNames:()=>[],getOutputNames:()=>[{name:ss,type:ye.Boolean,description:"Triggered when the recipe is fully loaded"}]};var as={onParentEvent:async()=>{},getInputNames:()=>[],getOutputNames:()=>[],getDefaultState:()=>({text:"",color:"#eac43e",size:{width:300,height:200}})};var cs={onParentEvent:async(e,t,n,r)=>{try{const e=((e,t)=>{switch(t){case ye.Number:case ye.Boolean:case ye.String:return String(e);case ye.Array:case ye.JsonObj:case ye.Rect:case ye.Point:return JSON.stringify(e,((e,t)=>"bigint"==typeof t?t.toString():t));case ye.ArrayBuffer:if(e instanceof ArrayBuffer){if(ne)return Buffer.from(e).toString("base64");{const t=new Uint8Array(e),n=t.length,r=new Array(n);for(let e=0;e<n;e++)r[e]=String.fromCharCode(t[e]);return btoa(r.join(""))}}throw new Error("Type is ArrayBuffer but value is not an ArrayBuffer");case ye.ImageData:{if(!Fe(e))throw new Error("Expected ImageData");const t=e,n=Ce(t.width,t.height),r=Oe(n);if(!r)throw new Error("Failed to get canvas context");r.putImageData(t,0,0);const i=n.toDataURL("image/png");if(!i)throw new Error("Failed to convert canvas to data URL");return i.split(",")[1]}default:return String(e)}})(n.data.value,n.data.type);return r.nextWidget("text",{type:ye.String,value:e})}catch(e){return r.nextWidget("error",{type:ye.String,value:e instanceof Error?e.message:"Failed to stringify object"})}},getInputNames:()=>[{name:"object",type:[ye.Number,ye.String,ye.ArrayBuffer,ye.Array,ye.Boolean,ye.JsonObj,ye.Rect,ye.Point,ye.ImageData]}],getOutputNames:()=>[{name:"text",type:ye.String},{name:"error",type:ye.String}],getDefaultState:()=>({})};const ls=e=>{if(Array.isArray(e))return e.map(((e,t,n)=>null===e||"object"!=typeof e?{value:e,"@index":t,"@indexPlus1":t+1,"@isFirst":0===t,"@isLast":t===n.length-1}:{...ls(e),"@index":t,"@indexPlus1":t+1,"@isFirst":0===t,"@isLast":t===n.length-1}));if("object"==typeof e&&null!==e){const t={};for(const n in e){const r=e[n];t[n]=ls(r)}return t}return e},us=(e,t)=>{const n=(e=>{const t=new Date;return{input:"object"==typeof e&&null!==e?ls(e):{value:e},date:{year:t.getFullYear(),month:t.getMonth()+1,day:t.getDate(),hours:t.getHours(),minutes:t.getMinutes(),seconds:t.getSeconds(),milliseconds:t.getMilliseconds(),time:t.getTime(),dayOfWeek:t.getDay(),dayName:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][t.getDay()],shortDayName:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][t.getDay()],date:t.getDate(),fullYear:t.getFullYear(),timezoneOffset:t.getTimezoneOffset(),UTCDate:t.getUTCDate(),UTCDay:t.getUTCDay(),UTCFullYear:t.getUTCFullYear(),UTCHours:t.getUTCHours(),UTCMilliseconds:t.getUTCMilliseconds(),UTCMonth:t.getUTCMonth()+1,UTCMinutes:t.getUTCMinutes(),UTCSeconds:t.getUTCSeconds(),isoString:t.toISOString(),localeString:t.toLocaleString()}}})(t);return l.render(e,n)},ds=()=>({text:"",format:"Text"});var hs={onParentEvent:async(e,t,n,r)=>{const i={text:"",format:"Text",...r.getState()},s=us(i.text,n.data.value);return r.nextWidget("text",{type:ye.String,value:s})},getInputNames:()=>[{name:"input",type:ye.Anything}],getOutputNames:()=>[{name:"text",type:ye.String}],getDefaultState:ds};const fs=()=>({expression:""});var ps={onParentEvent:async(e,t,n,r)=>{const i={expression:"",...r.getState()},s=((e,t)=>{const n=Symbol("error"),r=`\n // 'data' is an argument to this function, passed by new Function call.\n // 'SError' is also an argument, providing the error symbol.\n // 'this' inside this function (created by new Function) is the global object.\n\n\t\t// Shadow eval and Function in this non-strict scope.\n\t\tvar eval = undefined;\n\t\tvar Function = undefined;\n\n // Define the sandbox environment\n const sandboxEnvironment = {\n // Make input 'data' accessible\n data: data,\n \n // Safe console (bind methods to the original console)\n console: undefined,\n\n // Mocked/disabled globals\n process: undefined,\n document: undefined,\n navigator: undefined,\n \n require: undefined,\n // eval and Function are shadowed by var declarations above\n \n // Allowed safe globals (pointing to the real ones, accessed via 'this')\n Math: this.Math,\n Date: this.Date,\n JSON: this.JSON,\n Array: this.Array,\n Object: this.Object,\n String: this.String,\n Number: this.Number,\n Boolean: this.Boolean,\n RegExp: this.RegExp,\n // Error: this.Error, // Not Allow Error constructor\n Symbol: this.Symbol, // Allow Symbol constructor\n Map: this.Map,\n Set: this.Set,\n Promise: this.Promise, // Allow Promise if async expressions are intended\n // setTimeout, setInterval, fetch, etc., are deliberately omitted\n };\n\n // Assign the sandboxEnvironment to act as the 'global' context variables\n const global = sandboxEnvironment;\n const window = sandboxEnvironment;\n const globalThis = sandboxEnvironment;\n\n // Shadow top-level variables that might be accessed directly,\n // ensuring they use the sandboxed versions.\n const process = sandboxEnvironment.process;\n const document = sandboxEnvironment.document;\n const navigator = sandboxEnvironment.navigator;\n const console = sandboxEnvironment.console; // Use the sandboxed console for the expression\n const require = sandboxEnvironment.require;\n // 'eval' and 'Function' are already shadowed by var declarations\n\n // The expression will be evaluated in this scope.\n // 'data' is available as it's an argument to the outer function.\n // 'global.xxx' will resolve to 'sandboxEnvironment.xxx'.\n // 'process.yyy' will resolve to 'sandboxEnvironment.process.yyy'.\n \n return () => {\n "use strict"; // Apply strict mode only to the expression evaluation scope\n const abort = Symbol('abort'); // Local symbol for the expression's optional special return value\n\n let result;\n try {\n // Strict mode can add a layer of security and prevent some common errors.\n // It also changes 'this' binding within the expression if it uses 'this'.\n // If the expression uses 'this', under strict mode it would be undefined unless explicitly set.\n // For expressions not using 'this', strict mode is generally safer.\n result = (() => { return ${t}; })();\n } catch(e) {\n // Log the error using the sandboxed console\n // Use 'instanceof Error' to ensure 'e' has a message property.\n const errorMessage = e instanceof Error ? e.message : String(e);\n return {\n\t\t\t\t\terror: 'Error during expression execution: ' + errorMessage, \n\t\t\t\t\tvalue: null\n\t\t\t\t}; // Return the SError symbol passed into this function's scope\n }\n \n\t\t\t// allows ternary expressions that return 'abort' to cancel the evaluation\n if (result !== abort) {\n // Original logic: if result is strictly true, and expression wasn't literally "true", return original data.\n if (result === true && String(expression).trim() !== 'true') {\n return {value: data, error: null}; \n } else {\n return {value: result, error: null};\n }\n }\n \n // If the expression explicitly returned the 'abort' symbol\n return {value: abort, error: null}; \n }\n // End of functionBody template literal\n `;try{return new Function("data","SError",r)(e,n).call({})}catch(e){return{error:e.message,value:null}}})(n.data.value,i.expression);if("symbol"==typeof s.value)return;if(s.error)throw new Error(s.error);if(Number.isNaN(s.value))throw new Error("Expression resulted in NaN");if(void 0===s.value||null===s.value)return;const o=We(s.value);return o!==i.$$lastResultType&&r.setState({...i,$$lastResultType:o}),r.nextWidget("result",{type:o,value:s.value})},getInputNames:()=>[{name:"data",type:ye.Anything}],getOutputNames:e=>[{name:"result",type:e.$$lastResultType||ye.Anything}],getDefaultState:fs};var gs={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};r.setState({...i,$$lastEventType:n.data.type});try{await r.nextWidget("event",n.data)}catch(e){const t=e;await r.nextWidget("error",{type:ye.JsonObj,value:{error:{message:e.message,targetWidgetId:t.targetWidgetId,targetPortName:t.targetPortName,sourcePortName:t.sourcePortName,sourceWidgetId:t.sourceWidgetId,targetWidgetType:t.targetWidgetType,sourceWidgetType:t.sourceWidgetType,stack:e.stack},inputEvent:{type:n.data.type,data:n.data.value}}})}},getInputNames:()=>[{name:"event",type:ye.Anything}],getOutputNames:e=>[{name:"event",type:{...e}.$$lastEventType??ye.Anything},{name:"error",type:ye.JsonObj,jsonShape:{error:ye.JsonObj,inputEvent:ye.JsonObj}}]};const ms={},ys=Object.freeze({output:"output"}),vs=Object.freeze({read:"read",clear:"clear"}),bs=()=>({$$$time:0,totalInputs:1});var ws={onParentEvent:async(e,t,n,r)=>{const i={$$$time:0,totalInputs:1,...r.getState()};if(ms[r.id]||(ms[r.id]={}),t.name===vs.clear)return ms[r.id]={},void r.setState(i);const s=t.name===vs.read;if(!(s||n.data.type!==ye.JsonObj&&n.data.type!==ye.Anything&&n.data.type!==ye.Rect||"object"!=typeof n.data.value||null===n.data.value||Array.isArray(n.data.value))){const e=ms[r.id]||{};ms[r.id]={...e,...n.data.value}}if(s){const e={...ms[r.id]};return ms[r.id]={},r.setState({...i}),r.nextWidget(ys.output,{type:ye.JsonObj,value:e})}},getInputNames:e=>{const t={$$$time:0,totalInputs:1,...e},n=Array(t.totalInputs||1).fill(0).map(((e,t)=>({name:`input${t+1}`,type:ye.Anything})));return n.push({name:vs.clear,type:ye.Anything},{name:vs.read,type:ye.Anything,triggerPort:!0}),n},getOutputNames:()=>[{name:ys.output,type:ye.JsonObj}],getDefaultState:bs,initialize:async e=>{ms[e.widgetId]={}},terminate:async e=>{delete ms[e.widgetId]}};const Ss={},_s=Object.freeze({output:"output",index:"index",finish:"finish"}),Is=Object.freeze({array:"array",next:"next",clear:"clear"}),xs=()=>({autoLoop:!1,autoClear:!1,$$outputType:ye.Anything,totalItems:0,currentIndex:0});var ks={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...xs(),...i};if(t.name===Is.clear)return delete Ss[r.id],void r.setState({...xs(),autoLoop:s.autoLoop,autoClear:s.autoClear});if(t.name!==Is.array)t.name===Is.next&&await(async e=>{const t=e.id,n=Ss[t],r={...xs(),...e.getState()};if(n&&n.index<n.list.length){const i=n.index,s=n.list[i];await e.nextWidget(_s.index,{type:ye.Number,value:i}),await e.nextWidget(_s.output,{type:r.$$outputType,value:s}),n.index++,e.setState({...r,currentIndex:n.index}),n.index===n.list.length&&(await e.nextWidget(_s.finish,{type:ye.Boolean,value:!0}),r.autoClear?(delete Ss[t],e.setState({...xs()})):(n.index=0,e.setState({...r,currentIndex:0})))}})(r);else if((n.data.type===ye.Array||n.data.type===ye.Anything)&&Array.isArray(n.data.value)){const e=n.data.value,t=e[0],i=void 0!==t?We(t):ye.Anything,o={list:e,index:0};Ss[r.id]=o;const a={...s,$$outputType:i,totalItems:e.length,currentIndex:0};if(r.setState(a),a.autoLoop&&e.length>0){for(const t of e){const e=o.index;r.setState({...a,currentIndex:e}),await r.nextWidget(_s.index,{type:ye.Number,value:e}),await r.nextWidget(_s.output,{type:a.$$outputType,value:t}),o.index++}await r.nextWidget(_s.finish,{type:ye.Boolean,value:!0}),a.autoClear?(delete Ss[r.id],r.setState({...a,$$outputType:ye.Anything,totalItems:0,currentIndex:0})):(o.index=0,r.setState({...a,currentIndex:0}))}}},getInputNames:()=>[{name:Is.array,type:ye.Array},{name:Is.next,type:ye.Anything},{name:Is.clear,type:ye.Anything}],getOutputNames:e=>{const t={...xs(),...e};return[{name:_s.index,type:ye.Number},{name:_s.output,type:t.$$outputType},{name:_s.finish,type:ye.Anything}]},getDefaultState:xs,initialize:async e=>{const t={...xs(),...e.getState()};Ss[e.widgetId]={list:[],index:0},e.setState({...t,currentIndex:0,totalItems:0})},terminate:async e=>{delete Ss[e.widgetId]}};const Es={input:ot,counter:lt,elapsed:ht,ifGate:mt,skipEvent:bt,between:It,map:Et,parser:$t,slider:Tt,suspend:Dt,display:jt,json:Bt,arrayItem:Yt,extractImage:qt,imageConvolution:Qt,firstEvent:rn,pixelDraw:hn,randomBetween:mn,arrayCombine:Sn,clock:kn,multiplication:$n,object:jn,widgetGroup:Un,script:Yr,base64ToImageData:Kr,jsonParse:ei,text:ii,imageCrop:ci,imageResize:hi,value:mi,imageWarp:wi,widgetBundle:Fi,sequence:Gi,variable:qi,hubService:es,imageFilter:is,recipeLoad:os,note:as,stringify:cs,templateString:hs,expressionEval:ps,rescue:gs,objectCombine:ws,loop:ks,play:{getInputNames:()=>[],onParentEvent:()=>Promise.resolve(),getOutputNames:()=>[{name:"out",type:ye.Boolean}]}},Cs={},Os=async()=>{if(!Object.keys(Cs).length)for(const e in Es){const t=Es[e];Cs[e]=Object.freeze({...t})}};var $s=e=>{if(Cs[e])return Cs[e];throw new Error(rt(tt,e))},Ms=Os;const Ns=new o,Ts="invoked";let As={},Ps={},Ds={},Ls={};const js=(e,t,n)=>`${e}-${t}${n?`-${n}`:""}`;var Rs=(e,t,n,r,i)=>{const s=js(e,t,n),o=js(e,t),a=js(e,t,"produced"),c=Ds[o],l=Date.now();Ls[o]=l,As[s]={data:r,sourcePortName:n,...i?{target:{widgetId:i.widgetId,portName:i.portName}}:{}},Ns.emit(a,{currentTime:l,prevTime:c,...i?{targetPort:i?.portName}:{}})},Fs=(e,t,n,r,i)=>{const s=js(e,t,n),o=js(e,t),a=js(e,t,Ts),c=Ds[o],l=Date.now();Ds[o]=l,Ps[s]={data:r,sourcePortName:n,...i?{source:{widgetId:i.widgetId,portName:i.portName}}:{}},Ns.emit(a,{prevTime:c,currentTime:l,targetPort:n,sourceInfo:i})},Bs=()=>{As={},Ps={},Ds={},Ls={},Ns.clearListeners()};const Us={};let Ws={};const Ys=new o;let Gs=!1,Hs=!1,Vs=!1,zs=null,qs=null;const Js="processing-state-change",Ks="error-event",Zs={abortRequested:!1,isPaused:!1,pausePromise:null,pausePromiseResolve:null,lastPausedWidgetId:null},Xs=e=>(qs=e,Ys.emit(Js,e)),Qs=(e,t)=>`${e}-${t}`,eo=(e,t)=>`state-change:${Qs(e,t)}`,to=e=>{const{thingId:t,widgetId:n}=e,r=Qs(t,n);return Us[r]||{isProcessing:!1}},no=()=>{Zs.abortRequested=!1,Zs.isPaused=!1},ro=e=>(Zs.pausePromise||(Zs.isPaused=!0,Zs.pausePromise=new Promise((e=>{Zs.pausePromiseResolve=e})),e&&(Zs.lastPausedWidgetId=e),Xs({isProcessing:!0,isPaused:!0,...e?{pauseTrapWidgetId:e}:{}})),Zs.pausePromise);var io,so,oo=async e=>{const{thingId:t,widgetId:n}=e,r=Qs(t,n),i=eo(t,n),s=to({thingId:t,widgetId:n});if(s.isProcessing)return;const o={isProcessing:!0,isPaused:!1,startTime:Date.now()};Us[r]=o,Gs||(Gs=!0,zs=null,await Xs({isProcessing:!0,isPaused:!1})),await Ys.emit(i,{thingId:t,widgetId:n,prevState:s,newState:o})},ao=async e=>{const{thingId:t,widgetId:n,error:r}=e,i=Qs(t,n),s=eo(t,n),o=to({thingId:t,widgetId:n}),a={isProcessing:!1,isPaused:!1,startTime:o.startTime,endTime:Date.now(),error:r};Us[i]=a,await Ys.emit(s,{thingId:t,widgetId:n,prevState:o,newState:a}),r&&(zs=r,await Ys.emit(Ks,r)),Gs&&0===Object.values(Us).filter((e=>e.isProcessing)).length&&(Gs=!1,Hs=!1,no(),await Xs({isProcessing:!1,isPaused:!1}))},co=()=>{Gs=!1;for(const e in Us)delete Us[e];Zs.abortRequested=!1,Zs.isPaused=!1,Zs.pausePromise=null,Zs.pausePromiseResolve=null,Zs.lastPausedWidgetId=null,Ys.clearListeners()},lo=()=>Zs.abortRequested,uo=e=>{Zs.lastPausedWidgetId=e,Zs.isPaused=!0,Xs({isProcessing:!0,isPaused:!0,pauseTrapWidgetId:e})},ho=()=>Hs||Vs?null:Zs.pausePromise,fo=e=>Vs?null:Ws[e]??null,po=()=>Hs,go=e=>ro(e);!function(e){e.ServiceCreationLog="service-creation-log"}(io=io||(io={})),function(e){e.Service="service",e.ServiceUI="serviceUI"}(so=so||(so={}));let mo={},yo={},vo=null;const bo=(e,t)=>{const n=(()=>{if(null===vo)throw new Error("Recipe execution type not set, please set the execution type using `setRecipeExecutionType`");return vo===Hn.Desktop})();let r=n?yo[e]:void 0;return r||(r=(e=>{const{widgets:t,targetId:n,allowedTypes:r}=e;if(!t[n])return[];const i=new Set;Object.values(t).forEach((e=>{e.children?.forEach((e=>i.add(e.childId)))}));const s=Object.keys(t).filter((e=>!i.has(e))),o=s.length>0?s:Object.keys(t),a=[],c=(e,i,s)=>{if(s.has(e))return;s.add(e);const o=t[e],l=!r||r.includes(o.type),u=[...i];l&&u.push(e),e===n?a.push(u.join("/")):o.children?.forEach((e=>c(e.childId,u,s))),s.delete(e)};return o.forEach((e=>c(e,[],new Set))),[...new Set(a)]})({widgets:t,targetId:e,allowedTypes:[qe.hubService]}),n&&(yo[e]=r)),r},wo=(e,t,n)=>{bo(t,n).forEach((n=>{mo[n]={eventContext:e,widgetId:t}}))},So=(e,t)=>{const n=t[e].state,r=n.service?.name;if(!r)return[];const i=bo(e,t),s=new Map;for(const e of i){const n=e.split("/");let i="";for(let e=0;e<n.length-1;e++){i=0===e?n[e]:`${i}/${n[e]}`;const o=mo[i];if(o&&!s.has(o.widgetId)){const e=t[o.widgetId].state;e.service?.name===r&&s.set(o.widgetId,{path:i,data:o,pathSegments:i.split("/").length})}}}return Array.from(s.values())},_o=()=>{mo={}},Io=e=>{vo=e},xo=()=>{mo={},yo={}};let ko,Eo,Co,Oo=!1,$o=0;const Mo=async e=>{const{widgetId:t,thingId:n,recipeId:r,targetPortName:i,data:s}=e,o=ae(r,n);if(!o)return;const a=o.gates[t];if(!a||a.disabled)return;const c={...s,timestamp:Date.now()},l=$s(a.type),u=Do({gateId:t,originalEvent:c,blockRecipeId:o.recipeId,blockDbId:o.id,blockVersion:o.version,recipeId:r});if(u&&l.onParentEvent){const e={name:i};return ko&&await ko({recipeId:r,blockId:o.recipeId,gateId:t,targetPort:e.name,data:s}),l.onParentEvent(null,e,{originalEvent:c,data:{...c}},u)}},No=async e=>{const{interruptDriven:t,childGateId:n,recipeId:r,sourcePortName:i,targetPort:s,data:o,sourceOutputNames:a,sourceGateId:c}=e;let{originalEvent:l,block:u}=e;if(!t&&!c)throw new Error("Missing parameter ['sourceGateId']");if(!t&&!l)throw new Error("Missing parameter ['originalEvent']");t&&(l={timestamp:Date.now(),type:ye.Boolean,value:!0});const d=l;if("string"==typeof u){const e=ae(r,u);if(!e)return;u=e}const h=u.gates[n];if(!h||h.disabled)return;const f=a.findIndex((e=>e.name===i)),p=$s(h.type),g=Do({gateId:n,originalEvent:d,blockRecipeId:u.recipeId,blockDbId:u.id,blockVersion:u.version,recipeId:r});if(g&&p.onParentEvent&&-1!==f){ko&&await ko({recipeId:r,blockId:u.recipeId,gateId:n,targetPort:s.name,data:o,sourceGate:t?"interrupt_widget":c,sourcePort:t?ue:i});const e={name:a[f].name,type:a[f].type,...a[f].jsonShape?{jsonShape:a[f].jsonShape}:void 0};return Fs(u.recipeId,n,s.name,o,c?{widgetId:c,portName:i}:void 0),p.onParentEvent(e,s,{originalEvent:d,data:o},g)}},To=async e=>{const{portName:t,originalEvent:n,data:r,currentGateId:i,blockRecipeId:s,thingDbId:o,thingVersion:a,recipeId:c,eventContext:l}=e,u=oe(c);if(!u)throw new Error(`Failed to find recipe "${c}" in cache`);const d=u.dbInfo.recipeType,h=ce(c,s,i);if(!h)return;const f={...r,timestamp:n.timestamp},p=$s(h.type);let g;g=h.type===qe.input?p.getOutputNames(h.state,{thingRecipeId:s,thingDbId:o,thingVersion:a,id:i,recipeId:c,recipeType:d,recipePoolId:c}):await p.getOutputNames(h.state,{recipePoolId:c,recipeType:d,thingRecipeId:s,widgetId:i});const m=g.findIndex((e=>e.name===t));if(-1!==m){const e=ae(c,s);if(!e)return;Rs(s,i,t,f);let r=null;const o=h.children.length;if(h.type===qe.hubService&&l){const t=h.state,n=t.service?.name;n&&wo(l,h.id,e.gates)}try{for(let a=0;a<o;a++){const o=e.gates[h.children[a].childId];if(o?.disabled)continue;const l=He(h.children[a]?.sourcePort),u=He(h.children[a]?.targetPort);if(l.portName===t&&o&&!o.disabled){if(Oo&&ho()&&(uo(o.id),await ho()),fo(o.id)&&!po()&&"innerInput"!==u?.portType){const e=go(o.id);await e}if(Oo&&lo())break;const a=$s(o.type);let l;const p={recipePoolId:c,recipeType:d,thingRecipeId:s,widgetId:i};l=o.type===qe.hubService?await a.getInputNames(o.state,p):a.getInputNames(o.state,p);const m=l.find((e=>e.name===u.portName));if(m){Oo&&await oo({thingId:s,widgetId:o.id}),$o++;if(!await No({interruptDriven:!1,childGateId:o.id,block:e,recipeId:c,sourcePortName:t,targetPort:{name:m.name},data:h.returnOriginalEvent?n:f,sourceOutputNames:g,sourceGateId:h.id,originalEvent:n}).then((()=>!0)).catch((e=>{const n=o.type===qe.hubService&&"CHILD_WIDGET_ERROR"===e.errCode;if(e instanceof rr)throw e;if(n&&e.errData){const t=e.errData;throw new rr(e.error||e.message||("string"==typeof e?e:JSON.stringify(e)),{targetWidgetId:t.targetWidgetId,targetPortName:t.targetPortName,sourcePortName:t.sourcePortName,sourceWidgetId:t.sourceWidgetId,targetWidgetType:t.targetWidgetType,sourceWidgetType:t.sourceWidgetType})}if(!r){const n="string"==typeof e?e:e.message||JSON.stringify(e);r={targetWidgetId:o.id,targetPortName:m.name,sourcePortName:t,error:n}}throw new rr(e.message||("string"==typeof e?e:JSON.stringify(e)),{stack:e.stack,targetWidgetId:o.id,targetPortName:m.name,sourcePortName:t,sourceWidgetId:h.id,targetWidgetType:o.type,sourceWidgetType:h.type})})).finally((()=>{if($o--,Oo)return ao({thingId:s,widgetId:o.id,error:r})})))break}}}}catch(e){if(e instanceof rr)throw e;console.error(`Error processing next widget [${i}]: ${e}`)}finally{$o<0&&(console.warn("Active execution counter is negative, this should never happen"),$o=0),0===$o&&_o()}}},Ao=async(e,t,n,r)=>{const i=oe(r);if(!i)return null;const s=ae(r,n);if(!s)return s;const o=s.gates,a=s.gates[t],c=$s(a.type),l=await c.getInputNames(a.state,{recipePoolId:r,recipeType:i.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 i=n[r],s=i.children.length;for(let n=0;n<s;n++){const r=i.children[n],s=He(r.targetPort);if(r.childId===e&&s.portName===t)return i}}return null})(t,l[u].name,o);if(e){const t=$s(e.type);return{getValue:()=>"function"==typeof t.getValue?t.getValue():null}}}return null},Po=e=>{const{gateId:t,originalEvent:n,thingRecipeId:r,thingDbId:i,thingVersion:s,recipeId:o}=e;if(!oe(o))throw new Error(`Failed to find recipe "${o}" in cache`);if(!ce(o,r,t))throw console.warn(`Gate ${t} not found in block ${r} for recipe ${o}`),new Error(`Gate ${t} not found in block ${r} for recipe ${o}`);return async(e,a)=>To({portName:e,originalEvent:n||{timestamp:Date.now(),type:a.type,value:a.value},data:a,currentGateId:t,blockRecipeId:r,thingDbId:i,thingVersion:s,recipeId:o})},Do=e=>{const{gateId:t,originalEvent:n,blockRecipeId:r,blockDbId:i,blockVersion:s,recipeId:o}=e,a=oe(o);if(!a)throw new Error(`Failed to find recipe "${o}" in cache`);const c=ce(o,r,t);if(!c)return console.warn(`Gate ${t} not found in block ${r} for recipe ${o}`),null;const l=Po({gateId:t,originalEvent:n,thingRecipeId:r,thingDbId:i,thingVersion:s,recipeId:o}),u=c.type===qe.hubService,d=u?So(t,a.blocks[r].gates):[],h=d.reduce(((e,t)=>e.pathSegments>t.pathSegments?e:t),d[0]),f={id:t,type:c.type,recipePoolId:o,thingRecipeId:r,recipeType:a.dbInfo.recipeType,returnOriginalEvent:!!c.returnOriginalEvent,registerInterrupt:(e,n,i,s,a)=>Qe.createInterrupt(e,o,r,t,n,i,s,a),cancelInterrupt:e=>Qe.destroyInterrupt(e),nextWidget:l,nextGate:l,getParentAtPort:e=>Ao(e,t,r,o),getState:()=>Object.freeze({...c.state,...c.type===qe.input&&{customInputs:[]}}),setState:e=>{if("object"!=typeof e)return void console.warn(`Invalid state type [${typeof e}]. Expected an 'object'`);const n={...e,...c.type===qe.input&&!e.customInputs&&{customInputs:[]}},i={...c.state};c.state=n,Eo&&Eo({blockId:r,gateId:t,prevState:i,newState:{...n},recipeId:o})},...u&&h&&{eventContext:h.data.eventContext}};return f};Qe.setInvokeChildGateCb((async(e,t,n,r,i,s,o,a,c,l)=>No({interruptDriven:e,childGateId:t,block:n,recipeId:r,sourcePortName:i,targetPort:s,data:o,sourceOutputNames:a,sourceGateId:c,originalEvent:l})));const Lo=(e,t,n,r,i)=>{const s=ce(e,n,r);if(!s)return console.warn(`Gate ${r} not found in block ${n} for recipe ${e}`),null;const o=(t,i,s,o)=>Qe.createInterrupt(t,e,n,r,i,s,o),a=()=>Object.freeze({...s.state,...s.type===qe.input&&{customInputs:[]}}),c=e=>{if("object"!=typeof e)return void console.warn(`Invalid state type [${typeof e}]. Expected an 'object'`);const t={...e,...s.type===qe.input&&!e.customInputs&&{customInputs:[]}};s.state=t},l=async t=>{const r=((e,t,n)=>{const r=oe(e);if(!r)throw new Error(`Recipe [${e} does not exist]`);if(!r.storage)return null;const i=ae(e,t);if(!i)throw new Error(`The Thing "${t}" does not exist in recipe ${e}`);if(!(i.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};if(i){return{getState:a,setState:c,registerInterrupt:o,getStorageData:l,nextWidget:Po({gateId:r,thingRecipeId:n,thingDbId:s.id,thingVersion:"default",recipeId:e}),recipePoolId:e,recipeType:t,thingRecipeId:n,widgetId:r}}return{getState:a,setState:c,recipePoolId:e,widgetId:r}},jo=new o,Ro="invoked",Fo="state",Bo=()=>{Qe.destroyAllInterrupts()},Uo=async(e,t,n)=>{const r=oe(e),i=ce(e,t,n);if(i&&r){const s=$s(i.type);if(s&&"function"==typeof s.terminate){const i=((e,t,n,r)=>Lo(e,t,n,r))(e,r.dbInfo.recipeType,t,n);if(i)try{await s.terminate(i)}catch(e){console.warn(`Error terminating widget "${n}" in thing "${t}". Failing silently: `,e)}}}},Wo=async e=>{const{recipePoolId:t,thingRecipeId:n,widgetRecipeId:r,options:i}=e,s=oe(t),o=ce(t,n,r);if(o&&s){const e=$s(o.type);if(e&&"function"==typeof e.initialize){const a=((e,t,n,r)=>Lo(e,t,n,r,!0))(t,s.dbInfo.recipeType,n,r);if(a){const t=e.initialize;try{(e=>{if(e.type===qe.script){const t=e.state;if((t.version||0)<2){const n=Object.keys(e.variablesListener||{});for(const t of n)if(e.variablesListener){const n=_r(t);e.variablesListener[n]=e.variablesListener[t],delete e.variablesListener[t],delete e.variables}t.version=2}}})(o),await t(a,i||{})}catch(e){throw console.warn(`Error initializing widget "${r}" in thing "${n}": `,e),e}}}}},Yo=(e,t)=>{const n=oe(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},Go=(e,t="",n="")=>`block:${t}:gate:${n||""}:${e}`,Ho=e=>{jo.emit(Go(Fo),e),jo.emit(Go(Fo,e.blockId,e.gateId),e)};ko=async e=>{await jo.emit(Go(Ro),e),await jo.emit(Go(Ro,e.blockId,e.gateId),e)},(e=>{Eo=e})(Ho);var Vo,zo,qo,Jo,Ko,Zo,Xo,Qo,ea,ta,na,ra,ia,sa=async(e,t,n,r,i)=>{const s=le(e,{id:t,authorId:r,version:n,recipeType:i});Bs(),xo(),Io(i);const o=oe(s);return o&&(o.startedAt=Date.now(),o.retryAttempts=0,o.execCounter=0,o.status=Q.STARTING,o.addLog("recipe registered")),s},oa=async e=>{const t=oe(e);var n;if(!t)return null;t.addLog("terminating recipe"),Bo(),co();for(const n in t.blocks){const r=t.blocks[n];for(const t in r.gates)await Uo(e,n,t)}re[n=e]&&delete re[n]},aa=async(e,t)=>{const n=oe(e),r=[],i=[];if(n){$r({recipePoolId:e,thingId:ge});for(const s in n.blocks){const o=n.blocks[s];if(!t||!Array.isArray(t)||t.includes(s))for(const t in o.gates)try{if(n.dbInfo?.recipeType===Hn.Desktop){const e=o.gates[t];if(e.type===qe.hubService){const r=e.state;if(r?.service?.webOnly){n?.addLog(`skipping initialization of web-only widget "${t}"`);continue}}e.type===qe.recipeLoad&&i.push(e)}await Wo({recipePoolId:e,thingRecipeId:s,widgetRecipeId:t,options:{keepCurrentState:!0}})}catch(e){r.push({widgetId:t,error:e.message})}}}return{failed:r,sendToInputWidget:(t,n,r=ge)=>(async(e,t,n,r)=>{const i=oe(n),s=ae(n,r),o=Date.now();if(s&&i)for(const i in s.gates){const a=s.gates[i];if(a.type===qe.input&&!a.disabled){const c=a.state.inputName||"";if(c===e){const e=$s(a.type),l={...t,timestamp:o},u=Do({gateId:i,originalEvent:l,blockRecipeId:r,blockDbId:s.id,blockVersion:s.version,recipeId:n});if(u&&e.processEvent){const s={...u,getState:u.getState};ko&&await ko({recipeId:n,blockId:r,gateId:i,targetPort:st,data:t}),Co?await Co(r,n,c,t):await e.processEvent(l,s)}}}}})(t,n,e,r),invokeRecipeLoadedWidgets:async()=>{for(const t of i)await Mo({widgetId:t.id,thingId:ge,recipeId:e,targetPortName:ss,data:{type:ye.Boolean,value:!0}})}}},ca=e=>{Ki(e)},la=(e,t,n,r=!1)=>{const i=Yo(t,e);if(i){const{widget:s,thing:o}=i,a={...s.state};s.state=n,r&&Ho({blockId:o.recipeId,gateId:t,recipeId:e,newState:{...n},prevState:a})}},ua=(e,t)=>{const n=Yo(t,e);return n?n.widget.state:null},da=async e=>{const{recipePoolId:t,currentGateId:n,sourcePortName:r,originalEvent:i,data:s,eventContext:o}=e,a=Yo(n,t);if(a)return To({portName:r,originalEvent:i,data:s,currentGateId:n,blockRecipeId:a.thing.recipeId,thingDbId:a.thing.id,thingVersion:a.thing.version,recipeId:t,eventContext:o})};!function(e){e.Seats="seats",e.RecipeInvocations="recipe_invocations",e.HubServices="hub_services",e.RecipeExports="recipe_exports"}(Vo||(Vo={})),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"}(zo||(zo={})),function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(qo||(qo={})),function(e){e.Bundle="bundle",e.Group="group"}(Jo||(Jo={})),function(e){e.Hardware="hardware",e.Virtual="virtual"}(Ko||(Ko={})),function(e){e.Cloud="cloud",e.Web="web"}(Zo||(Zo={})),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"}(Xo||(Xo={})),function(e){e.Gateway="gateway",e.Timer="timer"}(Qo||(Qo={})),function(e){e.InstallInProgress="installation-in-progress"}(ea||(ea={})),function(e){e.InstallDependencies="install-dependencies",e.GetInstalledDependencies="get-installed-dep"}(ta||(ta={})),function(e){e.Success="success",e.Error="error",e.Pending="pending"}(na||(na={})),function(e){e.NotFound="not-found",e.BadRequest="bad-request",e.Forbidden="forbidden",e.InternalError="internal-error"}(ra||(ra={})),function(e){e.KeyCreated="key_created",e.ValidateKey="validate_key",e.ExecuteRecipe="execute_recipe",e.InstallHubService="install_hub_service",e.UninstallHubService="uninstall_hub_service",e.ExportRecipe="export_recipe"}(ia||(ia={}));const ha=(e,t)=>((e,t,n)=>{const r=Buffer.from(n,"base64"),i=r.subarray(0,16),s=r.subarray(16).toString("base64"),o=d(e,t,32),a=h("aes-256-cbc",o,i);let c=a.update(s,"base64","utf8");return c+=a.final("utf8"),c})(e.id||"recipe.kemu","kemu",t),fa=e=>{try{return JSON.parse(e)}catch(e){return null}},pa="undefined"!=typeof window,ga={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},ma={protocolPrefix:4,txtLength:4},ya=Object.values(ga).reduce(((e,t)=>e+t),0),va=Object.values(ma).reduce(((e,t)=>e+t),0),ba=["width","height","colorSpace"],wa=(e,t)=>{const n={},r=[];let i=0,s=Array.isArray(e)?[]:{};const o=(e,s)=>{const a=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,i=e instanceof Uint8Array,s=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":i?"Uint8Array":s?"Int8Array":null})(e);if(!a){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=o(e[n],`${s}[${n}]`);return t}if("object"==typeof e){const t={},n=(e=>{const t=e instanceof Int16Array,n=e instanceof Uint16Array,r=e instanceof Int32Array,i=e instanceof Uint32Array,s=e instanceof Float32Array,o=e instanceof Float64Array,a=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":i?"Uint32Array":s?"Float32Array":o?"Float64Array":a?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${s}"`);for(const n in e)Object.hasOwn(e,n)||ba.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${s}`),t[n]=o(e[n],`${s.length?`${s}.`:""}${n}`);return t}return e}n[s]={index:i,length:e.byteLength,binaryType:a},"Buffer"===t?r.push(Buffer.from(e)):"ArrayBuffer"===a?r.push(e):r.push(e.buffer),i+=e.byteLength};s=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:s}:null},Sa=(e,t,n)=>{const r=t.match(/(\[\d+\])|([^[\].]+)/g)||[];let i=e;for(let e=0;e<r.length;e++){let t=r[e];const s=t.startsWith("[")&&t.endsWith("]"),o=e===r.length-1;if(s){t=t.slice(1,-1);const s=parseInt(t,10);if(!Array.isArray(i))throw new Error(`Expected an array at key "${r.slice(0,e).join(".")}" but found an object.`);o?i[s]=n:(i[s]||(i[s]=r[e+1].startsWith("[")?[]:{}),i=i[s])}else o?i[t]=n:(i[t]||(i[t]=r[e+1].startsWith("[")?[]:{}),i=i[t])}return e},_a=(e,t,n)=>{const r="undefined"!=typeof Buffer,i=t instanceof Uint8Array;for(const s in n)if(Object.hasOwn(n,s)){const{index:o,length:a,binaryType:c}=n[s];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=i?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a):t.slice(o,o+a);break;case"Uint8Array":l=i?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&&Sa(e,s,l)}return e},Ia=e=>g(e),xa="KMSG",ka="KCMD",Ea=Ia("klProtocol");var Ca={encode:(e,t,n)=>{const r={json:e.json},i=wa(r.json,"Buffer"),s=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const o=s?s.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),l=c.byteLength,u=ga.protocolPrefix+ga.protocolVersion+ga.jsonLength+ga.binaryLength+ga.fromServiceId+ga.toServiceId+ga.sentAt+l+o,d=Buffer.alloc(u),h=Date.now();let f=0;return d.write(xa,f),f+=ga.protocolPrefix,d.writeUInt8(1,f),f+=ga.protocolVersion,d.writeUInt32LE(l,f),f+=ga.jsonLength,d.writeUInt32LE(o,f),f+=ga.binaryLength,d.writeUInt32LE(t,f),f+=ga.fromServiceId,d.writeUInt32LE(n,f),f+=ga.toServiceId,d.writeBigInt64LE(BigInt(h),f),f+=ga.sentAt,c.copy(d,f),f+=l,s&&o&&s.copy(d,f),d},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,ga.protocolPrefix);if(t+=ga.protocolPrefix,n!==xa)return null;if(e.byteLength<ya)return Ea(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=ga.protocolVersion;const i=e.readUInt32LE(t);t+=ga.jsonLength;const s=e.readUInt32LE(t);t+=ga.binaryLength;const o=e.readUInt32LE(t);t+=ga.fromServiceId;const a=e.readUInt32LE(t);t+=ga.toServiceId;const c=e.readBigInt64LE(t);t+=ga.sentAt;const l=i+s,u=e.subarray(t,t+l),d=e.subarray(0,ya);let h=null;return e.byteLength-ya-i-s>0&&(h=e.subarray(ya+i+s)),{header:{protocolVersion:r,jsonLength:i,binaryLength:s,fromServiceId:o,toServiceId:a,sentAt:new Date(Number(c)),packages:[u],headerPackage:d},remaining:h}},decodeFullKlMessage:e=>{const t=Buffer.concat(e.packages),n=t.subarray(0,e.jsonLength).toString(),r=t.subarray(e.jsonLength,e.jsonLength+e.binaryLength),i=fa(n);if(!i?.json)return Ea("Invalid JSON in KL message"),null;i.jsonBinaryMap&&r.byteLength&&_a(i.json,r,i.jsonBinaryMap);const s=Buffer.concat([e.headerPackage,t]);let o=s,a=null;const c=ya+e.jsonLength+e.binaryLength;return s.byteLength>c&&(a=s.subarray(c),o=s.subarray(0,c)),{message:{json:i.json,rawMessage:o},remaining:a}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<ya)return Ea("Invalid Header Size"),e;let n=0;return n+=ga.protocolPrefix,n+=ga.protocolVersion,n+=ga.jsonLength,n+=ga.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=ga.fromServiceId,void 0!==t.toServiceId&&e.writeUInt32LE(t.toServiceId,n),e},encodeCommand:e=>{let t=0;const n=Buffer.from(e),r=n.byteLength,i=va+r,s=Buffer.alloc(i);return s.write(ka,t),t+=ma.protocolPrefix,s.writeUint32LE(r,t),t+=ma.txtLength,n.copy(s,t),s},decodeCommand:e=>{let t=0;if(e.byteLength<va)return{command:null};const n=e.toString("utf-8",t,ma.protocolPrefix);if(t+=ma.protocolPrefix,n!==ka)return{command:null};const r=e.readUInt32LE(t);t+=ma.txtLength;const i=e.toString("utf-8",t,t+r),s=e.byteLength-va-r;let o=null;s>0&&(o=e.subarray(va+r));let a=0;return s<0&&(a=Math.abs(s)),{command:i,remainingData:o,missing:a}}};const Oa="KMSG",$a="KCMD",Ma=Ia("klProtocol"),Na=new TextEncoder;var Ta={encode:(e,t,n)=>{const r={json:e.json},i=wa(e.json,"ArrayBuffer"),s=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const o=s?s.byteLength:0,a=JSON.stringify(r),c=Na.encode(a),l=c.byteLength,u=new ArrayBuffer(ga.protocolPrefix+ga.protocolVersion+ga.jsonLength+ga.binaryLength+ga.fromServiceId+ga.toServiceId+ga.sentAt+l+o),d=new DataView(u),h=new Uint8Array(u),f=Date.now();let p=0;for(let e=0;e<4;++e)h[p++]=Oa.charCodeAt(e);return d.setUint8(p,1),p+=ga.protocolVersion,d.setUint32(p,l,!0),p+=ga.jsonLength,d.setUint32(p,o,!0),p+=ga.binaryLength,d.setUint32(p,t,!0),p+=ga.fromServiceId,d.setUint32(p,n,!0),p+=ga.toServiceId,d.setBigInt64(p,BigInt(f),!0),p+=ga.sentAt,h.set(c,p),p+=l,s&&o&&h.set(new Uint8Array(s),p),u},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<ga.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Oa)return null;if(e.byteLength<ya)return Ma.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const i=t.getUint8(n);n+=ga.protocolVersion;const s=t.getUint32(n,!0);n+=ga.jsonLength;const o=t.getUint32(n,!0);n+=ga.binaryLength;const a=t.getUint32(n,!0);n+=ga.fromServiceId;const c=t.getUint32(n,!0);n+=ga.toServiceId;const l=t.getBigInt64(n,!0);n+=ga.sentAt;const u=s+o,d=e.slice(n,n+u),h=new Uint8Array(e,0,ya);let f=null;if(e.byteLength-ya-s-o>0){f=new Uint8Array(e,ya+s+o).slice().buffer}return{header:{protocolVersion:i,jsonLength:s,binaryLength:o,fromServiceId:a,toServiceId:c,sentAt:new Date(Number(l)),packages:[d],headerPackage:h.slice().buffer},remaining:f}},decodeFullKlMessage:e=>{const t=e.packages.reduce(((e,t)=>e+t.byteLength),0),n=new Uint8Array(t);let r,i=0;for(const t of e.packages)r=new Uint8Array(t),n.set(r,i),i+=r.byteLength;const s=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),o=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=fa(s);if(!a?.json)return Ma.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&o.byteLength&&_a(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=ya+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<ya)return Ma("Invalid Header Size"),e;let n=0;n+=ga.protocolPrefix,n+=ga.protocolVersion,n+=ga.jsonLength,n+=ga.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=ga.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=Na.encode(e),r=n.byteLength,i=new ArrayBuffer(va+r),s=new DataView(i),o=new Uint8Array(i);for(let e=0;e<4;++e)o[t++]=$a.charCodeAt(e);return s.setUint32(t,r,!0),t+=ma.txtLength,o.set(n,t),i},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<va)return{command:null};let r="";for(let e=0;e<ma.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==$a)return{command:null};const i=t.getUint32(n,!0);n+=ma.txtLength;const s=e.byteLength-va-i,o=new Uint8Array(e,n,Math.min(i,e.byteLength-va)),a=(new TextDecoder).decode(o);let c=null;s>0&&(c=e.slice(va+i));let l=0;return s<0&&(l=Math.abs(s)),{command:a,remainingData:c,missing:l}}};let Aa=Ca;pa&&(Aa=Ta);var Pa,Da=Aa;!function(e){e.FunctionNotFound="FNC_NOT_FOUND",e.ParentEventCallbackError="PARENT_EVENT_CALLBACK_ERROR"}(Pa||(Pa={}));let La=Math.ceil(Date.now()/1e3);let ja,Ra,Fa,Ba,Ua,Wa=!1;var Ya=()=>{Wa=!0},Ga=(e,t)=>{if(!ja)throw new Error("Memory connection not set.");ja.sendBuf(e,t)},Ha=e=>Ra=e,Va=e=>Ua=e,za=e=>Fa=e,qa=e=>Ba=e;const Ja=async(e,t=2)=>{const n=async(e,r)=>{if(Array.isArray(e))for(let i=0;i<e.length;i++){const s=e[i];if(s&&"object"==typeof s)if(Array.isArray(s))await n(s,r+1);else{const o=s._kemuType;void 0!==o?o===ye.ImageData&&(e[i]=await Ve(s)):r<t&&await n(s,r+1)}}else if("object"==typeof e&&null!==e){const i=Object.keys(e);for(const s of i){const i=e[s];if(i&&"object"==typeof i){const o=i._kemuType;void 0!==o?o===ye.ImageData&&(e[s]=await Ve(i)):r<t&&await n(i,r+1)}}}};return await n(e,1),e};Ia("klTransmissionManager"),Ia("ipcClient");Ia("kemuWidgetService"),C(process.argv.slice(2));const Ka=e=>g(`runner:${e}`),Za=Ka("connectionManager"),Xa=Ka("remoteInvoke"),Qa=new function(e){const t={};let n=console.log;const r={};let i=e||String(Date.now());const s={},o=e=>!s[e],a=(e,t,n,r,i,s)=>{let a=pa?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:s.success?s.success:[s],messageId:t,type:s.success?"response":"error"}};return o(r)&&(a=Da.encode(c,n,r)),i(a,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{n=e},processMessage:(e,i,s,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,s.targetServiceId,s.sourceServiceId,i,e)};t({transport:e,args:c.args,reply:n,messageId:c.messageId,sourceServiceId:s.sourceServiceId,send:i})}else{const e=`Function "${c.functionName}" not found.`;n&&n(e),a(c.functionName,c.messageId,s.targetServiceId,s.sourceServiceId,i,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(e,r,s,a,c,l)=>{if(!s){const e="No send buffer function provided.";throw n&&n(e),e}La+=1;const u=`${i}-${La}-exec-${e.substring(0,10)}`,d={messageId:u,functionName:e,send:s,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};d.promise=new Promise(((e,t)=>{d.resolve=e,d.reject=t}));let h=pa?new ArrayBuffer(0):Buffer.alloc(0);const f={json:{functionName:e,args:r,messageId:u,type:"execute"}};o(c)&&(h=Da.encode(f,a,c)),t[u]=d,n&&n(`Calling remote function "${e}" with message id "${u}"`);const p="true"===process.env.NO_INVOKE_TIMEOUT;return l?.async?(d.fulfilled=!0,d.resolve([void 0]),delete t[u]):0===l?.timeout||p||(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)),s(h,{sourceServiceId:a,targetServiceId:c,msg:f}),d.promise},sendResponse:a,registerFunction:(e,t)=>{r[e]=t},getTransportSendFunction:e=>{const n=t[e];return n?n.send:null},setServiceName:e=>{i=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,s)=>{La+=1;const a=`${i}-${La}-multicast-${e.substring(0,10)}`;let c=pa?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=Da.encode(l,s,r[0].serviceId));for(let t=0;t<r.length;t++)try{const i=r[t];n&&n(`Broadcasting function "${e}" with message id "${a}" to client [${i.serviceId}]`),0!==t&&(u=o(i.serviceId),u&&(c=Da.patchEncodedHeader(c,{toServiceId:i.serviceId}))),i.sendFn(c,{msg:l,sourceServiceId:s,targetServiceId:i.serviceId})}catch(e){n&&n(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{s[e]=t}}}("kweb");Qa.setLogger(Xa);const ec=new o,tc=new o;let nc,rc=null,ic=null,sc=null,oc=null;const ac={},cc=()=>{if(!sc)throw new Error("API key is required to interact with the hub");return sc},lc=(e,t,n)=>{const r=`${e}_${t}`,i={contents:n,lastRequestedAt:Date.now(),contentsChecksum:""};return ac[r]=i,i},uc=(e,t)=>ac[`${e}_${t}`]||null,dc=async(e,t)=>{if(!rc)return Za("Hub Link has not been acknowledged. Cannot get services."),null;const n=[{serviceName:e,version:t}];return(await Qa.execute(Se.GetServiceContents,n,fc,rc,0))[0]},hc=async(e,t,n=!1)=>{if(!e||!t)return null;const r=uc(e,t);if(!r||n){const n=r||lc(e,t);try{const r=await dc(e,t);return r&&(n.contents=r.uiContent,n.contentsChecksum=r.uiContentsChecksum||""),n.contents||null}catch(n){Za(`Failed to fetch service contents for ${e} v${t}`,n)}}return r?.contents||null},fc=Ga,pc=()=>{Za("Disconnected from the server"),rc=null,oc=null,Qa.rejectAllPending("Disconnected from the server"),ec.emit("disconnected")},gc=()=>{Za("Connected to the server"),ec.emit("connected")},mc=()=>ic,yc=(e,t,n,r)=>`${e}_${t}_${n}_${r}`,vc=async()=>{const e=mc();if(e){const t=oe(e)?.blocks;if(t){const n={};for(const r in t){const i=t[r];for(const t in i.gates){const r=i.gates[t];if(r.type===qe.hubService){const t=r.state;if(t.service?.eventEmitter){const r=`${t.service.name}_${t.service.version}`;if(!n[r])try{Za(`Re-issuing subscription for service ${t.service.name} (${t.service.version})`),n[r]=!0,await Ac({listener:{recipeId:e},targetService:{serviceName:t.service.name,version:t.service.version}})}catch(e){Za(`Failed to re-issue subscription for service ${t.service.name} (${t.service.version})`,e)}}}}}}}},bc=async e=>{if(!e)return void Za("Hub sent ACK request without service id");const t={apiKey:cc(),ackSessionId:e};await Qa.execute(Se.SocketAckResponse,[t],fc,e,0),Za("Hub Link acknowledged"),rc=e,ec.emit("acknowledged"),vc()},wc=async e=>{const t=e.args[0],n=yc("broadcast",`hub_${t.type}`,(0).toString(),"");await tc.emit(n,t)},Sc=async e=>{const t=e.args[0];for(const e of t.outputs||[])e.type===ye.ImageData&&Fe(e.value)&&(e.value=await Ve(e.value));const n=mc();if(n){const r=oe(n);if(r){const i=async e=>{const n=yc("broadcast",t.source.serviceName,t.source.serviceVersion,e);try{await tc.emit(n,t)}catch(t){Za(`Failed to emit broadcast event for target ${e}`,t)}};await i("app");for(const s in r.blocks){const o=r.blocks[s];for(const r in o.gates){const s=o.gates[r];if(s.disabled)continue;const a=s.state;if(s.type===qe.hubService&&a.service?.name===t.source.serviceName&&a.service?.version===t.source.serviceVersion&&a.variantId===t.variantId){await i(r);const s=a?.service?.name&&t.eventContext?{[a.service.name]:t.eventContext}:void 0;for(const i of t.outputs||[])if(null!==i.value&&void 0!==i.value){const t={type:i.type,value:i.value,timestamp:Date.now()};Za(`Sending data to output ${i.name} requested by messageId ${e.messageId}`),await da({recipePoolId:n,currentGateId:r,sourcePortName:i.name,originalEvent:t,data:t,eventContext:s})}}}}}}},_c=async e=>{const t=e.args[0],{finalState:n,recipeId:r,widgetId:i}=t,s=ua(r,i);let o=s;if(n&&o&&s&&(o={...s,customState:n},la(r,i,o,!0)),o?.service)try{const e=yc("setOutputs",o.service.name,o.service.version,i);await tc.emit(e,t.outputs)}catch(e){Za(`Failed to emit setOutputs event for widget ${i}`,e)}let a=null;for(const n of t.outputs)if(null!==n.value&&void 0!==n.value){if(n.type===ye.ImageData){if(!Fe(n.value)){Za(`Invalid ImageData value received for output ${n.name}. Expected an ImageData-like object`);continue}n.value=await Ve(n.value)}else n.type!==ye.JsonObj&&n.type!==ye.Array||await Ja(n.value);const s={type:n.type,value:n.value,timestamp:Date.now()};Za(`Sending data to output ${n.name} requested by messageId ${e.messageId}`);const c=o?.service?.name&&t.eventContext?{[o.service.name]:t.eventContext}:void 0;try{await da({recipePoolId:r,currentGateId:i,sourcePortName:n.name,originalEvent:s,data:s,eventContext:c})}catch(e){Za(`Failed to trigger next global widget for output ${n.name}`,e),a=e;break}}if(a){const t=a instanceof rr,n=a;e.reply({error:a.message,errCode:t?"CHILD_WIDGET_ERROR":"INVOKING_ERROR",errData:{targetWidgetId:n.targetWidgetId,targetPortName:n.targetPortName,sourcePortName:n.sourcePortName,sourceWidgetId:n.sourceWidgetId,targetWidgetType:n.targetWidgetType,sourceWidgetType:n.sourceWidgetType}})}else e.reply({success:[]})},Ic=async e=>{const t=e.args[0],{newState:n,recipeId:r,widgetId:i}=t,s=ua(r,i);if(s){const t={...s,customState:{...s.customState,...n}};return la(r,i,t,!0),e.reply({success:[]})}},xc=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:i,path:s,key:o}=n;Za(`Received request to set a dependency path for "${o}" on widget "${i}" in recipe "${r}"`);const a=ua(r,i);if(a){const e={...a};e.dependencies=e.dependencies||{},e.dependencies[o]={path:s},la(r,i,e,!0)}return t({success:[]})},kc=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:i,key:s}=n;Za(`Received request to get a dependency path for "${s}" on widget "${i}" in recipe "${r}"`);const o=ua(r,i);if(o){const e=o.dependencies?.[s]?.path;return Za(`Returning dependency path for "${s}" on widget "${i}": "${e}"`),t({success:[e||null]})}return t({error:"Widget not found",errCode:"WIDGET_NOT_FOUND"})},Ec=async()=>{if(Za(`Requesting services on ${(new Date).toISOString()}`),!rc)return Za("Hub Link has not been acknowledged. Cannot get services."),{available:[],installed:[],failed:[]};const[e]=await Qa.execute(Se.GetServices,[],fc,rc,0);nc=e;for(const t of e.available){if(t.internal)continue;const e=uc(t.name,t.version);if(!e||e?.contentsChecksum!==t.uiContentChecksum)try{const n=e||lc(t.name,t.version);Za(`Service ${t.name} v${t.version} contents have changed, fetching new contents`);const r=await dc(t.name,t.version);r&&(n.contents=r.uiContent,n.contentsChecksum=t.uiContentChecksum||"")}catch(e){Za(`Failed to update service contents for ${t.name} v${t.version}`,e)}}return e},Cc=()=>nc||{available:[],installed:[],failed:[]},Oc=()=>!!nc,$c=async e=>{const{targetServiceSessionId:t}=e;if(!rc)return void Za("No target service session id provided");Za(`Forwarding "onParentEvent" to service ${t}`);return await Qa.execute(Se.OnParentEvent,[e],fc,rc,t,e.config).catch((e=>{throw Za(`Error invoking onParentEvent callback: ${e}`),e.errCode===Pa.ParentEventCallbackError?e.error:e}))},Mc=async e=>{if(!rc)return Za("Hub Link has not been acknowledged. Cannot get services."),{};const[t]=await Qa.execute(Se.GetDefaultState,[],fc,rc,e);return t},Nc=async(e,t,n,r)=>{if(!rc)return Za("Hub Link has not been acknowledged. Cannot get services."),null;const[i]=await Qa.execute(Se.UIEvent,[t,n],fc,rc,e,r);return i},Tc=(e,t)=>{const n=()=>{t()};return ec.on(e,n),()=>ec.off(e,n)},Ac=async e=>{if(rc)return Qa.execute(Se.SubscribeToService,[e],fc,rc,0);Za("Hub Link has not been acknowledged. Cannot subscribe to services.")},Pc=async e=>{if(rc)return Qa.execute(Se.UnsubscribeFromService,[e],fc,rc,0);Za("Hub Link has not been acknowledged. Cannot subscribe to services.")},Dc=(e,t,n,r)=>{const i=yc("broadcast",t,n,e);return tc.on(i,r)},Lc=(e,t,n,r)=>{const i=yc("setOutputs",t,n,e);return tc.on(i,r)},jc=async(e,t,n)=>rc?Qa.execute(e,t,fc,rc,0,n):(Za("Hub Link has not been acknowledged. Cannot execute function."),null),Rc=async e=>{if(!rc)return void Za("Hub Link has not been acknowledged. Cannot execute function.");const t=ua(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,recipeName:e.recipeName,currentDependencies:n}],[i]=await Qa.execute(Se.InitializeInstance,r,fc,rc,e.sessionId);if(i){const t=ua(e.recipeId,e.widgetId);if(t){const n={...t,customState:i};la(e.recipeId,e.widgetId,n,!0)}}},Fc=async(e,t,n,r)=>{if(!rc)return void Za("Hub Link has not been acknowledged. Cannot execute function.");const i=ua(n,t);if(!i)throw new Error("Widget or recipe pool not found. Cannot initialize service instance.");const s=[{currentState:i.customState,recipeId:n,widgetId:t,variantId:r}];await Qa.execute(Se.TerminateInstance,s,fc,rc,e)},Bc=async(e,t,n="^",r)=>{const i=["^","~",">=",">","<=","<","="];if(!i.includes(n))throw new Error(`Invalid compare mode "${n}". Must be one of ${i.join(", ")}`);const s=Oc(),o=r||!s?await Ec():Cc();for(const r of o.available)if(r.name===e){if(r.version===t)return r;if(p(r.version,`${n}${t}`))return r}return null},Uc=async()=>{if(!rc)return Za("Hub Link has not been acknowledged. Cannot get services."),null;if(oc)return oc;const[e]=await Qa.execute(Se.GetSystemInfo,[],fc,rc,0).catch((e=>(Za("Failed to get system info",e),[null])));return oc=e,e};var Wc,Yc,Gc,Hc,Vc,zc,qc,Jc,Kc=async e=>{za(gc),qa(pc),sc=e,Va((({json:e,transmission:t})=>{Qa.processMessage("websocket",fc,t,e)})),Qa.registerFunction(Se.SetState,Ic),Qa.registerFunction(Se.SetOutputs,_c),Qa.registerFunction(Se.BroadcastEvent,Sc),Qa.registerFunction(Se.HubBroadcastEvent,wc),Qa.registerFunction(_e.SetDependencyPath,xc),Qa.registerFunction(_e.GetDependencyPath,kc),Ha((e=>{((e,t)=>{const n=we.SocketAcknowledge,r=we.IpcAcknowledge,i=e.startsWith(n);if(e===r)return t&&t(),0;if(i){const s=e.split(i?n:r),o=parseInt(s[1]);return t&&t(o),o}})(e,bc),((e,t)=>{e===we.ServicesListChanged&&(t&&t())})(e,(()=>{Za("Services list changed"),ec.emit("services-changed")}))})),await Ya()},Zc=(e,t)=>{ec.on(e,t)},Xc=()=>({getServices:Ec,getServiceContents:hc,onParentEvent:$c,onCommand:Tc,getDefaultState:Mc,getCachedServices:Cc,areServicesCached:Oc,subscribeToServiceEvents:Ac,unsubscribeFromServiceEvents:Pc,callProcessorHandler:Nc,onBroadcastEvent:Dc,onSetOutputsEvent:Lc,executeHubFunction:jc,initializeServiceInstance:Rc,terminateServiceInstance:Fc,getCompatibleService:Bc,getHubSystemInfo:Uc}),Qc=e=>{ic=e},el=()=>Qa;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(Wc||(Wc={})),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"}(Yc||(Yc={})),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"}(Gc||(Gc={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(Hc||(Hc={})),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:"}(Vc||(Vc={})),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.GetSystemInfo="getSystemInfo",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.UninstallService="uninstallService",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.GetUniqueId="getUniqueId",e.RebootToInstallUpdate="rebootToInstallUpdate",e.GetFileContentFromCacheId="getFileContentFromCacheId",e.GetDecryptedEdgeApiKey="getDecryptedEdgeApiKey"}(zc||(zc={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(qc||(qc={})),function(e){e.IPC="ipc",e.WS="ws"}(Jc||(Jc={}));const tl=e=>{try{return JSON.parse(e)}catch(e){return null}},nl=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,rl=e=>{if("string"!=typeof e)throw new TypeError("Invalid argument expected string");const t=e.match(nl);if(!t)throw new Error(`Invalid argument not valid semver ('${e}' received)`);return t.shift(),t},il=e=>"*"===e||"x"===e||"X"===e,sl=e=>{const t=parseInt(e,10);return isNaN(t)?e:t},ol=(e,t)=>{if(il(e)||il(t))return 0;const[n,r]=((e,t)=>typeof e!=typeof t?[String(e),String(t)]:[e,t])(sl(e),sl(t));return n>r?1:n<r?-1:0},al=(e,t)=>{for(let n=0;n<Math.max(e.length,t.length);n++){const r=ol(e[n]||"0",t[n]||"0");if(0!==r)return r}return 0},cl=(e,t,n)=>{dl(n);const r=((e,t)=>{const n=rl(e),r=rl(t),i=n.pop(),s=r.pop(),o=al(n,r);return 0!==o?o:i&&s?al(i.split("."),s.split(".")):i||s?i?-1:1:0})(e,t);return ll[n].includes(r)},ll={">":[1],">=":[0,1],"=":[0],"<=":[-1,0],"<":[-1],"!=":[-1,1]},ul=Object.keys(ll),dl=e=>{if(-1===ul.indexOf(e))throw new Error(`Invalid operator, expected one of ${ul.join("|")}`)};var hl="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function fl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function pl(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var n=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})})),n}var gl,ml,yl,vl,bl,wl={exports:{}},Sl={exports:{}};function _l(){if(ml)return gl;ml=1;var e=1e3,t=60*e,n=60*t,r=24*n,i=7*r,s=365.25*r;function o(e,t,n,r){var i=t>=1.5*n;return Math.round(e/n)+" "+r+(i?"s":"")}return gl=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*s;case"weeks":case"week":case"w":return c*i;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(i){var s=Math.abs(i);if(s>=r)return o(i,s,r,"day");if(s>=n)return o(i,s,n,"hour");if(s>=t)return o(i,s,t,"minute");if(s>=e)return o(i,s,e,"second");return i+" ms"}(a):function(i){var s=Math.abs(i);if(s>=r)return Math.round(i/r)+"d";if(s>=n)return Math.round(i/n)+"h";if(s>=t)return Math.round(i/t)+"m";if(s>=e)return Math.round(i/e)+"s";return i+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))}}function Il(){if(vl)return yl;return vl=1,yl=function(e){function t(e){let r,i,s,o=null;function a(...e){if(!a.enabled)return;const n=a,i=Number(new Date),s=i-(r||i);n.diff=s,n.prev=r,n.curr=i,r=i,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,i)=>{if("%%"===r)return"%";o++;const s=t.formatters[i];if("function"==typeof s){const t=e[o];r=s.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:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),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,]+/),i=r.length;for(n=0;n<i;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=_l(),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},yl}var xl,kl,El,Cl,Ol,$l={exports:{}};function Ml(){if(Cl)return El;Cl=1;const e=$,t=O,n=(kl||(kl=1,xl=(e,t=process.argv)=>{const n=e.startsWith("-")?"":1===e.length?"-":"--",r=t.indexOf(n+e),i=t.indexOf("--");return-1!==r&&(-1===i||r<i)}),xl),{env:r}=process;let i;function s(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function o(t,s){if(0===i)return 0;if(n("color=16m")||n("color=full")||n("color=truecolor"))return 3;if(n("color=256"))return 2;if(t&&!s&&void 0===i)return 0;const o=i||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")?i=0:(n("color")||n("colors")||n("color=true")||n("color=always"))&&(i=1),"FORCE_COLOR"in r&&(i="true"===r.FORCE_COLOR?1:"false"===r.FORCE_COLOR?0:0===r.FORCE_COLOR.length?1:Math.min(parseInt(r.FORCE_COLOR,10),3)),El={supportsColor:function(e){return s(o(e,e&&e.isTTY))},stdout:s(o(!0,t.isatty(1))),stderr:s(o(!0,t.isatty(2)))},El}"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?wl.exports=(bl||(bl=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,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(i=r))})),t.splice(i,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=Il()(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Sl,Sl.exports)),Sl.exports):wl.exports=(Ol||(Ol=1,function(e,t){const n=O,r=c;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:i}=this;if(i){const t=this.color,i="[3"+(t<8?t:"8;5;"+t),s=` ${i};1m${r} [0m`;n[0]=s+n[0].split("\n").join("\n"+s),n.push(i+"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=Ml();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=Il()(t);const{formatters:i}=e.exports;i.o=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts).split("\n").map((e=>e.trim())).join(" ")},i.O=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts)}}($l,$l.exports)),$l.exports);var Nl=fl(wl.exports);const Tl=e=>Nl(e);var Al={},Pl={};class Dl extends Error{constructor(e){super(`Format functions must be synchronous taking a two arguments: (info, opts)\nFound: ${e.toString().split("\n")[0]}\n`),Error.captureStackTrace(this,Dl)}}var Ll,jl,Rl,Fl,Bl,Ul=e=>{if(e.length>2)throw new Dl(e);function t(e={}){this.options=e}function n(e){return new t(e)}return t.prototype.transform=e,n.Format=t,n},Wl={exports:{}},Yl={exports:{}},Gl={exports:{}},Hl={exports:{}};function Vl(){return Ll||(Ll=1,function(e){var t={};e.exports=t;var n={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],grey:[90,39],brightRed:[91,39],brightGreen:[92,39],brightYellow:[93,39],brightBlue:[94,39],brightMagenta:[95,39],brightCyan:[96,39],brightWhite:[97,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgGray:[100,49],bgGrey:[100,49],bgBrightRed:[101,49],bgBrightGreen:[102,49],bgBrightYellow:[103,49],bgBrightBlue:[104,49],bgBrightMagenta:[105,49],bgBrightCyan:[106,49],bgBrightWhite:[107,49],blackBG:[40,49],redBG:[41,49],greenBG:[42,49],yellowBG:[43,49],blueBG:[44,49],magentaBG:[45,49],cyanBG:[46,49],whiteBG:[47,49]};Object.keys(n).forEach((function(e){var r=n[e],i=t[e]=[];i.open="["+r[0]+"m",i.close="["+r[1]+"m"}))}(Hl)),Hl.exports}function zl(){return Rl||(Rl=1,jl=function(e,t){var n=(t=t||process.argv||[]).indexOf("--"),r=/^-{1,2}/.test(e)?"":"--",i=t.indexOf(r+e);return-1!==i&&(-1===n||i<n)}),jl}function ql(){if(Bl)return Fl;Bl=1;var e=$,t=zl(),n=process.env,r=void 0;function i(i){var s=function(i){if(!1===r)return 0;if(t("color=16m")||t("color=full")||t("color=truecolor"))return 3;if(t("color=256"))return 2;if(i&&!i.isTTY&&!0!==r)return 0;var s=r?1:0;if("win32"===process.platform){var o=e.release().split(".");return Number(process.versions.node.split(".")[0])>=8&&Number(o[0])>=10&&Number(o[2])>=10586?Number(o[2])>=14931?3:2:1}if("CI"in n)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI"].some((function(e){return e in n}))||"codeship"===n.CI_NAME?1:s;if("TEAMCITY_VERSION"in n)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(n.TEAMCITY_VERSION)?1:0;if("TERM_PROGRAM"in n){var a=parseInt((n.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(n.TERM_PROGRAM){case"iTerm.app":return a>=3?3:2;case"Hyper":return 3;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(n.TERM)?2:/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(n.TERM)||"COLORTERM"in n?1:(n.TERM,s)}(i);return function(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}(s)}return t("no-color")||t("no-colors")||t("color=false")?r=!1:(t("color")||t("colors")||t("color=true")||t("color=always"))&&(r=!0),"FORCE_COLOR"in n&&(r=0===n.FORCE_COLOR.length||0!==parseInt(n.FORCE_COLOR,10)),Fl={supportsColor:i,stdout:i(process.stdout),stderr:i(process.stderr)}}var Jl,Kl={exports:{}};var Zl,Xl={exports:{}};var Ql,eu={exports:{}};var tu,nu={exports:{}};var ru,iu={exports:{}};var su,ou,au,cu={exports:{}};function lu(){return ou||(ou=1,function(e){var t={};e.exports=t,t.themes={};var n=c,r=t.styles=Vl(),i=Object.defineProperties,s=new RegExp(/[\r\n]+/g);t.supportsColor=ql().supportsColor,void 0===t.enabled&&(t.enabled=!1!==t.supportsColor()),t.enable=function(){t.enabled=!0},t.disable=function(){t.enabled=!1},t.stripColors=t.strip=function(e){return(""+e).replace(/\x1B\[\d+m/g,"")},t.stylize=function(e,n){if(!t.enabled)return e+"";var i=r[n];return!i&&n in t?t[n](e):i.open+e+i.close};var o=/[|\\{}()[\]^$+*?.]/g;function a(e){var t=function e(){return h.apply(e,arguments)};return t._styles=e,t.__proto__=d,t}var l,u=(l={},r.grey=r.gray,Object.keys(r).forEach((function(e){r[e].closeRe=new RegExp(function(e){if("string"!=typeof e)throw new TypeError("Expected a string");return e.replace(o,"\\$&")}(r[e].close),"g"),l[e]={get:function(){return a(this._styles.concat(e))}}})),l),d=i((function(){}),u);function h(){var e=Array.prototype.slice.call(arguments).map((function(e){return null!=e&&e.constructor===String?e:n.inspect(e)})).join(" ");if(!t.enabled||!e)return e;for(var i=-1!=e.indexOf("\n"),o=this._styles,a=o.length;a--;){var c=r[o[a]];e=c.open+e.replace(c.closeRe,c.open)+c.close,i&&(e=e.replace(s,(function(e){return c.close+e+c.open})))}return e}t.setTheme=function(e){if("string"!=typeof e)for(var n in e)!function(n){t[n]=function(r){if("object"==typeof e[n]){var i=r;for(var s in e[n])i=t[e[n][s]](i);return i}return t[e[n]](r)}}(n);else console.log("colors.setTheme now only accepts an object, not a string. If you are trying to set a theme from a file, it is now your (the caller's) responsibility to require the file. The old syntax looked like colors.setTheme(__dirname + '/../themes/generic-logging.js'); The new syntax looks like colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));")};var f=function(e,t){var n=t.split("");return(n=n.map(e)).join("")};for(var p in t.trap=(Jl||(Jl=1,Kl.exports=function(e){var t="";e=(e=e||"Run the trap, drop the bass").split("");var n={a:["@","Ą","Ⱥ","Ʌ","Δ","Λ","Д"],b:["ß","Ɓ","Ƀ","ɮ","β","฿"],c:["©","Ȼ","Ͼ"],d:["Ð","Ɗ","Ԁ","ԁ","Ԃ","ԃ"],e:["Ë","ĕ","Ǝ","ɘ","Σ","ξ","Ҽ","੬"],f:["Ӻ"],g:["ɢ"],h:["Ħ","ƕ","Ң","Һ","Ӈ","Ԋ"],i:["༏"],j:["Ĵ"],k:["ĸ","Ҡ","Ӄ","Ԟ"],l:["Ĺ"],m:["ʍ","Ӎ","ӎ","Ԡ","ԡ","൩"],n:["Ñ","ŋ","Ɲ","Ͷ","Π","Ҋ"],o:["Ø","õ","ø","Ǿ","ʘ","Ѻ","ם","","๏"],p:["Ƿ","Ҏ"],q:["্"],r:["®","Ʀ","Ȑ","Ɍ","ʀ","Я"],s:["§","Ϟ","ϟ","Ϩ"],t:["Ł","Ŧ","ͳ"],u:["Ʊ","Ս"],v:["ט"],w:["Ш","Ѡ","Ѽ","൰"],x:["Ҳ","Ӿ","Ӽ","ӽ"],y:["¥","Ұ","Ӌ"],z:["Ƶ","ɀ"]};return e.forEach((function(e){e=e.toLowerCase();var r=n[e]||[" "],i=Math.floor(Math.random()*r.length);t+=void 0!==n[e]?n[e][i]:e})),t}),Kl.exports),t.zalgo=(Zl||(Zl=1,Xl.exports=function(e,t){e=e||" he is here ";var n={up:["̍","̎","̄","̅","̿","̑","̆","̐","͒","͗","͑","̇","̈","̊","͂","̓","̈","͊","͋","͌","̃","̂","̌","͐","̀","́","̋","̏","̒","̓","̔","̽","̉","ͣ","ͤ","ͥ","ͦ","ͧ","ͨ","ͩ","ͪ","ͫ","ͬ","ͭ","ͮ","ͯ","̾","͛","͆","̚"],down:["̖","̗","̘","̙","̜","̝","̞","̟","̠","̤","̥","̦","̩","̪","̫","̬","̭","̮","̯","̰","̱","̲","̳","̹","̺","̻","̼","ͅ","͇","͈","͉","͍","͎","͓","͔","͕","͖","͙","͚","̣"],mid:["̕","̛","̀","́","͘","̡","̢","̧","̨","̴","̵","̶","͜","͝","͞","͟","͠","͢","̸","̷","͡"," ҉"]},r=[].concat(n.up,n.down,n.mid);function i(e){return Math.floor(Math.random()*e)}function s(e){var t=!1;return r.filter((function(n){t=n===e})),t}return function(e,t){var r,o,a="";for(o in(t=t||{}).up=void 0===t.up||t.up,t.mid=void 0===t.mid||t.mid,t.down=void 0===t.down||t.down,t.size=void 0!==t.size?t.size:"maxi",e=e.split(""))if(!s(o)){switch(a+=e[o],r={up:0,down:0,mid:0},t.size){case"mini":r.up=i(8),r.mid=i(2),r.down=i(8);break;case"maxi":r.up=i(16)+3,r.mid=i(4)+1,r.down=i(64)+3;break;default:r.up=i(8)+1,r.mid=i(6)/2,r.down=i(8)+1}var c=["up","mid","down"];for(var l in c)for(var u=c[l],d=0;d<=r[u];d++)t[u]&&(a+=n[u][i(n[u].length)])}return a}(e,t)}),Xl.exports),t.maps={},t.maps.america=(Ql||(Ql=1,eu.exports=function(e){return function(t,n){if(" "===t)return t;switch(n%3){case 0:return e.red(t);case 1:return e.white(t);case 2:return e.blue(t)}}}),eu.exports)(t),t.maps.zebra=(tu||(tu=1,nu.exports=function(e){return function(t,n){return n%2==0?t:e.inverse(t)}}),nu.exports)(t),t.maps.rainbow=(ru||(ru=1,iu.exports=function(e){var t=["red","yellow","green","blue","magenta"];return function(n,r){return" "===n?n:e[t[r++%t.length]](n)}}),iu.exports)(t),t.maps.random=(su||(su=1,cu.exports=function(e){var t=["underline","inverse","grey","yellow","red","green","blue","white","cyan","magenta","brightYellow","brightRed","brightGreen","brightBlue","brightWhite","brightCyan","brightMagenta"];return function(n){return" "===n?n:e[t[Math.round(Math.random()*(t.length-2))]](n)}}),cu.exports)(t),t.maps)!function(e){t[e]=function(n){return f(t.maps[e],n)}}(p);i(t,function(){var e={};return Object.keys(u).forEach((function(t){e[t]={get:function(){return a([t])}}})),e}())}(Gl)),Gl.exports}function uu(){return au||(au=1,function(e){var t=lu();e.exports=t}(Yl)),Yl.exports}var du,hu,fu={},pu={},gu={levels:{error:0,warn:1,help:2,data:3,info:4,debug:5,prompt:6,verbose:7,input:8,silly:9},colors:{error:"red",warn:"yellow",help:"cyan",data:"grey",info:"green",debug:"blue",prompt:"grey",verbose:"cyan",input:"grey",silly:"magenta"}},mu={levels:{error:0,warn:1,info:2,http:3,verbose:4,debug:5,silly:6},colors:{error:"red",warn:"yellow",info:"green",http:"green",verbose:"cyan",debug:"blue",silly:"magenta"}},yu={};function vu(){if(hu)return Wl.exports;hu=1;const e=uu(),{LEVEL:t,MESSAGE:n}=fu;e.enabled=!0;const r=/\s+/;class i{constructor(e={}){e.colors&&this.addColors(e.colors),this.options=e}static addColors(e){const t=Object.keys(e).reduce(((t,n)=>(t[n]=r.test(e[n])?e[n].split(r):e[n],t)),{});return i.allColors=Object.assign({},i.allColors||{},t),i.allColors}addColors(e){return i.addColors(e)}colorize(t,n,r){if(void 0===r&&(r=n),!Array.isArray(i.allColors[t]))return e[i.allColors[t]](r);for(let n=0,s=i.allColors[t].length;n<s;n++)r=e[i.allColors[t][n]](r);return r}transform(e,r){return r.all&&"string"==typeof e[n]&&(e[n]=this.colorize(e[t],e.level,e[n])),(r.level||r.all||!r.message)&&(e.level=this.colorize(e[t],e.level)),(r.all||r.message)&&(e.message=this.colorize(e[t],e.level,e.message)),e}}return Wl.exports=e=>new i(e),Wl.exports.Colorizer=Wl.exports.Format=i,Wl.exports}yu.levels={emerg:0,alert:1,crit:2,error:3,warning:4,notice:5,info:6,debug:7},yu.colors={emerg:"red",alert:"yellow",crit:"red",error:"red",warning:"red",notice:"yellow",info:"green",debug:"blue"},du=pu,Object.defineProperty(du,"cli",{value:gu}),Object.defineProperty(du,"npm",{value:mu}),Object.defineProperty(du,"syslog",{value:yu}),function(e){Object.defineProperty(e,"LEVEL",{value:Symbol.for("level")}),Object.defineProperty(e,"MESSAGE",{value:Symbol.for("message")}),Object.defineProperty(e,"SPLAT",{value:Symbol.for("splat")}),Object.defineProperty(e,"configs",{value:pu})}(fu);const{Colorizer:bu}=vu();var wu,Su,_u,Iu;var xu,ku,Eu={exports:{}},Cu={exports:{}};function Ou(){if(xu)return Cu.exports;xu=1;const{configs:e,LEVEL:t,MESSAGE:n}=fu;class r{constructor(t={levels:e.npm.levels}){this.paddings=r.paddingForLevels(t.levels,t.filler),this.options=t}static getLongestLevel(e){const t=Object.keys(e).map((e=>e.length));return Math.max(...t)}static paddingForLevel(e,t,n){const r=n+1-e.length,i=Math.floor(r/t.length);return`${t}${t.repeat(i)}`.slice(0,r)}static paddingForLevels(e,t=" "){const n=r.getLongestLevel(e);return Object.keys(e).reduce(((e,i)=>(e[i]=r.paddingForLevel(i,t,n),e)),{})}transform(e,r){return e.message=`${this.paddings[e[t]]}${e.message}`,e[n]&&(e[n]=`${this.paddings[e[t]]}${e[n]}`),e}}return Cu.exports=e=>new r(e),Cu.exports.Padder=Cu.exports.Format=r,Cu.exports}var $u,Mu={exports:{}};var Nu,Tu,Au,Pu,Du,Lu,ju,Ru,Fu,Bu,Uu,Wu,Yu,Gu={exports:{}};function Hu(){return Nu||(Nu=1,function(e,t){const{hasOwnProperty:n}=Object.prototype,r=h();r.configure=h,r.stringify=r,r.default=r,t.stringify=r,t.configure=h,e.exports=r;const i=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function s(e){return e.length<5e3&&!i.test(e)?`"${e}"`:JSON.stringify(e)}function o(e,t){if(e.length>200||t)return e.sort(t);for(let t=1;t<e.length;t++){const n=e[t];let r=t;for(;0!==r&&e[r-1]>n;)e[r]=e[r-1],r--;e[r]=n}return e}const a=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function c(e){return void 0!==a.call(e)&&0!==e.length}function l(e,t,n){e.length<n&&(n=e.length);const r=","===t?"":" ";let i=`"0":${r}${e[0]}`;for(let s=1;s<n;s++)i+=`${t}"${s}":${r}${e[s]}`;return i}function u(e,t){let r;if(n.call(e,t)){if(r=e[t],"number"!=typeof r)throw new TypeError(`The "${t}" argument must be of type number`);if(!Number.isInteger(r))throw new TypeError(`The "${t}" argument must be an integer`);if(r<1)throw new RangeError(`The "${t}" argument must be >= 1`)}return void 0===r?1/0:r}function d(e){return 1===e?"1 item":`${e} items`}function h(e){const t=function(e){if(n.call(e,"strict")){const t=e.strict;if("boolean"!=typeof t)throw new TypeError('The "strict" argument must be of type boolean');if(t)return e=>{let t="Object can not safely be stringified. Received type "+typeof e;throw"function"!=typeof e&&(t+=` (${e.toString()})`),new Error(t)}}}(e={...e});t&&(void 0===e.bigint&&(e.bigint=!1),"circularValue"in e||(e.circularValue=Error));const r=function(e){if(n.call(e,"circularValue")){const t=e.circularValue;if("string"==typeof t)return`"${t}"`;if(null==t)return t;if(t===Error||t===TypeError)return{toString(){throw new TypeError("Converting circular structure to JSON")}};throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined')}return'"[Circular]"'}(e),i=function(e,t){let r;if(n.call(e,t)&&(r=e[t],"boolean"!=typeof r))throw new TypeError(`The "${t}" argument must be of type boolean`);return void 0===r||r}(e,"bigint"),a=function(e){let t;if(n.call(e,"deterministic")&&(t=e.deterministic,"boolean"!=typeof t&&"function"!=typeof t))throw new TypeError('The "deterministic" argument must be of type boolean or comparator function');return void 0===t||t}(e),h="function"==typeof a?a:void 0,f=u(e,"maximumDepth"),p=u(e,"maximumBreadth");function g(e,n,l,u,m,y){let v=n[e];switch("object"==typeof v&&null!==v&&"function"==typeof v.toJSON&&(v=v.toJSON(e)),v=u.call(n,e,v),typeof v){case"string":return s(v);case"object":{if(null===v)return"null";if(-1!==l.indexOf(v))return r;let e="",t=",";const n=y;if(Array.isArray(v)){if(0===v.length)return"[]";if(f<l.length+1)return'"[Array]"';l.push(v),""!==m&&(e+=`\n${y+=m}`,t=`,\n${y}`);const r=Math.min(v.length,p);let i=0;for(;i<r-1;i++){const n=g(String(i),v,l,u,m,y);e+=void 0!==n?n:"null",e+=t}const s=g(String(i),v,l,u,m,y);if(e+=void 0!==s?s:"null",v.length-1>p){e+=`${t}"... ${d(v.length-p-1)} not stringified"`}return""!==m&&(e+=`\n${n}`),l.pop(),`[${e}]`}let i=Object.keys(v);const b=i.length;if(0===b)return"{}";if(f<l.length+1)return'"[Object]"';let w="",S="";""!==m&&(t=`,\n${y+=m}`,w=" ");const _=Math.min(b,p);a&&!c(v)&&(i=o(i,h)),l.push(v);for(let n=0;n<_;n++){const r=i[n],o=g(r,v,l,u,m,y);void 0!==o&&(e+=`${S}${s(r)}:${w}${o}`,S=t)}if(b>p){e+=`${S}"...":${w}"${d(b-p)} not stringified"`,S=t}return""!==m&&S.length>1&&(e=`\n${y}${e}\n${n}`),l.pop(),`{${e}}`}case"number":return isFinite(v)?String(v):t?t(v):"null";case"boolean":return!0===v?"true":"false";case"undefined":return;case"bigint":if(i)return String(v);default:return t?t(v):void 0}}function m(e,n,o,a,c,l){switch("object"==typeof n&&null!==n&&"function"==typeof n.toJSON&&(n=n.toJSON(e)),typeof n){case"string":return s(n);case"object":{if(null===n)return"null";if(-1!==o.indexOf(n))return r;const e=l;let t="",i=",";if(Array.isArray(n)){if(0===n.length)return"[]";if(f<o.length+1)return'"[Array]"';o.push(n),""!==c&&(t+=`\n${l+=c}`,i=`,\n${l}`);const r=Math.min(n.length,p);let s=0;for(;s<r-1;s++){const e=m(String(s),n[s],o,a,c,l);t+=void 0!==e?e:"null",t+=i}const u=m(String(s),n[s],o,a,c,l);if(t+=void 0!==u?u:"null",n.length-1>p){t+=`${i}"... ${d(n.length-p-1)} not stringified"`}return""!==c&&(t+=`\n${e}`),o.pop(),`[${t}]`}o.push(n);let u="";""!==c&&(i=`,\n${l+=c}`,u=" ");let h="";for(const e of a){const r=m(e,n[e],o,a,c,l);void 0!==r&&(t+=`${h}${s(e)}:${u}${r}`,h=i)}return""!==c&&h.length>1&&(t=`\n${l}${t}\n${e}`),o.pop(),`{${t}}`}case"number":return isFinite(n)?String(n):t?t(n):"null";case"boolean":return!0===n?"true":"false";case"undefined":return;case"bigint":if(i)return String(n);default:return t?t(n):void 0}}function y(e,n,u,g,m){switch(typeof n){case"string":return s(n);case"object":{if(null===n)return"null";if("function"==typeof n.toJSON){if("object"!=typeof(n=n.toJSON(e)))return y(e,n,u,g,m);if(null===n)return"null"}if(-1!==u.indexOf(n))return r;const t=m;if(Array.isArray(n)){if(0===n.length)return"[]";if(f<u.length+1)return'"[Array]"';u.push(n);let e=`\n${m+=g}`;const r=`,\n${m}`,i=Math.min(n.length,p);let s=0;for(;s<i-1;s++){const t=y(String(s),n[s],u,g,m);e+=void 0!==t?t:"null",e+=r}const o=y(String(s),n[s],u,g,m);if(e+=void 0!==o?o:"null",n.length-1>p){e+=`${r}"... ${d(n.length-p-1)} not stringified"`}return e+=`\n${t}`,u.pop(),`[${e}]`}let i=Object.keys(n);const v=i.length;if(0===v)return"{}";if(f<u.length+1)return'"[Object]"';const b=`,\n${m+=g}`;let w="",S="",_=Math.min(v,p);c(n)&&(w+=l(n,b,p),i=i.slice(n.length),_-=n.length,S=b),a&&(i=o(i,h)),u.push(n);for(let e=0;e<_;e++){const t=i[e],r=y(t,n[t],u,g,m);void 0!==r&&(w+=`${S}${s(t)}: ${r}`,S=b)}if(v>p){w+=`${S}"...": "${d(v-p)} not stringified"`,S=b}return""!==S&&(w=`\n${m}${w}\n${t}`),u.pop(),`{${w}}`}case"number":return isFinite(n)?String(n):t?t(n):"null";case"boolean":return!0===n?"true":"false";case"undefined":return;case"bigint":if(i)return String(n);default:return t?t(n):void 0}}function v(e,n,u){switch(typeof n){case"string":return s(n);case"object":{if(null===n)return"null";if("function"==typeof n.toJSON){if("object"!=typeof(n=n.toJSON(e)))return v(e,n,u);if(null===n)return"null"}if(-1!==u.indexOf(n))return r;let t="";const i=void 0!==n.length;if(i&&Array.isArray(n)){if(0===n.length)return"[]";if(f<u.length+1)return'"[Array]"';u.push(n);const e=Math.min(n.length,p);let r=0;for(;r<e-1;r++){const e=v(String(r),n[r],u);t+=void 0!==e?e:"null",t+=","}const i=v(String(r),n[r],u);if(t+=void 0!==i?i:"null",n.length-1>p){t+=`,"... ${d(n.length-p-1)} not stringified"`}return u.pop(),`[${t}]`}let g=Object.keys(n);const m=g.length;if(0===m)return"{}";if(f<u.length+1)return'"[Object]"';let y="",b=Math.min(m,p);i&&c(n)&&(t+=l(n,",",p),g=g.slice(n.length),b-=n.length,y=","),a&&(g=o(g,h)),u.push(n);for(let e=0;e<b;e++){const r=g[e],i=v(r,n[r],u);void 0!==i&&(t+=`${y}${s(r)}:${i}`,y=",")}if(m>p){t+=`${y}"...":"${d(m-p)} not stringified"`}return u.pop(),`{${t}}`}case"number":return isFinite(n)?String(n):t?t(n):"null";case"boolean":return!0===n?"true":"false";case"undefined":return;case"bigint":if(i)return String(n);default:return t?t(n):void 0}}return function(e,t,n){if(arguments.length>1){let r="";if("number"==typeof n?r=" ".repeat(Math.min(n,10)):"string"==typeof n&&(r=n.slice(0,10)),null!=t){if("function"==typeof t)return g("",{"":e},[],t,r,"");if(Array.isArray(t))return m("",e,[],function(e){const t=new Set;for(const n of e)"string"!=typeof n&&"number"!=typeof n||t.add(String(n));return t}(t),r,"")}if(0!==r.length)return y("",e,[],r,"")}return v("",e,[])}}}(Gu,Gu.exports)),Gu.exports}function Vu(){if(Au)return Tu;Au=1;const e=Ul,{MESSAGE:t}=fu,n=Hu();function r(e,t){return"bigint"==typeof t?t.toString():t}return Tu=e(((e,i)=>{const s=n.configure(i);return e[t]=s(e,i.replacer||r,i.space),e}))}function zu(){if(Fu)return Ru;Fu=1;return Ru=Ul(((e,t={})=>{let n="metadata";t.key&&(n=t.key);let r=[];return t.fillExcept||t.fillWith||(r.push("level"),r.push("message")),t.fillExcept&&(r=t.fillExcept),r.length>0?function(e,t,n){const r=t.reduce(((t,n)=>(t[n]=e[n],delete e[n],t)),{}),i=Object.keys(e).reduce(((t,n)=>(t[n]=e[n],delete e[n],t)),{});return Object.assign(e,r,{[n]:i}),e}(e,r,n):t.fillWith?function(e,t,n){return e[n]=t.reduce(((t,n)=>(t[n]=e[n],delete e[n],t)),{}),e}(e,t.fillWith,n):e}))}var qu,Ju,Ku,Zu,Xu,Qu={exports:{}};var ed=/d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|Z|([HhMsDm])\1?|[aA]|"[^"]*"|'[^']*'/g,td="\\d\\d?",nd="\\d\\d",rd="[^\\s]+",id=/\[([^]*?)\]/gm;function sd(e,t){for(var n=[],r=0,i=e.length;r<i;r++)n.push(e[r].substr(0,t));return n}var od=function(e){return function(t,n){var r=n[e].map((function(e){return e.toLowerCase()})),i=r.indexOf(t.toLowerCase());return i>-1?i:null}};function ad(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];for(var r=0,i=t;r<i.length;r++){var s=i[r];for(var o in s)e[o]=s[o]}return e}var cd=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],ld=["January","February","March","April","May","June","July","August","September","October","November","December"],ud=sd(ld,3),dd={dayNamesShort:sd(cd,3),dayNames:cd,monthNamesShort:ud,monthNames:ld,amPm:["am","pm"],DoFn:function(e){return e+["th","st","nd","rd"][e%10>3?0:(e-e%10!=10?1:0)*e%10]}},hd=ad({},dd),fd=function(e){return hd=ad(hd,e)},pd=function(e){return e.replace(/[|\\{()[^$+*?.-]/g,"\\$&")},gd=function(e,t){for(void 0===t&&(t=2),e=String(e);e.length<t;)e="0"+e;return e},md={D:function(e){return String(e.getDate())},DD:function(e){return gd(e.getDate())},Do:function(e,t){return t.DoFn(e.getDate())},d:function(e){return String(e.getDay())},dd:function(e){return gd(e.getDay())},ddd:function(e,t){return t.dayNamesShort[e.getDay()]},dddd:function(e,t){return t.dayNames[e.getDay()]},M:function(e){return String(e.getMonth()+1)},MM:function(e){return gd(e.getMonth()+1)},MMM:function(e,t){return t.monthNamesShort[e.getMonth()]},MMMM:function(e,t){return t.monthNames[e.getMonth()]},YY:function(e){return gd(String(e.getFullYear()),4).substr(2)},YYYY:function(e){return gd(e.getFullYear(),4)},h:function(e){return String(e.getHours()%12||12)},hh:function(e){return gd(e.getHours()%12||12)},H:function(e){return String(e.getHours())},HH:function(e){return gd(e.getHours())},m:function(e){return String(e.getMinutes())},mm:function(e){return gd(e.getMinutes())},s:function(e){return String(e.getSeconds())},ss:function(e){return gd(e.getSeconds())},S:function(e){return String(Math.round(e.getMilliseconds()/100))},SS:function(e){return gd(Math.round(e.getMilliseconds()/10),2)},SSS:function(e){return gd(e.getMilliseconds(),3)},a:function(e,t){return e.getHours()<12?t.amPm[0]:t.amPm[1]},A:function(e,t){return e.getHours()<12?t.amPm[0].toUpperCase():t.amPm[1].toUpperCase()},ZZ:function(e){var t=e.getTimezoneOffset();return(t>0?"-":"+")+gd(100*Math.floor(Math.abs(t)/60)+Math.abs(t)%60,4)},Z:function(e){var t=e.getTimezoneOffset();return(t>0?"-":"+")+gd(Math.floor(Math.abs(t)/60),2)+":"+gd(Math.abs(t)%60,2)}},yd=function(e){return+e-1},vd=[null,td],bd=[null,rd],wd=["isPm",rd,function(e,t){var n=e.toLowerCase();return n===t.amPm[0]?0:n===t.amPm[1]?1:null}],Sd=["timezoneOffset","[^\\s]*?[\\+\\-]\\d\\d:?\\d\\d|[^\\s]*?Z?",function(e){var t=(e+"").match(/([+-]|\d\d)/gi);if(t){var n=60*+t[1]+parseInt(t[2],10);return"+"===t[0]?n:-n}return 0}],_d={D:["day",td],DD:["day",nd],Do:["day",td+rd,function(e){return parseInt(e,10)}],M:["month",td,yd],MM:["month",nd,yd],YY:["year",nd,function(e){var t=+(""+(new Date).getFullYear()).substr(0,2);return+(""+(+e>68?t-1:t)+e)}],h:["hour",td,void 0,"isPm"],hh:["hour",nd,void 0,"isPm"],H:["hour",td],HH:["hour",nd],m:["minute",td],mm:["minute",nd],s:["second",td],ss:["second",nd],YYYY:["year","\\d{4}"],S:["millisecond","\\d",function(e){return 100*+e}],SS:["millisecond",nd,function(e){return 10*+e}],SSS:["millisecond","\\d{3}"],d:vd,dd:vd,ddd:bd,dddd:bd,MMM:["month",rd,od("monthNamesShort")],MMMM:["month",rd,od("monthNames")],a:wd,A:wd,ZZ:Sd,Z:Sd},Id={default:"ddd MMM DD YYYY HH:mm:ss",shortDate:"M/D/YY",mediumDate:"MMM D, YYYY",longDate:"MMMM D, YYYY",fullDate:"dddd, MMMM D, YYYY",isoDate:"YYYY-MM-DD",isoDateTime:"YYYY-MM-DDTHH:mm:ssZ",shortTime:"HH:mm",mediumTime:"HH:mm:ss",longTime:"HH:mm:ss.SSS"},xd=function(e){return ad(Id,e)},kd=function(e,t,n){if(void 0===t&&(t=Id.default),void 0===n&&(n={}),"number"==typeof e&&(e=new Date(e)),"[object Date]"!==Object.prototype.toString.call(e)||isNaN(e.getTime()))throw new Error("Invalid Date pass to format");var r=[];t=(t=Id[t]||t).replace(id,(function(e,t){return r.push(t),"@@@"}));var i=ad(ad({},hd),n);return(t=t.replace(ed,(function(t){return md[t](e,i)}))).replace(/@@@/g,(function(){return r.shift()}))};function Ed(e,t,n){if(void 0===n&&(n={}),"string"!=typeof t)throw new Error("Invalid format in fecha parse");if(t=Id[t]||t,e.length>1e3)return null;var r={year:(new Date).getFullYear(),month:0,day:1,hour:0,minute:0,second:0,millisecond:0,isPm:null,timezoneOffset:null},i=[],s=[],o=t.replace(id,(function(e,t){return s.push(pd(t)),"@@@"})),a={},c={};o=pd(o).replace(ed,(function(e){var t=_d[e],n=t[0],r=t[1],s=t[3];if(a[n])throw new Error("Invalid format. "+n+" specified twice in format");return a[n]=!0,s&&(c[s]=!0),i.push(t),"("+r+")"})),Object.keys(c).forEach((function(e){if(!a[e])throw new Error("Invalid format. "+e+" is required in specified format")})),o=o.replace(/@@@/g,(function(){return s.shift()}));var l=e.match(new RegExp(o,"i"));if(!l)return null;for(var u,d=ad(ad({},hd),n),h=1;h<l.length;h++){var f=i[h-1],p=f[0],g=f[2],m=g?g(l[h],d):+l[h];if(null==m)return null;r[p]=m}if(1===r.isPm&&null!=r.hour&&12!=+r.hour?r.hour=+r.hour+12:0===r.isPm&&12==+r.hour&&(r.hour=0),null==r.timezoneOffset){u=new Date(r.year,r.month,r.day,r.hour,r.minute,r.second,r.millisecond);for(var y=[["month","getMonth"],["day","getDate"],["hour","getHours"],["minute","getMinutes"],["second","getSeconds"]],v=(h=0,y.length);h<v;h++)if(a[y[h][0]]&&r[y[h][0]]!==u[y[h][1]]())return null}else if(u=new Date(Date.UTC(r.year,r.month,r.day,r.hour,r.minute-r.timezoneOffset,r.second,r.millisecond)),r.month>11||r.month<0||r.day>31||r.day<1||r.hour>23||r.hour<0||r.minute>59||r.minute<0||r.second>59||r.second<0)return null;return u}var Cd,Od,$d,Md,Nd={format:kd,parse:Ed,defaultI18n:dd,setGlobalDateI18n:fd,setGlobalDateMasks:xd},Td=pl(Object.freeze({__proto__:null,assign:ad,default:Nd,defaultI18n:dd,format:kd,parse:Ed,setGlobalDateI18n:fd,setGlobalDateMasks:xd}));const Ad=Pl.format=Ul;function Pd(e,t){Object.defineProperty(Ad,e,{get:()=>t(),configurable:!0})}Pl.levels=e=>(bu.addColors(e.colors||e),e),Pd("align",(function(){return Su?wu:(Su=1,wu=Ul((e=>(e.message=`\t${e.message}`,e))))})),Pd("errors",(function(){return function(){if(Iu)return _u;Iu=1;const e=Ul,{LEVEL:t,MESSAGE:n}=fu;return _u=e(((e,{stack:r,cause:i})=>{if(e instanceof Error){const s=Object.assign({},e,{level:e.level,[t]:e[t]||e.level,message:e.message,[n]:e[n]||e.message});return r&&(s.stack=e.stack),i&&(s.cause=e.cause),s}if(!(e.message instanceof Error))return e;const s=e.message;return Object.assign(e,s),e.message=s.message,e[n]=s.message,r&&(e.stack=s.stack),i&&(e.cause=s.cause),e}))}()})),Pd("cli",(function(){return function(){if(ku)return Eu.exports;ku=1;const{Colorizer:e}=vu(),{Padder:t}=Ou(),{configs:n,MESSAGE:r}=fu;class i{constructor(r={}){r.levels||(r.levels=n.cli.levels),this.colorizer=new e(r),this.padder=new t(r),this.options=r}transform(e,t){return this.colorizer.transform(this.padder.transform(e,t),t),e[r]=`${e.level}:${e.message}`,e}}return Eu.exports=e=>new i(e),Eu.exports.Format=i,Eu.exports}()})),Pd("combine",(function(){return function(){if($u)return Mu.exports;$u=1;const e=Ul;function t(e){if(e.every(n))return t=>{let n=t;for(let t=0;t<e.length;t++)if(n=e[t].transform(n,e[t].options),!n)return!1;return n}}function n(e){if("function"!=typeof e.transform)throw new Error(["No transform function found on format. Did you create a format instance?","const myFormat = format(formatFn);","const instance = myFormat();"].join("\n"));return!0}return Mu.exports=(...n)=>{const r=e(t(n)),i=r();return i.Format=r.Format,i},Mu.exports.cascade=t,Mu.exports}()})),Pd("colorize",(function(){return vu()})),Pd("json",(function(){return Vu()})),Pd("label",(function(){return Du?Pu:(Du=1,Pu=Ul(((e,t)=>t.message?(e.message=`[${t.label}] ${e.message}`,e):(e.label=t.label,e))))})),Pd("logstash",(function(){return function(){if(ju)return Lu;ju=1;const e=Ul,{MESSAGE:t}=fu,n=Hu();return Lu=e((e=>{const r={};return e.message&&(r["@message"]=e.message,delete e.message),e.timestamp&&(r["@timestamp"]=e.timestamp,delete e.timestamp),r["@fields"]=e,e[t]=n(r),e}))}()})),Pd("metadata",(function(){return zu()})),Pd("ms",(function(){return function(){if(Uu)return Bu;Uu=1;const e=Ul,t=_l();return Bu=e((e=>{const n=+new Date;return this.diff=n-(this.prevTime||n),this.prevTime=n,e.ms=`+${t(this.diff)}`,e}))}()})),Pd("padLevels",(function(){return Ou()})),Pd("prettyPrint",(function(){return function(){if(Yu)return Wu;Yu=1;const e=c.inspect,t=Ul,{LEVEL:n,MESSAGE:r,SPLAT:i}=fu;return Wu=t(((t,s={})=>{const o=Object.assign({},t);return delete o[n],delete o[r],delete o[i],t[r]=e(o,!1,s.depth||null,s.colorize),t}))}()})),Pd("printf",(function(){return function(){if(qu)return Qu.exports;qu=1;const{MESSAGE:e}=fu;class t{constructor(e){this.template=e}transform(t){return t[e]=this.template(t),t}}return Qu.exports=e=>new t(e),Qu.exports.Printf=Qu.exports.Format=t,Qu.exports}()})),Pd("simple",(function(){return function(){if(Ku)return Ju;Ku=1;const e=Ul,{MESSAGE:t}=fu,n=Hu();return Ju=e((e=>{const r=n(Object.assign({},e,{level:void 0,message:void 0,splat:void 0})),i=e.padding&&e.padding[e.level]||"";return e[t]="{}"!==r?`${e.level}:${i} ${e.message} ${r}`:`${e.level}:${i} ${e.message}`,e}))}()})),Pd("splat",(function(){return function(){if(Xu)return Zu;Xu=1;const e=c,{SPLAT:t}=fu,n=/%[scdjifoO%]/g,r=/%%/g;class i{constructor(e){this.options=e}_splat(n,i){const s=n.message,o=n[t]||n.splat||[],a=s.match(r),c=a&&a.length||0,l=i.length-c-o.length,u=l<0?o.splice(l,-1*l):[],d=u.length;if(d)for(let e=0;e<d;e++)Object.assign(n,u[e]);return n.message=e.format(s,...o),n}transform(e){const r=e.message,i=e[t]||e.splat;if(!i||!i.length)return e;const s=r&&r.match&&r.match(n);if(!s&&(i||i.length)){const t=i.length>1?i.splice(0):i,n=t.length;if(n)for(let r=0;r<n;r++)Object.assign(e,t[r]);return e}return s?this._splat(e,s):e}}return Zu=e=>new i(e)}()})),Pd("timestamp",(function(){return function(){if(Od)return Cd;Od=1;const e=Td;return Cd=Ul(((t,n={})=>(n.format&&(t.timestamp="function"==typeof n.format?n.format():e.format(new Date,n.format)),t.timestamp||(t.timestamp=(new Date).toISOString()),n.alias&&(t[n.alias]=t.timestamp),t)))}()})),Pd("uncolorize",(function(){return function(){if(Md)return $d;Md=1;const e=uu(),t=Ul,{MESSAGE:n}=fu;return $d=t(((t,r)=>(!1!==r.level&&(t.level=e.strip(t.level)),!1!==r.message&&(t.message=e.strip(String(t.message))),!1!==r.raw&&t[n]&&(t[n]=e.strip(String(t[n]))),t)))}()}));var Dd={};!function(e){const{format:t}=c;e.warn={deprecated:e=>()=>{throw new Error(t("{ %s } was removed in winston@3.0.0.",e))},useFormat:e=>()=>{throw new Error([t("{ %s } was removed in winston@3.0.0.",e),"Use a custom winston.format = winston.format(function) instead."].join("\n"))},forFunctions(t,n,r){r.forEach((r=>{t[r]=e.warn[n](r)}))},forProperties(t,n,r){r.forEach((r=>{const i=e.warn[n](r);Object.defineProperty(t,r,{get:i,set:i})}))}}}(Dd);var Ld,jd,Rd,Fd,Bd,Ud,Wd="3.17.0",Yd={},Gd={exports:{}},Hd={exports:{}};function Vd(){return Fd?Rd:(Fd=1,Rd=N)}function zd(){if(Ud)return Bd;function e(e,r){n(e,r),t(e)}function t(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function n(e,t){e.emit("error",t)}return Ud=1,Bd={destroy:function(r,i){var s=this,o=this._readableState&&this._readableState.destroyed,a=this._writableState&&this._writableState.destroyed;return o||a?(i?i(r):r&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(n,this,r)):process.nextTick(n,this,r)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(r||null,(function(n){!i&&n?s._writableState?s._writableState.errorEmitted?process.nextTick(t,s):(s._writableState.errorEmitted=!0,process.nextTick(e,s,n)):process.nextTick(e,s,n):i?(process.nextTick(t,s),i(n)):process.nextTick(t,s)})),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit("error",t)}},Bd}var qd,Jd,Kd,Zd={};function Xd(){if(qd)return Zd;qd=1;const e={};function t(t,n,r){r||(r=Error);class i extends r{constructor(e,t,r){super(function(e,t,r){return"string"==typeof n?n:n(e,t,r)}(e,t,r))}}i.prototype.name=r.name,i.prototype.code=t,e[t]=i}function n(e,t){if(Array.isArray(e)){const n=e.length;return e=e.map((e=>String(e))),n>2?`one of ${t} ${e.slice(0,n-1).join(", ")}, or `+e[n-1]:2===n?`one of ${t} ${e[0]} or ${e[1]}`:`of ${t} ${e[0]}`}return`of ${t} ${String(e)}`}return t("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError),t("ERR_INVALID_ARG_TYPE",(function(e,t,r){let i;var s;let o;if("string"==typeof t&&(s="not ",t.substr(0,s.length)===s)?(i="must not be",t=t.replace(/^not /,"")):i="must be",function(e,t,n){return(void 0===n||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}(e," argument"))o=`The ${e} ${i} ${n(t,"type")}`;else{const r=function(e,t,n){return"number"!=typeof n&&(n=0),!(n+t.length>e.length)&&-1!==e.indexOf(t,n)}(e,".")?"property":"argument";o=`The "${e}" ${r} ${i} ${n(t,"type")}`}return o+=". Received type "+typeof r,o}),TypeError),t("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),t("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"})),t("ERR_STREAM_PREMATURE_CLOSE","Premature close"),t("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"})),t("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),t("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),t("ERR_STREAM_WRITE_AFTER_END","write after end"),t("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),t("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError),t("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),Zd.codes=e,Zd}function Qd(){if(Kd)return Jd;Kd=1;var e=Xd().codes.ERR_INVALID_OPT_VALUE;return Jd={getHighWaterMark:function(t,n,r,i){var s=function(e,t,n){return null!=e.highWaterMark?e.highWaterMark:t?e[n]:null}(n,i,r);if(null!=s){if(!isFinite(s)||Math.floor(s)!==s||s<0)throw new e(i?r:"highWaterMark",s);return Math.floor(s)}return t.objectMode?16:16384}}}var eh,th,nh,rh,ih={exports:{}},sh={exports:{}};function oh(){if(th)return ih.exports;th=1;try{var e=require("util");if("function"!=typeof e.inherits)throw"";ih.exports=e.inherits}catch(e){ih.exports=(eh||(eh=1,"function"==typeof Object.create?sh.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:sh.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}),sh.exports)}return ih.exports}function ah(){if(rh)return nh;function e(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function t(t){for(var r=1;r<arguments.length;r++){var i=null!=arguments[r]?arguments[r]:{};r%2?e(Object(i),!0).forEach((function(e){n(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):e(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}function n(e,t,n){return(t=i(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function r(e,t){return t&&function(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,i(r.key),r)}}(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function i(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}rh=1;var s=T.Buffer,o=c.inspect,a=o&&o.custom||"inspect";function l(e,t,n){s.prototype.copy.call(e,t,n)}return nh=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.head=null,this.tail=null,this.length=0}return r(e,[{key:"push",value:function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:"unshift",value:function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}},{key:"shift",value:function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n}},{key:"concat",value:function(e){if(0===this.length)return s.alloc(0);for(var t=s.allocUnsafe(e>>>0),n=this.head,r=0;n;)l(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:"consume",value:function(e,t){var n;return e<this.head.data.length?(n=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):n=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),n}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(e){var t=this.head,n=1,r=t.data;for(e-=r.length;t=t.next;){var i=t.data,s=e>i.length?i.length:e;if(s===i.length?r+=i:r+=i.slice(0,e),0===(e-=s)){s===i.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=i.slice(s));break}++n}return this.length-=n,r}},{key:"_getBuffer",value:function(e){var t=s.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var i=n.data,o=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,o),0===(e-=o)){o===i.length?(++r,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=i.slice(o));break}++r}return this.length-=r,t}},{key:a,value:function(e,n){return o(this,t(t({},n),{},{depth:0,customInspect:!1}))}}]),e}()}var ch,lh,uh,dh,hh,fh,ph,gh,mh,yh,vh,bh,wh,Sh,_h={},Ih={exports:{}};function xh(){if(lh)return _h;lh=1;var e=(ch||(ch=1,function(e,t){var n=T,r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}function s(e,t,n){return r(e,t,n)}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=n:(i(n,t),t.Buffer=s),s.prototype=Object.create(r.prototype),i(r,s),s.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return r(e,t,n)},s.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var i=r(e);return void 0!==t?"string"==typeof n?i.fill(t,n):i.fill(t):i.fill(0),i},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r(e)},s.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}}(Ih,Ih.exports)),Ih.exports).Buffer,t=e.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function n(n){var r;switch(this.encoding=function(n){var r=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(n);if("string"!=typeof r&&(e.isEncoding===t||!t(n)))throw new Error("Unknown encoding: "+n);return r||n}(n),this.encoding){case"utf16le":this.text=s,this.end=o,r=4;break;case"utf8":this.fillLast=i,r=4;break;case"base64":this.text=a,this.end=c,r=3;break;default:return this.write=l,void(this.end=u)}this.lastNeed=0,this.lastTotal=0,this.lastChar=e.allocUnsafe(r)}function r(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function i(e){var t=this.lastTotal-this.lastNeed,n=function(e,t){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0!==n?n:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function s(e,t){if((e.length-t)%2==0){var n=e.toString("utf16le",t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function o(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function a(e,t){var n=(e.length-t)%3;return 0===n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function c(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function l(e){return e.toString(this.encoding)}function u(e){return e&&e.length?this.write(e):""}return _h.StringDecoder=n,n.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||""},n.prototype.end=function(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t},n.prototype.text=function(e,t){var n=function(e,t,n){var i=t.length-1;if(i<n)return 0;var s=r(t[i]);if(s>=0)return s>0&&(e.lastNeed=s-1),s;if(--i<n||-2===s)return 0;if(s=r(t[i]),s>=0)return s>0&&(e.lastNeed=s-2),s;if(--i<n||-2===s)return 0;if(s=r(t[i]),s>=0)return s>0&&(2===s?s=0:e.lastNeed=s-3),s;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var i=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,i),e.toString("utf8",t,i)},n.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length},_h}function kh(){if(dh)return uh;dh=1;var e=Xd().codes.ERR_STREAM_PREMATURE_CLOSE;function t(){}return uh=function n(r,i,s){if("function"==typeof i)return n(r,null,i);i||(i={}),s=function(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];e.apply(this,r)}}}(s||t);var o=i.readable||!1!==i.readable&&r.readable,a=i.writable||!1!==i.writable&&r.writable,c=function(){r.writable||u()},l=r._writableState&&r._writableState.finished,u=function(){a=!1,l=!0,o||s.call(r)},d=r._readableState&&r._readableState.endEmitted,h=function(){o=!1,d=!0,a||s.call(r)},f=function(e){s.call(r,e)},p=function(){var t;return o&&!d?(r._readableState&&r._readableState.ended||(t=new e),s.call(r,t)):a&&!l?(r._writableState&&r._writableState.ended||(t=new e),s.call(r,t)):void 0},g=function(){r.req.on("finish",u)};return!function(e){return e.setHeader&&"function"==typeof e.abort}(r)?a&&!r._writableState&&(r.on("end",c),r.on("close",c)):(r.on("complete",u),r.on("abort",p),r.req?g():r.on("request",g)),r.on("end",h),r.on("finish",u),!1!==i.error&&r.on("error",f),r.on("close",p),function(){r.removeListener("complete",u),r.removeListener("abort",p),r.removeListener("request",g),r.req&&r.req.removeListener("finish",u),r.removeListener("end",c),r.removeListener("close",c),r.removeListener("finish",u),r.removeListener("end",h),r.removeListener("error",f),r.removeListener("close",p)}},uh}function Eh(){if(fh)return hh;var e;function t(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}fh=1;var n=kh(),r=Symbol("lastResolve"),i=Symbol("lastReject"),s=Symbol("error"),o=Symbol("ended"),a=Symbol("lastPromise"),c=Symbol("handlePromise"),l=Symbol("stream");function u(e,t){return{value:e,done:t}}function d(e){var t=e[r];if(null!==t){var n=e[l].read();null!==n&&(e[a]=null,e[r]=null,e[i]=null,t(u(n,!1)))}}function h(e){process.nextTick(d,e)}var f=Object.getPrototypeOf((function(){})),p=Object.setPrototypeOf((e={get stream(){return this[l]},next:function(){var e=this,t=this[s];if(null!==t)return Promise.reject(t);if(this[o])return Promise.resolve(u(void 0,!0));if(this[l].destroyed)return new Promise((function(t,n){process.nextTick((function(){e[s]?n(e[s]):t(u(void 0,!0))}))}));var n,r=this[a];if(r)n=new Promise(function(e,t){return function(n,r){e.then((function(){t[o]?n(u(void 0,!0)):t[c](n,r)}),r)}}(r,this));else{var i=this[l].read();if(null!==i)return Promise.resolve(u(i,!1));n=new Promise(this[c])}return this[a]=n,n}},t(e,Symbol.asyncIterator,(function(){return this})),t(e,"return",(function(){var e=this;return new Promise((function(t,n){e[l].destroy(null,(function(e){e?n(e):t(u(void 0,!0))}))}))})),e),f);return hh=function(e){var d,f=Object.create(p,(t(d={},l,{value:e,writable:!0}),t(d,r,{value:null,writable:!0}),t(d,i,{value:null,writable:!0}),t(d,s,{value:null,writable:!0}),t(d,o,{value:e._readableState.endEmitted,writable:!0}),t(d,c,{value:function(e,t){var n=f[l].read();n?(f[a]=null,f[r]=null,f[i]=null,e(u(n,!1))):(f[r]=e,f[i]=t)},writable:!0}),d));return f[a]=null,n(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=f[i];return null!==t&&(f[a]=null,f[r]=null,f[i]=null,t(e)),void(f[s]=e)}var n=f[r];null!==n&&(f[a]=null,f[r]=null,f[i]=null,n(u(void 0,!0))),f[o]=!0})),e.on("readable",h.bind(null,f)),f},hh}function Ch(){if(gh)return ph;function e(e,t,n,r,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(r,i)}function t(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function n(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}gh=1;var r=Xd().codes.ERR_INVALID_ARG_TYPE;return ph=function(i,s,o){var a;if(s&&"function"==typeof s.next)a=s;else if(s&&s[Symbol.asyncIterator])a=s[Symbol.asyncIterator]();else{if(!s||!s[Symbol.iterator])throw new r("iterable",["Iterable"],s);a=s[Symbol.iterator]()}var c=new i(function(e){for(var r=1;r<arguments.length;r++){var i=null!=arguments[r]?arguments[r]:{};r%2?t(Object(i),!0).forEach((function(t){n(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):t(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({objectMode:!0},o)),l=!1;function u(){return d.apply(this,arguments)}function d(){var t;return t=function*(){try{var e=yield a.next(),t=e.value;e.done?c.push(null):c.push(yield t)?u():l=!1}catch(e){c.destroy(e)}},d=function(){var n=this,r=arguments;return new Promise((function(i,s){var o=t.apply(n,r);function a(t){e(o,i,s,a,c,"next",t)}function c(t){e(o,i,s,a,c,"throw",t)}a(void 0)}))},d.apply(this,arguments)}return c._read=function(){l||(l=!0,u())},c},ph}function Oh(){if(yh)return mh;var e;yh=1,mh=_,_.ReadableState=S,A.EventEmitter;var t=function(e,t){return e.listeners(t).length},n=Vd(),r=T.Buffer,i=(void 0!==hl?hl:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}).Uint8Array||function(){};var s,o=c;s=o&&o.debuglog?o.debuglog("stream"):function(){};var a,l,u,d=ah(),h=zd(),f=Qd().getHighWaterMark,p=Xd().codes,g=p.ERR_INVALID_ARG_TYPE,m=p.ERR_STREAM_PUSH_AFTER_EOF,y=p.ERR_METHOD_NOT_IMPLEMENTED,v=p.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;oh()(_,n);var b=h.errorOrDestroy,w=["error","close","destroy","pause","resume"];function S(t,n,r){e=e||$h(),t=t||{},"boolean"!=typeof r&&(r=n instanceof e),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=f(this,t,"readableHighWaterMark",r),this.buffer=new d,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(a||(a=xh().StringDecoder),this.decoder=new a(t.encoding),this.encoding=t.encoding)}function _(t){if(e=e||$h(),!(this instanceof _))return new _(t);var r=this instanceof e;this._readableState=new S(t,this,r),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),n.call(this)}function I(e,t,n,o,a){s("readableAddChunk",t);var c,l=e._readableState;if(null===t)l.reading=!1,function(e,t){if(s("onEofChunk"),t.ended)return;if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?C(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,O(e)))}(e,l);else if(a||(c=function(e,t){var n;s=t,r.isBuffer(s)||s instanceof i||"string"==typeof t||void 0===t||e.objectMode||(n=new g("chunk",["string","Buffer","Uint8Array"],t));var s;return n}(l,t)),c)b(e,c);else if(l.objectMode||t&&t.length>0)if("string"==typeof t||l.objectMode||Object.getPrototypeOf(t)===r.prototype||(t=function(e){return r.from(e)}(t)),o)l.endEmitted?b(e,new v):x(e,l,t,!0);else if(l.ended)b(e,new m);else{if(l.destroyed)return!1;l.reading=!1,l.decoder&&!n?(t=l.decoder.write(t),l.objectMode||0!==t.length?x(e,l,t,!1):$(e,l)):x(e,l,t,!1)}else o||(l.reading=!1,$(e,l));return!l.ended&&(l.length<l.highWaterMark||0===l.length)}function x(e,t,n,r){t.flowing&&0===t.length&&!t.sync?(t.awaitDrain=0,e.emit("data",n)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&C(e)),$(e,t)}Object.defineProperty(_.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),_.prototype.destroy=h.destroy,_.prototype._undestroy=h.undestroy,_.prototype._destroy=function(e,t){t(e)},_.prototype.push=function(e,t){var n,i=this._readableState;return i.objectMode?n=!0:"string"==typeof e&&((t=t||i.defaultEncoding)!==i.encoding&&(e=r.from(e,t),t=""),n=!0),I(this,e,t,!1,n)},_.prototype.unshift=function(e){return I(this,e,null,!0,!1)},_.prototype.isPaused=function(){return!1===this._readableState.flowing},_.prototype.setEncoding=function(e){a||(a=xh().StringDecoder);var t=new a(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;for(var n=this._readableState.buffer.head,r="";null!==n;)r+=t.write(n.data),n=n.next;return this._readableState.buffer.clear(),""!==r&&this._readableState.buffer.push(r),this._readableState.length=r.length,this};var k=1073741824;function E(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!=e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=function(e){return e>=k?e=k:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function C(e){var t=e._readableState;s("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(s("emitReadable",t.flowing),t.emittedReadable=!0,process.nextTick(O,e))}function O(e){var t=e._readableState;s("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,L(e)}function $(e,t){t.readingMore||(t.readingMore=!0,process.nextTick(M,e,t))}function M(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&0===t.length);){var n=t.length;if(s("maybeReadMore read 0"),e.read(0),n===t.length)break}t.readingMore=!1}function N(e){var t=e._readableState;t.readableListening=e.listenerCount("readable")>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function P(e){s("readable nexttick read 0"),e.read(0)}function D(e,t){s("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),L(e),t.flowing&&!t.reading&&e.read(0)}function L(e){var t=e._readableState;for(s("flow",t.flowing);t.flowing&&null!==e.read(););}function j(e,t){return 0===t.length?null:(t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n);var n}function R(e){var t=e._readableState;s("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,process.nextTick(F,t,e))}function F(e,t){if(s("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}function B(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}return _.prototype.read=function(e){s("read",e),e=parseInt(e,10);var t=this._readableState,n=e;if(0!==e&&(t.emittedReadable=!1),0===e&&t.needReadable&&((0!==t.highWaterMark?t.length>=t.highWaterMark:t.length>0)||t.ended))return s("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?R(this):C(this),null;if(0===(e=E(e,t))&&t.ended)return 0===t.length&&R(this),null;var r,i=t.needReadable;return s("need readable",i),(0===t.length||t.length-e<t.highWaterMark)&&s("length less than watermark",i=!0),t.ended||t.reading?s("reading or ended",i=!1):i&&(s("do read"),t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=E(n,t))),null===(r=e>0?j(e,t):null)?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&R(this)),null!==r&&this.emit("data",r),r},_.prototype._read=function(){b(this,new y("_read()"))},_.prototype.pipe=function(e,n){var r=this,i=this._readableState;switch(i.pipesCount){case 0:i.pipes=e;break;case 1:i.pipes=[i.pipes,e];break;default:i.pipes.push(e)}i.pipesCount+=1,s("pipe count=%d opts=%j",i.pipesCount,n);var o=(!n||!1!==n.end)&&e!==process.stdout&&e!==process.stderr?c:g;function a(t,n){s("onunpipe"),t===r&&n&&!1===n.hasUnpiped&&(n.hasUnpiped=!0,s("cleanup"),e.removeListener("close",f),e.removeListener("finish",p),e.removeListener("drain",l),e.removeListener("error",h),e.removeListener("unpipe",a),r.removeListener("end",c),r.removeListener("end",g),r.removeListener("data",d),u=!0,!i.awaitDrain||e._writableState&&!e._writableState.needDrain||l())}function c(){s("onend"),e.end()}i.endEmitted?process.nextTick(o):r.once("end",o),e.on("unpipe",a);var l=function(e){return function(){var n=e._readableState;s("pipeOnDrain",n.awaitDrain),n.awaitDrain&&n.awaitDrain--,0===n.awaitDrain&&t(e,"data")&&(n.flowing=!0,L(e))}}(r);e.on("drain",l);var u=!1;function d(t){s("ondata");var n=e.write(t);s("dest.write",n),!1===n&&((1===i.pipesCount&&i.pipes===e||i.pipesCount>1&&-1!==B(i.pipes,e))&&!u&&(s("false write response, pause",i.awaitDrain),i.awaitDrain++),r.pause())}function h(n){s("onerror",n),g(),e.removeListener("error",h),0===t(e,"error")&&b(e,n)}function f(){e.removeListener("finish",p),g()}function p(){s("onfinish"),e.removeListener("close",f),g()}function g(){s("unpipe"),r.unpipe(e)}return r.on("data",d),function(e,t,n){if("function"==typeof e.prependListener)return e.prependListener(t,n);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}(e,"error",h),e.once("close",f),e.once("finish",p),e.emit("pipe",r),i.flowing||(s("pipe resume"),r.resume()),e},_.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n)),this;if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var s=0;s<i;s++)r[s].emit("unpipe",this,{hasUnpiped:!1});return this}var o=B(t.pipes,e);return-1===o||(t.pipes.splice(o,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,n)),this},_.prototype.on=function(e,t){var r=n.prototype.on.call(this,e,t),i=this._readableState;return"data"===e?(i.readableListening=this.listenerCount("readable")>0,!1!==i.flowing&&this.resume()):"readable"===e&&(i.endEmitted||i.readableListening||(i.readableListening=i.needReadable=!0,i.flowing=!1,i.emittedReadable=!1,s("on readable",i.length,i.reading),i.length?C(this):i.reading||process.nextTick(P,this))),r},_.prototype.addListener=_.prototype.on,_.prototype.removeListener=function(e,t){var r=n.prototype.removeListener.call(this,e,t);return"readable"===e&&process.nextTick(N,this),r},_.prototype.removeAllListeners=function(e){var t=n.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||process.nextTick(N,this),t},_.prototype.resume=function(){var e=this._readableState;return e.flowing||(s("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,process.nextTick(D,e,t))}(this,e)),e.paused=!1,this},_.prototype.pause=function(){return s("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(s("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},_.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var i in e.on("end",(function(){if(s("wrapped end"),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(i){(s("wrapped data"),n.decoder&&(i=n.decoder.write(i)),n.objectMode&&null==i)||(n.objectMode||i&&i.length)&&(t.push(i)||(r=!0,e.pause()))})),e)void 0===this[i]&&"function"==typeof e[i]&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var o=0;o<w.length;o++)e.on(w[o],this.emit.bind(this,w[o]));return this._read=function(t){s("wrapped _read",t),r&&(r=!1,e.resume())},this},"function"==typeof Symbol&&(_.prototype[Symbol.asyncIterator]=function(){return void 0===l&&(l=Eh()),l(this)}),Object.defineProperty(_.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(_.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(_.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),_._fromList=j,Object.defineProperty(_.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(_.from=function(e,t){return void 0===u&&(u=Ch()),u(_,e,t)}),mh}function $h(){if(bh)return vh;bh=1;var e=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};vh=o;var t=Oh(),n=Mh();oh()(o,t);for(var r=e(n.prototype),i=0;i<r.length;i++){var s=r[i];o.prototype[s]||(o.prototype[s]=n.prototype[s])}function o(e){if(!(this instanceof o))return new o(e);t.call(this,e),n.call(this,e),this.allowHalfOpen=!0,e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",a)))}function a(){this._writableState.ended||process.nextTick(c,this)}function c(e){e.end()}return Object.defineProperty(o.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(o.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(o.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(o.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed&&this._writableState.destroyed)},set:function(e){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}}),vh}function Mh(){if(Sh)return wh;function e(e){var t=this;this.next=null,this.entry=null,this.finish=function(){!function(e,t,n){var r=e.entry;e.entry=null;for(;r;){var i=r.callback;t.pendingcb--,i(n),r=r.next}t.corkedRequestsFree.next=e}(t,e)}}var t;Sh=1,wh=_,_.WritableState=S;var n={deprecate:jd?Ld:(jd=1,Ld=c.deprecate)},r=Vd(),i=T.Buffer,s=(void 0!==hl?hl:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}).Uint8Array||function(){};var o,a=zd(),l=Qd().getHighWaterMark,u=Xd().codes,d=u.ERR_INVALID_ARG_TYPE,h=u.ERR_METHOD_NOT_IMPLEMENTED,f=u.ERR_MULTIPLE_CALLBACK,p=u.ERR_STREAM_CANNOT_PIPE,g=u.ERR_STREAM_DESTROYED,m=u.ERR_STREAM_NULL_VALUES,y=u.ERR_STREAM_WRITE_AFTER_END,v=u.ERR_UNKNOWN_ENCODING,b=a.errorOrDestroy;function w(){}function S(n,r,i){t=t||$h(),n=n||{},"boolean"!=typeof i&&(i=r instanceof t),this.objectMode=!!n.objectMode,i&&(this.objectMode=this.objectMode||!!n.writableObjectMode),this.highWaterMark=l(this,n,"writableHighWaterMark",i),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var s=!1===n.decodeStrings;this.decodeStrings=!s,this.defaultEncoding=n.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var n=e._writableState,r=n.sync,i=n.writecb;if("function"!=typeof i)throw new f;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(n),t)!function(e,t,n,r,i){--t.pendingcb,n?(process.nextTick(i,r),process.nextTick(O,e,t),e._writableState.errorEmitted=!0,b(e,r)):(i(r),e._writableState.errorEmitted=!0,b(e,r),O(e,t))}(e,n,r,t,i);else{var s=E(n)||e.destroyed;s||n.corked||n.bufferProcessing||!n.bufferedRequest||k(e,n),r?process.nextTick(x,e,n,s,i):x(e,n,s,i)}}(r,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==n.emitClose,this.autoDestroy=!!n.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new e(this)}function _(e){var n=this instanceof(t=t||$h());if(!n&&!o.call(_,this))return new _(e);this._writableState=new S(e,this,n),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final&&(this._final=e.final)),r.call(this)}function I(e,t,n,r,i,s,o){t.writelen=r,t.writecb=o,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new g("write")):n?e._writev(i,t.onwrite):e._write(i,s,t.onwrite),t.sync=!1}function x(e,t,n,r){n||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,r(),O(e,t)}function k(t,n){n.bufferProcessing=!0;var r=n.bufferedRequest;if(t._writev&&r&&r.next){var i=n.bufferedRequestCount,s=new Array(i),o=n.corkedRequestsFree;o.entry=r;for(var a=0,c=!0;r;)s[a]=r,r.isBuf||(c=!1),r=r.next,a+=1;s.allBuffers=c,I(t,n,!0,n.length,s,"",o.finish),n.pendingcb++,n.lastBufferedRequest=null,o.next?(n.corkedRequestsFree=o.next,o.next=null):n.corkedRequestsFree=new e(n),n.bufferedRequestCount=0}else{for(;r;){var l=r.chunk,u=r.encoding,d=r.callback;if(I(t,n,!1,n.objectMode?1:l.length,l,u,d),r=r.next,n.bufferedRequestCount--,n.writing)break}null===r&&(n.lastBufferedRequest=null)}n.bufferedRequest=r,n.bufferProcessing=!1}function E(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function C(e,t){e._final((function(n){t.pendingcb--,n&&b(e,n),t.prefinished=!0,e.emit("prefinish"),O(e,t)}))}function O(e,t){var n=E(t);if(n&&(function(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.pendingcb++,t.finalCalled=!0,process.nextTick(C,e,t)))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"),t.autoDestroy))){var r=e._readableState;(!r||r.autoDestroy&&r.endEmitted)&&e.destroy()}return n}return oh()(_,r),S.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(S.prototype,"buffer",{get:n.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(o=Function.prototype[Symbol.hasInstance],Object.defineProperty(_,Symbol.hasInstance,{value:function(e){return!!o.call(this,e)||this===_&&(e&&e._writableState instanceof S)}})):o=function(e){return e instanceof this},_.prototype.pipe=function(){b(this,new p)},_.prototype.write=function(e,t,n){var r,o=this._writableState,a=!1,c=!o.objectMode&&(r=e,i.isBuffer(r)||r instanceof s);return c&&!i.isBuffer(e)&&(e=function(e){return i.from(e)}(e)),"function"==typeof t&&(n=t,t=null),c?t="buffer":t||(t=o.defaultEncoding),"function"!=typeof n&&(n=w),o.ending?function(e,t){var n=new y;b(e,n),process.nextTick(t,n)}(this,n):(c||function(e,t,n,r){var i;return null===n?i=new m:"string"==typeof n||t.objectMode||(i=new d("chunk",["string","Buffer"],n)),!i||(b(e,i),process.nextTick(r,i),!1)}(this,o,e,n))&&(o.pendingcb++,a=function(e,t,n,r,s,o){if(!n){var a=function(e,t,n){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=i.from(t,n));return t}(t,r,s);r!==a&&(n=!0,s="buffer",r=a)}var c=t.objectMode?1:r.length;t.length+=c;var l=t.length<t.highWaterMark;l||(t.needDrain=!0);if(t.writing||t.corked){var u=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:s,isBuf:n,callback:o,next:null},u?u.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else I(e,t,!1,c,r,s,o);return l}(this,o,c,e,t,n)),a},_.prototype.cork=function(){this._writableState.corked++},_.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.bufferProcessing||!e.bufferedRequest||k(this,e))},_.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new v(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(_.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(_.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),_.prototype._write=function(e,t,n){n(new h("_write()"))},_.prototype._writev=null,_.prototype.end=function(e,t,n){var r=this._writableState;return"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||function(e,t,n){t.ending=!0,O(e,t),n&&(t.finished?process.nextTick(n):e.once("finish",n));t.ended=!0,e.writable=!1}(this,r,n),this},Object.defineProperty(_.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(_.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),_.prototype.destroy=a.destroy,_.prototype._undestroy=a.undestroy,_.prototype._destroy=function(e,t){t(e)},wh}const Nh=c,Th=Mh(),{LEVEL:Ah}=fu,Ph=Hd.exports=function(e={}){Th.call(this,{objectMode:!0,highWaterMark:e.highWaterMark}),this.format=e.format,this.level=e.level,this.handleExceptions=e.handleExceptions,this.handleRejections=e.handleRejections,this.silent=e.silent,e.log&&(this.log=e.log),e.logv&&(this.logv=e.logv),e.close&&(this.close=e.close),this.once("pipe",(e=>{this.levels=e.levels,this.parent=e})),this.once("unpipe",(e=>{e===this.parent&&(this.parent=null,this.close&&this.close())}))};Nh.inherits(Ph,Th),Ph.prototype._write=function(e,t,n){if(this.silent||!0===e.exception&&!this.handleExceptions)return n(null);const r=this.level||this.parent&&this.parent.level;if(!r||this.levels[r]>=this.levels[e[Ah]]){if(e&&!this.format)return this.log(e,n);let t,r;try{r=this.format.transform(Object.assign({},e),this.format.options)}catch(e){t=e}if(t||!r){if(n(),t)throw t;return}return this.log(r,n)}return this._writableState.sync=!1,n(null)},Ph.prototype._writev=function(e,t){if(this.logv){const n=e.filter(this._accept,this);return n.length?this.logv(n,t):t(null)}for(let n=0;n<e.length;n++){if(!this._accept(e[n]))continue;if(e[n].chunk&&!this.format){this.log(e[n].chunk,e[n].callback);continue}let r,i;try{i=this.format.transform(Object.assign({},e[n].chunk),this.format.options)}catch(e){r=e}if(r||!i){if(e[n].callback(),r)throw t(null),r}else this.log(i,e[n].callback)}return t(null)},Ph.prototype._accept=function(e){const t=e.chunk;if(this.silent)return!1;const n=this.level||this.parent&&this.parent.level;return!(!0!==t.exception&&n&&!(this.levels[n]>=this.levels[t[Ah]])||!this.handleExceptions&&!0===t.exception)},Ph.prototype._nop=function(){};var Dh=Hd.exports,Lh={exports:{}};const jh=c,{LEVEL:Rh}=fu,Fh=Dh,Bh=Lh.exports=function(e={}){if(Fh.call(this,e),!e.transport||"function"!=typeof e.transport.log)throw new Error("Invalid transport, must be an object with a log method.");this.transport=e.transport,this.level=this.level||e.transport.level,this.handleExceptions=this.handleExceptions||e.transport.handleExceptions,this._deprecated(),this.transport.__winstonError||(this.transport.__winstonError=function(e){this.emit("error",e,this.transport)}.bind(this),this.transport.on("error",this.transport.__winstonError))};jh.inherits(Bh,Fh),Bh.prototype._write=function(e,t,n){if(this.silent||!0===e.exception&&!this.handleExceptions)return n(null);(!this.level||this.levels[this.level]>=this.levels[e[Rh]])&&this.transport.log(e[Rh],e.message,e,this._nop),n(null)},Bh.prototype._writev=function(e,t){for(let t=0;t<e.length;t++)this._accept(e[t])&&(this.transport.log(e[t].chunk[Rh],e[t].chunk.message,e[t].chunk,this._nop),e[t].callback());return t(null)},Bh.prototype._deprecated=function(){console.error([`${this.transport.name} is a legacy winston transport. Consider upgrading: `,"- Upgrade docs: https://github.com/winstonjs/winston/blob/master/UPGRADE-3.0.md"].join("\n"))},Bh.prototype.close=function(){this.transport.close&&this.transport.close(),this.transport.__winstonError&&(this.transport.removeListener("error",this.transport.__winstonError),this.transport.__winstonError=null)};var Uh=Lh.exports;Gd.exports=Dh,Gd.exports.LegacyTransportStream=Uh;var Wh,Yh,Gh=Gd.exports;var Hh={exports:{}},Vh={exports:{}},zh={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return e&&"number"==typeof e.length&&e.length>=0&&e.length%1==0},e.exports=t.default}(zh,zh.exports);var qh=zh.exports,Jh={},Kh={exports:{}},Zh={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return function(...t){var n=t.pop();return e.call(this,t,n)}},e.exports=t.default}(Zh,Zh.exports);var Xh=Zh.exports,Qh={};Object.defineProperty(Qh,"__esModule",{value:!0}),Qh.fallback=af,Qh.wrap=cf;var ef,tf,nf,rf=Qh.hasQueueMicrotask="function"==typeof queueMicrotask&&queueMicrotask,sf=Qh.hasSetImmediate="function"==typeof setImmediate&&setImmediate,of=Qh.hasNextTick="object"==typeof process&&"function"==typeof process.nextTick;function af(e){setTimeout(e,0)}function cf(e){return(t,...n)=>e((()=>t(...n)))}function lf(){if(nf)return Jh;nf=1,Object.defineProperty(Jh,"__esModule",{value:!0}),Jh.isAsyncIterable=Jh.isAsyncGenerator=Jh.isAsync=void 0;var e,t=(tf||(tf=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return(0,i.isAsync)(e)?function(...t){const n=t.pop();return o(e.apply(this,t),n)}:(0,n.default)((function(t,n){var r;try{r=e.apply(this,t)}catch(e){return n(e)}if(r&&"function"==typeof r.then)return o(r,n);n(null,r)}))};var n=s(Xh),r=s(Qh),i=lf();function s(e){return e&&e.__esModule?e:{default:e}}function o(e,t){return e.then((e=>{a(t,null,e)}),(e=>{a(t,e&&(e instanceof Error||e.message)?e:new Error(e))}))}function a(e,t,n){try{e(t,n)}catch(e){(0,r.default)((e=>{throw e}),e)}}e.exports=t.default}(Kh,Kh.exports)),Kh.exports),n=(e=t)&&e.__esModule?e:{default:e};function r(e){return"AsyncFunction"===e[Symbol.toStringTag]}return Jh.default=function(e){if("function"!=typeof e)throw new Error("expected a function");return r(e)?(0,n.default)(e):e},Jh.isAsync=r,Jh.isAsyncGenerator=function(e){return"AsyncGenerator"===e[Symbol.toStringTag]},Jh.isAsyncIterable=function(e){return"function"==typeof e[Symbol.asyncIterator]},Jh}ef=rf?queueMicrotask:sf?setImmediate:of?process.nextTick:af,Qh.default=cf(ef);var uf={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){t||(t=e.length);if(!t)throw new Error("arity is undefined");return function(...n){return"function"==typeof n[t-1]?e.apply(this,n):new Promise(((r,i)=>{n[t-1]=(e,...t)=>{if(e)return i(e);r(t.length>1?t:t[0])},e.apply(this,n)}))}},e.exports=t.default}(uf,uf.exports);var df,hf=uf.exports;var ff={exports:{}},pf={exports:{}},gf={exports:{}},mf={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){function t(...t){if(null!==e){var n=e;e=null,n.apply(this,t)}}return Object.assign(t,e),t},e.exports=t.default}(mf,mf.exports);var yf=mf.exports,vf={exports:{}},bf={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return e[Symbol.iterator]&&e[Symbol.iterator]()},e.exports=t.default}(bf,bf.exports);var wf=bf.exports;!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){if((0,n.default)(e))return function(e){var t=-1,n=e.length;return function(){return++t<n?{value:e[t],key:t}:null}}(e);var t=(0,r.default)(e);return t?function(e){var t=-1;return function(){var n=e.next();return n.done?null:(t++,{value:n.value,key:t})}}(t):(i=e,s=i?Object.keys(i):[],o=-1,a=s.length,function e(){var t=s[++o];return"__proto__"===t?e():o<a?{value:i[t],key:t}:null});var i,s,o,a};var n=i(qh),r=i(wf);function i(e){return e&&e.__esModule?e:{default:e}}e.exports=t.default}(vf,vf.exports);var Sf=vf.exports,_f={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return function(...t){if(null===e)throw new Error("Callback was already called.");var n=e;e=null,n.apply(this,t)}},e.exports=t.default}(_f,_f.exports);var If=_f.exports,xf={exports:{}},kf={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0});t.default={},e.exports=t.default}(kf,kf.exports);var Ef=kf.exports;!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,n,i){let s=!1,o=!1,a=!1,c=0,l=0;function u(){c>=t||a||s||(a=!0,e.next().then((({value:e,done:t})=>{if(!o&&!s){if(a=!1,t)return s=!0,void(c<=0&&i(null));c++,n(e,l,d),l++,u()}})).catch(h))}function d(e,t){if(c-=1,!o)return e?h(e):!1===e?(s=!0,void(o=!0)):t===r.default||s&&c<=0?(s=!0,i(null)):void u()}function h(e){o||(a=!1,s=!0,i(e))}u()};var n,r=(n=Ef)&&n.__esModule?n:{default:n};e.exports=t.default}(xf,xf.exports);var Cf=xf.exports;!function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=c(yf),r=c(Sf),i=c(If),s=lf(),o=c(Cf),a=c(Ef);function c(e){return e&&e.__esModule?e:{default:e}}t.default=e=>(t,c,l)=>{if(l=(0,n.default)(l),e<=0)throw new RangeError("concurrency limit cannot be less than 1");if(!t)return l(null);if((0,s.isAsyncGenerator)(t))return(0,o.default)(t,e,c,l);if((0,s.isAsyncIterable)(t))return(0,o.default)(t[Symbol.asyncIterator](),e,c,l);var u=(0,r.default)(t),d=!1,h=!1,f=0,p=!1;function g(e,t){if(!h)if(f-=1,e)d=!0,l(e);else if(!1===e)d=!0,h=!0;else{if(t===a.default||d&&f<=0)return d=!0,l(null);p||m()}}function m(){for(p=!0;f<e&&!d;){var t=u();if(null===t)return d=!0,void(f<=0&&l(null));f+=1,c(t.value,t.key,(0,i.default)(g))}p=!1}m()},e.exports=t.default}(gf,gf.exports);var Of=gf.exports;!function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=s(Of),r=s(lf()),i=s(hf);function s(e){return e&&e.__esModule?e:{default:e}}t.default=(0,i.default)((function(e,t,i,s){return(0,n.default)(t)(e,(0,r.default)(i),s)}),4),e.exports=t.default}(pf,pf.exports);var $f,Mf,Nf=pf.exports;function Tf(){return Mf||(Mf=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){return(0,r.default)(s.default,e,t)};var n=(df||(df=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=s(qh),r=s(lf()),i=s(hf);function s(e){return e&&e.__esModule?e:{default:e}}t.default=(0,i.default)(((e,t,i)=>{var s=(0,n.default)(t)?[]:{};e(t,((e,t,n)=>{(0,r.default)(e)(((e,...r)=>{r.length<2&&([r]=r),s[t]=r,n(e)}))}),(e=>i(e,s)))}),3),e.exports=t.default}(Vh,Vh.exports)),Vh.exports),r=o(n),i=($f||($f=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=i(Nf),r=i(hf);function i(e){return e&&e.__esModule?e:{default:e}}t.default=(0,r.default)((function(e,t,r){return(0,n.default)(e,1,t,r)}),3),e.exports=t.default}(ff,ff.exports)),ff.exports),s=o(i);function o(e){return e&&e.__esModule?e:{default:e}}e.exports=t.default}(Hh,Hh.exports)),Hh.exports}var Af,Pf,Df,Lf,jf,Rf,Ff={exports:{}};function Bf(){if(Pf)return Af;Pf=1,Af=a;var e=Xd().codes,t=e.ERR_METHOD_NOT_IMPLEMENTED,n=e.ERR_MULTIPLE_CALLBACK,r=e.ERR_TRANSFORM_ALREADY_TRANSFORMING,i=e.ERR_TRANSFORM_WITH_LENGTH_0,s=$h();function o(e,t){var r=this._transformState;r.transforming=!1;var i=r.writecb;if(null===i)return this.emit("error",new n);r.writechunk=null,r.writecb=null,null!=t&&this.push(t),i(e);var s=this._readableState;s.reading=!1,(s.needReadable||s.length<s.highWaterMark)&&this._read(s.highWaterMark)}function a(e){if(!(this instanceof a))return new a(e);s.call(this,e),this._transformState={afterTransform:o.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),this.on("prefinish",c)}function c(){var e=this;"function"!=typeof this._flush||this._readableState.destroyed?l(this,null,null):this._flush((function(t,n){l(e,t,n)}))}function l(e,t,n){if(t)return e.emit("error",t);if(null!=n&&e.push(n),e._writableState.length)throw new i;if(e._transformState.transforming)throw new r;return e.push(null)}return oh()(a,s),a.prototype.push=function(e,t){return this._transformState.needTransform=!1,s.prototype.push.call(this,e,t)},a.prototype._transform=function(e,n,r){r(new t("_transform()"))},a.prototype._write=function(e,t,n){var r=this._transformState;if(r.writecb=n,r.writechunk=e,r.writeencoding=t,!r.transforming){var i=this._readableState;(r.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},a.prototype._read=function(){var e=this._transformState;null===e.writechunk||e.transforming?e.needTransform=!0:(e.transforming=!0,this._transform(e.writechunk,e.writeencoding,e.afterTransform))},a.prototype._destroy=function(e,t){s.prototype._destroy.call(this,e,(function(e){t(e)}))},Af}function Uf(){if(Rf)return jf;var e;Rf=1;var t=Xd().codes,n=t.ERR_MISSING_ARGS,r=t.ERR_STREAM_DESTROYED;function i(e){if(e)throw e}function s(e){e()}function o(e,t){return e.pipe(t)}return jf=function(){for(var t=arguments.length,a=new Array(t),c=0;c<t;c++)a[c]=arguments[c];var l,u=function(e){return e.length?"function"!=typeof e[e.length-1]?i:e.pop():i}(a);if(Array.isArray(a[0])&&(a=a[0]),a.length<2)throw new n("streams");var d=a.map((function(t,n){var i=n<a.length-1;return function(t,n,i,s){s=function(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}(s);var o=!1;t.on("close",(function(){o=!0})),void 0===e&&(e=kh()),e(t,{readable:n,writable:i},(function(e){if(e)return s(e);o=!0,s()}));var a=!1;return function(e){if(!o&&!a)return a=!0,function(e){return e.setHeader&&"function"==typeof e.abort}(t)?t.abort():"function"==typeof t.destroy?t.destroy():void s(e||new r("pipe"))}}(t,i,n>0,(function(e){l||(l=e),e&&d.forEach(s),i||(d.forEach(s),u(l))}))}));return a.reduce(o)},jf}!function(e,t){var n=N;"disable"===process.env.READABLE_STREAM&&n?(e.exports=n.Readable,Object.assign(e.exports,n),e.exports.Stream=n):((t=e.exports=Oh()).Stream=n||t,t.Readable=t,t.Writable=Mh(),t.Duplex=$h(),t.Transform=Bf(),t.PassThrough=function(){if(Lf)return Df;Lf=1,Df=t;var e=Bf();function t(n){if(!(this instanceof t))return new t(n);e.call(this,n)}return oh()(t,e),t.prototype._transform=function(e,t,n){n(null,e)},Df}(),t.finished=kh(),t.pipeline=Uf())}(Ff,Ff.exports);var Wf,Yf,Gf,Hf,Vf=Ff.exports,zf={exports:{}};function qf(){if(Yf)return Wf;Yf=1;var e=[],t=[],n=function(){};function r(t){return!~e.indexOf(t)&&(e.push(t),!0)}function i(e){n=e}function s(t){for(var n=[],r=0;r<e.length;r++)if(e[r].async)n.push(e[r]);else if(e[r](t))return!0;return!!n.length&&new Promise((function(e){Promise.all(n.map((function(e){return e(t)}))).then((function(t){e(t.some(Boolean))}))}))}function o(e){return!~t.indexOf(e)&&(t.push(e),!0)}function a(){n.apply(n,arguments)}function c(e){for(var n=0;n<t.length;n++)e=t[n].apply(t[n],arguments);return e}function l(e,t){var n=Object.prototype.hasOwnProperty;for(var r in t)n.call(t,r)&&(e[r]=t[r]);return e}function u(e){return e.enabled=!1,e.modify=o,e.set=i,e.use=r,l((function(){return!1}),e)}function d(e){return e.enabled=!0,e.modify=o,e.set=i,e.use=r,l((function(){var t=Array.prototype.slice.call(arguments,0);return a.call(a,e,c(t,e)),!0}),e)}return Wf=function(e){return e.introduce=l,e.enabled=s,e.process=c,e.modify=o,e.write=a,e.nope=u,e.yep=d,e.set=i,e.use=r,e}}var Jf,Kf,Zf={exports:{}};var Xf,Qf,ep,tp,np={exports:{}};function rp(){return Qf?Xf:(Qf=1,Xf=function(e){return!(!e||"string"==typeof e)&&(e instanceof Array||Array.isArray(e)||e.length>=0&&(e.splice instanceof Function||Object.getOwnPropertyDescriptor(e,e.length-1)&&"String"!==e.constructor.name))})}function ip(){if(tp)return Zf.exports;tp=1;var e=Kf?Jf:(Kf=1,Jf={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}),t=function(){if(ep)return np.exports;ep=1;var e=rp(),t=Array.prototype.concat,n=Array.prototype.slice,r=np.exports=function(r){for(var i=[],s=0,o=r.length;s<o;s++){var a=r[s];e(a)?i=t.call(i,n.call(a)):i.push(a)}return i};return r.wrap=function(e){return function(){return e(r(arguments))}},np.exports}(),n=Object.hasOwnProperty,r=Object.create(null);for(var i in e)n.call(e,i)&&(r[e[i]]=i);var s=Zf.exports={to:{},get:{}};function o(e,t,n){return Math.min(Math.max(t,e),n)}function a(e){var t=Math.round(e).toString(16).toUpperCase();return t.length<2?"0"+t:t}return s.get=function(e){var t,n;switch(e.substring(0,3).toLowerCase()){case"hsl":t=s.get.hsl(e),n="hsl";break;case"hwb":t=s.get.hwb(e),n="hwb";break;default:t=s.get.rgb(e),n="rgb"}return t?{model:n,value:t}:null},s.get.rgb=function(t){if(!t)return null;var r,i,s,a=[0,0,0,1];if(r=t.match(/^#([a-f0-9]{6})([a-f0-9]{2})?$/i)){for(s=r[2],r=r[1],i=0;i<3;i++){var c=2*i;a[i]=parseInt(r.slice(c,c+2),16)}s&&(a[3]=parseInt(s,16)/255)}else if(r=t.match(/^#([a-f0-9]{3,4})$/i)){for(s=(r=r[1])[3],i=0;i<3;i++)a[i]=parseInt(r[i]+r[i],16);s&&(a[3]=parseInt(s+s,16)/255)}else if(r=t.match(/^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/)){for(i=0;i<3;i++)a[i]=parseInt(r[i+1],0);r[4]&&(r[5]?a[3]=.01*parseFloat(r[4]):a[3]=parseFloat(r[4]))}else{if(!(r=t.match(/^rgba?\(\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/)))return(r=t.match(/^(\w+)$/))?"transparent"===r[1]?[0,0,0,0]:n.call(e,r[1])?((a=e[r[1]])[3]=1,a):null:null;for(i=0;i<3;i++)a[i]=Math.round(2.55*parseFloat(r[i+1]));r[4]&&(r[5]?a[3]=.01*parseFloat(r[4]):a[3]=parseFloat(r[4]))}for(i=0;i<3;i++)a[i]=o(a[i],0,255);return a[3]=o(a[3],0,1),a},s.get.hsl=function(e){if(!e)return null;var t=e.match(/^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d\.]+)%\s*,?\s*([+-]?[\d\.]+)%\s*(?:[,|\/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/);if(t){var n=parseFloat(t[4]);return[(parseFloat(t[1])%360+360)%360,o(parseFloat(t[2]),0,100),o(parseFloat(t[3]),0,100),o(isNaN(n)?1:n,0,1)]}return null},s.get.hwb=function(e){if(!e)return null;var t=e.match(/^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/);if(t){var n=parseFloat(t[4]);return[(parseFloat(t[1])%360+360)%360,o(parseFloat(t[2]),0,100),o(parseFloat(t[3]),0,100),o(isNaN(n)?1:n,0,1)]}return null},s.to.hex=function(){var e=t(arguments);return"#"+a(e[0])+a(e[1])+a(e[2])+(e[3]<1?a(Math.round(255*e[3])):"")},s.to.rgb=function(){var e=t(arguments);return e.length<4||1===e[3]?"rgb("+Math.round(e[0])+", "+Math.round(e[1])+", "+Math.round(e[2])+")":"rgba("+Math.round(e[0])+", "+Math.round(e[1])+", "+Math.round(e[2])+", "+e[3]+")"},s.to.rgb.percent=function(){var e=t(arguments),n=Math.round(e[0]/255*100),r=Math.round(e[1]/255*100),i=Math.round(e[2]/255*100);return e.length<4||1===e[3]?"rgb("+n+"%, "+r+"%, "+i+"%)":"rgba("+n+"%, "+r+"%, "+i+"%, "+e[3]+")"},s.to.hsl=function(){var e=t(arguments);return e.length<4||1===e[3]?"hsl("+e[0]+", "+e[1]+"%, "+e[2]+"%)":"hsla("+e[0]+", "+e[1]+"%, "+e[2]+"%, "+e[3]+")"},s.to.hwb=function(){var e=t(arguments),n="";return e.length>=4&&1!==e[3]&&(n=", "+e[3]),"hwb("+e[0]+", "+e[1]+"%, "+e[2]+"%"+n+")"},s.to.keyword=function(e){return r[e.slice(0,3)]},Zf.exports}var sp,op,ap,cp,lp,up,dp,hp,fp,pp,gp,mp,yp,vp,bp,wp,Sp,_p,Ip,xp,kp,Ep,Cp,Op,$p,Mp,Np,Tp={exports:{}};function Ap(){if(ap)return Tp.exports;ap=1;var e=op?sp:(op=1,sp={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}),t={};for(var n in e)e.hasOwnProperty(n)&&(t[e[n]]=n);var r=Tp.exports={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};for(var i in r)if(r.hasOwnProperty(i)){if(!("channels"in r[i]))throw new Error("missing channels property: "+i);if(!("labels"in r[i]))throw new Error("missing channel labels property: "+i);if(r[i].labels.length!==r[i].channels)throw new Error("channel and label counts mismatch: "+i);var s=r[i].channels,o=r[i].labels;delete r[i].channels,delete r[i].labels,Object.defineProperty(r[i],"channels",{value:s}),Object.defineProperty(r[i],"labels",{value:o})}return r.rgb.hsl=function(e){var t,n,r=e[0]/255,i=e[1]/255,s=e[2]/255,o=Math.min(r,i,s),a=Math.max(r,i,s),c=a-o;return a===o?t=0:r===a?t=(i-s)/c:i===a?t=2+(s-r)/c:s===a&&(t=4+(r-i)/c),(t=Math.min(60*t,360))<0&&(t+=360),n=(o+a)/2,[t,100*(a===o?0:n<=.5?c/(a+o):c/(2-a-o)),100*n]},r.rgb.hsv=function(e){var t,n,r,i,s,o=e[0]/255,a=e[1]/255,c=e[2]/255,l=Math.max(o,a,c),u=l-Math.min(o,a,c),d=function(e){return(l-e)/6/u+.5};return 0===u?i=s=0:(s=u/l,t=d(o),n=d(a),r=d(c),o===l?i=r-n:a===l?i=1/3+t-r:c===l&&(i=2/3+n-t),i<0?i+=1:i>1&&(i-=1)),[360*i,100*s,100*l]},r.rgb.hwb=function(e){var t=e[0],n=e[1],i=e[2];return[r.rgb.hsl(e)[0],100*(1/255*Math.min(t,Math.min(n,i))),100*(i=1-1/255*Math.max(t,Math.max(n,i)))]},r.rgb.cmyk=function(e){var t,n=e[0]/255,r=e[1]/255,i=e[2]/255;return[100*((1-n-(t=Math.min(1-n,1-r,1-i)))/(1-t)||0),100*((1-r-t)/(1-t)||0),100*((1-i-t)/(1-t)||0),100*t]},r.rgb.keyword=function(n){var r=t[n];if(r)return r;var i,s,o,a=1/0;for(var c in e)if(e.hasOwnProperty(c)){var l=e[c],u=(s=n,o=l,Math.pow(s[0]-o[0],2)+Math.pow(s[1]-o[1],2)+Math.pow(s[2]-o[2],2));u<a&&(a=u,i=c)}return i},r.keyword.rgb=function(t){return e[t]},r.rgb.xyz=function(e){var t=e[0]/255,n=e[1]/255,r=e[2]/255;return[100*(.4124*(t=t>.04045?Math.pow((t+.055)/1.055,2.4):t/12.92)+.3576*(n=n>.04045?Math.pow((n+.055)/1.055,2.4):n/12.92)+.1805*(r=r>.04045?Math.pow((r+.055)/1.055,2.4):r/12.92)),100*(.2126*t+.7152*n+.0722*r),100*(.0193*t+.1192*n+.9505*r)]},r.rgb.lab=function(e){var t=r.rgb.xyz(e),n=t[0],i=t[1],s=t[2];return i/=100,s/=108.883,n=(n/=95.047)>.008856?Math.pow(n,1/3):7.787*n+16/116,[116*(i=i>.008856?Math.pow(i,1/3):7.787*i+16/116)-16,500*(n-i),200*(i-(s=s>.008856?Math.pow(s,1/3):7.787*s+16/116))]},r.hsl.rgb=function(e){var t,n,r,i,s,o=e[0]/360,a=e[1]/100,c=e[2]/100;if(0===a)return[s=255*c,s,s];t=2*c-(n=c<.5?c*(1+a):c+a-c*a),i=[0,0,0];for(var l=0;l<3;l++)(r=o+1/3*-(l-1))<0&&r++,r>1&&r--,s=6*r<1?t+6*(n-t)*r:2*r<1?n:3*r<2?t+(n-t)*(2/3-r)*6:t,i[l]=255*s;return i},r.hsl.hsv=function(e){var t=e[0],n=e[1]/100,r=e[2]/100,i=n,s=Math.max(r,.01);return n*=(r*=2)<=1?r:2-r,i*=s<=1?s:2-s,[t,100*(0===r?2*i/(s+i):2*n/(r+n)),100*((r+n)/2)]},r.hsv.rgb=function(e){var t=e[0]/60,n=e[1]/100,r=e[2]/100,i=Math.floor(t)%6,s=t-Math.floor(t),o=255*r*(1-n),a=255*r*(1-n*s),c=255*r*(1-n*(1-s));switch(r*=255,i){case 0:return[r,c,o];case 1:return[a,r,o];case 2:return[o,r,c];case 3:return[o,a,r];case 4:return[c,o,r];case 5:return[r,o,a]}},r.hsv.hsl=function(e){var t,n,r,i=e[0],s=e[1]/100,o=e[2]/100,a=Math.max(o,.01);return r=(2-s)*o,n=s*a,[i,100*(n=(n/=(t=(2-s)*a)<=1?t:2-t)||0),100*(r/=2)]},r.hwb.rgb=function(e){var t,n,r,i,s,o,a,c=e[0]/360,l=e[1]/100,u=e[2]/100,d=l+u;switch(d>1&&(l/=d,u/=d),r=6*c-(t=Math.floor(6*c)),1&t&&(r=1-r),i=l+r*((n=1-u)-l),t){default:case 6:case 0:s=n,o=i,a=l;break;case 1:s=i,o=n,a=l;break;case 2:s=l,o=n,a=i;break;case 3:s=l,o=i,a=n;break;case 4:s=i,o=l,a=n;break;case 5:s=n,o=l,a=i}return[255*s,255*o,255*a]},r.cmyk.rgb=function(e){var t=e[0]/100,n=e[1]/100,r=e[2]/100,i=e[3]/100;return[255*(1-Math.min(1,t*(1-i)+i)),255*(1-Math.min(1,n*(1-i)+i)),255*(1-Math.min(1,r*(1-i)+i))]},r.xyz.rgb=function(e){var t,n,r,i=e[0]/100,s=e[1]/100,o=e[2]/100;return n=-.9689*i+1.8758*s+.0415*o,r=.0557*i+-.204*s+1.057*o,t=(t=3.2406*i+-1.5372*s+-.4986*o)>.0031308?1.055*Math.pow(t,1/2.4)-.055:12.92*t,n=n>.0031308?1.055*Math.pow(n,1/2.4)-.055:12.92*n,r=r>.0031308?1.055*Math.pow(r,1/2.4)-.055:12.92*r,[255*(t=Math.min(Math.max(0,t),1)),255*(n=Math.min(Math.max(0,n),1)),255*(r=Math.min(Math.max(0,r),1))]},r.xyz.lab=function(e){var t=e[0],n=e[1],r=e[2];return n/=100,r/=108.883,t=(t/=95.047)>.008856?Math.pow(t,1/3):7.787*t+16/116,[116*(n=n>.008856?Math.pow(n,1/3):7.787*n+16/116)-16,500*(t-n),200*(n-(r=r>.008856?Math.pow(r,1/3):7.787*r+16/116))]},r.lab.xyz=function(e){var t,n,r,i=e[0];t=e[1]/500+(n=(i+16)/116),r=n-e[2]/200;var s=Math.pow(n,3),o=Math.pow(t,3),a=Math.pow(r,3);return n=s>.008856?s:(n-16/116)/7.787,t=o>.008856?o:(t-16/116)/7.787,r=a>.008856?a:(r-16/116)/7.787,[t*=95.047,n*=100,r*=108.883]},r.lab.lch=function(e){var t,n=e[0],r=e[1],i=e[2];return(t=360*Math.atan2(i,r)/2/Math.PI)<0&&(t+=360),[n,Math.sqrt(r*r+i*i),t]},r.lch.lab=function(e){var t,n=e[0],r=e[1];return t=e[2]/360*2*Math.PI,[n,r*Math.cos(t),r*Math.sin(t)]},r.rgb.ansi16=function(e){var t=e[0],n=e[1],i=e[2],s=1 in arguments?arguments[1]:r.rgb.hsv(e)[2];if(0===(s=Math.round(s/50)))return 30;var o=30+(Math.round(i/255)<<2|Math.round(n/255)<<1|Math.round(t/255));return 2===s&&(o+=60),o},r.hsv.ansi16=function(e){return r.rgb.ansi16(r.hsv.rgb(e),e[2])},r.rgb.ansi256=function(e){var t=e[0],n=e[1],r=e[2];return t===n&&n===r?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5)},r.ansi16.rgb=function(e){var t=e%10;if(0===t||7===t)return e>50&&(t+=3.5),[t=t/10.5*255,t,t];var n=.5*(1+~~(e>50));return[(1&t)*n*255,(t>>1&1)*n*255,(t>>2&1)*n*255]},r.ansi256.rgb=function(e){if(e>=232){var t=10*(e-232)+8;return[t,t,t]}var n;return e-=16,[Math.floor(e/36)/5*255,Math.floor((n=e%36)/6)/5*255,n%6/5*255]},r.rgb.hex=function(e){var t=(((255&Math.round(e[0]))<<16)+((255&Math.round(e[1]))<<8)+(255&Math.round(e[2]))).toString(16).toUpperCase();return"000000".substring(t.length)+t},r.hex.rgb=function(e){var t=e.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!t)return[0,0,0];var n=t[0];3===t[0].length&&(n=n.split("").map((function(e){return e+e})).join(""));var r=parseInt(n,16);return[r>>16&255,r>>8&255,255&r]},r.rgb.hcg=function(e){var t,n=e[0]/255,r=e[1]/255,i=e[2]/255,s=Math.max(Math.max(n,r),i),o=Math.min(Math.min(n,r),i),a=s-o;return t=a<=0?0:s===n?(r-i)/a%6:s===r?2+(i-n)/a:4+(n-r)/a+4,t/=6,[360*(t%=1),100*a,100*(a<1?o/(1-a):0)]},r.hsl.hcg=function(e){var t=e[1]/100,n=e[2]/100,r=1,i=0;return(r=n<.5?2*t*n:2*t*(1-n))<1&&(i=(n-.5*r)/(1-r)),[e[0],100*r,100*i]},r.hsv.hcg=function(e){var t=e[1]/100,n=e[2]/100,r=t*n,i=0;return r<1&&(i=(n-r)/(1-r)),[e[0],100*r,100*i]},r.hcg.rgb=function(e){var t=e[0]/360,n=e[1]/100,r=e[2]/100;if(0===n)return[255*r,255*r,255*r];var i,s=[0,0,0],o=t%1*6,a=o%1,c=1-a;switch(Math.floor(o)){case 0:s[0]=1,s[1]=a,s[2]=0;break;case 1:s[0]=c,s[1]=1,s[2]=0;break;case 2:s[0]=0,s[1]=1,s[2]=a;break;case 3:s[0]=0,s[1]=c,s[2]=1;break;case 4:s[0]=a,s[1]=0,s[2]=1;break;default:s[0]=1,s[1]=0,s[2]=c}return i=(1-n)*r,[255*(n*s[0]+i),255*(n*s[1]+i),255*(n*s[2]+i)]},r.hcg.hsv=function(e){var t=e[1]/100,n=t+e[2]/100*(1-t),r=0;return n>0&&(r=t/n),[e[0],100*r,100*n]},r.hcg.hsl=function(e){var t=e[1]/100,n=e[2]/100*(1-t)+.5*t,r=0;return n>0&&n<.5?r=t/(2*n):n>=.5&&n<1&&(r=t/(2*(1-n))),[e[0],100*r,100*n]},r.hcg.hwb=function(e){var t=e[1]/100,n=t+e[2]/100*(1-t);return[e[0],100*(n-t),100*(1-n)]},r.hwb.hcg=function(e){var t=e[1]/100,n=1-e[2]/100,r=n-t,i=0;return r<1&&(i=(n-r)/(1-r)),[e[0],100*r,100*i]},r.apple.rgb=function(e){return[e[0]/65535*255,e[1]/65535*255,e[2]/65535*255]},r.rgb.apple=function(e){return[e[0]/255*65535,e[1]/255*65535,e[2]/255*65535]},r.gray.rgb=function(e){return[e[0]/100*255,e[0]/100*255,e[0]/100*255]},r.gray.hsl=r.gray.hsv=function(e){return[0,0,e[0]]},r.gray.hwb=function(e){return[0,100,e[0]]},r.gray.cmyk=function(e){return[0,0,0,e[0]]},r.gray.lab=function(e){return[e[0],0,0]},r.gray.hex=function(e){var t=255&Math.round(e[0]/100*255),n=((t<<16)+(t<<8)+t).toString(16).toUpperCase();return"000000".substring(n.length)+n},r.rgb.gray=function(e){return[(e[0]+e[1]+e[2])/3/255*100]},Tp.exports}function Pp(){if(lp)return cp;lp=1;var e=Ap();function t(t){var n=function(){for(var t={},n=Object.keys(e),r=n.length,i=0;i<r;i++)t[n[i]]={distance:-1,parent:null};return t}(),r=[t];for(n[t].distance=0;r.length;)for(var i=r.pop(),s=Object.keys(e[i]),o=s.length,a=0;a<o;a++){var c=s[a],l=n[c];-1===l.distance&&(l.distance=n[i].distance+1,l.parent=i,r.unshift(c))}return n}function n(e,t){return function(n){return t(e(n))}}function r(t,r){for(var i=[r[t].parent,t],s=e[r[t].parent][t],o=r[t].parent;r[o].parent;)i.unshift(r[o].parent),s=n(e[r[o].parent][o],s),o=r[o].parent;return s.conversion=i,s}return cp=function(e){for(var n=t(e),i={},s=Object.keys(n),o=s.length,a=0;a<o;a++){var c=s[a];null!==n[c].parent&&(i[c]=r(c,n))}return i}}function Dp(){if(dp)return up;dp=1;var e=Ap(),t=Pp(),n={};return Object.keys(e).forEach((function(r){n[r]={},Object.defineProperty(n[r],"channels",{value:e[r].channels}),Object.defineProperty(n[r],"labels",{value:e[r].labels});var i=t(r);Object.keys(i).forEach((function(e){var t=i[e];n[r][e]=function(e){var t=function(t){if(null==t)return t;arguments.length>1&&(t=Array.prototype.slice.call(arguments));var n=e(t);if("object"==typeof n)for(var r=n.length,i=0;i<r;i++)n[i]=Math.round(n[i]);return n};return"conversion"in e&&(t.conversion=e.conversion),t}(t),n[r][e].raw=function(e){var t=function(t){return null==t?t:(arguments.length>1&&(t=Array.prototype.slice.call(arguments)),e(t))};return"conversion"in e&&(t.conversion=e.conversion),t}(t)}))})),up=n}function Lp(){if(fp)return hp;fp=1;var e=ip(),t=Dp(),n=[].slice,r=["keyword","gray","hex"],i={};Object.keys(t).forEach((function(e){i[n.call(t[e].labels).sort().join("")]=e}));var s={};function o(a,c){if(!(this instanceof o))return new o(a,c);if(c&&c in r&&(c=null),c&&!(c in t))throw new Error("Unknown model: "+c);var u,d;if(null==a)this.model="rgb",this.color=[0,0,0],this.valpha=1;else if(a instanceof o)this.model=a.model,this.color=a.color.slice(),this.valpha=a.valpha;else if("string"==typeof a){var h=e.get(a);if(null===h)throw new Error("Unable to parse color from string: "+a);this.model=h.model,d=t[this.model].channels,this.color=h.value.slice(0,d),this.valpha="number"==typeof h.value[d]?h.value[d]:1}else if(a.length){this.model=c||"rgb",d=t[this.model].channels;var f=n.call(a,0,d);this.color=l(f,d),this.valpha="number"==typeof a[d]?a[d]:1}else if("number"==typeof a)a&=16777215,this.model="rgb",this.color=[a>>16&255,a>>8&255,255&a],this.valpha=1;else{this.valpha=1;var p=Object.keys(a);"alpha"in a&&(p.splice(p.indexOf("alpha"),1),this.valpha="number"==typeof a.alpha?a.alpha:0);var g=p.sort().join("");if(!(g in i))throw new Error("Unable to parse color from object: "+JSON.stringify(a));this.model=i[g];var m=t[this.model].labels,y=[];for(u=0;u<m.length;u++)y.push(a[m[u]]);this.color=l(y)}if(s[this.model])for(d=t[this.model].channels,u=0;u<d;u++){var v=s[this.model][u];v&&(this.color[u]=v(this.color[u]))}this.valpha=Math.max(0,Math.min(1,this.valpha)),Object.freeze&&Object.freeze(this)}function a(e,t,n){return(e=Array.isArray(e)?e:[e]).forEach((function(e){(s[e]||(s[e]=[]))[t]=n})),e=e[0],function(r){var i;return arguments.length?(n&&(r=n(r)),(i=this[e]()).color[t]=r,i):(i=this[e]().color[t],n&&(i=n(i)),i)}}function c(e){return function(t){return Math.max(0,Math.min(e,t))}}function l(e,t){for(var n=0;n<t;n++)"number"!=typeof e[n]&&(e[n]=0);return e}return o.prototype={toString:function(){return this.string()},toJSON:function(){return this[this.model]()},string:function(t){var n=this.model in e.to?this:this.rgb(),r=1===(n=n.round("number"==typeof t?t:1)).valpha?n.color:n.color.concat(this.valpha);return e.to[n.model](r)},percentString:function(t){var n=this.rgb().round("number"==typeof t?t:1),r=1===n.valpha?n.color:n.color.concat(this.valpha);return e.to.rgb.percent(r)},array:function(){return 1===this.valpha?this.color.slice():this.color.concat(this.valpha)},object:function(){for(var e={},n=t[this.model].channels,r=t[this.model].labels,i=0;i<n;i++)e[r[i]]=this.color[i];return 1!==this.valpha&&(e.alpha=this.valpha),e},unitArray:function(){var e=this.rgb().color;return e[0]/=255,e[1]/=255,e[2]/=255,1!==this.valpha&&e.push(this.valpha),e},unitObject:function(){var e=this.rgb().object();return e.r/=255,e.g/=255,e.b/=255,1!==this.valpha&&(e.alpha=this.valpha),e},round:function(e){return e=Math.max(e||0,0),new o(this.color.map(function(e){return function(t){return function(e,t){return Number(e.toFixed(t))}(t,e)}}(e)).concat(this.valpha),this.model)},alpha:function(e){return arguments.length?new o(this.color.concat(Math.max(0,Math.min(1,e))),this.model):this.valpha},red:a("rgb",0,c(255)),green:a("rgb",1,c(255)),blue:a("rgb",2,c(255)),hue:a(["hsl","hsv","hsl","hwb","hcg"],0,(function(e){return(e%360+360)%360})),saturationl:a("hsl",1,c(100)),lightness:a("hsl",2,c(100)),saturationv:a("hsv",1,c(100)),value:a("hsv",2,c(100)),chroma:a("hcg",1,c(100)),gray:a("hcg",2,c(100)),white:a("hwb",1,c(100)),wblack:a("hwb",2,c(100)),cyan:a("cmyk",0,c(100)),magenta:a("cmyk",1,c(100)),yellow:a("cmyk",2,c(100)),black:a("cmyk",3,c(100)),x:a("xyz",0,c(100)),y:a("xyz",1,c(100)),z:a("xyz",2,c(100)),l:a("lab",0,c(100)),a:a("lab",1),b:a("lab",2),keyword:function(e){return arguments.length?new o(e):t[this.model].keyword(this.color)},hex:function(t){return arguments.length?new o(t):e.to.hex(this.rgb().round().color)},rgbNumber:function(){var e=this.rgb().color;return(255&e[0])<<16|(255&e[1])<<8|255&e[2]},luminosity:function(){for(var e=this.rgb().color,t=[],n=0;n<e.length;n++){var r=e[n]/255;t[n]=r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4)}return.2126*t[0]+.7152*t[1]+.0722*t[2]},contrast:function(e){var t=this.luminosity(),n=e.luminosity();return t>n?(t+.05)/(n+.05):(n+.05)/(t+.05)},level:function(e){var t=this.contrast(e);return t>=7.1?"AAA":t>=4.5?"AA":""},isDark:function(){var e=this.rgb().color;return(299*e[0]+587*e[1]+114*e[2])/1e3<128},isLight:function(){return!this.isDark()},negate:function(){for(var e=this.rgb(),t=0;t<3;t++)e.color[t]=255-e.color[t];return e},lighten:function(e){var t=this.hsl();return t.color[2]+=t.color[2]*e,t},darken:function(e){var t=this.hsl();return t.color[2]-=t.color[2]*e,t},saturate:function(e){var t=this.hsl();return t.color[1]+=t.color[1]*e,t},desaturate:function(e){var t=this.hsl();return t.color[1]-=t.color[1]*e,t},whiten:function(e){var t=this.hwb();return t.color[1]+=t.color[1]*e,t},blacken:function(e){var t=this.hwb();return t.color[2]+=t.color[2]*e,t},grayscale:function(){var e=this.rgb().color,t=.3*e[0]+.59*e[1]+.11*e[2];return o.rgb(t,t,t)},fade:function(e){return this.alpha(this.valpha-this.valpha*e)},opaquer:function(e){return this.alpha(this.valpha+this.valpha*e)},rotate:function(e){var t=this.hsl(),n=t.color[0];return n=(n=(n+e)%360)<0?360+n:n,t.color[0]=n,t},mix:function(e,t){if(!e||!e.rgb)throw new Error('Argument to "mix" was not a Color instance, but rather an instance of '+typeof e);var n=e.rgb(),r=this.rgb(),i=void 0===t?.5:t,s=2*i-1,a=n.alpha()-r.alpha(),c=((s*a==-1?s:(s+a)/(1+s*a))+1)/2,l=1-c;return o.rgb(c*n.red()+l*r.red(),c*n.green()+l*r.green(),c*n.blue()+l*r.blue(),n.alpha()*i+r.alpha()*(1-i))}},Object.keys(t).forEach((function(e){if(-1===r.indexOf(e)){var i=t[e].channels;o.prototype[e]=function(){if(this.model===e)return new o(this);if(arguments.length)return new o(arguments,e);var n,r="number"==typeof arguments[i]?i:this.valpha;return new o((n=t[this.model][e].raw(this.color),Array.isArray(n)?n:[n]).concat(r),e)},o[e]=function(t){return"number"==typeof t&&(t=l(n.call(arguments),i)),new o(t,e)}}})),hp=o}function jp(){if(yp)return mp;yp=1;var e=Lp(),t=(gp||(gp=1,pp=function(e){for(var t=0,n=0;t<e.length;n=e.charCodeAt(t++)+((n<<5)-n));var r=Math.floor(Math.abs(1e4*Math.sin(n)%1*16777216)).toString(16);return"#"+Array(6-r.length+1).join("0")+r}),pp);return mp=function(n,r){var i=n.split(r||":"),s=t(i[0]);if(!i.length)return s;for(var o=0,a=i.length-1;o<a;o++)s=e(s).mix(e(t(i[o+1]))).saturate(1).hex();return s},mp}function Rp(){if(bp)return vp;function e(t,n){return n?new e(t).style(n):this instanceof e?void(this.text=t):new e(t)}return bp=1,e.prototype.prefix="[",e.prototype.suffix="m",e.prototype.hex=function(e){3===(e="#"===e[0]?e.substring(1):e).length&&((e=e.split(""))[5]=e[2],e[4]=e[2],e[3]=e[1],e[2]=e[1],e[1]=e[0],e=e.join(""));var t=e.substring(0,2),n=e.substring(2,4),r=e.substring(4,6);return[parseInt(t,16),parseInt(n,16),parseInt(r,16)]},e.prototype.rgb=function(e,t,n){var r=e/255*5,i=t/255*5,s=n/255*5;return this.ansi(r,i,s)},e.prototype.ansi=function(e,t,n){return 16+36*Math.round(e)+6*Math.round(t)+Math.round(n)},e.prototype.reset=function(){return this.prefix+"39;49"+this.suffix},e.prototype.style=function(e){return this.prefix+"38;5;"+this.rgb.apply(this,this.hex(e))+this.suffix+this.text+this.reset()},vp=e}function Fp(){return Ip||(Ip=1,_p=function(e,t){if(!t)return!1;for(var n=t.split(/[\s,]+/),r=0;r<n.length;r++)if("-"!==(t=n[r].replace("*",".*?")).charAt(0)){if(new RegExp("^"+t+"$").test(e))return!0}else if(new RegExp("^"+t.substr(1)+"$").test(e))return!1;return!1}),_p}function Bp(){if(Cp)return Ep;Cp=1;var e=function(){if(kp)return xp;kp=1;var e=Fp();return xp=function(t){return function(n){try{return e(n,t())}catch(e){}return!1}}}();return Ep=e((function(){return process.env.DEBUG||process.env.DIAGNOSTICS}))}"production"===process.env.NODE_ENV?zf.exports=function(){if(Hf)return Gf;Hf=1;var e=qf()((function e(t,n){return(n=n||{}).namespace=t,n.prod=!0,n.dev=!1,n.force||e.force?e.yep(n):e.nope(n)}));return Gf=e}():zf.exports=function(){if(Np)return Mp;Np=1;var e=qf(),t=O.isatty(1),n=e((function e(n,r){return(r=r||{}).colors="colors"in r?r.colors:t,r.namespace=n,r.prod=!1,r.dev=!0,e.enabled(n)||r.force||e.force?e.yep(r):e.nope(r)}));return n.modify(function(){if(Sp)return wp;Sp=1;var e=jp(),t=Rp();return wp=function(n,r){var i=r.namespace,s=!1!==r.colors?t(i+":",e(i)):i+":";return n[0]=s+" "+n[0],n}}()),n.use(Bp()),n.set($p?Op:($p=1,Op=function(e,t){try{Function.prototype.apply.call(console.log,console,t)}catch(e){}})),Mp=n}();var Up,Wp,Yp,Gp,Hp,Vp,zp=zf.exports;function qp(){if(Wp)return Up;Wp=1;const e=P,{StringDecoder:t}=j,{Stream:n}=Vf;function r(){}return Up=(i,s)=>{const o=Buffer.alloc(65536),a=new t("utf8"),c=new n;let l="",u=0,d=0;return-1===i.start&&delete i.start,c.readable=!0,c.destroy=()=>{c.destroyed=!0,c.emit("end"),c.emit("close")},e.open(i.file,"a+","0644",((t,n)=>{if(t)return s?s(t):c.emit("error",t),void c.destroy();!function t(){if(!c.destroyed)return e.read(n,o,0,o.length,u,((e,n)=>{if(e)return s?s(e):c.emit("error",e),void c.destroy();if(!n)return l&&((null==i.start||d>i.start)&&(s?s(null,l):c.emit("line",l)),d++,l=""),setTimeout(t,1e3);let r=a.write(o.slice(0,n));s||c.emit("data",r),r=(l+r).split(/\n+/);const h=r.length-1;let f=0;for(;f<h;f++)(null==i.start||d>i.start)&&(s?s(null,r[f]):c.emit("line",r[f])),d++;return l=r[h],u+=n,t()}));e.close(n,r)}()})),s?c.destroy:c},Up}function Jp(){if(Gp)return Yp;Gp=1;const e=P,t=m,n=Tf(),r=L,{MESSAGE:i}=fu,{Stream:s,PassThrough:o}=Vf,a=Gh,c=zp("winston:file"),l=$,u=qp();return Yp=class extends a{constructor(e={}){function n(t,...n){n.slice(1).forEach((n=>{if(e[n])throw new Error(`Cannot set ${n} and ${t} together`)}))}if(super(e),this.name=e.name||"file",this._stream=new o,this._stream.setMaxListeners(30),this._onError=this._onError.bind(this),e.filename||e.dirname)n("filename or dirname","stream"),this._basename=this.filename=e.filename?t.basename(e.filename):"winston.log",this.dirname=e.dirname||t.dirname(e.filename),this.options=e.options||{flags:"a"};else{if(!e.stream)throw new Error("Cannot log to file without filename or stream.");console.warn("options.stream will be removed in winston@4. Use winston.transports.Stream"),n("stream","filename","maxsize"),this._dest=this._stream.pipe(this._setupStream(e.stream)),this.dirname=t.dirname(this._dest.path)}this.maxsize=e.maxsize||null,this.rotationFormat=e.rotationFormat||!1,this.zippedArchive=e.zippedArchive||!1,this.maxFiles=e.maxFiles||null,this.eol="string"==typeof e.eol?e.eol:l.EOL,this.tailable=e.tailable||!1,this.lazy=e.lazy||!1,this._size=0,this._pendingSize=0,this._created=0,this._drain=!1,this._opening=!1,this._ending=!1,this._fileExist=!1,this.dirname&&this._createLogDirIfNotExist(this.dirname),this.lazy||this.open()}finishIfEnding(){this._ending&&(this._opening?this.once("open",(()=>{this._stream.once("finish",(()=>this.emit("finish"))),setImmediate((()=>this._stream.end()))})):(this._stream.once("finish",(()=>this.emit("finish"))),setImmediate((()=>this._stream.end()))))}log(e,t=()=>{}){if(this.silent)return t(),!0;if(this._drain)return void this._stream.once("drain",(()=>{this._drain=!1,this.log(e,t)}));if(this._rotate)return void this._stream.once("rotate",(()=>{this._rotate=!1,this.log(e,t)}));if(this.lazy){if(!this._fileExist)return this._opening||this.open(),void this.once("open",(()=>{this._fileExist=!0,this.log(e,t)}));if(this._needsNewFile(this._pendingSize))return void this._dest.once("close",(()=>{this._opening||this.open(),this.once("open",(()=>{this.log(e,t)}))}))}const n=`${e[i]}${this.eol}`,r=Buffer.byteLength(n);this._pendingSize+=r,this._opening&&!this.rotatedWhileOpening&&this._needsNewFile(this._size+this._pendingSize)&&(this.rotatedWhileOpening=!0);const s=this._stream.write(n,function(){this._size+=r,this._pendingSize-=r,c("logged %s %s",this._size,n),this.emit("logged",e),this._rotate||this._opening||this._needsNewFile()&&(this.lazy?this._endStream((()=>{this.emit("fileclosed")})):(this._rotate=!0,this._endStream((()=>this._rotateFile()))))}.bind(this));return s?t():(this._drain=!0,this._stream.once("drain",(()=>{this._drain=!1,t()}))),c("written",s,this._drain),this.finishIfEnding(),s}query(n,r){"function"==typeof n&&(r=n,n={}),n=function(e){e=e||{},e.rows=e.rows||e.limit||10,e.start=e.start||0,e.until=e.until||new Date,"object"!=typeof e.until&&(e.until=new Date(e.until));e.from=e.from||e.until-864e5,"object"!=typeof e.from&&(e.from=new Date(e.from));return e.order=e.order||"desc",e}(n);const i=t.join(this.dirname,this.filename);let s="",o=[],a=0;const c=e.createReadStream(i,{encoding:"utf8"});function l(e,t){try{const t=JSON.parse(e);(function(e){if(!e)return;if("object"!=typeof e)return;const t=new Date(e.timestamp);if(n.from&&t<n.from||n.until&&t>n.until||n.level&&n.level!==e.level)return;return!0})(t)&&function(e){if(n.rows&&o.length>=n.rows&&"desc"!==n.order)return void(c.readable&&c.destroy());n.fields&&(e=n.fields.reduce(((t,n)=>(t[n]=e[n],t)),{}));"desc"===n.order&&o.length>=n.rows&&o.shift();o.push(e)}(t)}catch(e){t||c.emit("error",e)}}c.on("error",(e=>{if(c.readable&&c.destroy(),r)return"ENOENT"!==e.code?r(e):r(null,o)})),c.on("data",(e=>{const t=(e=(s+e).split(/\n+/)).length-1;let r=0;for(;r<t;r++)(!n.start||a>=n.start)&&l(e[r]),a++;s=e[t]})),c.on("close",(()=>{s&&l(s,!0),"desc"===n.order&&(o=o.reverse()),r&&r(null,o)}))}stream(e={}){const n=t.join(this.dirname,this.filename),r=new s,i={file:n,start:e.start};return r.destroy=u(i,((e,t)=>{if(e)return r.emit("error",e);try{r.emit("data",t),t=JSON.parse(t),r.emit("log",t)}catch(e){r.emit("error",e)}})),r}open(){this.filename&&(this._opening||(this._opening=!0,this.stat(((e,t)=>{if(e)return this.emit("error",e);c("stat done: %s { size: %s }",this.filename,t),this._size=t,this._dest=this._createStream(this._stream),this._opening=!1,this.once("open",(()=>{this._stream.emit("rotate")||(this._rotate=!1)}))}))))}stat(n){const r=this._getFile(),i=t.join(this.dirname,r);e.stat(i,((e,t)=>e&&"ENOENT"===e.code?(c("ENOENT ok",i),this.filename=r,n(null,0)):e?(c(`err ${e.code} ${i}`),n(e)):!t||this._needsNewFile(t.size)?this._incFile((()=>this.stat(n))):(this.filename=r,void n(null,t.size))))}close(e){this._stream&&this._stream.end((()=>{e&&e(),this.emit("flush"),this.emit("closed")}))}_needsNewFile(e){return e=e||this._size,this.maxsize&&e>=this.maxsize}_onError(e){this.emit("error",e)}_setupStream(e){return e.on("error",this._onError),e}_cleanupStream(e){return e.removeListener("error",this._onError),e.destroy(),e}_rotateFile(){this._incFile((()=>this.open()))}_endStream(e=()=>{}){this._dest?(this._stream.unpipe(this._dest),this._dest.end((()=>{this._cleanupStream(this._dest),e()}))):e()}_createStream(n){const r=t.join(this.dirname,this.filename);c("create stream start",r,this.options);const i=e.createWriteStream(r,this.options).on("error",(e=>c(e))).on("close",(()=>c("close",i.path,i.bytesWritten))).on("open",(()=>{c("file open ok",r),this.emit("open",r),n.pipe(i),this.rotatedWhileOpening&&(this._stream=new o,this._stream.setMaxListeners(30),this._rotateFile(),this.rotatedWhileOpening=!1,this._cleanupStream(i),n.end())}));return c("create stream ok",r),i}_incFile(e){c("_incFile",this.filename);const r=t.extname(this._basename),i=t.basename(this._basename,r),s=[];this.zippedArchive&&s.push(function(e){const n=this._created>0&&!this.tailable?this._created:"";this._compressFile(t.join(this.dirname,`${i}${n}${r}`),t.join(this.dirname,`${i}${n}${r}.gz`),e)}.bind(this)),s.push(function(e){this.tailable?this._checkMaxFilesTailable(r,i,e):(this._created+=1,this._checkMaxFilesIncrementing(r,i,e))}.bind(this)),n(s,e)}_getFile(){const e=t.extname(this._basename),n=t.basename(this._basename,e),r=this.rotationFormat?this.rotationFormat():this._created;return!this.tailable&&this._created?`${n}${r}${e}`:`${n}${e}`}_checkMaxFilesIncrementing(n,r,i){if(!this.maxFiles||this._created<this.maxFiles)return setImmediate(i);const s=this._created-this.maxFiles,o=`${r}${0!==s?s:""}${n}${this.zippedArchive?".gz":""}`,a=t.join(this.dirname,o);e.unlink(a,i)}_checkMaxFilesTailable(r,i,s){const o=[];if(!this.maxFiles)return;const a=this.zippedArchive?".gz":"";for(let n=this.maxFiles-1;n>1;n--)o.push(function(n,s){let o=`${i}${n-1}${r}${a}`;const c=t.join(this.dirname,o);e.exists(c,(l=>{if(!l)return s(null);o=`${i}${n}${r}${a}`,e.rename(c,t.join(this.dirname,o),s)}))}.bind(this,n));n(o,(()=>{e.rename(t.join(this.dirname,`${i}${r}${a}`),t.join(this.dirname,`${i}1${r}${a}`),s)}))}_compressFile(t,n,i){e.access(t,e.F_OK,(s=>{if(s)return i();var o=r.createGzip(),a=e.createReadStream(t),c=e.createWriteStream(n);c.on("finish",(()=>{e.unlink(t,i)})),a.pipe(o).pipe(c)}))}_createLogDirIfNotExist(t){e.existsSync(t)||e.mkdirSync(t,{recursive:!0})}},Yp}const Kp=e=>null!==e&&"object"==typeof e&&"function"==typeof e.pipe;Kp.writable=e=>Kp(e)&&!1!==e.writable&&"function"==typeof e._write&&"object"==typeof e._writableState,Kp.readable=e=>Kp(e)&&!1!==e.readable&&"function"==typeof e._read&&"object"==typeof e._readableState,Kp.duplex=e=>Kp.writable(e)&&Kp.readable(e),Kp.transform=e=>Kp.duplex(e)&&"function"==typeof e._transform;var Zp,Xp,Qp=Kp;!function(e){Object.defineProperty(e,"Console",{configurable:!0,enumerable:!0,get:()=>function(){if(Yh)return Wh;Yh=1;const e=$,{LEVEL:t,MESSAGE:n}=fu,r=Gh;return Wh=class extends r{constructor(t={}){super(t),this.name=t.name||"console",this.stderrLevels=this._stringArrayToSet(t.stderrLevels),this.consoleWarnLevels=this._stringArrayToSet(t.consoleWarnLevels),this.eol="string"==typeof t.eol?t.eol:e.EOL,this.forceConsole=t.forceConsole||!1,this._consoleLog=console.log.bind(console),this._consoleWarn=console.warn.bind(console),this._consoleError=console.error.bind(console),this.setMaxListeners(30)}log(e,r){return setImmediate((()=>this.emit("logged",e))),this.stderrLevels[e[t]]?(console._stderr&&!this.forceConsole?console._stderr.write(`${e[n]}${this.eol}`):this._consoleError(e[n]),void(r&&r())):this.consoleWarnLevels[e[t]]?(console._stderr&&!this.forceConsole?console._stderr.write(`${e[n]}${this.eol}`):this._consoleWarn(e[n]),void(r&&r())):(console._stdout&&!this.forceConsole?console._stdout.write(`${e[n]}${this.eol}`):this._consoleLog(e[n]),void(r&&r()))}_stringArrayToSet(e,t){if(!e)return{};if(t=t||"Cannot make set from type other than Array of string elements",!Array.isArray(e))throw new Error(t);return e.reduce(((e,n)=>{if("string"!=typeof n)throw new Error(t);return e[n]=!0,e}),{})}}}()}),Object.defineProperty(e,"File",{configurable:!0,enumerable:!0,get:()=>Jp()}),Object.defineProperty(e,"Http",{configurable:!0,enumerable:!0,get:()=>function(){if(Vp)return Hp;Vp=1;const e=R,t=F,{Stream:n}=Vf,r=Gh,{configure:i}=Hu();return Hp=class extends r{constructor(e={}){super(e),this.options=e,this.name=e.name||"http",this.ssl=!!e.ssl,this.host=e.host||"localhost",this.port=e.port,this.auth=e.auth,this.path=e.path||"",this.maximumDepth=e.maximumDepth,this.agent=e.agent,this.headers=e.headers||{},this.headers["content-type"]="application/json",this.batch=e.batch||!1,this.batchInterval=e.batchInterval||5e3,this.batchCount=e.batchCount||10,this.batchOptions=[],this.batchTimeoutID=-1,this.batchCallback={},this.port||(this.port=this.ssl?443:80)}log(e,t){this._request(e,null,null,((t,n)=>{n&&200!==n.statusCode&&(t=new Error(`Invalid HTTP Status Code: ${n.statusCode}`)),t?this.emit("warn",t):this.emit("logged",e)})),t&&setImmediate(t)}query(e,t){"function"==typeof e&&(t=e,e={});const n=(e={method:"query",params:this.normalizeQuery(e)}).params.auth||null;delete e.params.auth;const r=e.params.path||null;delete e.params.path,this._request(e,n,r,((e,n,r)=>{if(n&&200!==n.statusCode&&(e=new Error(`Invalid HTTP Status Code: ${n.statusCode}`)),e)return t(e);if("string"==typeof r)try{r=JSON.parse(r)}catch(e){return t(e)}t(null,r)}))}stream(e={}){const t=new n,r=(e={method:"stream",params:e}).params.path||null;delete e.params.path;const i=e.params.auth||null;delete e.params.auth;let s="";const o=this._request(e,i,r);return t.destroy=()=>o.destroy(),o.on("data",(e=>{const n=(e=(s+e).split(/\n+/)).length-1;let r=0;for(;r<n;r++)try{t.emit("log",JSON.parse(e[r]))}catch(e){t.emit("error",e)}s=e[n]})),o.on("error",(e=>t.emit("error",e))),t}_request(e,t,n,r){e=e||{},t=t||this.auth,n=n||this.path||"",this.batch?this._doBatch(e,r,t,n):this._doRequest(e,r,t,n)}_doBatch(e,t,n,r){if(this.batchOptions.push(e),1===this.batchOptions.length){const e=this;this.batchCallback=t,this.batchTimeoutID=setTimeout((function(){e.batchTimeoutID=-1,e._doBatchRequest(e.batchCallback,n,r)}),this.batchInterval)}this.batchOptions.length===this.batchCount&&this._doBatchRequest(this.batchCallback,n,r)}_doBatchRequest(e,t,n){this.batchTimeoutID>0&&(clearTimeout(this.batchTimeoutID),this.batchTimeoutID=-1);const r=this.batchOptions.slice();this.batchOptions=[],this._doRequest(r,e,t,n)}_doRequest(n,r,s,o){const a=Object.assign({},this.headers);s&&s.bearer&&(a.Authorization=`Bearer ${s.bearer}`);const c=(this.ssl?t:e).request({...this.options,method:"POST",host:this.host,port:this.port,path:`/${o.replace(/^\//,"")}`,headers:a,auth:s&&s.username&&s.password?`${s.username}:${s.password}`:"",agent:this.agent});c.on("error",r),c.on("response",(e=>e.on("end",(()=>r(null,e))).resume()));const l=i({...this.maximumDepth&&{maximumDepth:this.maximumDepth}});c.end(Buffer.from(l(n,this.options.replacer),"utf8"))}},Hp}()}),Object.defineProperty(e,"Stream",{configurable:!0,enumerable:!0,get:()=>function(){if(Xp)return Zp;Xp=1;const e=Qp,{MESSAGE:t}=fu,n=$,r=Gh;return Zp=class extends r{constructor(t={}){if(super(t),!t.stream||!e(t.stream))throw new Error("options.stream is required.");this._stream=t.stream,this._stream.setMaxListeners(1/0),this.isObjectMode=t.stream._writableState.objectMode,this.eol="string"==typeof t.eol?t.eol:n.EOL}log(e,n){if(setImmediate((()=>this.emit("logged",e))),this.isObjectMode)return this._stream.write(e),void(n&&n());this._stream.write(`${e[t]}${this.eol}`),n&&n()}}}()})}(Yd);var eg={};const tg=Pl,{configs:ng}=fu;eg.cli=tg.levels(ng.cli),eg.npm=tg.levels(ng.npm),eg.syslog=tg.levels(ng.syslog),eg.addColors=tg.levels;var rg={exports:{}},ig={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=l(qh),r=l(Ef),i=l(Nf),s=l(yf),o=l(If),a=l(lf()),c=l(hf);function l(e){return e&&e.__esModule?e:{default:e}}function u(e,t,n){n=(0,s.default)(n);var i=0,a=0,{length:c}=e,l=!1;function u(e,t){!1===e&&(l=!0),!0!==l&&(e?n(e):++a!==c&&t!==r.default||n(null))}for(0===c&&n(null);i<c;i++)t(e[i],i,(0,o.default)(u))}function d(e,t,n){return(0,i.default)(e,1/0,t,n)}t.default=(0,c.default)((function(e,t,r){return((0,n.default)(e)?u:d)(e,(0,a.default)(t),r)}),3),e.exports=t.default}(ig,ig.exports);var sg=ig.exports,og={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return(t,n,r)=>e(t,r)},e.exports=t.default}(og,og.exports);var ag=og.exports;!function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=o(sg),r=o(ag),i=o(lf()),s=o(hf);function o(e){return e&&e.__esModule?e:{default:e}}t.default=(0,s.default)((function(e,t,s){return(0,n.default)(e,(0,r.default)((0,i.default)(t)),s)}),3),e.exports=t.default}(rg,rg.exports);var cg=rg.exports,lg=Object.prototype.toString,ug=function(e){if("string"==typeof e.displayName&&e.constructor.name)return e.displayName;if("string"==typeof e.name&&e.name)return e.name;if("object"==typeof e&&e.constructor&&"string"==typeof e.constructor.name)return e.constructor.name;var t=e.toString(),n=lg.call(e).slice(8,-1);return(t="Function"===n?t.substring(t.indexOf("(")+1,t.indexOf(")")):n)||"anonymous"},dg=function(e){var t,n=0;function r(){return n||(n=1,t=e.apply(this,arguments),e=null),t}return r.displayName=ug(e),r},hg={};!function(e){function t(e){for(var t in e)this[t]=e[t]}e.get=function(t){var n=Error.stackTraceLimit;Error.stackTraceLimit=1/0;var r={},i=Error.prepareStackTrace;Error.prepareStackTrace=function(e,t){return t},Error.captureStackTrace(r,t||e.get);var s=r.stack;return Error.prepareStackTrace=i,Error.stackTraceLimit=n,s},e.parse=function(e){if(!e.stack)return[];var t=this;return e.stack.split("\n").slice(1).map((function(e){if(e.match(/^\s*[-]{4,}$/))return t._createParsedCallSite({fileName:e,lineNumber:null,functionName:null,typeName:null,methodName:null,columnNumber:null,native:null});var n=e.match(/at (?:(.+)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/);if(n){var r=null,i=null,s=null,o=null,a=null,c="native"===n[5];if(n[1]){var l=(s=n[1]).lastIndexOf(".");if("."==s[l-1]&&l--,l>0){r=s.substr(0,l),i=s.substr(l+1);var u=r.indexOf(".Module");u>0&&(s=s.substr(u+1),r=r.substr(0,u))}o=null}i&&(o=r,a=i),"<anonymous>"===i&&(a=null,s=null);var d={fileName:n[2]||null,lineNumber:parseInt(n[3],10)||null,functionName:s,typeName:o,methodName:a,columnNumber:parseInt(n[4],10)||null,native:c};return t._createParsedCallSite(d)}})).filter((function(e){return!!e}))};["this","typeName","functionName","methodName","fileName","lineNumber","columnNumber","function","evalOrigin"].forEach((function(e){t.prototype[e]=null,t.prototype["get"+e[0].toUpperCase()+e.substr(1)]=function(){return this[e]}})),["topLevel","eval","native","constructor"].forEach((function(e){t.prototype[e]=!1,t.prototype["is"+e[0].toUpperCase()+e.substr(1)]=function(){return this[e]}})),e._createParsedCallSite=function(e){return new t(e)}}(hg);const{Writable:fg}=Vf;const pg=$,gg=cg,mg=zp("winston:exception"),yg=dg,vg=hg,bg=class extends fg{constructor(e){if(super({objectMode:!0}),!e)throw new Error("ExceptionStream requires a TransportStream instance.");this.handleExceptions=!0,this.transport=e}_write(e,t,n){return e.exception?this.transport.log(e,n):(n(),!0)}};var wg=class{constructor(e){if(!e)throw new Error("Logger is required to handle exceptions");this.logger=e,this.handlers=new Map}handle(...e){e.forEach((e=>{if(Array.isArray(e))return e.forEach((e=>this._addHandler(e)));this._addHandler(e)})),this.catcher||(this.catcher=this._uncaughtException.bind(this),process.on("uncaughtException",this.catcher))}unhandle(){this.catcher&&(process.removeListener("uncaughtException",this.catcher),this.catcher=!1,Array.from(this.handlers.values()).forEach((e=>this.logger.unpipe(e))))}getAllInfo(e){let t=null;return e&&(t="string"==typeof e?e:e.message),{error:e,level:"error",message:[`uncaughtException: ${t||"(no error message)"}`,e&&e.stack||" No stack trace"].join("\n"),stack:e&&e.stack,exception:!0,date:(new Date).toString(),process:this.getProcessInfo(),os:this.getOsInfo(),trace:this.getTrace(e)}}getProcessInfo(){return{pid:process.pid,uid:process.getuid?process.getuid():null,gid:process.getgid?process.getgid():null,cwd:process.cwd(),execPath:process.execPath,version:process.version,argv:process.argv,memoryUsage:process.memoryUsage()}}getOsInfo(){return{loadavg:pg.loadavg(),uptime:pg.uptime()}}getTrace(e){return(e?vg.parse(e):vg.get()).map((e=>({column:e.getColumnNumber(),file:e.getFileName(),function:e.getFunctionName(),line:e.getLineNumber(),method:e.getMethodName(),native:e.isNative()})))}_addHandler(e){if(!this.handlers.has(e)){e.handleExceptions=!0;const t=new bg(e);this.handlers.set(e,t),this.logger.pipe(t)}}_uncaughtException(e){const t=this.getAllInfo(e),n=this._getExceptionHandlers();let r,i="function"==typeof this.logger.exitOnError?this.logger.exitOnError(e):this.logger.exitOnError;function s(){mg("doExit",i),mg("process._exiting",process._exiting),i&&!process._exiting&&(r&&clearTimeout(r),process.exit(1))}if(!n.length&&i&&(console.warn("winston: exitOnError cannot be true with no exception handlers."),console.warn("winston: not exiting process."),i=!1),!n||0===n.length)return process.nextTick(s);gg(n,((e,t)=>{const n=yg(t),r=e.transport||e;function i(e){return()=>{mg(e),n()}}r._ending=!0,r.once("finish",i("finished")),r.once("error",i("error"))}),(()=>i&&s())),this.logger.log(t),i&&(r=setTimeout(s,3e3))}_getExceptionHandlers(){return this.logger.transports.filter((e=>(e.transport||e).handleExceptions))}};const{Writable:Sg}=Vf;const _g=$,Ig=cg,xg=zp("winston:rejection"),kg=dg,Eg=hg,Cg=class extends Sg{constructor(e){if(super({objectMode:!0}),!e)throw new Error("RejectionStream requires a TransportStream instance.");this.handleRejections=!0,this.transport=e}_write(e,t,n){return e.rejection?this.transport.log(e,n):(n(),!0)}};var Og,$g,Mg,Ng,Tg=class{constructor(e){if(!e)throw new Error("Logger is required to handle rejections");this.logger=e,this.handlers=new Map}handle(...e){e.forEach((e=>{if(Array.isArray(e))return e.forEach((e=>this._addHandler(e)));this._addHandler(e)})),this.catcher||(this.catcher=this._unhandledRejection.bind(this),process.on("unhandledRejection",this.catcher))}unhandle(){this.catcher&&(process.removeListener("unhandledRejection",this.catcher),this.catcher=!1,Array.from(this.handlers.values()).forEach((e=>this.logger.unpipe(e))))}getAllInfo(e){let t=null;return e&&(t="string"==typeof e?e:e.message),{error:e,level:"error",message:[`unhandledRejection: ${t||"(no error message)"}`,e&&e.stack||" No stack trace"].join("\n"),stack:e&&e.stack,rejection:!0,date:(new Date).toString(),process:this.getProcessInfo(),os:this.getOsInfo(),trace:this.getTrace(e)}}getProcessInfo(){return{pid:process.pid,uid:process.getuid?process.getuid():null,gid:process.getgid?process.getgid():null,cwd:process.cwd(),execPath:process.execPath,version:process.version,argv:process.argv,memoryUsage:process.memoryUsage()}}getOsInfo(){return{loadavg:_g.loadavg(),uptime:_g.uptime()}}getTrace(e){return(e?Eg.parse(e):Eg.get()).map((e=>({column:e.getColumnNumber(),file:e.getFileName(),function:e.getFunctionName(),line:e.getLineNumber(),method:e.getMethodName(),native:e.isNative()})))}_addHandler(e){if(!this.handlers.has(e)){e.handleRejections=!0;const t=new Cg(e);this.handlers.set(e,t),this.logger.pipe(t)}}_unhandledRejection(e){const t=this.getAllInfo(e),n=this._getRejectionHandlers();let r,i="function"==typeof this.logger.exitOnError?this.logger.exitOnError(e):this.logger.exitOnError;function s(){xg("doExit",i),xg("process._exiting",process._exiting),i&&!process._exiting&&(r&&clearTimeout(r),process.exit(1))}if(!n.length&&i&&(console.warn("winston: exitOnError cannot be true with no rejection handlers."),console.warn("winston: not exiting process."),i=!1),!n||0===n.length)return process.nextTick(s);Ig(n,((e,t)=>{const n=kg(t),r=e.transport||e;function i(e){return()=>{xg(e),n()}}r._ending=!0,r.once("finish",i("finished")),r.once("error",i("error"))}),(()=>i&&s())),this.logger.log(t),i&&(r=setTimeout(s,3e3))}_getRejectionHandlers(){return this.logger.transports.filter((e=>(e.transport||e).handleRejections))}};function Ag(){if(Ng)return Mg;Ng=1;const{Stream:e,Transform:t}=Vf,n=cg,{LEVEL:r,SPLAT:i}=fu,s=Qp,o=wg,a=Tg,c=Uh,l=($g||($g=1,Og=class{constructor(e){const t=Ag();if("object"!=typeof e||Array.isArray(e)||!(e instanceof t))throw new Error("Logger is required for profiling");this.logger=e,this.start=Date.now()}done(...e){"function"==typeof e[e.length-1]&&(console.warn("Callback function no longer supported as of winston@3.0.0"),e.pop());const t="object"==typeof e[e.length-1]?e.pop():{};return t.level=t.level||"info",t.durationMs=Date.now()-this.start,this.logger.write(t)}}),Og),{warn:u}=Dd,d=eg,h=/%[scdjifoO%]/g;class f extends t{constructor(e){super({objectMode:!0}),this.configure(e)}child(e){const t=this;return Object.create(t,{write:{value:function(n){const r=Object.assign({},e,n);n instanceof Error&&(r.stack=n.stack,r.message=n.message),t.write(r)}}})}configure({silent:e,format:t,defaultMeta:n,levels:r,level:i="info",exitOnError:s=!0,transports:c,colors:l,emitErrs:u,formatters:h,padLevels:f,rewriters:p,stripColors:g,exceptionHandlers:m,rejectionHandlers:y}={}){if(this.transports.length&&this.clear(),this.silent=e,this.format=t||this.format||Vu()(),this.defaultMeta=n||null,this.levels=r||this.levels||d.npm.levels,this.level=i,this.exceptions&&this.exceptions.unhandle(),this.rejections&&this.rejections.unhandle(),this.exceptions=new o(this),this.rejections=new a(this),this.profilers={},this.exitOnError=s,c&&(c=Array.isArray(c)?c:[c]).forEach((e=>this.add(e))),l||u||h||f||p||g)throw new Error(["{ colors, emitErrs, formatters, padLevels, rewriters, stripColors } were removed in winston@3.0.0.","Use a custom winston.format(function) instead.","See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md"].join("\n"));m&&this.exceptions.handle(m),y&&this.rejections.handle(y)}isLevelEnabled(e){const t=p(this.levels,e);if(null===t)return!1;const n=p(this.levels,this.level);if(null===n)return!1;if(!this.transports||0===this.transports.length)return n>=t;return-1!==this.transports.findIndex((e=>{let r=p(this.levels,e.level);return null===r&&(r=n),r>=t}))}log(e,t,...n){if(1===arguments.length)return e[r]=e.level,this._addDefaultMeta(e),this.write(e),this;if(2===arguments.length)return t&&"object"==typeof t?(t[r]=t.level=e,this._addDefaultMeta(t),this.write(t),this):(t={[r]:e,level:e,message:t},this._addDefaultMeta(t),this.write(t),this);const[s]=n;if("object"==typeof s&&null!==s){if(!(t&&t.match&&t.match(h))){const o=Object.assign({},this.defaultMeta,s,{[r]:e,[i]:n,level:e,message:t});return s.message&&(o.message=`${o.message} ${s.message}`),s.stack&&(o.stack=s.stack),s.cause&&(o.cause=s.cause),this.write(o),this}}return this.write(Object.assign({},this.defaultMeta,{[r]:e,[i]:n,level:e,message:t})),this}_transform(e,t,n){if(this.silent)return n();e[r]||(e[r]=e.level),this.levels[e[r]]||0===this.levels[e[r]]||console.error("[winston] Unknown logger level: %s",e[r]),this._readableState.pipes||console.error("[winston] Attempt to write logs with no transports, which can increase memory usage: %j",e);try{this.push(this.format.transform(e,this.format.options))}finally{this._writableState.sync=!1,n()}}_final(e){const t=this.transports.slice();n(t,((e,t)=>{if(!e||e.finished)return setImmediate(t);e.once("finish",t),e.end()}),e)}add(e){const t=!s(e)||e.log.length>2?new c({transport:e}):e;if(!t._writableState||!t._writableState.objectMode)throw new Error("Transports must WritableStreams in objectMode. Set { objectMode: true }.");return this._onEvent("error",t),this._onEvent("warn",t),this.pipe(t),e.handleExceptions&&this.exceptions.handle(),e.handleRejections&&this.rejections.handle(),this}remove(e){if(!e)return this;let t=e;return(!s(e)||e.log.length>2)&&(t=this.transports.filter((t=>t.transport===e))[0]),t&&this.unpipe(t),this}clear(){return this.unpipe(),this}close(){return this.exceptions.unhandle(),this.rejections.unhandle(),this.clear(),this.emit("close"),this}setLevels(){u.deprecated("setLevels")}query(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const r={},i=Object.assign({},e.query||{});n(this.transports.filter((e=>!!e.query)),(function(t,n){!function(t,n){e.query&&"function"==typeof t.formatQuery&&(e.query=t.formatQuery(i)),t.query(e,((r,i)=>{if(r)return n(r);"function"==typeof t.formatResults&&(i=t.formatResults(i,e.format)),n(null,i)}))}(t,((e,i)=>{n&&((i=e||i)&&(r[t.name]=i),n()),n=null}))}),(()=>t(null,r)))}stream(t={}){const n=new e,r=[];return n._streams=r,n.destroy=()=>{let e=r.length;for(;e--;)r[e].destroy()},this.transports.filter((e=>!!e.stream)).forEach((e=>{const i=e.stream(t);i&&(r.push(i),i.on("log",(t=>{t.transport=t.transport||[],t.transport.push(e.name),n.emit("log",t)})),i.on("error",(t=>{t.transport=t.transport||[],t.transport.push(e.name),n.emit("error",t)})))})),n}startTimer(){return new l(this)}profile(e,...t){const n=Date.now();if(this.profilers[e]){const r=this.profilers[e];delete this.profilers[e],"function"==typeof t[t.length-2]&&(console.warn("Callback function no longer supported as of winston@3.0.0"),t.pop());const i="object"==typeof t[t.length-1]?t.pop():{};return i.level=i.level||"info",i.durationMs=n-r,i.message=i.message||e,this.write(i)}return this.profilers[e]=n,this}handleExceptions(...e){console.warn("Deprecated: .handleExceptions() will be removed in winston@4. Use .exceptions.handle()"),this.exceptions.handle(...e)}unhandleExceptions(...e){console.warn("Deprecated: .unhandleExceptions() will be removed in winston@4. Use .exceptions.unhandle()"),this.exceptions.unhandle(...e)}cli(){throw new Error(["Logger.cli() was removed in winston@3.0.0","Use a custom winston.formats.cli() instead.","See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md"].join("\n"))}_onEvent(e,t){t["__winston"+e]||(t["__winston"+e]=function(n){"error"!==e||this.transports.includes(t)||this.add(t),this.emit(e,n,t)}.bind(this),t.on(e,t["__winston"+e]))}_addDefaultMeta(e){this.defaultMeta&&Object.assign(e,this.defaultMeta)}}function p(e,t){const n=e[t];return n||0===n?n:null}return Object.defineProperty(f.prototype,"transports",{configurable:!1,enumerable:!0,get(){const{pipes:e}=this._readableState;return Array.isArray(e)?e:[e].filter(Boolean)}}),Mg=f}const{LEVEL:Pg}=fu,Dg=eg,Lg=Ag(),jg=zp("winston:create-logger");var Rg=function(e={}){e.levels=e.levels||Dg.npm.levels;class t extends Lg{constructor(e){super(e)}}const n=new t(e);return Object.keys(e.levels).forEach((function(e){jg('Define prototype method for "%s"',e),"log"!==e?(t.prototype[e]=function(...t){const r=this||n;if(1===t.length){const[i]=t,s=i&&i.message&&i||{message:i};return s.level=s[Pg]=e,r._addDefaultMeta(s),r.write(s),this||n}return 0===t.length?(r.log(e,""),r):r.log(e,...t)},t.prototype[function(e){return"is"+e.charAt(0).toUpperCase()+e.slice(1)+"Enabled"}(e)]=function(){return(this||n).isLevelEnabled(e)}):console.warn('Level "log" not defined: conflicts with the method "log". Use a different level name.')})),n};const Fg=Rg;var Bg=class{constructor(e={}){this.loggers=new Map,this.options=e}add(e,t){if(!this.loggers.has(e)){const n=(t=Object.assign({},t||this.options)).transports||this.options.transports;t.transports=n?Array.isArray(n)?n.slice():[n]:[];const r=Fg(t);r.on("close",(()=>this._delete(e))),this.loggers.set(e,r)}return this.loggers.get(e)}get(e,t){return this.add(e,t)}has(e){return!!this.loggers.has(e)}close(e){if(e)return this._removeLogger(e);this.loggers.forEach(((e,t)=>this._removeLogger(t)))}_removeLogger(e){if(!this.loggers.has(e))return;this.loggers.get(e).close(),this._delete(e)}_delete(e){this.loggers.delete(e)}};!function(e){const t=Pl,{warn:n}=Dd;e.version=Wd,e.transports=Yd,e.config=eg,e.addColors=t.levels,e.format=t.format,e.createLogger=Rg,e.Logger=Ag(),e.ExceptionHandler=wg,e.RejectionHandler=Tg,e.Container=Bg,e.Transport=Gh,e.loggers=new e.Container;const r=e.createLogger();Object.keys(e.config.npm.levels).concat(["log","query","stream","add","remove","clear","profile","startTimer","handleExceptions","unhandleExceptions","handleRejections","unhandleRejections","configure","child"]).forEach((t=>e[t]=(...e)=>r[t](...e))),Object.defineProperty(e,"level",{get:()=>r.level,set(e){r.level=e}}),Object.defineProperty(e,"exceptions",{get:()=>r.exceptions}),Object.defineProperty(e,"rejections",{get:()=>r.rejections}),["exitOnError"].forEach((t=>{Object.defineProperty(e,t,{get:()=>r[t],set(e){r[t]=e}})})),Object.defineProperty(e,"default",{get:()=>({exceptionHandlers:r.exceptionHandlers,rejectionHandlers:r.rejectionHandlers,transports:r.transports})}),n.deprecated(e,"setLevels"),n.forFunctions(e,"useFormat",["cli"]),n.forProperties(e,"useFormat",["padLevels","stripColors"]),n.forFunctions(e,"deprecated",["addRewriter","addFilter","clone","extend"]),n.forProperties(e,"deprecated",["emitErrs","levelLength"])}(Al);var Ug=fl(Al),Wg={exports:{}};function Yg(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}!function(e,t){var n=u;function r(e,t){return function(e,t){var r;r="passthrough"!==t.algorithm?n.createHash(t.algorithm):new l;void 0===r.write&&(r.write=r.update,r.end=r.update);var i=c(t,r);i.dispatch(e),r.update||r.end("");if(r.digest)return r.digest("buffer"===t.encoding?void 0:t.encoding);var s=r.read();if("buffer"===t.encoding)return s;return s.toString(t.encoding)}(e,t=o(e,t))}(t=e.exports=r).sha1=function(e){return r(e)},t.keys=function(e){return r(e,{excludeValues:!0,algorithm:"sha1",encoding:"hex"})},t.MD5=function(e){return r(e,{algorithm:"md5",encoding:"hex"})},t.keysMD5=function(e){return r(e,{algorithm:"md5",encoding:"hex",excludeValues:!0})};var i=n.getHashes?n.getHashes().slice():["sha1","md5"];i.push("passthrough");var s=["buffer","hex","binary","base64"];function o(e,t){t=t||{};var n={};if(n.algorithm=t.algorithm||"sha1",n.encoding=t.encoding||"hex",n.excludeValues=!!t.excludeValues,n.algorithm=n.algorithm.toLowerCase(),n.encoding=n.encoding.toLowerCase(),n.ignoreUnknown=!0===t.ignoreUnknown,n.respectType=!1!==t.respectType,n.respectFunctionNames=!1!==t.respectFunctionNames,n.respectFunctionProperties=!1!==t.respectFunctionProperties,n.unorderedArrays=!0===t.unorderedArrays,n.unorderedSets=!1!==t.unorderedSets,n.unorderedObjects=!1!==t.unorderedObjects,n.replacer=t.replacer||void 0,n.excludeKeys=t.excludeKeys||void 0,void 0===e)throw new Error("Object argument required.");for(var r=0;r<i.length;++r)i[r].toLowerCase()===n.algorithm.toLowerCase()&&(n.algorithm=i[r]);if(-1===i.indexOf(n.algorithm))throw new Error('Algorithm "'+n.algorithm+'" not supported. supported values: '+i.join(", "));if(-1===s.indexOf(n.encoding)&&"passthrough"!==n.algorithm)throw new Error('Encoding "'+n.encoding+'" not supported. supported values: '+s.join(", "));return n}function a(e){if("function"!=typeof e)return!1;return null!=/^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i.exec(Function.prototype.toString.call(e))}function c(e,t,n){n=n||[];var r=function(e){return t.update?t.update(e,"utf8"):t.write(e,"utf8")};return{dispatch:function(t){e.replacer&&(t=e.replacer(t));var n=typeof t;return null===t&&(n="null"),this["_"+n](t)},_object:function(t){var i=Object.prototype.toString.call(t),s=/\[object (.*)\]/i.exec(i);s=(s=s?s[1]:"unknown:["+i+"]").toLowerCase();var o;if((o=n.indexOf(t))>=0)return this.dispatch("[CIRCULAR:"+o+"]");if(n.push(t),"undefined"!=typeof Buffer&&Buffer.isBuffer&&Buffer.isBuffer(t))return r("buffer:"),r(t);if("object"===s||"function"===s||"asyncfunction"===s){var c=Object.keys(t);e.unorderedObjects&&(c=c.sort()),!1===e.respectType||a(t)||c.splice(0,0,"prototype","__proto__","constructor"),e.excludeKeys&&(c=c.filter((function(t){return!e.excludeKeys(t)}))),r("object:"+c.length+":");var l=this;return c.forEach((function(n){l.dispatch(n),r(":"),e.excludeValues||l.dispatch(t[n]),r(",")}))}if(!this["_"+s]){if(e.ignoreUnknown)return r("["+s+"]");throw new Error('Unknown object type "'+s+'"')}this["_"+s](t)},_array:function(t,i){i=void 0!==i?i:!1!==e.unorderedArrays;var s=this;if(r("array:"+t.length+":"),!i||t.length<=1)return t.forEach((function(e){return s.dispatch(e)}));var o=[],a=t.map((function(t){var r=new l,i=n.slice();return c(e,r,i).dispatch(t),o=o.concat(i.slice(n.length)),r.read().toString()}));return n=n.concat(o),a.sort(),this._array(a,!1)},_date:function(e){return r("date:"+e.toJSON())},_symbol:function(e){return r("symbol:"+e.toString())},_error:function(e){return r("error:"+e.toString())},_boolean:function(e){return r("bool:"+e.toString())},_string:function(e){r("string:"+e.length+":"),r(e.toString())},_function:function(t){r("fn:"),a(t)?this.dispatch("[native]"):this.dispatch(t.toString()),!1!==e.respectFunctionNames&&this.dispatch("function-name:"+String(t.name)),e.respectFunctionProperties&&this._object(t)},_number:function(e){return r("number:"+e.toString())},_xml:function(e){return r("xml:"+e.toString())},_null:function(){return r("Null")},_undefined:function(){return r("Undefined")},_regexp:function(e){return r("regex:"+e.toString())},_uint8array:function(e){return r("uint8array:"),this.dispatch(Array.prototype.slice.call(e))},_uint8clampedarray:function(e){return r("uint8clampedarray:"),this.dispatch(Array.prototype.slice.call(e))},_int8array:function(e){return r("int8array:"),this.dispatch(Array.prototype.slice.call(e))},_uint16array:function(e){return r("uint16array:"),this.dispatch(Array.prototype.slice.call(e))},_int16array:function(e){return r("int16array:"),this.dispatch(Array.prototype.slice.call(e))},_uint32array:function(e){return r("uint32array:"),this.dispatch(Array.prototype.slice.call(e))},_int32array:function(e){return r("int32array:"),this.dispatch(Array.prototype.slice.call(e))},_float32array:function(e){return r("float32array:"),this.dispatch(Array.prototype.slice.call(e))},_float64array:function(e){return r("float64array:"),this.dispatch(Array.prototype.slice.call(e))},_arraybuffer:function(e){return r("arraybuffer:"),this.dispatch(new Uint8Array(e))},_url:function(e){return r("url:"+e.toString())},_map:function(t){r("map:");var n=Array.from(t);return this._array(n,!1!==e.unorderedSets)},_set:function(t){r("set:");var n=Array.from(t);return this._array(n,!1!==e.unorderedSets)},_file:function(e){return r("file:"),this.dispatch([e.name,e.size,e.type,e.lastModfied])},_blob:function(){if(e.ignoreUnknown)return r("[blob]");throw Error('Hashing Blob objects is currently not supported\n(see https://github.com/puleos/object-hash/issues/26)\nUse "options.replacer" or "options.ignoreUnknown"\n')},_domwindow:function(){return r("domwindow")},_bigint:function(e){return r("bigint:"+e.toString())},_process:function(){return r("process")},_timer:function(){return r("timer")},_pipe:function(){return r("pipe")},_tcp:function(){return r("tcp")},_udp:function(){return r("udp")},_tty:function(){return r("tty")},_statwatcher:function(){return r("statwatcher")},_securecontext:function(){return r("securecontext")},_connection:function(){return r("connection")},_zlib:function(){return r("zlib")},_context:function(){return r("context")},_nodescript:function(){return r("nodescript")},_httpparser:function(){return r("httpparser")},_dataview:function(){return r("dataview")},_signal:function(){return r("signal")},_fsevent:function(){return r("fsevent")},_tlswrap:function(){return r("tlswrap")}}}function l(){return{buf:"",write:function(e){this.buf+=e},end:function(e){this.buf+=e},read:function(){return this.buf}}}t.writeToStream=function(e,t,n){return void 0===n&&(n=t,t={}),c(t=o(e,t),n).dispatch(e)}}(Wg,Wg.exports);var Gg,Hg,Vg,zg={exports:{}};function qg(){return Gg||(Gg=1,(e=zg).exports=function(){var t,n;function r(){return t.apply(null,arguments)}function i(e){t=e}function s(e){return e instanceof Array||"[object Array]"===Object.prototype.toString.call(e)}function o(e){return null!=e&&"[object Object]"===Object.prototype.toString.call(e)}function a(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function c(e){if(Object.getOwnPropertyNames)return 0===Object.getOwnPropertyNames(e).length;var t;for(t in e)if(a(e,t))return!1;return!0}function l(e){return void 0===e}function u(e){return"number"==typeof e||"[object Number]"===Object.prototype.toString.call(e)}function d(e){return e instanceof Date||"[object Date]"===Object.prototype.toString.call(e)}function h(e,t){var n,r=[],i=e.length;for(n=0;n<i;++n)r.push(t(e[n],n));return r}function f(e,t){for(var n in t)a(t,n)&&(e[n]=t[n]);return a(t,"toString")&&(e.toString=t.toString),a(t,"valueOf")&&(e.valueOf=t.valueOf),e}function p(e,t,n,r){return qn(e,t,n,r,!0).utc()}function g(){return{empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidEra:null,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],era:null,meridiem:null,rfc2822:!1,weekdayMismatch:!1}}function m(e){return null==e._pf&&(e._pf=g()),e._pf}function y(e){var t=null,r=!1,i=e._d&&!isNaN(e._d.getTime());return i&&(t=m(e),r=n.call(t.parsedDateParts,(function(e){return null!=e})),i=t.overflow<0&&!t.empty&&!t.invalidEra&&!t.invalidMonth&&!t.invalidWeekday&&!t.weekdayMismatch&&!t.nullInput&&!t.invalidFormat&&!t.userInvalidated&&(!t.meridiem||t.meridiem&&r),e._strict&&(i=i&&0===t.charsLeftOver&&0===t.unusedTokens.length&&void 0===t.bigHour)),null!=Object.isFrozen&&Object.isFrozen(e)?i:(e._isValid=i,e._isValid)}function v(e){var t=p(NaN);return null!=e?f(m(t),e):m(t).userInvalidated=!0,t}n=Array.prototype.some?Array.prototype.some:function(e){var t,n=Object(this),r=n.length>>>0;for(t=0;t<r;t++)if(t in n&&e.call(this,n[t],t,n))return!0;return!1};var b=r.momentProperties=[],w=!1;function S(e,t){var n,r,i,s=b.length;if(l(t._isAMomentObject)||(e._isAMomentObject=t._isAMomentObject),l(t._i)||(e._i=t._i),l(t._f)||(e._f=t._f),l(t._l)||(e._l=t._l),l(t._strict)||(e._strict=t._strict),l(t._tzm)||(e._tzm=t._tzm),l(t._isUTC)||(e._isUTC=t._isUTC),l(t._offset)||(e._offset=t._offset),l(t._pf)||(e._pf=m(t)),l(t._locale)||(e._locale=t._locale),s>0)for(n=0;n<s;n++)l(i=t[r=b[n]])||(e[r]=i);return e}function _(e){S(this,e),this._d=new Date(null!=e._d?e._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),!1===w&&(w=!0,r.updateOffset(this),w=!1)}function I(e){return e instanceof _||null!=e&&null!=e._isAMomentObject}function x(e){!1===r.suppressDeprecationWarnings&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+e)}function k(e,t){var n=!0;return f((function(){if(null!=r.deprecationHandler&&r.deprecationHandler(null,e),n){var i,s,o,c=[],l=arguments.length;for(s=0;s<l;s++){if(i="","object"==typeof arguments[s]){for(o in i+="\n["+s+"] ",arguments[0])a(arguments[0],o)&&(i+=o+": "+arguments[0][o]+", ");i=i.slice(0,-2)}else i=arguments[s];c.push(i)}x(e+"\nArguments: "+Array.prototype.slice.call(c).join("")+"\n"+(new Error).stack),n=!1}return t.apply(this,arguments)}),t)}var E,C={};function O(e,t){null!=r.deprecationHandler&&r.deprecationHandler(e,t),C[e]||(x(t),C[e]=!0)}function $(e){return"undefined"!=typeof Function&&e instanceof Function||"[object Function]"===Object.prototype.toString.call(e)}function M(e){var t,n;for(n in e)a(e,n)&&($(t=e[n])?this[n]=t:this["_"+n]=t);this._config=e,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)}function N(e,t){var n,r=f({},e);for(n in t)a(t,n)&&(o(e[n])&&o(t[n])?(r[n]={},f(r[n],e[n]),f(r[n],t[n])):null!=t[n]?r[n]=t[n]:delete r[n]);for(n in e)a(e,n)&&!a(t,n)&&o(e[n])&&(r[n]=f({},r[n]));return r}function T(e){null!=e&&this.set(e)}r.suppressDeprecationWarnings=!1,r.deprecationHandler=null,E=Object.keys?Object.keys:function(e){var t,n=[];for(t in e)a(e,t)&&n.push(t);return n};var A={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"};function P(e,t,n){var r=this._calendar[e]||this._calendar.sameElse;return $(r)?r.call(t,n):r}function D(e,t,n){var r=""+Math.abs(e),i=t-r.length;return(e>=0?n?"+":"":"-")+Math.pow(10,Math.max(0,i)).toString().substr(1)+r}var L=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,j=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,R={},F={};function B(e,t,n,r){var i=r;"string"==typeof r&&(i=function(){return this[r]()}),e&&(F[e]=i),t&&(F[t[0]]=function(){return D(i.apply(this,arguments),t[1],t[2])}),n&&(F[n]=function(){return this.localeData().ordinal(i.apply(this,arguments),e)})}function U(e){return e.match(/\[[\s\S]/)?e.replace(/^\[|\]$/g,""):e.replace(/\\/g,"")}function W(e){var t,n,r=e.match(L);for(t=0,n=r.length;t<n;t++)F[r[t]]?r[t]=F[r[t]]:r[t]=U(r[t]);return function(t){var i,s="";for(i=0;i<n;i++)s+=$(r[i])?r[i].call(t,e):r[i];return s}}function Y(e,t){return e.isValid()?(t=G(t,e.localeData()),R[t]=R[t]||W(t),R[t](e)):e.localeData().invalidDate()}function G(e,t){var n=5;function r(e){return t.longDateFormat(e)||e}for(j.lastIndex=0;n>=0&&j.test(e);)e=e.replace(j,r),j.lastIndex=0,n-=1;return e}var H={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"};function V(e){var t=this._longDateFormat[e],n=this._longDateFormat[e.toUpperCase()];return t||!n?t:(this._longDateFormat[e]=n.match(L).map((function(e){return"MMMM"===e||"MM"===e||"DD"===e||"dddd"===e?e.slice(1):e})).join(""),this._longDateFormat[e])}var z="Invalid date";function q(){return this._invalidDate}var J="%d",K=/\d{1,2}/;function Z(e){return this._ordinal.replace("%d",e)}var X={future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",w:"a week",ww:"%d weeks",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function Q(e,t,n,r){var i=this._relativeTime[n];return $(i)?i(e,t,n,r):i.replace(/%d/i,e)}function ee(e,t){var n=this._relativeTime[e>0?"future":"past"];return $(n)?n(t):n.replace(/%s/i,t)}var te={D:"date",dates:"date",date:"date",d:"day",days:"day",day:"day",e:"weekday",weekdays:"weekday",weekday:"weekday",E:"isoWeekday",isoweekdays:"isoWeekday",isoweekday:"isoWeekday",DDD:"dayOfYear",dayofyears:"dayOfYear",dayofyear:"dayOfYear",h:"hour",hours:"hour",hour:"hour",ms:"millisecond",milliseconds:"millisecond",millisecond:"millisecond",m:"minute",minutes:"minute",minute:"minute",M:"month",months:"month",month:"month",Q:"quarter",quarters:"quarter",quarter:"quarter",s:"second",seconds:"second",second:"second",gg:"weekYear",weekyears:"weekYear",weekyear:"weekYear",GG:"isoWeekYear",isoweekyears:"isoWeekYear",isoweekyear:"isoWeekYear",w:"week",weeks:"week",week:"week",W:"isoWeek",isoweeks:"isoWeek",isoweek:"isoWeek",y:"year",years:"year",year:"year"};function ne(e){return"string"==typeof e?te[e]||te[e.toLowerCase()]:void 0}function re(e){var t,n,r={};for(n in e)a(e,n)&&(t=ne(n))&&(r[t]=e[n]);return r}var ie={date:9,day:11,weekday:11,isoWeekday:11,dayOfYear:4,hour:13,millisecond:16,minute:14,month:8,quarter:7,second:15,weekYear:1,isoWeekYear:1,week:5,isoWeek:5,year:1};function se(e){var t,n=[];for(t in e)a(e,t)&&n.push({unit:t,priority:ie[t]});return n.sort((function(e,t){return e.priority-t.priority})),n}var oe,ae=/\d/,ce=/\d\d/,le=/\d{3}/,ue=/\d{4}/,de=/[+-]?\d{6}/,he=/\d\d?/,fe=/\d\d\d\d?/,pe=/\d\d\d\d\d\d?/,ge=/\d{1,3}/,me=/\d{1,4}/,ye=/[+-]?\d{1,6}/,ve=/\d+/,be=/[+-]?\d+/,we=/Z|[+-]\d\d:?\d\d/gi,Se=/Z|[+-]\d\d(?::?\d\d)?/gi,_e=/[+-]?\d+(\.\d{1,3})?/,Ie=/[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i,xe=/^[1-9]\d?/,ke=/^([1-9]\d|\d)/;function Ee(e,t,n){oe[e]=$(t)?t:function(e){return e&&n?n:t}}function Ce(e,t){return a(oe,e)?oe[e](t._strict,t._locale):new RegExp(Oe(e))}function Oe(e){return $e(e.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,(function(e,t,n,r,i){return t||n||r||i})))}function $e(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function Me(e){return e<0?Math.ceil(e)||0:Math.floor(e)}function Ne(e){var t=+e,n=0;return 0!==t&&isFinite(t)&&(n=Me(t)),n}oe={};var Te={};function Ae(e,t){var n,r,i=t;for("string"==typeof e&&(e=[e]),u(t)&&(i=function(e,n){n[t]=Ne(e)}),r=e.length,n=0;n<r;n++)Te[e[n]]=i}function Pe(e,t){Ae(e,(function(e,n,r,i){r._w=r._w||{},t(e,r._w,r,i)}))}function De(e,t,n){null!=t&&a(Te,e)&&Te[e](t,n._a,n,e)}function Le(e){return e%4==0&&e%100!=0||e%400==0}var je=0,Re=1,Fe=2,Be=3,Ue=4,We=5,Ye=6,Ge=7,He=8;function Ve(e){return Le(e)?366:365}B("Y",0,0,(function(){var e=this.year();return e<=9999?D(e,4):"+"+e})),B(0,["YY",2],0,(function(){return this.year()%100})),B(0,["YYYY",4],0,"year"),B(0,["YYYYY",5],0,"year"),B(0,["YYYYYY",6,!0],0,"year"),Ee("Y",be),Ee("YY",he,ce),Ee("YYYY",me,ue),Ee("YYYYY",ye,de),Ee("YYYYYY",ye,de),Ae(["YYYYY","YYYYYY"],je),Ae("YYYY",(function(e,t){t[je]=2===e.length?r.parseTwoDigitYear(e):Ne(e)})),Ae("YY",(function(e,t){t[je]=r.parseTwoDigitYear(e)})),Ae("Y",(function(e,t){t[je]=parseInt(e,10)})),r.parseTwoDigitYear=function(e){return Ne(e)+(Ne(e)>68?1900:2e3)};var ze,qe=Ke("FullYear",!0);function Je(){return Le(this.year())}function Ke(e,t){return function(n){return null!=n?(Xe(this,e,n),r.updateOffset(this,t),this):Ze(this,e)}}function Ze(e,t){if(!e.isValid())return NaN;var n=e._d,r=e._isUTC;switch(t){case"Milliseconds":return r?n.getUTCMilliseconds():n.getMilliseconds();case"Seconds":return r?n.getUTCSeconds():n.getSeconds();case"Minutes":return r?n.getUTCMinutes():n.getMinutes();case"Hours":return r?n.getUTCHours():n.getHours();case"Date":return r?n.getUTCDate():n.getDate();case"Day":return r?n.getUTCDay():n.getDay();case"Month":return r?n.getUTCMonth():n.getMonth();case"FullYear":return r?n.getUTCFullYear():n.getFullYear();default:return NaN}}function Xe(e,t,n){var r,i,s,o,a;if(e.isValid()&&!isNaN(n)){switch(r=e._d,i=e._isUTC,t){case"Milliseconds":return void(i?r.setUTCMilliseconds(n):r.setMilliseconds(n));case"Seconds":return void(i?r.setUTCSeconds(n):r.setSeconds(n));case"Minutes":return void(i?r.setUTCMinutes(n):r.setMinutes(n));case"Hours":return void(i?r.setUTCHours(n):r.setHours(n));case"Date":return void(i?r.setUTCDate(n):r.setDate(n));case"FullYear":break;default:return}s=n,o=e.month(),a=29!==(a=e.date())||1!==o||Le(s)?a:28,i?r.setUTCFullYear(s,o,a):r.setFullYear(s,o,a)}}function Qe(e){return $(this[e=ne(e)])?this[e]():this}function et(e,t){if("object"==typeof e){var n,r=se(e=re(e)),i=r.length;for(n=0;n<i;n++)this[r[n].unit](e[r[n].unit])}else if($(this[e=ne(e)]))return this[e](t);return this}function tt(e,t){return(e%t+t)%t}function nt(e,t){if(isNaN(e)||isNaN(t))return NaN;var n=tt(t,12);return e+=(t-n)/12,1===n?Le(e)?29:28:31-n%7%2}ze=Array.prototype.indexOf?Array.prototype.indexOf:function(e){var t;for(t=0;t<this.length;++t)if(this[t]===e)return t;return-1},B("M",["MM",2],"Mo",(function(){return this.month()+1})),B("MMM",0,0,(function(e){return this.localeData().monthsShort(this,e)})),B("MMMM",0,0,(function(e){return this.localeData().months(this,e)})),Ee("M",he,xe),Ee("MM",he,ce),Ee("MMM",(function(e,t){return t.monthsShortRegex(e)})),Ee("MMMM",(function(e,t){return t.monthsRegex(e)})),Ae(["M","MM"],(function(e,t){t[Re]=Ne(e)-1})),Ae(["MMM","MMMM"],(function(e,t,n,r){var i=n._locale.monthsParse(e,r,n._strict);null!=i?t[Re]=i:m(n).invalidMonth=e}));var rt="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),it="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),st=/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,ot=Ie,at=Ie;function ct(e,t){return e?s(this._months)?this._months[e.month()]:this._months[(this._months.isFormat||st).test(t)?"format":"standalone"][e.month()]:s(this._months)?this._months:this._months.standalone}function lt(e,t){return e?s(this._monthsShort)?this._monthsShort[e.month()]:this._monthsShort[st.test(t)?"format":"standalone"][e.month()]:s(this._monthsShort)?this._monthsShort:this._monthsShort.standalone}function ut(e,t,n){var r,i,s,o=e.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],r=0;r<12;++r)s=p([2e3,r]),this._shortMonthsParse[r]=this.monthsShort(s,"").toLocaleLowerCase(),this._longMonthsParse[r]=this.months(s,"").toLocaleLowerCase();return n?"MMM"===t?-1!==(i=ze.call(this._shortMonthsParse,o))?i:null:-1!==(i=ze.call(this._longMonthsParse,o))?i:null:"MMM"===t?-1!==(i=ze.call(this._shortMonthsParse,o))||-1!==(i=ze.call(this._longMonthsParse,o))?i:null:-1!==(i=ze.call(this._longMonthsParse,o))||-1!==(i=ze.call(this._shortMonthsParse,o))?i:null}function dt(e,t,n){var r,i,s;if(this._monthsParseExact)return ut.call(this,e,t,n);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),r=0;r<12;r++){if(i=p([2e3,r]),n&&!this._longMonthsParse[r]&&(this._longMonthsParse[r]=new RegExp("^"+this.months(i,"").replace(".","")+"$","i"),this._shortMonthsParse[r]=new RegExp("^"+this.monthsShort(i,"").replace(".","")+"$","i")),n||this._monthsParse[r]||(s="^"+this.months(i,"")+"|^"+this.monthsShort(i,""),this._monthsParse[r]=new RegExp(s.replace(".",""),"i")),n&&"MMMM"===t&&this._longMonthsParse[r].test(e))return r;if(n&&"MMM"===t&&this._shortMonthsParse[r].test(e))return r;if(!n&&this._monthsParse[r].test(e))return r}}function ht(e,t){if(!e.isValid())return e;if("string"==typeof t)if(/^\d+$/.test(t))t=Ne(t);else if(!u(t=e.localeData().monthsParse(t)))return e;var n=t,r=e.date();return r=r<29?r:Math.min(r,nt(e.year(),n)),e._isUTC?e._d.setUTCMonth(n,r):e._d.setMonth(n,r),e}function ft(e){return null!=e?(ht(this,e),r.updateOffset(this,!0),this):Ze(this,"Month")}function pt(){return nt(this.year(),this.month())}function gt(e){return this._monthsParseExact?(a(this,"_monthsRegex")||yt.call(this),e?this._monthsShortStrictRegex:this._monthsShortRegex):(a(this,"_monthsShortRegex")||(this._monthsShortRegex=ot),this._monthsShortStrictRegex&&e?this._monthsShortStrictRegex:this._monthsShortRegex)}function mt(e){return this._monthsParseExact?(a(this,"_monthsRegex")||yt.call(this),e?this._monthsStrictRegex:this._monthsRegex):(a(this,"_monthsRegex")||(this._monthsRegex=at),this._monthsStrictRegex&&e?this._monthsStrictRegex:this._monthsRegex)}function yt(){function e(e,t){return t.length-e.length}var t,n,r,i,s=[],o=[],a=[];for(t=0;t<12;t++)n=p([2e3,t]),r=$e(this.monthsShort(n,"")),i=$e(this.months(n,"")),s.push(r),o.push(i),a.push(i),a.push(r);s.sort(e),o.sort(e),a.sort(e),this._monthsRegex=new RegExp("^("+a.join("|")+")","i"),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=new RegExp("^("+o.join("|")+")","i"),this._monthsShortStrictRegex=new RegExp("^("+s.join("|")+")","i")}function vt(e,t,n,r,i,s,o){var a;return e<100&&e>=0?(a=new Date(e+400,t,n,r,i,s,o),isFinite(a.getFullYear())&&a.setFullYear(e)):a=new Date(e,t,n,r,i,s,o),a}function bt(e){var t,n;return e<100&&e>=0?((n=Array.prototype.slice.call(arguments))[0]=e+400,t=new Date(Date.UTC.apply(null,n)),isFinite(t.getUTCFullYear())&&t.setUTCFullYear(e)):t=new Date(Date.UTC.apply(null,arguments)),t}function wt(e,t,n){var r=7+t-n;return-(7+bt(e,0,r).getUTCDay()-t)%7+r-1}function St(e,t,n,r,i){var s,o,a=1+7*(t-1)+(7+n-r)%7+wt(e,r,i);return a<=0?o=Ve(s=e-1)+a:a>Ve(e)?(s=e+1,o=a-Ve(e)):(s=e,o=a),{year:s,dayOfYear:o}}function _t(e,t,n){var r,i,s=wt(e.year(),t,n),o=Math.floor((e.dayOfYear()-s-1)/7)+1;return o<1?r=o+It(i=e.year()-1,t,n):o>It(e.year(),t,n)?(r=o-It(e.year(),t,n),i=e.year()+1):(i=e.year(),r=o),{week:r,year:i}}function It(e,t,n){var r=wt(e,t,n),i=wt(e+1,t,n);return(Ve(e)-r+i)/7}function xt(e){return _t(e,this._week.dow,this._week.doy).week}B("w",["ww",2],"wo","week"),B("W",["WW",2],"Wo","isoWeek"),Ee("w",he,xe),Ee("ww",he,ce),Ee("W",he,xe),Ee("WW",he,ce),Pe(["w","ww","W","WW"],(function(e,t,n,r){t[r.substr(0,1)]=Ne(e)}));var kt={dow:0,doy:6};function Et(){return this._week.dow}function Ct(){return this._week.doy}function Ot(e){var t=this.localeData().week(this);return null==e?t:this.add(7*(e-t),"d")}function $t(e){var t=_t(this,1,4).week;return null==e?t:this.add(7*(e-t),"d")}function Mt(e,t){return"string"!=typeof e?e:isNaN(e)?"number"==typeof(e=t.weekdaysParse(e))?e:null:parseInt(e,10)}function Nt(e,t){return"string"==typeof e?t.weekdaysParse(e)%7||7:isNaN(e)?null:e}function Tt(e,t){return e.slice(t,7).concat(e.slice(0,t))}B("d",0,"do","day"),B("dd",0,0,(function(e){return this.localeData().weekdaysMin(this,e)})),B("ddd",0,0,(function(e){return this.localeData().weekdaysShort(this,e)})),B("dddd",0,0,(function(e){return this.localeData().weekdays(this,e)})),B("e",0,0,"weekday"),B("E",0,0,"isoWeekday"),Ee("d",he),Ee("e",he),Ee("E",he),Ee("dd",(function(e,t){return t.weekdaysMinRegex(e)})),Ee("ddd",(function(e,t){return t.weekdaysShortRegex(e)})),Ee("dddd",(function(e,t){return t.weekdaysRegex(e)})),Pe(["dd","ddd","dddd"],(function(e,t,n,r){var i=n._locale.weekdaysParse(e,r,n._strict);null!=i?t.d=i:m(n).invalidWeekday=e})),Pe(["d","e","E"],(function(e,t,n,r){t[r]=Ne(e)}));var At="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),Pt="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),Dt="Su_Mo_Tu_We_Th_Fr_Sa".split("_"),Lt=Ie,jt=Ie,Rt=Ie;function Ft(e,t){var n=s(this._weekdays)?this._weekdays:this._weekdays[e&&!0!==e&&this._weekdays.isFormat.test(t)?"format":"standalone"];return!0===e?Tt(n,this._week.dow):e?n[e.day()]:n}function Bt(e){return!0===e?Tt(this._weekdaysShort,this._week.dow):e?this._weekdaysShort[e.day()]:this._weekdaysShort}function Ut(e){return!0===e?Tt(this._weekdaysMin,this._week.dow):e?this._weekdaysMin[e.day()]:this._weekdaysMin}function Wt(e,t,n){var r,i,s,o=e.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],r=0;r<7;++r)s=p([2e3,1]).day(r),this._minWeekdaysParse[r]=this.weekdaysMin(s,"").toLocaleLowerCase(),this._shortWeekdaysParse[r]=this.weekdaysShort(s,"").toLocaleLowerCase(),this._weekdaysParse[r]=this.weekdays(s,"").toLocaleLowerCase();return n?"dddd"===t?-1!==(i=ze.call(this._weekdaysParse,o))?i:null:"ddd"===t?-1!==(i=ze.call(this._shortWeekdaysParse,o))?i:null:-1!==(i=ze.call(this._minWeekdaysParse,o))?i:null:"dddd"===t?-1!==(i=ze.call(this._weekdaysParse,o))||-1!==(i=ze.call(this._shortWeekdaysParse,o))||-1!==(i=ze.call(this._minWeekdaysParse,o))?i:null:"ddd"===t?-1!==(i=ze.call(this._shortWeekdaysParse,o))||-1!==(i=ze.call(this._weekdaysParse,o))||-1!==(i=ze.call(this._minWeekdaysParse,o))?i:null:-1!==(i=ze.call(this._minWeekdaysParse,o))||-1!==(i=ze.call(this._weekdaysParse,o))||-1!==(i=ze.call(this._shortWeekdaysParse,o))?i:null}function Yt(e,t,n){var r,i,s;if(this._weekdaysParseExact)return Wt.call(this,e,t,n);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),r=0;r<7;r++){if(i=p([2e3,1]).day(r),n&&!this._fullWeekdaysParse[r]&&(this._fullWeekdaysParse[r]=new RegExp("^"+this.weekdays(i,"").replace(".","\\.?")+"$","i"),this._shortWeekdaysParse[r]=new RegExp("^"+this.weekdaysShort(i,"").replace(".","\\.?")+"$","i"),this._minWeekdaysParse[r]=new RegExp("^"+this.weekdaysMin(i,"").replace(".","\\.?")+"$","i")),this._weekdaysParse[r]||(s="^"+this.weekdays(i,"")+"|^"+this.weekdaysShort(i,"")+"|^"+this.weekdaysMin(i,""),this._weekdaysParse[r]=new RegExp(s.replace(".",""),"i")),n&&"dddd"===t&&this._fullWeekdaysParse[r].test(e))return r;if(n&&"ddd"===t&&this._shortWeekdaysParse[r].test(e))return r;if(n&&"dd"===t&&this._minWeekdaysParse[r].test(e))return r;if(!n&&this._weekdaysParse[r].test(e))return r}}function Gt(e){if(!this.isValid())return null!=e?this:NaN;var t=Ze(this,"Day");return null!=e?(e=Mt(e,this.localeData()),this.add(e-t,"d")):t}function Ht(e){if(!this.isValid())return null!=e?this:NaN;var t=(this.day()+7-this.localeData()._week.dow)%7;return null==e?t:this.add(e-t,"d")}function Vt(e){if(!this.isValid())return null!=e?this:NaN;if(null!=e){var t=Nt(e,this.localeData());return this.day(this.day()%7?t:t-7)}return this.day()||7}function zt(e){return this._weekdaysParseExact?(a(this,"_weekdaysRegex")||Kt.call(this),e?this._weekdaysStrictRegex:this._weekdaysRegex):(a(this,"_weekdaysRegex")||(this._weekdaysRegex=Lt),this._weekdaysStrictRegex&&e?this._weekdaysStrictRegex:this._weekdaysRegex)}function qt(e){return this._weekdaysParseExact?(a(this,"_weekdaysRegex")||Kt.call(this),e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(a(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=jt),this._weekdaysShortStrictRegex&&e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)}function Jt(e){return this._weekdaysParseExact?(a(this,"_weekdaysRegex")||Kt.call(this),e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(a(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=Rt),this._weekdaysMinStrictRegex&&e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)}function Kt(){function e(e,t){return t.length-e.length}var t,n,r,i,s,o=[],a=[],c=[],l=[];for(t=0;t<7;t++)n=p([2e3,1]).day(t),r=$e(this.weekdaysMin(n,"")),i=$e(this.weekdaysShort(n,"")),s=$e(this.weekdays(n,"")),o.push(r),a.push(i),c.push(s),l.push(r),l.push(i),l.push(s);o.sort(e),a.sort(e),c.sort(e),l.sort(e),this._weekdaysRegex=new RegExp("^("+l.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+c.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+a.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+o.join("|")+")","i")}function Zt(){return this.hours()%12||12}function Xt(){return this.hours()||24}function Qt(e,t){B(e,0,0,(function(){return this.localeData().meridiem(this.hours(),this.minutes(),t)}))}function en(e,t){return t._meridiemParse}function tn(e){return"p"===(e+"").toLowerCase().charAt(0)}B("H",["HH",2],0,"hour"),B("h",["hh",2],0,Zt),B("k",["kk",2],0,Xt),B("hmm",0,0,(function(){return""+Zt.apply(this)+D(this.minutes(),2)})),B("hmmss",0,0,(function(){return""+Zt.apply(this)+D(this.minutes(),2)+D(this.seconds(),2)})),B("Hmm",0,0,(function(){return""+this.hours()+D(this.minutes(),2)})),B("Hmmss",0,0,(function(){return""+this.hours()+D(this.minutes(),2)+D(this.seconds(),2)})),Qt("a",!0),Qt("A",!1),Ee("a",en),Ee("A",en),Ee("H",he,ke),Ee("h",he,xe),Ee("k",he,xe),Ee("HH",he,ce),Ee("hh",he,ce),Ee("kk",he,ce),Ee("hmm",fe),Ee("hmmss",pe),Ee("Hmm",fe),Ee("Hmmss",pe),Ae(["H","HH"],Be),Ae(["k","kk"],(function(e,t){var n=Ne(e);t[Be]=24===n?0:n})),Ae(["a","A"],(function(e,t,n){n._isPm=n._locale.isPM(e),n._meridiem=e})),Ae(["h","hh"],(function(e,t,n){t[Be]=Ne(e),m(n).bigHour=!0})),Ae("hmm",(function(e,t,n){var r=e.length-2;t[Be]=Ne(e.substr(0,r)),t[Ue]=Ne(e.substr(r)),m(n).bigHour=!0})),Ae("hmmss",(function(e,t,n){var r=e.length-4,i=e.length-2;t[Be]=Ne(e.substr(0,r)),t[Ue]=Ne(e.substr(r,2)),t[We]=Ne(e.substr(i)),m(n).bigHour=!0})),Ae("Hmm",(function(e,t){var n=e.length-2;t[Be]=Ne(e.substr(0,n)),t[Ue]=Ne(e.substr(n))})),Ae("Hmmss",(function(e,t){var n=e.length-4,r=e.length-2;t[Be]=Ne(e.substr(0,n)),t[Ue]=Ne(e.substr(n,2)),t[We]=Ne(e.substr(r))}));var nn=/[ap]\.?m?\.?/i,rn=Ke("Hours",!0);function sn(e,t,n){return e>11?n?"pm":"PM":n?"am":"AM"}var on,an={calendar:A,longDateFormat:H,invalidDate:z,ordinal:J,dayOfMonthOrdinalParse:K,relativeTime:X,months:rt,monthsShort:it,week:kt,weekdays:At,weekdaysMin:Dt,weekdaysShort:Pt,meridiemParse:nn},cn={},ln={};function un(e,t){var n,r=Math.min(e.length,t.length);for(n=0;n<r;n+=1)if(e[n]!==t[n])return n;return r}function dn(e){return e?e.toLowerCase().replace("_","-"):e}function hn(e){for(var t,n,r,i,s=0;s<e.length;){for(t=(i=dn(e[s]).split("-")).length,n=(n=dn(e[s+1]))?n.split("-"):null;t>0;){if(r=pn(i.slice(0,t).join("-")))return r;if(n&&n.length>=t&&un(i,n)>=t-1)break;t--}s++}return on}function fn(e){return!(!e||!e.match("^[^/\\\\]*$"))}function pn(t){var n=null;if(void 0===cn[t]&&e&&e.exports&&fn(t))try{n=on._abbr,Yg("./locale/"+t),gn(n)}catch(e){cn[t]=null}return cn[t]}function gn(e,t){var n;return e&&((n=l(t)?vn(e):mn(e,t))?on=n:"undefined"!=typeof console&&console.warn&&console.warn("Locale "+e+" not found. Did you forget to load it?")),on._abbr}function mn(e,t){if(null!==t){var n,r=an;if(t.abbr=e,null!=cn[e])O("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."),r=cn[e]._config;else if(null!=t.parentLocale)if(null!=cn[t.parentLocale])r=cn[t.parentLocale]._config;else{if(null==(n=pn(t.parentLocale)))return ln[t.parentLocale]||(ln[t.parentLocale]=[]),ln[t.parentLocale].push({name:e,config:t}),null;r=n._config}return cn[e]=new T(N(r,t)),ln[e]&&ln[e].forEach((function(e){mn(e.name,e.config)})),gn(e),cn[e]}return delete cn[e],null}function yn(e,t){if(null!=t){var n,r,i=an;null!=cn[e]&&null!=cn[e].parentLocale?cn[e].set(N(cn[e]._config,t)):(null!=(r=pn(e))&&(i=r._config),t=N(i,t),null==r&&(t.abbr=e),(n=new T(t)).parentLocale=cn[e],cn[e]=n),gn(e)}else null!=cn[e]&&(null!=cn[e].parentLocale?(cn[e]=cn[e].parentLocale,e===gn()&&gn(e)):null!=cn[e]&&delete cn[e]);return cn[e]}function vn(e){var t;if(e&&e._locale&&e._locale._abbr&&(e=e._locale._abbr),!e)return on;if(!s(e)){if(t=pn(e))return t;e=[e]}return hn(e)}function bn(){return E(cn)}function wn(e){var t,n=e._a;return n&&-2===m(e).overflow&&(t=n[Re]<0||n[Re]>11?Re:n[Fe]<1||n[Fe]>nt(n[je],n[Re])?Fe:n[Be]<0||n[Be]>24||24===n[Be]&&(0!==n[Ue]||0!==n[We]||0!==n[Ye])?Be:n[Ue]<0||n[Ue]>59?Ue:n[We]<0||n[We]>59?We:n[Ye]<0||n[Ye]>999?Ye:-1,m(e)._overflowDayOfYear&&(t<je||t>Fe)&&(t=Fe),m(e)._overflowWeeks&&-1===t&&(t=Ge),m(e)._overflowWeekday&&-1===t&&(t=He),m(e).overflow=t),e}var Sn=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,_n=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,In=/Z|[+-]\d\d(?::?\d\d)?/,xn=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,!1],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,!1],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,!1],["YYYYDDD",/\d{7}/],["YYYYMM",/\d{6}/,!1],["YYYY",/\d{4}/,!1]],kn=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]],En=/^\/?Date\((-?\d+)/i,Cn=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/,On={UT:0,GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function $n(e){var t,n,r,i,s,o,a=e._i,c=Sn.exec(a)||_n.exec(a),l=xn.length,u=kn.length;if(c){for(m(e).iso=!0,t=0,n=l;t<n;t++)if(xn[t][1].exec(c[1])){i=xn[t][0],r=!1!==xn[t][2];break}if(null==i)return void(e._isValid=!1);if(c[3]){for(t=0,n=u;t<n;t++)if(kn[t][1].exec(c[3])){s=(c[2]||" ")+kn[t][0];break}if(null==s)return void(e._isValid=!1)}if(!r&&null!=s)return void(e._isValid=!1);if(c[4]){if(!In.exec(c[4]))return void(e._isValid=!1);o="Z"}e._f=i+(s||"")+(o||""),Un(e)}else e._isValid=!1}function Mn(e,t,n,r,i,s){var o=[Nn(e),it.indexOf(t),parseInt(n,10),parseInt(r,10),parseInt(i,10)];return s&&o.push(parseInt(s,10)),o}function Nn(e){var t=parseInt(e,10);return t<=49?2e3+t:t<=999?1900+t:t}function Tn(e){return e.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").replace(/^\s\s*/,"").replace(/\s\s*$/,"")}function An(e,t,n){return!e||Pt.indexOf(e)===new Date(t[0],t[1],t[2]).getDay()||(m(n).weekdayMismatch=!0,n._isValid=!1,!1)}function Pn(e,t,n){if(e)return On[e];if(t)return 0;var r=parseInt(n,10),i=r%100;return(r-i)/100*60+i}function Dn(e){var t,n=Cn.exec(Tn(e._i));if(n){if(t=Mn(n[4],n[3],n[2],n[5],n[6],n[7]),!An(n[1],t,e))return;e._a=t,e._tzm=Pn(n[8],n[9],n[10]),e._d=bt.apply(null,e._a),e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),m(e).rfc2822=!0}else e._isValid=!1}function Ln(e){var t=En.exec(e._i);null===t?($n(e),!1===e._isValid&&(delete e._isValid,Dn(e),!1===e._isValid&&(delete e._isValid,e._strict?e._isValid=!1:r.createFromInputFallback(e)))):e._d=new Date(+t[1])}function jn(e,t,n){return null!=e?e:null!=t?t:n}function Rn(e){var t=new Date(r.now());return e._useUTC?[t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()]:[t.getFullYear(),t.getMonth(),t.getDate()]}function Fn(e){var t,n,r,i,s,o=[];if(!e._d){for(r=Rn(e),e._w&&null==e._a[Fe]&&null==e._a[Re]&&Bn(e),null!=e._dayOfYear&&(s=jn(e._a[je],r[je]),(e._dayOfYear>Ve(s)||0===e._dayOfYear)&&(m(e)._overflowDayOfYear=!0),n=bt(s,0,e._dayOfYear),e._a[Re]=n.getUTCMonth(),e._a[Fe]=n.getUTCDate()),t=0;t<3&&null==e._a[t];++t)e._a[t]=o[t]=r[t];for(;t<7;t++)e._a[t]=o[t]=null==e._a[t]?2===t?1:0:e._a[t];24===e._a[Be]&&0===e._a[Ue]&&0===e._a[We]&&0===e._a[Ye]&&(e._nextDay=!0,e._a[Be]=0),e._d=(e._useUTC?bt:vt).apply(null,o),i=e._useUTC?e._d.getUTCDay():e._d.getDay(),null!=e._tzm&&e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),e._nextDay&&(e._a[Be]=24),e._w&&void 0!==e._w.d&&e._w.d!==i&&(m(e).weekdayMismatch=!0)}}function Bn(e){var t,n,r,i,s,o,a,c,l;null!=(t=e._w).GG||null!=t.W||null!=t.E?(s=1,o=4,n=jn(t.GG,e._a[je],_t(Jn(),1,4).year),r=jn(t.W,1),((i=jn(t.E,1))<1||i>7)&&(c=!0)):(s=e._locale._week.dow,o=e._locale._week.doy,l=_t(Jn(),s,o),n=jn(t.gg,e._a[je],l.year),r=jn(t.w,l.week),null!=t.d?((i=t.d)<0||i>6)&&(c=!0):null!=t.e?(i=t.e+s,(t.e<0||t.e>6)&&(c=!0)):i=s),r<1||r>It(n,s,o)?m(e)._overflowWeeks=!0:null!=c?m(e)._overflowWeekday=!0:(a=St(n,r,i,s,o),e._a[je]=a.year,e._dayOfYear=a.dayOfYear)}function Un(e){if(e._f!==r.ISO_8601)if(e._f!==r.RFC_2822){e._a=[],m(e).empty=!0;var t,n,i,s,o,a,c,l=""+e._i,u=l.length,d=0;for(c=(i=G(e._f,e._locale).match(L)||[]).length,t=0;t<c;t++)s=i[t],(n=(l.match(Ce(s,e))||[])[0])&&((o=l.substr(0,l.indexOf(n))).length>0&&m(e).unusedInput.push(o),l=l.slice(l.indexOf(n)+n.length),d+=n.length),F[s]?(n?m(e).empty=!1:m(e).unusedTokens.push(s),De(s,n,e)):e._strict&&!n&&m(e).unusedTokens.push(s);m(e).charsLeftOver=u-d,l.length>0&&m(e).unusedInput.push(l),e._a[Be]<=12&&!0===m(e).bigHour&&e._a[Be]>0&&(m(e).bigHour=void 0),m(e).parsedDateParts=e._a.slice(0),m(e).meridiem=e._meridiem,e._a[Be]=Wn(e._locale,e._a[Be],e._meridiem),null!==(a=m(e).era)&&(e._a[je]=e._locale.erasConvertYear(a,e._a[je])),Fn(e),wn(e)}else Dn(e);else $n(e)}function Wn(e,t,n){var r;return null==n?t:null!=e.meridiemHour?e.meridiemHour(t,n):null!=e.isPM?((r=e.isPM(n))&&t<12&&(t+=12),r||12!==t||(t=0),t):t}function Yn(e){var t,n,r,i,s,o,a=!1,c=e._f.length;if(0===c)return m(e).invalidFormat=!0,void(e._d=new Date(NaN));for(i=0;i<c;i++)s=0,o=!1,t=S({},e),null!=e._useUTC&&(t._useUTC=e._useUTC),t._f=e._f[i],Un(t),y(t)&&(o=!0),s+=m(t).charsLeftOver,s+=10*m(t).unusedTokens.length,m(t).score=s,a?s<r&&(r=s,n=t):(null==r||s<r||o)&&(r=s,n=t,o&&(a=!0));f(e,n||t)}function Gn(e){if(!e._d){var t=re(e._i),n=void 0===t.day?t.date:t.day;e._a=h([t.year,t.month,n,t.hour,t.minute,t.second,t.millisecond],(function(e){return e&&parseInt(e,10)})),Fn(e)}}function Hn(e){var t=new _(wn(Vn(e)));return t._nextDay&&(t.add(1,"d"),t._nextDay=void 0),t}function Vn(e){var t=e._i,n=e._f;return e._locale=e._locale||vn(e._l),null===t||void 0===n&&""===t?v({nullInput:!0}):("string"==typeof t&&(e._i=t=e._locale.preparse(t)),I(t)?new _(wn(t)):(d(t)?e._d=t:s(n)?Yn(e):n?Un(e):zn(e),y(e)||(e._d=null),e))}function zn(e){var t=e._i;l(t)?e._d=new Date(r.now()):d(t)?e._d=new Date(t.valueOf()):"string"==typeof t?Ln(e):s(t)?(e._a=h(t.slice(0),(function(e){return parseInt(e,10)})),Fn(e)):o(t)?Gn(e):u(t)?e._d=new Date(t):r.createFromInputFallback(e)}function qn(e,t,n,r,i){var a={};return!0!==t&&!1!==t||(r=t,t=void 0),!0!==n&&!1!==n||(r=n,n=void 0),(o(e)&&c(e)||s(e)&&0===e.length)&&(e=void 0),a._isAMomentObject=!0,a._useUTC=a._isUTC=i,a._l=n,a._i=e,a._f=t,a._strict=r,Hn(a)}function Jn(e,t,n,r){return qn(e,t,n,r,!1)}r.createFromInputFallback=k("value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.",(function(e){e._d=new Date(e._i+(e._useUTC?" UTC":""))})),r.ISO_8601=function(){},r.RFC_2822=function(){};var Kn=k("moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/",(function(){var e=Jn.apply(null,arguments);return this.isValid()&&e.isValid()?e<this?this:e:v()})),Zn=k("moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/",(function(){var e=Jn.apply(null,arguments);return this.isValid()&&e.isValid()?e>this?this:e:v()}));function Xn(e,t){var n,r;if(1===t.length&&s(t[0])&&(t=t[0]),!t.length)return Jn();for(n=t[0],r=1;r<t.length;++r)t[r].isValid()&&!t[r][e](n)||(n=t[r]);return n}function Qn(){return Xn("isBefore",[].slice.call(arguments,0))}function er(){return Xn("isAfter",[].slice.call(arguments,0))}var tr=function(){return Date.now?Date.now():+new Date},nr=["year","quarter","month","week","day","hour","minute","second","millisecond"];function rr(e){var t,n,r=!1,i=nr.length;for(t in e)if(a(e,t)&&(-1===ze.call(nr,t)||null!=e[t]&&isNaN(e[t])))return!1;for(n=0;n<i;++n)if(e[nr[n]]){if(r)return!1;parseFloat(e[nr[n]])!==Ne(e[nr[n]])&&(r=!0)}return!0}function ir(){return this._isValid}function sr(){return Or(NaN)}function or(e){var t=re(e),n=t.year||0,r=t.quarter||0,i=t.month||0,s=t.week||t.isoWeek||0,o=t.day||0,a=t.hour||0,c=t.minute||0,l=t.second||0,u=t.millisecond||0;this._isValid=rr(t),this._milliseconds=+u+1e3*l+6e4*c+1e3*a*60*60,this._days=+o+7*s,this._months=+i+3*r+12*n,this._data={},this._locale=vn(),this._bubble()}function ar(e){return e instanceof or}function cr(e){return e<0?-1*Math.round(-1*e):Math.round(e)}function lr(e,t){var n,r=Math.min(e.length,t.length),i=Math.abs(e.length-t.length),s=0;for(n=0;n<r;n++)Ne(e[n])!==Ne(t[n])&&s++;return s+i}function ur(e,t){B(e,0,0,(function(){var e=this.utcOffset(),n="+";return e<0&&(e=-e,n="-"),n+D(~~(e/60),2)+t+D(~~e%60,2)}))}ur("Z",":"),ur("ZZ",""),Ee("Z",Se),Ee("ZZ",Se),Ae(["Z","ZZ"],(function(e,t,n){n._useUTC=!0,n._tzm=hr(Se,e)}));var dr=/([\+\-]|\d\d)/gi;function hr(e,t){var n,r,i=(t||"").match(e);return null===i?null:0===(r=60*(n=((i[i.length-1]||[])+"").match(dr)||["-",0,0])[1]+Ne(n[2]))?0:"+"===n[0]?r:-r}function fr(e,t){var n,i;return t._isUTC?(n=t.clone(),i=(I(e)||d(e)?e.valueOf():Jn(e).valueOf())-n.valueOf(),n._d.setTime(n._d.valueOf()+i),r.updateOffset(n,!1),n):Jn(e).local()}function pr(e){return-Math.round(e._d.getTimezoneOffset())}function gr(e,t,n){var i,s=this._offset||0;if(!this.isValid())return null!=e?this:NaN;if(null!=e){if("string"==typeof e){if(null===(e=hr(Se,e)))return this}else Math.abs(e)<16&&!n&&(e*=60);return!this._isUTC&&t&&(i=pr(this)),this._offset=e,this._isUTC=!0,null!=i&&this.add(i,"m"),s!==e&&(!t||this._changeInProgress?Ar(this,Or(e-s,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,r.updateOffset(this,!0),this._changeInProgress=null)),this}return this._isUTC?s:pr(this)}function mr(e,t){return null!=e?("string"!=typeof e&&(e=-e),this.utcOffset(e,t),this):-this.utcOffset()}function yr(e){return this.utcOffset(0,e)}function vr(e){return this._isUTC&&(this.utcOffset(0,e),this._isUTC=!1,e&&this.subtract(pr(this),"m")),this}function br(){if(null!=this._tzm)this.utcOffset(this._tzm,!1,!0);else if("string"==typeof this._i){var e=hr(we,this._i);null!=e?this.utcOffset(e):this.utcOffset(0,!0)}return this}function wr(e){return!!this.isValid()&&(e=e?Jn(e).utcOffset():0,(this.utcOffset()-e)%60==0)}function Sr(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()}function _r(){if(!l(this._isDSTShifted))return this._isDSTShifted;var e,t={};return S(t,this),(t=Vn(t))._a?(e=t._isUTC?p(t._a):Jn(t._a),this._isDSTShifted=this.isValid()&&lr(t._a,e.toArray())>0):this._isDSTShifted=!1,this._isDSTShifted}function Ir(){return!!this.isValid()&&!this._isUTC}function xr(){return!!this.isValid()&&this._isUTC}function kr(){return!!this.isValid()&&this._isUTC&&0===this._offset}r.updateOffset=function(){};var Er=/^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,Cr=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;function Or(e,t){var n,r,i,s=e,o=null;return ar(e)?s={ms:e._milliseconds,d:e._days,M:e._months}:u(e)||!isNaN(+e)?(s={},t?s[t]=+e:s.milliseconds=+e):(o=Er.exec(e))?(n="-"===o[1]?-1:1,s={y:0,d:Ne(o[Fe])*n,h:Ne(o[Be])*n,m:Ne(o[Ue])*n,s:Ne(o[We])*n,ms:Ne(cr(1e3*o[Ye]))*n}):(o=Cr.exec(e))?(n="-"===o[1]?-1:1,s={y:$r(o[2],n),M:$r(o[3],n),w:$r(o[4],n),d:$r(o[5],n),h:$r(o[6],n),m:$r(o[7],n),s:$r(o[8],n)}):null==s?s={}:"object"==typeof s&&("from"in s||"to"in s)&&(i=Nr(Jn(s.from),Jn(s.to)),(s={}).ms=i.milliseconds,s.M=i.months),r=new or(s),ar(e)&&a(e,"_locale")&&(r._locale=e._locale),ar(e)&&a(e,"_isValid")&&(r._isValid=e._isValid),r}function $r(e,t){var n=e&&parseFloat(e.replace(",","."));return(isNaN(n)?0:n)*t}function Mr(e,t){var n={};return n.months=t.month()-e.month()+12*(t.year()-e.year()),e.clone().add(n.months,"M").isAfter(t)&&--n.months,n.milliseconds=+t-+e.clone().add(n.months,"M"),n}function Nr(e,t){var n;return e.isValid()&&t.isValid()?(t=fr(t,e),e.isBefore(t)?n=Mr(e,t):((n=Mr(t,e)).milliseconds=-n.milliseconds,n.months=-n.months),n):{milliseconds:0,months:0}}function Tr(e,t){return function(n,r){var i;return null===r||isNaN(+r)||(O(t,"moment()."+t+"(period, number) is deprecated. Please use moment()."+t+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."),i=n,n=r,r=i),Ar(this,Or(n,r),e),this}}function Ar(e,t,n,i){var s=t._milliseconds,o=cr(t._days),a=cr(t._months);e.isValid()&&(i=null==i||i,a&&ht(e,Ze(e,"Month")+a*n),o&&Xe(e,"Date",Ze(e,"Date")+o*n),s&&e._d.setTime(e._d.valueOf()+s*n),i&&r.updateOffset(e,o||a))}Or.fn=or.prototype,Or.invalid=sr;var Pr=Tr(1,"add"),Dr=Tr(-1,"subtract");function Lr(e){return"string"==typeof e||e instanceof String}function jr(e){return I(e)||d(e)||Lr(e)||u(e)||Fr(e)||Rr(e)||null==e}function Rr(e){var t,n,r=o(e)&&!c(e),i=!1,s=["years","year","y","months","month","M","days","day","d","dates","date","D","hours","hour","h","minutes","minute","m","seconds","second","s","milliseconds","millisecond","ms"],l=s.length;for(t=0;t<l;t+=1)n=s[t],i=i||a(e,n);return r&&i}function Fr(e){var t=s(e),n=!1;return t&&(n=0===e.filter((function(t){return!u(t)&&Lr(e)})).length),t&&n}function Br(e){var t,n,r=o(e)&&!c(e),i=!1,s=["sameDay","nextDay","lastDay","nextWeek","lastWeek","sameElse"];for(t=0;t<s.length;t+=1)n=s[t],i=i||a(e,n);return r&&i}function Ur(e,t){var n=e.diff(t,"days",!0);return n<-6?"sameElse":n<-1?"lastWeek":n<0?"lastDay":n<1?"sameDay":n<2?"nextDay":n<7?"nextWeek":"sameElse"}function Wr(e,t){1===arguments.length&&(arguments[0]?jr(arguments[0])?(e=arguments[0],t=void 0):Br(arguments[0])&&(t=arguments[0],e=void 0):(e=void 0,t=void 0));var n=e||Jn(),i=fr(n,this).startOf("day"),s=r.calendarFormat(this,i)||"sameElse",o=t&&($(t[s])?t[s].call(this,n):t[s]);return this.format(o||this.localeData().calendar(s,this,Jn(n)))}function Yr(){return new _(this)}function Gr(e,t){var n=I(e)?e:Jn(e);return!(!this.isValid()||!n.isValid())&&("millisecond"===(t=ne(t)||"millisecond")?this.valueOf()>n.valueOf():n.valueOf()<this.clone().startOf(t).valueOf())}function Hr(e,t){var n=I(e)?e:Jn(e);return!(!this.isValid()||!n.isValid())&&("millisecond"===(t=ne(t)||"millisecond")?this.valueOf()<n.valueOf():this.clone().endOf(t).valueOf()<n.valueOf())}function Vr(e,t,n,r){var i=I(e)?e:Jn(e),s=I(t)?t:Jn(t);return!!(this.isValid()&&i.isValid()&&s.isValid())&&("("===(r=r||"()")[0]?this.isAfter(i,n):!this.isBefore(i,n))&&(")"===r[1]?this.isBefore(s,n):!this.isAfter(s,n))}function zr(e,t){var n,r=I(e)?e:Jn(e);return!(!this.isValid()||!r.isValid())&&("millisecond"===(t=ne(t)||"millisecond")?this.valueOf()===r.valueOf():(n=r.valueOf(),this.clone().startOf(t).valueOf()<=n&&n<=this.clone().endOf(t).valueOf()))}function qr(e,t){return this.isSame(e,t)||this.isAfter(e,t)}function Jr(e,t){return this.isSame(e,t)||this.isBefore(e,t)}function Kr(e,t,n){var r,i,s;if(!this.isValid())return NaN;if(!(r=fr(e,this)).isValid())return NaN;switch(i=6e4*(r.utcOffset()-this.utcOffset()),t=ne(t)){case"year":s=Zr(this,r)/12;break;case"month":s=Zr(this,r);break;case"quarter":s=Zr(this,r)/3;break;case"second":s=(this-r)/1e3;break;case"minute":s=(this-r)/6e4;break;case"hour":s=(this-r)/36e5;break;case"day":s=(this-r-i)/864e5;break;case"week":s=(this-r-i)/6048e5;break;default:s=this-r}return n?s:Me(s)}function Zr(e,t){if(e.date()<t.date())return-Zr(t,e);var n=12*(t.year()-e.year())+(t.month()-e.month()),r=e.clone().add(n,"months");return-(n+(t-r<0?(t-r)/(r-e.clone().add(n-1,"months")):(t-r)/(e.clone().add(n+1,"months")-r)))||0}function Xr(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")}function Qr(e){if(!this.isValid())return null;var t=!0!==e,n=t?this.clone().utc():this;return n.year()<0||n.year()>9999?Y(n,t?"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYYYY-MM-DD[T]HH:mm:ss.SSSZ"):$(Date.prototype.toISOString)?t?this.toDate().toISOString():new Date(this.valueOf()+60*this.utcOffset()*1e3).toISOString().replace("Z",Y(n,"Z")):Y(n,t?"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYY-MM-DD[T]HH:mm:ss.SSSZ")}function ei(){if(!this.isValid())return"moment.invalid(/* "+this._i+" */)";var e,t,n,r,i="moment",s="";return this.isLocal()||(i=0===this.utcOffset()?"moment.utc":"moment.parseZone",s="Z"),e="["+i+'("]',t=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY",n="-MM-DD[T]HH:mm:ss.SSS",r=s+'[")]',this.format(e+t+n+r)}function ti(e){e||(e=this.isUtc()?r.defaultFormatUtc:r.defaultFormat);var t=Y(this,e);return this.localeData().postformat(t)}function ni(e,t){return this.isValid()&&(I(e)&&e.isValid()||Jn(e).isValid())?Or({to:this,from:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()}function ri(e){return this.from(Jn(),e)}function ii(e,t){return this.isValid()&&(I(e)&&e.isValid()||Jn(e).isValid())?Or({from:this,to:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()}function si(e){return this.to(Jn(),e)}function oi(e){var t;return void 0===e?this._locale._abbr:(null!=(t=vn(e))&&(this._locale=t),this)}r.defaultFormat="YYYY-MM-DDTHH:mm:ssZ",r.defaultFormatUtc="YYYY-MM-DDTHH:mm:ss[Z]";var ai=k("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",(function(e){return void 0===e?this.localeData():this.locale(e)}));function ci(){return this._locale}var li=1e3,ui=60*li,di=60*ui,hi=3506328*di;function fi(e,t){return(e%t+t)%t}function pi(e,t,n){return e<100&&e>=0?new Date(e+400,t,n)-hi:new Date(e,t,n).valueOf()}function gi(e,t,n){return e<100&&e>=0?Date.UTC(e+400,t,n)-hi:Date.UTC(e,t,n)}function mi(e){var t,n;if(void 0===(e=ne(e))||"millisecond"===e||!this.isValid())return this;switch(n=this._isUTC?gi:pi,e){case"year":t=n(this.year(),0,1);break;case"quarter":t=n(this.year(),this.month()-this.month()%3,1);break;case"month":t=n(this.year(),this.month(),1);break;case"week":t=n(this.year(),this.month(),this.date()-this.weekday());break;case"isoWeek":t=n(this.year(),this.month(),this.date()-(this.isoWeekday()-1));break;case"day":case"date":t=n(this.year(),this.month(),this.date());break;case"hour":t=this._d.valueOf(),t-=fi(t+(this._isUTC?0:this.utcOffset()*ui),di);break;case"minute":t=this._d.valueOf(),t-=fi(t,ui);break;case"second":t=this._d.valueOf(),t-=fi(t,li)}return this._d.setTime(t),r.updateOffset(this,!0),this}function yi(e){var t,n;if(void 0===(e=ne(e))||"millisecond"===e||!this.isValid())return this;switch(n=this._isUTC?gi:pi,e){case"year":t=n(this.year()+1,0,1)-1;break;case"quarter":t=n(this.year(),this.month()-this.month()%3+3,1)-1;break;case"month":t=n(this.year(),this.month()+1,1)-1;break;case"week":t=n(this.year(),this.month(),this.date()-this.weekday()+7)-1;break;case"isoWeek":t=n(this.year(),this.month(),this.date()-(this.isoWeekday()-1)+7)-1;break;case"day":case"date":t=n(this.year(),this.month(),this.date()+1)-1;break;case"hour":t=this._d.valueOf(),t+=di-fi(t+(this._isUTC?0:this.utcOffset()*ui),di)-1;break;case"minute":t=this._d.valueOf(),t+=ui-fi(t,ui)-1;break;case"second":t=this._d.valueOf(),t+=li-fi(t,li)-1}return this._d.setTime(t),r.updateOffset(this,!0),this}function vi(){return this._d.valueOf()-6e4*(this._offset||0)}function bi(){return Math.floor(this.valueOf()/1e3)}function wi(){return new Date(this.valueOf())}function Si(){var e=this;return[e.year(),e.month(),e.date(),e.hour(),e.minute(),e.second(),e.millisecond()]}function _i(){var e=this;return{years:e.year(),months:e.month(),date:e.date(),hours:e.hours(),minutes:e.minutes(),seconds:e.seconds(),milliseconds:e.milliseconds()}}function Ii(){return this.isValid()?this.toISOString():null}function xi(){return y(this)}function ki(){return f({},m(this))}function Ei(){return m(this).overflow}function Ci(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}}function Oi(){var e,t,n,i=this._eras||vn("en")._eras;for(e=0,t=i.length;e<t;++e)switch("string"==typeof i[e].since&&(n=r(i[e].since).startOf("day"),i[e].since=n.valueOf()),typeof i[e].until){case"undefined":i[e].until=1/0;break;case"string":n=r(i[e].until).startOf("day").valueOf(),i[e].until=n.valueOf()}return i}function $i(e,t,n){var r,i,s,o,a,c=this.eras();for(e=e.toUpperCase(),r=0,i=c.length;r<i;++r)if(s=c[r].name.toUpperCase(),o=c[r].abbr.toUpperCase(),a=c[r].narrow.toUpperCase(),n)switch(t){case"N":case"NN":case"NNN":if(o===e)return c[r];break;case"NNNN":if(s===e)return c[r];break;case"NNNNN":if(a===e)return c[r]}else if([s,o,a].indexOf(e)>=0)return c[r]}function Mi(e,t){var n=e.since<=e.until?1:-1;return void 0===t?r(e.since).year():r(e.since).year()+(t-e.offset)*n}function Ni(){var e,t,n,r=this.localeData().eras();for(e=0,t=r.length;e<t;++e){if(n=this.clone().startOf("day").valueOf(),r[e].since<=n&&n<=r[e].until)return r[e].name;if(r[e].until<=n&&n<=r[e].since)return r[e].name}return""}function Ti(){var e,t,n,r=this.localeData().eras();for(e=0,t=r.length;e<t;++e){if(n=this.clone().startOf("day").valueOf(),r[e].since<=n&&n<=r[e].until)return r[e].narrow;if(r[e].until<=n&&n<=r[e].since)return r[e].narrow}return""}function Ai(){var e,t,n,r=this.localeData().eras();for(e=0,t=r.length;e<t;++e){if(n=this.clone().startOf("day").valueOf(),r[e].since<=n&&n<=r[e].until)return r[e].abbr;if(r[e].until<=n&&n<=r[e].since)return r[e].abbr}return""}function Pi(){var e,t,n,i,s=this.localeData().eras();for(e=0,t=s.length;e<t;++e)if(n=s[e].since<=s[e].until?1:-1,i=this.clone().startOf("day").valueOf(),s[e].since<=i&&i<=s[e].until||s[e].until<=i&&i<=s[e].since)return(this.year()-r(s[e].since).year())*n+s[e].offset;return this.year()}function Di(e){return a(this,"_erasNameRegex")||Wi.call(this),e?this._erasNameRegex:this._erasRegex}function Li(e){return a(this,"_erasAbbrRegex")||Wi.call(this),e?this._erasAbbrRegex:this._erasRegex}function ji(e){return a(this,"_erasNarrowRegex")||Wi.call(this),e?this._erasNarrowRegex:this._erasRegex}function Ri(e,t){return t.erasAbbrRegex(e)}function Fi(e,t){return t.erasNameRegex(e)}function Bi(e,t){return t.erasNarrowRegex(e)}function Ui(e,t){return t._eraYearOrdinalRegex||ve}function Wi(){var e,t,n,r,i,s=[],o=[],a=[],c=[],l=this.eras();for(e=0,t=l.length;e<t;++e)n=$e(l[e].name),r=$e(l[e].abbr),i=$e(l[e].narrow),o.push(n),s.push(r),a.push(i),c.push(n),c.push(r),c.push(i);this._erasRegex=new RegExp("^("+c.join("|")+")","i"),this._erasNameRegex=new RegExp("^("+o.join("|")+")","i"),this._erasAbbrRegex=new RegExp("^("+s.join("|")+")","i"),this._erasNarrowRegex=new RegExp("^("+a.join("|")+")","i")}function Yi(e,t){B(0,[e,e.length],0,t)}function Gi(e){return Ki.call(this,e,this.week(),this.weekday()+this.localeData()._week.dow,this.localeData()._week.dow,this.localeData()._week.doy)}function Hi(e){return Ki.call(this,e,this.isoWeek(),this.isoWeekday(),1,4)}function Vi(){return It(this.year(),1,4)}function zi(){return It(this.isoWeekYear(),1,4)}function qi(){var e=this.localeData()._week;return It(this.year(),e.dow,e.doy)}function Ji(){var e=this.localeData()._week;return It(this.weekYear(),e.dow,e.doy)}function Ki(e,t,n,r,i){var s;return null==e?_t(this,r,i).year:(t>(s=It(e,r,i))&&(t=s),Zi.call(this,e,t,n,r,i))}function Zi(e,t,n,r,i){var s=St(e,t,n,r,i),o=bt(s.year,0,s.dayOfYear);return this.year(o.getUTCFullYear()),this.month(o.getUTCMonth()),this.date(o.getUTCDate()),this}function Xi(e){return null==e?Math.ceil((this.month()+1)/3):this.month(3*(e-1)+this.month()%3)}B("N",0,0,"eraAbbr"),B("NN",0,0,"eraAbbr"),B("NNN",0,0,"eraAbbr"),B("NNNN",0,0,"eraName"),B("NNNNN",0,0,"eraNarrow"),B("y",["y",1],"yo","eraYear"),B("y",["yy",2],0,"eraYear"),B("y",["yyy",3],0,"eraYear"),B("y",["yyyy",4],0,"eraYear"),Ee("N",Ri),Ee("NN",Ri),Ee("NNN",Ri),Ee("NNNN",Fi),Ee("NNNNN",Bi),Ae(["N","NN","NNN","NNNN","NNNNN"],(function(e,t,n,r){var i=n._locale.erasParse(e,r,n._strict);i?m(n).era=i:m(n).invalidEra=e})),Ee("y",ve),Ee("yy",ve),Ee("yyy",ve),Ee("yyyy",ve),Ee("yo",Ui),Ae(["y","yy","yyy","yyyy"],je),Ae(["yo"],(function(e,t,n){var r;n._locale._eraYearOrdinalRegex&&(r=e.match(n._locale._eraYearOrdinalRegex)),n._locale.eraYearOrdinalParse?t[je]=n._locale.eraYearOrdinalParse(e,r):t[je]=parseInt(e,10)})),B(0,["gg",2],0,(function(){return this.weekYear()%100})),B(0,["GG",2],0,(function(){return this.isoWeekYear()%100})),Yi("gggg","weekYear"),Yi("ggggg","weekYear"),Yi("GGGG","isoWeekYear"),Yi("GGGGG","isoWeekYear"),Ee("G",be),Ee("g",be),Ee("GG",he,ce),Ee("gg",he,ce),Ee("GGGG",me,ue),Ee("gggg",me,ue),Ee("GGGGG",ye,de),Ee("ggggg",ye,de),Pe(["gggg","ggggg","GGGG","GGGGG"],(function(e,t,n,r){t[r.substr(0,2)]=Ne(e)})),Pe(["gg","GG"],(function(e,t,n,i){t[i]=r.parseTwoDigitYear(e)})),B("Q",0,"Qo","quarter"),Ee("Q",ae),Ae("Q",(function(e,t){t[Re]=3*(Ne(e)-1)})),B("D",["DD",2],"Do","date"),Ee("D",he,xe),Ee("DD",he,ce),Ee("Do",(function(e,t){return e?t._dayOfMonthOrdinalParse||t._ordinalParse:t._dayOfMonthOrdinalParseLenient})),Ae(["D","DD"],Fe),Ae("Do",(function(e,t){t[Fe]=Ne(e.match(he)[0])}));var Qi=Ke("Date",!0);function es(e){var t=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==e?t:this.add(e-t,"d")}B("DDD",["DDDD",3],"DDDo","dayOfYear"),Ee("DDD",ge),Ee("DDDD",le),Ae(["DDD","DDDD"],(function(e,t,n){n._dayOfYear=Ne(e)})),B("m",["mm",2],0,"minute"),Ee("m",he,ke),Ee("mm",he,ce),Ae(["m","mm"],Ue);var ts=Ke("Minutes",!1);B("s",["ss",2],0,"second"),Ee("s",he,ke),Ee("ss",he,ce),Ae(["s","ss"],We);var ns,rs,is=Ke("Seconds",!1);for(B("S",0,0,(function(){return~~(this.millisecond()/100)})),B(0,["SS",2],0,(function(){return~~(this.millisecond()/10)})),B(0,["SSS",3],0,"millisecond"),B(0,["SSSS",4],0,(function(){return 10*this.millisecond()})),B(0,["SSSSS",5],0,(function(){return 100*this.millisecond()})),B(0,["SSSSSS",6],0,(function(){return 1e3*this.millisecond()})),B(0,["SSSSSSS",7],0,(function(){return 1e4*this.millisecond()})),B(0,["SSSSSSSS",8],0,(function(){return 1e5*this.millisecond()})),B(0,["SSSSSSSSS",9],0,(function(){return 1e6*this.millisecond()})),Ee("S",ge,ae),Ee("SS",ge,ce),Ee("SSS",ge,le),ns="SSSS";ns.length<=9;ns+="S")Ee(ns,ve);function ss(e,t){t[Ye]=Ne(1e3*("0."+e))}for(ns="S";ns.length<=9;ns+="S")Ae(ns,ss);function os(){return this._isUTC?"UTC":""}function as(){return this._isUTC?"Coordinated Universal Time":""}rs=Ke("Milliseconds",!1),B("z",0,0,"zoneAbbr"),B("zz",0,0,"zoneName");var cs=_.prototype;function ls(e){return Jn(1e3*e)}function us(){return Jn.apply(null,arguments).parseZone()}function ds(e){return e}cs.add=Pr,cs.calendar=Wr,cs.clone=Yr,cs.diff=Kr,cs.endOf=yi,cs.format=ti,cs.from=ni,cs.fromNow=ri,cs.to=ii,cs.toNow=si,cs.get=Qe,cs.invalidAt=Ei,cs.isAfter=Gr,cs.isBefore=Hr,cs.isBetween=Vr,cs.isSame=zr,cs.isSameOrAfter=qr,cs.isSameOrBefore=Jr,cs.isValid=xi,cs.lang=ai,cs.locale=oi,cs.localeData=ci,cs.max=Zn,cs.min=Kn,cs.parsingFlags=ki,cs.set=et,cs.startOf=mi,cs.subtract=Dr,cs.toArray=Si,cs.toObject=_i,cs.toDate=wi,cs.toISOString=Qr,cs.inspect=ei,"undefined"!=typeof Symbol&&null!=Symbol.for&&(cs[Symbol.for("nodejs.util.inspect.custom")]=function(){return"Moment<"+this.format()+">"}),cs.toJSON=Ii,cs.toString=Xr,cs.unix=bi,cs.valueOf=vi,cs.creationData=Ci,cs.eraName=Ni,cs.eraNarrow=Ti,cs.eraAbbr=Ai,cs.eraYear=Pi,cs.year=qe,cs.isLeapYear=Je,cs.weekYear=Gi,cs.isoWeekYear=Hi,cs.quarter=cs.quarters=Xi,cs.month=ft,cs.daysInMonth=pt,cs.week=cs.weeks=Ot,cs.isoWeek=cs.isoWeeks=$t,cs.weeksInYear=qi,cs.weeksInWeekYear=Ji,cs.isoWeeksInYear=Vi,cs.isoWeeksInISOWeekYear=zi,cs.date=Qi,cs.day=cs.days=Gt,cs.weekday=Ht,cs.isoWeekday=Vt,cs.dayOfYear=es,cs.hour=cs.hours=rn,cs.minute=cs.minutes=ts,cs.second=cs.seconds=is,cs.millisecond=cs.milliseconds=rs,cs.utcOffset=gr,cs.utc=yr,cs.local=vr,cs.parseZone=br,cs.hasAlignedHourOffset=wr,cs.isDST=Sr,cs.isLocal=Ir,cs.isUtcOffset=xr,cs.isUtc=kr,cs.isUTC=kr,cs.zoneAbbr=os,cs.zoneName=as,cs.dates=k("dates accessor is deprecated. Use date instead.",Qi),cs.months=k("months accessor is deprecated. Use month instead",ft),cs.years=k("years accessor is deprecated. Use year instead",qe),cs.zone=k("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",mr),cs.isDSTShifted=k("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",_r);var hs=T.prototype;function fs(e,t,n,r){var i=vn(),s=p().set(r,t);return i[n](s,e)}function ps(e,t,n){if(u(e)&&(t=e,e=void 0),e=e||"",null!=t)return fs(e,t,n,"month");var r,i=[];for(r=0;r<12;r++)i[r]=fs(e,r,n,"month");return i}function gs(e,t,n,r){"boolean"==typeof e?(u(t)&&(n=t,t=void 0),t=t||""):(n=t=e,e=!1,u(t)&&(n=t,t=void 0),t=t||"");var i,s=vn(),o=e?s._week.dow:0,a=[];if(null!=n)return fs(t,(n+o)%7,r,"day");for(i=0;i<7;i++)a[i]=fs(t,(i+o)%7,r,"day");return a}function ms(e,t){return ps(e,t,"months")}function ys(e,t){return ps(e,t,"monthsShort")}function vs(e,t,n){return gs(e,t,n,"weekdays")}function bs(e,t,n){return gs(e,t,n,"weekdaysShort")}function ws(e,t,n){return gs(e,t,n,"weekdaysMin")}hs.calendar=P,hs.longDateFormat=V,hs.invalidDate=q,hs.ordinal=Z,hs.preparse=ds,hs.postformat=ds,hs.relativeTime=Q,hs.pastFuture=ee,hs.set=M,hs.eras=Oi,hs.erasParse=$i,hs.erasConvertYear=Mi,hs.erasAbbrRegex=Li,hs.erasNameRegex=Di,hs.erasNarrowRegex=ji,hs.months=ct,hs.monthsShort=lt,hs.monthsParse=dt,hs.monthsRegex=mt,hs.monthsShortRegex=gt,hs.week=xt,hs.firstDayOfYear=Ct,hs.firstDayOfWeek=Et,hs.weekdays=Ft,hs.weekdaysMin=Ut,hs.weekdaysShort=Bt,hs.weekdaysParse=Yt,hs.weekdaysRegex=zt,hs.weekdaysShortRegex=qt,hs.weekdaysMinRegex=Jt,hs.isPM=tn,hs.meridiem=sn,gn("en",{eras:[{since:"0001-01-01",until:1/0,offset:1,name:"Anno Domini",narrow:"AD",abbr:"AD"},{since:"0000-12-31",until:-1/0,offset:1,name:"Before Christ",narrow:"BC",abbr:"BC"}],dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(e){var t=e%10;return e+(1===Ne(e%100/10)?"th":1===t?"st":2===t?"nd":3===t?"rd":"th")}}),r.lang=k("moment.lang is deprecated. Use moment.locale instead.",gn),r.langData=k("moment.langData is deprecated. Use moment.localeData instead.",vn);var Ss=Math.abs;function _s(){var e=this._data;return this._milliseconds=Ss(this._milliseconds),this._days=Ss(this._days),this._months=Ss(this._months),e.milliseconds=Ss(e.milliseconds),e.seconds=Ss(e.seconds),e.minutes=Ss(e.minutes),e.hours=Ss(e.hours),e.months=Ss(e.months),e.years=Ss(e.years),this}function Is(e,t,n,r){var i=Or(t,n);return e._milliseconds+=r*i._milliseconds,e._days+=r*i._days,e._months+=r*i._months,e._bubble()}function xs(e,t){return Is(this,e,t,1)}function ks(e,t){return Is(this,e,t,-1)}function Es(e){return e<0?Math.floor(e):Math.ceil(e)}function Cs(){var e,t,n,r,i,s=this._milliseconds,o=this._days,a=this._months,c=this._data;return s>=0&&o>=0&&a>=0||s<=0&&o<=0&&a<=0||(s+=864e5*Es($s(a)+o),o=0,a=0),c.milliseconds=s%1e3,e=Me(s/1e3),c.seconds=e%60,t=Me(e/60),c.minutes=t%60,n=Me(t/60),c.hours=n%24,o+=Me(n/24),a+=i=Me(Os(o)),o-=Es($s(i)),r=Me(a/12),a%=12,c.days=o,c.months=a,c.years=r,this}function Os(e){return 4800*e/146097}function $s(e){return 146097*e/4800}function Ms(e){if(!this.isValid())return NaN;var t,n,r=this._milliseconds;if("month"===(e=ne(e))||"quarter"===e||"year"===e)switch(t=this._days+r/864e5,n=this._months+Os(t),e){case"month":return n;case"quarter":return n/3;case"year":return n/12}else switch(t=this._days+Math.round($s(this._months)),e){case"week":return t/7+r/6048e5;case"day":return t+r/864e5;case"hour":return 24*t+r/36e5;case"minute":return 1440*t+r/6e4;case"second":return 86400*t+r/1e3;case"millisecond":return Math.floor(864e5*t)+r;default:throw new Error("Unknown unit "+e)}}function Ns(e){return function(){return this.as(e)}}var Ts=Ns("ms"),As=Ns("s"),Ps=Ns("m"),Ds=Ns("h"),Ls=Ns("d"),js=Ns("w"),Rs=Ns("M"),Fs=Ns("Q"),Bs=Ns("y"),Us=Ts;function Ws(){return Or(this)}function Ys(e){return e=ne(e),this.isValid()?this[e+"s"]():NaN}function Gs(e){return function(){return this.isValid()?this._data[e]:NaN}}var Hs=Gs("milliseconds"),Vs=Gs("seconds"),zs=Gs("minutes"),qs=Gs("hours"),Js=Gs("days"),Ks=Gs("months"),Zs=Gs("years");function Xs(){return Me(this.days()/7)}var Qs=Math.round,eo={ss:44,s:45,m:45,h:22,d:26,w:null,M:11};function to(e,t,n,r,i){return i.relativeTime(t||1,!!n,e,r)}function no(e,t,n,r){var i=Or(e).abs(),s=Qs(i.as("s")),o=Qs(i.as("m")),a=Qs(i.as("h")),c=Qs(i.as("d")),l=Qs(i.as("M")),u=Qs(i.as("w")),d=Qs(i.as("y")),h=s<=n.ss&&["s",s]||s<n.s&&["ss",s]||o<=1&&["m"]||o<n.m&&["mm",o]||a<=1&&["h"]||a<n.h&&["hh",a]||c<=1&&["d"]||c<n.d&&["dd",c];return null!=n.w&&(h=h||u<=1&&["w"]||u<n.w&&["ww",u]),(h=h||l<=1&&["M"]||l<n.M&&["MM",l]||d<=1&&["y"]||["yy",d])[2]=t,h[3]=+e>0,h[4]=r,to.apply(null,h)}function ro(e){return void 0===e?Qs:"function"==typeof e&&(Qs=e,!0)}function io(e,t){return void 0!==eo[e]&&(void 0===t?eo[e]:(eo[e]=t,"s"===e&&(eo.ss=t-1),!0))}function so(e,t){if(!this.isValid())return this.localeData().invalidDate();var n,r,i=!1,s=eo;return"object"==typeof e&&(t=e,e=!1),"boolean"==typeof e&&(i=e),"object"==typeof t&&(s=Object.assign({},eo,t),null!=t.s&&null==t.ss&&(s.ss=t.s-1)),r=no(this,!i,s,n=this.localeData()),i&&(r=n.pastFuture(+this,r)),n.postformat(r)}var oo=Math.abs;function ao(e){return(e>0)-(e<0)||+e}function co(){if(!this.isValid())return this.localeData().invalidDate();var e,t,n,r,i,s,o,a,c=oo(this._milliseconds)/1e3,l=oo(this._days),u=oo(this._months),d=this.asSeconds();return d?(e=Me(c/60),t=Me(e/60),c%=60,e%=60,n=Me(u/12),u%=12,r=c?c.toFixed(3).replace(/\.?0+$/,""):"",i=d<0?"-":"",s=ao(this._months)!==ao(d)?"-":"",o=ao(this._days)!==ao(d)?"-":"",a=ao(this._milliseconds)!==ao(d)?"-":"",i+"P"+(n?s+n+"Y":"")+(u?s+u+"M":"")+(l?o+l+"D":"")+(t||e||c?"T":"")+(t?a+t+"H":"")+(e?a+e+"M":"")+(c?a+r+"S":"")):"P0D"}var lo=or.prototype;return lo.isValid=ir,lo.abs=_s,lo.add=xs,lo.subtract=ks,lo.as=Ms,lo.asMilliseconds=Ts,lo.asSeconds=As,lo.asMinutes=Ps,lo.asHours=Ds,lo.asDays=Ls,lo.asWeeks=js,lo.asMonths=Rs,lo.asQuarters=Fs,lo.asYears=Bs,lo.valueOf=Us,lo._bubble=Cs,lo.clone=Ws,lo.get=Ys,lo.milliseconds=Hs,lo.seconds=Vs,lo.minutes=zs,lo.hours=qs,lo.days=Js,lo.weeks=Xs,lo.months=Ks,lo.years=Zs,lo.humanize=so,lo.toISOString=co,lo.toString=co,lo.toJSON=co,lo.locale=oi,lo.localeData=ci,lo.toIsoString=k("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",co),lo.lang=ai,B("X",0,0,"unix"),B("x",0,0,"valueOf"),Ee("x",be),Ee("X",_e),Ae("X",(function(e,t,n){n._d=new Date(1e3*parseFloat(e))})),Ae("x",(function(e,t,n){n._d=new Date(Ne(e))})),
|
|
2
|
+
//! moment.js
|
|
3
|
+
r.version="2.30.1",i(Jn),r.fn=cs,r.min=Qn,r.max=er,r.now=tr,r.utc=p,r.unix=ls,r.months=ms,r.isDate=d,r.locale=gn,r.invalid=v,r.duration=Or,r.isMoment=I,r.weekdays=vs,r.parseZone=us,r.localeData=vn,r.isDuration=ar,r.monthsShort=ys,r.weekdaysMin=ws,r.defineLocale=mn,r.updateLocale=yn,r.locales=bn,r.weekdaysShort=bs,r.normalizeUnits=ne,r.relativeTimeRounding=ro,r.relativeTimeThreshold=io,r.calendarFormat=Ur,r.prototype=cs,r.HTML5_FMT={DATETIME_LOCAL:"YYYY-MM-DDTHH:mm",DATETIME_LOCAL_SECONDS:"YYYY-MM-DDTHH:mm:ss",DATETIME_LOCAL_MS:"YYYY-MM-DDTHH:mm:ss.SSS",DATE:"YYYY-MM-DD",TIME:"HH:mm",TIME_SECONDS:"HH:mm:ss",TIME_MS:"HH:mm:ss.SSS",WEEK:"GGGG-[W]WW",MONTH:"YYYY-MM"},r}()),zg.exports;var e}function Jg(){if(Vg)return Hg;Vg=1;
|
|
4
|
+
/*!
|
|
5
|
+
* FileStreamRotator
|
|
6
|
+
* Copyright(c) 2012-2017 Holiday Extras.
|
|
7
|
+
* Copyright(c) 2017 Roger C.
|
|
8
|
+
* MIT Licensed
|
|
9
|
+
*/
|
|
10
|
+
var e=P,t=m,n=qg(),r=u,i=A,s={};Hg=s;var o=["daily","test","m","h","custom"],a="YYYYMMDDHHmm";function l(t,n){if(t.hash===r.createHash(t.hashType).update(t.name+"LOG_FILE"+t.date).digest("hex"))try{e.existsSync(t.name)&&e.unlinkSync(t.name)}catch(e){n&&console.error(new Date,"[FileStreamRotator] Could not remove old log file: ",t.name)}}s.getFrequency=function(e){var t=e.toLowerCase().match(/^(\d+)([mh])$/);if(t)return function(e,t){if("number"==typeof t){switch(e){case"m":if(t<0||t>60)return!1;break;case"h":if(t<0||t>24)return!1}return{type:e,digit:t}}}(t[2],parseInt(t[1]));var n=function(e){switch(e){case"custom":case"daily":return{type:e,digit:void 0};case"test":return{type:e,digit:0}}return!1}(e);return n||!1},s.parseFileSize=function(e){if(e&&"string"==typeof e){var t=e.toLowerCase().match(/^((?:0\.)?\d+)([kmg])$/);if(t)switch(t[2]){case"k":return 1024*t[1];case"m":return 1024*t[1]*1024;case"g":return 1024*t[1]*1024*1024}}return null},s.getDate=function(e,t,r){t=t||a;let i=r?n.utc():n().local();if(e&&-1!==o.indexOf(e.type))switch(e.type){case"m":var s=Math.floor(i.minutes()/e.digit)*e.digit;return i.minutes(s).format(t);case"h":var c=Math.floor(i.hour()/e.digit)*e.digit;return i.hour(c).format(t);case"daily":case"custom":case"test":return i.format(t)}return i.format(t)},s.setAuditLog=function(n,r,i){var s=null;if(n){var o=n.toString().substr(-1),a=n.toString().match(/^(\d+)/);if(Number(a[1])>0){var c=t.dirname(i.replace(/%DATE%.+/,"_filename"));try{if(r){var l=t.resolve(r);s=JSON.parse(e.readFileSync(l,{encoding:"utf-8"}))}else{l=t.resolve(c+"/.audit.json");s=JSON.parse(e.readFileSync(l,{encoding:"utf-8"}))}}catch(e){if("ENOENT"!==e.code)return null;s={keep:{days:!1,amount:Number(a[1])},auditLog:r||c+"/.audit.json",files:[]}}s.keep={days:"d"===o,amount:Number(a[1])}}}return s},s.writeAuditLog=function(t,n){try{d(t.auditLog),e.writeFileSync(t.auditLog,JSON.stringify(t,null,4))}catch(e){n&&console.error(new Date,"[FileStreamRotator] Failed to store log audit at:",t.auditLog,"Error:",e)}},s.addLogToAudit=function(e,t,i,o){if(t&&t.files){var a=t.files.findIndex((function(t){return t.name===e}));if(-1!==a)return t;var c=Date.now();if(t.files.push({date:c,name:e,hash:r.createHash(t.hashType).update(e+"LOG_FILE"+c).digest("hex")}),t.keep.days){var u=n().subtract(t.keep.amount,"days").valueOf(),d=t.files.filter((function(e){return e.date>u||(e.hashType=t.hashType,l(e,o),i.emit("logRemoved",e),!1)}));t.files=d}else{var h=t.files.splice(-t.keep.amount);t.files.length>0&&t.files.filter((function(e){return e.hashType=t.hashType,l(e,o),i.emit("logRemoved",e),!1})),t.files=h}s.writeAuditLog(t,o)}return t},s.getStream=function(r){var l=null,u=null,f=this;if(!r.filename)return console.error(new Date,"[FileStreamRotator] No filename supplied. Defaulting to STDOUT"),process.stdout;r.frequency&&(l=f.getFrequency(r.frequency));let p=f.setAuditLog(r.max_logs,r.audit_file,r.filename);null!=p&&(p.hashType=void 0!==r.audit_hash_type?r.audit_hash_type:"md5"),f.verbose=void 0===r.verbose||r.verbose;var g=null,m=0,y=0;r.size&&(g=s.parseFileSize(r.size));var v=r.date_format||a;l&&"daily"==l.type&&(r.date_format||(v="YYYY-MM-DD"),n().format(v)==n().endOf("day").format(v)&&n().format(v)!=n().add(1,"day").format(v)||(f.verbose&&console.log(new Date,"[FileStreamRotator] Changing type to custom as date format changes more often than once a day or not every day"),l.type="custom")),l&&(u=r.frequency?f.getDate(l,v,r.utc):""),r.create_symlink=r.create_symlink||!1,r.extension=r.extension||"";var b=r.filename,w=null,S=b+(u?"."+u:"");if(b.match(/%DATE%/)&&(S=b.replace(/%DATE%/g,u||f.getDate(null,v,r.utc))),g){var _=null,I=S;if(p&&p.files&&p.files instanceof Array&&p.files.length>0){var x=p.files[p.files.length-1].name;if(x.match(I)){var k=x.match(I+"\\.(\\d+)");k&&(I=x,m=k[1])}}for(0==m&&I==S&&(I+=r.extension);e.existsSync(I);)_=I,m++,I=S+"."+m+r.extension;if(_){var E=e.statSync(_);E.size<g&&(I=_,m--,y=E.size)}S=I}else S+=r.extension;f.verbose&&console.log(new Date,"[FileStreamRotator] Logging to: ",S),d(S);var C=r.file_options||{flags:"a"},O=e.createWriteStream(S,C);if(u&&l&&o.indexOf(l.type)>-1||g>0){f.verbose&&console.log(new Date,"[FileStreamRotator] Rotating file: ",l?l.type:"",g?"size: "+g:"");var $,M=new i;return M.auditLog=p,M.end=function(){O.end.apply(O,arguments)},h(O,M),M.on("close",(function(){$&&$.close()})),M.on("new",(function(n){M.auditLog=f.addLogToAudit(n,M.auditLog,M,f.verbose),r.create_symlink&&function(n,r,i){let s=r||"current.log",o=t.dirname(n),a=t.basename(n),c=o+"/"+s;try{e.lstatSync(c).isSymbolicLink()&&(e.unlinkSync(c),e.symlinkSync(a,c))}catch(t){if(t&&"ENOENT"==t.code)try{e.symlinkSync(a,c)}catch(e){i&&console.error(new Date,"[FileStreamRotator] Could not create symlink file: ",c," -> ",a)}}}(n,r.symlink_name,f.verbose),r.watch_log&&M.emit("addWatcher",n)})),M.on("addWatcher",(function(t){$&&$.close(),r.watch_log&&($=function(t,n,r){if(!t)return null;try{return e.lstatSync(t),e.watch(t,(function(n){if("rename"==n)try{e.lstatSync(t)}catch(e){r(e,t)}}))}catch(e){n&&console.log(new Date,"[FileStreamRotator] Could not add watcher for "+t)}}(t,f.verbose,(function(e,t){M.emit("createLog",t)})))})),M.on("createLog",(function(t){try{e.lstatSync(t)}catch(n){O&&"function"==O.end&&O.end(),O=e.createWriteStream(t,C),M.emit("new",t),h(O,M)}})),M.write=function(t,n){var i=l?this.getDate(l,v,r.utc):u;if(i!=u||g&&y>g){var s=b+(u&&l?"."+i:"");b.match(/%DATE%/)&&u&&(s=b.replace(/%DATE%/g,i)),g&&y>g?s+="."+ ++m+r.extension:(m=0,s+=r.extension),y=0,f.verbose&&console.log(new Date,c.format("[FileStreamRotator] Changing logs from %s to %s",S,s)),u=i,w=S,S=s,!0===r.end_stream?O.end():O.destroy(),d(S),O=e.createWriteStream(s,C),M.emit("new",s),M.emit("rotate",w,s),h(O,M)}O.write(t,n),y+=Buffer.byteLength(t,n)}.bind(this),process.nextTick((function(){M.emit("new",S)})),M.emit("new",S),M}return f.verbose&&console.log(new Date,"[FileStreamRotator] File won't be rotated: ",r.frequency,r.size),process.nextTick((function(){O.emit("new",S)})),O};var d=function(n){t.dirname(n).split(t.sep).reduce((function(n,r){if(n+=r+t.sep,!e.existsSync(n))try{e.mkdirSync(n)}catch(e){if("EEXIST"!==e.code)throw e}return n}),"")},h=function(e,t){e.on("close",(function(){t.emit("close")})),e.on("finish",(function(){t.emit("finish")})),e.on("error",(function(e){t.emit("error",e)})),e.on("open",(function(e){t.emit("open",e)}))};return Hg}const Kg=P,Zg=$,Xg=m,Qg=c,em=L,tm=Wg.exports,nm=fu.MESSAGE,rm=N.PassThrough,im=Gh,sm={json:!1,colorize:!1,eol:Zg.EOL,logstash:null,prettyPrint:!1,label:null,stringify:!1,depth:null,showLevel:!0,timestamp:()=>(new Date).toISOString()},om=function(e){if(e=e||{},im.call(this,e),this.options=Object.assign({},sm,e),e.stream)!function(t){Array.prototype.slice.call(arguments,1).forEach((n=>{if(e[n])throw new Error("Cannot set "+n+" and "+t+" together")}))}("stream","filename","maxsize"),this.logStream=new rm,this.logStream.pipe(e.stream);else{if(this.filename=e.filename?Xg.basename(e.filename):"winston.log",this.dirname=e.dirname||Xg.dirname(e.filename),t=this.filename,/["<>|:*?\\/\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f]/g.test(t)||!function(e){return!/["<>|\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f]/g.test(e)}(this.dirname))throw new Error("Your path or filename contain an invalid character.");this.logStream=Jg().getStream({filename:Xg.join(this.dirname,this.filename),frequency:e.frequency?e.frequency:"custom",date_format:e.datePattern?e.datePattern:"YYYY-MM-DD",verbose:!1,size:function(e){if(e&&"string"==typeof e){if(e.toLowerCase().match(/^((?:0\.)?\d+)([kmg])$/))return e}else if(e&&Number.isInteger(e)){const t=Math.round(e/1024);return 0===t?"1k":t+"k"}return null}(e.maxSize),max_logs:e.maxFiles,end_stream:!0,audit_file:e.auditFile?e.auditFile:Xg.join(this.dirname,"."+tm(e)+"-audit.json"),file_options:e.options?e.options:{flags:"a"},utc:!!e.utc&&e.utc,extension:e.extension?e.extension:"",create_symlink:!!e.createSymlink&&e.createSymlink,symlink_name:e.symlinkName?e.symlinkName:"current.log",watch_log:!!e.watchLog&&e.watchLog,audit_hash_type:e.auditHashType?e.auditHashType:"sha256"}),this.logStream.on("new",(e=>{this.emit("new",e)})),this.logStream.on("rotate",((e,t)=>{this.emit("rotate",e,t)})),this.logStream.on("logRemoved",(t=>{if(e.zippedArchive){const e=t.name+".gz";try{Kg.unlinkSync(e)}catch(t){if("ENOENT"!==t.code)return t.message=`Error occurred while removing ${e}: ${t.message}`,void this.emit("error",t)}this.emit("logRemoved",e)}else this.emit("logRemoved",t.name)})),e.zippedArchive&&this.logStream.on("rotate",(e=>{try{if(!Kg.existsSync(e))return}catch(t){return t.message=`Error occurred while checking existence of ${e}: ${t.message}`,void this.emit("error",t)}try{if(Kg.existsSync(`${e}.gz`))return}catch(t){return t.message=`Error occurred while checking existence of ${e}.gz: ${t.message}`,void this.emit("error",t)}const t=em.createGzip(),n=Kg.createReadStream(e);n.on("error",(t=>{t.message=`Error occurred while reading ${e}: ${t.message}`,this.emit("error",t)}));const r=Kg.createWriteStream(e+".gz");r.on("error",(t=>{t.message=`Error occurred while writing ${e}.gz: ${t.message}`,this.emit("error",t)})),n.pipe(t).pipe(r).on("finish",(()=>{try{Kg.unlinkSync(e)}catch(t){if("ENOENT"!==t.code)return t.message=`Error occurred while removing ${e}: ${t.message}`,void this.emit("error",t)}this.emit("archive",e+".gz")}))})),e.watchLog&&this.logStream.on("addWatcher",(e=>{this.emit("addWatcher",e)}))}var t};var am=om;Qg.inherits(om,im),om.prototype.name="dailyRotateFile";const cm=function(){};om.prototype.log=function(e,t){t=t||cm,this.logStream.write(e[nm]+this.options.eol),this.emit("logged",e),t(null,!0)},om.prototype.close=function(){this.logStream&&this.logStream.end((()=>{this.emit("finish")}))},om.prototype.query=function(e,t){if("function"==typeof e&&(t=e,e={}),!this.options.json)throw new Error("query() may not be used without the json option being set to true");if(!this.filename)throw new Error("query() may not be used when initializing with a stream");let n=[];(e=e||{}).rows=e.rows||e.limit||10,e.start=e.start||0,e.until=e.until||new Date,"object"!=typeof e.until&&(e.until=new Date(e.until)),e.from=e.from||e.until-864e5,"object"!=typeof e.from&&(e.from=new Date(e.from)),e.order=e.order||"desc";const r=(()=>{const e=new RegExp(this.filename.replace("%DATE%",".*"),"i");return Kg.readdirSync(this.dirname).filter((t=>Xg.basename(t).match(e)))})();0===r.length&&t&&t(null,n);const i=s=>{if(!s)return;const o=Xg.join(this.dirname,s);let a,c="";if(s.endsWith(".gz")){a=new rm;const e=Kg.createReadStream(o);e.on("error",(e=>{e.message=`Error occurred while reading ${o}: ${e.message}`,a.emit("error",e)})),e.pipe(em.createGunzip()).pipe(a)}else a=Kg.createReadStream(o,{encoding:"utf8"});function l(t,r){try{const r=JSON.parse(t);if(!r||"object"!=typeof r)return;const i=new Date(r.timestamp);if(e.from&&i<e.from||e.until&&i>e.until||e.level&&e.level!==r.level)return;n.push(r)}catch(e){r||a.emit("error",e)}}a.on("error",(e=>{if(a.readable&&a.destroy(),t)return"ENOENT"===e.code?t(null,n):t(e)})),a.on("data",(e=>{const t=(e=(c+e).split(/\n+/)).length-1;for(let n=0;n<t;n++)l(e[n]);c=e[t]})),a.on("end",(()=>{if(c&&l(c,!0),r.length)i(r.shift());else if(t){n.sort(((e,t)=>{const n=new Date(e.timestamp).getTime(),r=new Date(t.timestamp).getTime();return n>r?1:n<r?-1:0})),"desc"===e.order&&(n=n.reverse());const r=e.start||0,i=e.limit||n.length;n=n.slice(r,r+i),e.fields&&(n=n.map((t=>{const n={};return e.fields.forEach((e=>{n[e]=t[e]})),n}))),t(null,n)}}))};i(r.shift())};const lm=am;Al.transports.DailyRotateFile=lm;var um=fl(lm);const dm=Date.now();let hm=Math.ceil(dm/1e3);var fm=()=>hm+=1;const pm=y(M(),"kemu-user-services"),gm=y(M(),"kemu-test-services"),mm="KMU-CB-v1",ym=process.env.HUB_PKG_VERSION||'"1.4.0"';var vm;!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"}(vm||(vm={}));const bm=e=>({...e,type:Array.isArray(e.type)?e.type.map((e=>Yc[e])):Yc[e.type]}),wm=async e=>{try{return await _(e,"utf-8")}catch(e){return null}},Sm=e=>{if(e&&e.startsWith(mm)){const t=e.slice(9),n=decodeURI(t);return tl(n)}return null},_m=async(e,t,n)=>{let r=[];e.variants?.length&&(r=e.variants.map((e=>({...e,...e.inputs?{inputs:e.inputs.map(bm)}:{},...e.outputs?{outputs:e.outputs.map(bm)}:{}}))));const i={...e,path:t,customWidgets:[],...e.inputs?{inputs:e.inputs.map(bm)}:{inputs:[]},...e.outputs?{outputs:e.outputs.map(bm)}:{outputs:[]},variants:r,...e.widgetUI&&n?.widgetUIContents?{widgetUIContents:n.widgetUIContents}:{}},s=await(async(e,t,n=console.log)=>{const r=[];if(t.customWidgets?.length)for(const i of t.customWidgets){const t=await wm(y(e,i));if(!t){n(`Error loading custom widget file ${i}`);continue}const s=t.startsWith(mm)?t:`${mm}${t}`,o=Sm(s);if(!o){n(`Custom widget file "${i}" is not a valid Kemu Clipboard item`);continue}const a=Object.values(o).filter((e=>e.type===vm.widgetGroup&&!e.groupId));if(a.length>1){n(`Custom widget file "${i}" contains more than one top level widgetGroup`);continue}const c=a[0];if(!c){n(`Custom widget file "${i}" does not contain a top level widgetGroup`);continue}const l=c.state,u={name:l.name,color:l.color,description:l.description,contents:s,rootGroupId:c.id,icon:l.icon,protocolVersion:l.protocolVersion||"2"};r.push(u)}return r})(t,e,n?.log);if(s.length?i.customWidgets=s:delete i.customWidgets,i.variants?.length)for(const e of i.variants)if(e.svgIcon)try{const n=await _(y(t,e.svgIcon),"utf-8");e.svgIcon=n}catch(t){n?.log&&n?.log(`Error loading svgIcon for variant ${e.id}: ${t}`)}return i},Im=async e=>{try{return await I(e,x.F_OK),!0}catch{return!1}};let xm=null,km=null;const Em=()=>xm||pm,Cm=()=>km||gm;let Om=null;const $m={setGlobalUserId:e=>Om?.setGlobalUserId?.(e),captureError:e=>Om?.captureError?.(e),flushMessages:async()=>Om?.flushMessages?.(),isEnabled:()=>!!Om};var Mm={...$m,setTracker:e=>{Om=e}};const Nm=Tl("servicesManager"),Tm={};let Am=null,Pm=null,Dm=null;class Lm extends Error{code;originalError;constructor(e,t,n){super(e),this.code=t,this.originalError=n,this.name="ServiceError"}}const jm=async e=>{try{return await I(e),!0}catch{return!1}},Rm=async e=>{if(!Am)throw new Error('IPC config not set, call "setHubIpcConfig" first.');const t=e.info.internal?e.info.path:m.join(e.info.path,".."),n=e.logsEnabled?((e,t)=>{const n=Ug.createLogger({level:"info",format:Ug.format.combine(Ug.format.timestamp(),Ug.format.errors({stack:!0}),Ug.format.json()),defaultMeta:{service:e},transports:[new um({filename:m.join(t,"service-%DATE%.log"),datePattern:"YYYY-MM-DD",maxSize:"5m",maxFiles:"5d",auditFile:m.join(t,".service-log-audit.json")})]});return n.getLastLogs=async(n=100)=>{try{const r=m.join(t,".service-log-audit.json"),i=await w.readFile(r,"utf-8"),s=tl(i);if(!s)return console.warn(`Missing audit file for ${e}, skipping log retrieval.`),[];const o=async e=>(await w.readFile(e,"utf-8")).split("\n").filter((e=>e.trim())),a=[],c=[...s.files].reverse();for(const e of c){const t=await o(e.name);if(a.push(...t),a.length>=n)break}return a}catch(t){return console.error(`Failed to read service logs for ${e}: `,t),[]}},n})(e.info.name,t):null,r=t=>{if(!e.devMode){const{childProcess:r,...i}=e;Mm.isEnabled()&&Mm.captureError({error:t,data:{logs:n?.getLastLogs(),service:{...i,spawnargs:r?.spawnargs,info:void 0,name:e.info.name,version:e.info.version}}})}};try{if(e.info.processor===Hc.Javascript){Nm(`Spawning service ${e.info.name} with sessionId ${e.info.sessionId}`);const t=m.join(e.info.path,"processor.js"),i=m.join(e.info.path,"processor.mjs"),s=await jm(t)?t:i,o=[`--sessionId=${e.info.sessionId.toString()}`,`--ipcSpace=${Am.appSpace}`,`--ipcId=${Am?.id}`,`--recipePath=${Am.recipePath||""}`];if(e.info.internal&&o.push("--internal=true"),!Dm)throw new Error('Get secrets function not set, call "setGetSecretsFunction" first.');const a=await Dm({name:e.info.name,version:e.info.version,requiredSecrets:e.info.requiredSecrets||{}}),c=Object.entries(e.info.requiredSecrets||{}).filter((([e,t])=>{const n=a[e];return null==n&&!t.optional})).map((([e])=>e));if(c?.length)throw new Lm(`Missing required environment variables: ${c.join(", ")}`,"MISSING_REQUIRED_SECRETS");return new Promise(((t,i)=>{if(!Pm)throw new Error('Spawn function not set, call "setSpawnNodeFunction" first.');const c=Pm({args:[s,...o],serviceInfo:{name:e.info.name,version:e.info.version},options:{env:{...a}}});c.stdout.on("data",(t=>{const r=t.toString().trim();r&&(n?.info(r),Nm(`[${e.info.name}] - stdout: ${r}`))})),c.stderr.on("data",(t=>{const i=t.toString().trim();i&&(n?.error(i),r(new Error(i)),Nm(`[${e.info.name}] - stderr: ${i}`))})),c.on("exit",(t=>{const r=`exited with code ${t}`;n?.info(r,{code:t}),Nm(`[${e.info.name}] ${r}`)})),c.on("spawn",(()=>{const r=`spawned with PID ${c.pid}`;n?.info(r,{pid:c.pid}),Nm(`[${e.info.name}] ${r}`),t(c)})),c.on("error",(t=>{n?.error(`[${e.info.name}] error`,t),Nm(`[${e.info.name}] error: ${t}`),r(t),i(new Lm(`Error spawning service ${e.info.name}: ${t}`,"SPAWN_ERROR"))}))}))}throw`Unsupported processor type ${e.info.processor}`}catch(t){if(r(t),t instanceof Lm)throw t;throw`Error spawning service ${e.info.name}: ${t}`}},Fm=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[Hc.Javascript,Hc.Executable,Hc.Python].includes(e?.processor)?null:"Invalid processor"},Bm=async(e,t)=>{const n=m.join(e,"manifest.json");if(!await jm(n)){const t=`Missing manifest for service ${e}. Aborting.`;return Nm(t),{error:t}}const r=await _(n,"utf-8"),i=tl(r),s=Fm(i);if(!i||s){const t=`Invalid service manifest [${e}]: ${s}. Aborting.`;return Nm(t),{error:t}}let o;if(delete i.internal,t?.singleServiceName&&i.name!==t.singleServiceName){return{error:`Skipping service ${i.name} as it does not match the singleServiceName option`}}await Promise.all([(async()=>{if(i.widgetUI)try{o=await _(m.join(e,"widgetUI.js"))}catch(e){const t=`Error loading widgetUI file ${i.name}: ${e}`;return Nm(t),{error:t}}})(),(async()=>{if(i.svgIcon){const t=await wm(m.join(e,i.svgIcon));if(!t){return{error:`Error loading icon for service ${i.name}`}}i.svgIcon=t}})(),(async()=>{if(i.subServices?.length)for(const t of i.subServices){const n=m.join(e,t),{error:r,service:s}=await Bm(n);r?Nm(`Error loading sub-service ${t}: ${r}`):s&&(s.info.parentService={name:i.name,version:i.version})}delete i.subServices})(),(async()=>{if(i.variants?.length)for(const t of i.variants)if(t.svgIcon)try{const n=await _(m.join(e,t.svgIcon),"utf-8");t.svgIcon=n}catch(e){Nm(`Error loading svgIcon for variant ${t.id}: ${e}`)}})()]);const a=fm(),c=t?.fixedSession||a;Nm(`Loaded service ${i.name} with sessionId ${c}`);const l=await _m(i,e,{widgetUIContents:o});return Um(l),Tm[c]={info:{...l,path:e,sessionId:c},status:"loaded",childProcess:null,logsEnabled:t?.logsEnabled},{service:Tm[c]}},Um=e=>{e.widgetUIContents?e.uiContentChecksum=(e=>{const t=f("sha256");return t.update(e),t.digest("hex")})(e.widgetUIContents):e.uiContentChecksum=void 0},Wm=async e=>{try{return e.childProcess=await Rm(e),e.status="started",e.errorMsg=void 0,e.errorCode=void 0,!0}catch(t){return Nm(`Service [${e.info.name}] error: ${t}`),e.status="error",t instanceof Lm?(e.errorMsg=t.message,e.errorCode=t.code):(e.errorMsg="string"==typeof t?t:JSON.stringify(t),e.errorCode="UNKNOWN_ERROR"),!1}},Ym=e=>{const{path:t,...n}=e.info;return{...n}},Gm=()=>Object.values(Tm).filter((e=>"running"===e.status)).map(Ym),Hm=e=>{const{serviceName:t,version:n,force:r}=e,i=Object.values(Tm).find((t=>t.info.name===e.serviceName&&t.info.version===e.version));if(!i)return null;if(i.info.internal&&!r)throw`Cannot stop internal service ${t}`;if(i.childProcess){Nm(`Stopping service "${t} (v${n})"`);i.childProcess.kill("SIGINT")||Nm(`Failed to stop service ${t}`)}return i.status="stopped",Nm(`Service ${t} stopped`),i},Vm=e=>e.info.internal?e.info.path:m.join(e.info.path,".."),zm=e=>!!e.internal;var qm={isOfficialKemuService:e=>e.name.startsWith("kemu.io"),loadServices:async(e,t)=>{if(!await Im(e))return void Nm(`Failed to load services from "${e}". Directory does not exist.`);const n=(await k(e,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name));Nm(`Found ${n.length} services in "${e}"`);for(let r=0;r<n.length;r++){const i=n[r],s=m.join(e,i),{error:o,service:a}=await Bm(`${s}${t?.internalServices?"":"/dist"}`,{...t,logsEnabled:Array.isArray(t?.enableLogs)?t?.enableLogs.includes(i):t?.enableLogs});o&&Nm(`Failed to load service ${s}. Please check logs`),a&&t?.internalServices&&(a.info.internal=!0)}},launchServices:async e=>{if(Nm("Initializing services"),!Am)throw new Error('IPC config not set, call "setHubIpcConfig" first.');for(const t in Tm){const n=Tm[t];e.noSpawningList&&e.noSpawningList.includes(n.info.name)?Nm(`Service ${n.info.name} is in the noSpawningList. Skipping.`):Wm(n)}Nm("Services initialized")},setServiceStatus:(e,t)=>{const n=Tm[e];return n?(n.status=t,!0):(Nm(`Service with serviceId ${e} not found`),!1)},getActiveServices:Gm,getMatchingService:(e,t)=>{const n=Object.values(Tm).filter((e=>"running"===e.status));for(const r of n)if(r.info.name===e){if(r.info.version===t)return r;if(cl(r.info.version,t,">="))return r}return null},getServiceBySessionId:e=>Tm[e]||null,killAllServices:()=>{for(const e in Tm){const t=Tm[e];if(t.childProcess)try{Nm(`Killing service ${t.info.name} with PID ${t.childProcess.pid}`),t.childProcess.kill()}catch(e){Nm(`Error killing service ${t.info.name}: ${e}`)}}},addDevService:async(e,t,n)=>{const r={info:{...await _m(t,t.path),sessionId:e},status:n,startedAt:new Date,devMode:!0,childProcess:null};Tm[e]=r,Um(Tm[e].info)},setServiceManifest:(e,t,n)=>{const r=Tm[e];if(!r)return Nm(`Service with sessionId ${e} not found`),!1;const i=Fm(t);if(i)return Nm(`Invalid manifest for service ${r.info.name}: ${i}`),!1;Um(t),r.info={...r.info,...t},n&&(r.status=n)},getMatchingDevService:(e,t,n)=>{const r=Object.values(Tm).filter((e=>e.devMode));for(const i of r)if(i.info.name===e&&i.status===n&&i.info.version===t)return i;return null},getInternalServices:()=>Gm().filter((e=>e.internal)),getAllServices:()=>Object.values(Tm),stopService:Hm,uninstallService:async(e,t)=>{Nm(`Uninstalling service ${e} v${t}`);const n=Hm({serviceName:e,version:t});if(!n)return!1;Nm(`Service ${e} stopped. Removing from disk...`);const r=Vm(n),i=Em();return r.startsWith(i)?(await E(r,{recursive:!0,force:!0}),Nm(`Service ${e} successfully removed from disk`),(e=>{const t=Tm[e];delete Tm[e]})(n.info.sessionId),!0):(Nm(`Service ${e} is not installed in the user services directory. Aborting.`),!1)},getAllServiceVersions:e=>Object.values(Tm).filter((t=>t.info.name===e)),setHubIpcConfig:e=>{Am={...e}},loadAndLaunch:async(e,t,n)=>{const r=b(e,t),{error:i,service:s}=await Bm(r);if(i||!s)return{errorMsg:i};try{s.info.internal=!!n,s.childProcess=await Rm(s),s.status="started"}catch(e){s.status="error",e instanceof Lm?(Nm(`Service spawning error: ${e.message} (${e.code})`),s.errorMsg=e.message,s.errorCode=e.code):(Nm(`Error launching service ${s.info.name}: ${e}`),s.errorMsg="string"==typeof e?e:JSON.stringify(e))}return{service:s,errorCode:s.errorCode,errorMsg:s.errorMsg}},getServiceRootDirectory:Vm,setSpawnNodeFunction:e=>{Pm=e},setGetSecretsFunction:e=>{Dm=e},restartService:async(e,t)=>{Nm(`Restarting service ${e} v${t}`);const n=Hm({serviceName:e,version:t,force:!0});return!!n&&Wm(n)},getFailedServices:()=>Object.values(Tm).filter((e=>"error"===e.status)).map((e=>({...Ym(e),errorMsg:e.errorMsg||"",errorCode:e.errorCode,status:e.status}))),isInternalKemuService:zm,isNotInternalKemuService:e=>!zm(e),isNotDevService:e=>!e.devMode};class Jm{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 Km{constructor(e){e||(e=new Jm),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 Zm=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={}},Xm=fl(Zm);var Qm=fl((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 ey{}class ty{}const ny=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 ey,t=ty){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 ey}}())}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 ry{constructor(){}on(e,t,n=!1){return ny.string(e),ny.function(t),ny.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(ny.string(e),e!=this.#e.toString()&&"*"!=e||(e=this.#e),!this.#t[e])return this;if("*"==t)return delete this.#t[e],this;ny.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){ny.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)=>{ny.string(e),ny.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 iy=new Km;class sy extends ry{constructor(e,t){super(),this.config=e,this.log=t,this.publish=super.emit,e.maxRetries&&(this.retriesRemaining=e.maxRetries),iy=new Km(this.config)}Client=sy;queue=new Qm;socket=!1;connect=cy;emit=oy;retriesRemaining=0;explicitlyDisconnected=!1}function oy(e,t){this.log("dispatching event to ",this.id,this.path," : ",e,",",t);let n=new Xm;n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):iy.format(n),this.config.sync?this.queue.add(ay.bind(this,n)):this.socket.write(n)}function ay(e){this.log("dispatching event to ",this.id,this.path," : ",e),this.socket.write(e)}function cy(){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=P.readFileSync(e.config.tls.private)),e.config.tls.public&&(e.config.tls.cert=P.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(P.readFileSync(e.config.tls.trustedConnections[t]))}Object.assign(e.config.tls,t),e.socket=U.connect(e.config.tls)}else e.log("Connecting client via TCP to",t),e.socket=B.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=B.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)!=iy.delimiter||-1==t.indexOf(iy.delimiter))return void e.log("Messages are large, You may want to consider smaller messages.");this.ipcBuffer="";const n=iy.parse(t),r=n.length;for(let t=0;t<r;t++){let r=new Xm;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 ly=new Km;class uy extends ry{constructor(e,t,n,r){super(),this.config=t,this.path=e,this.port=r,this.log=n,this.publish=super.emit,ly=new Km(this.config),this.on("close",fy.bind(this))}udp4=!1;udp6=!1;server=!1;sockets=[];emit=dy;broadcast=hy;onStart(e){this.publish("start",e)}stop(){this.server.close()}start(){this.path?this.config.unlink?P.unlink(this.path,yy.bind(this)):yy.bind(this)():this.log("Socket Server Path not specified, refusing to start")}}function dy(e,t,n){this.log("dispatching event to socket"," : ",t,n);let r=new Xm;if(r.type=t,r.data=n,this.config.rawBuffer?(this.log(this.config.encoding),r=Buffer.from(t,this.config.encoding)):r=ly.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 hy(e,t){this.log("broadcasting event to all known sockets listening to ",this.path," : ",this.port?this.port:"",e,t);let n=new Xm;if(n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):ly.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 fy(){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 py(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)==ly.delimiter&&-1!=t.indexOf(ly.delimiter))for(r.ipcBuffer="",t=ly.parse(t);t.length>0;){let e=new Xm;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 gy(e){this.publish("close",e)}function my(e){this.sockets.push(e),e.setEncoding&&e.setEncoding(this.config.encoding),this.log("## socket connection to server detected ##"),e.on("close",gy.bind(this)),e.on("error",function(e){this.log("server socket error",e),this.publish("error",e)}.bind(this)),e.on("data",py.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 yy(){return this.log("starting server on ",this.path,this.port?`:${this.port}`:""),this.udp4||this.udp6?(this.server=W.createSocket(this.udp4?"udp4":"udp6"),this.server.write=by.bind(this),this.server.on("listening",function(){my.bind(this)(this.server)}.bind(this))):(this.log("starting TLS server",this.config.tls),this.config.tls?vy.bind(this)():this.server=B.createServer(my.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 vy(){if(this.log("starting TLS server",this.config.tls),this.config.tls.private?this.config.tls.key=P.readFileSync(this.config.tls.private):this.config.tls.key=P.readFileSync(`${__dirname}/../local-node-ipc-certs/private/server.key`),this.config.tls.public?this.config.tls.cert=P.readFileSync(this.config.tls.public):this.config.tls.cert=P.readFileSync(`${__dirname}/../local-node-ipc-certs/server.pub`),this.config.tls.dhparam&&(this.config.tls.dhparam=P.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(P.readFileSync(this.config.tls.trustedConnections[e]))}this.server=U.createServer(this.config.tls,my.bind(this))}function by(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 wy{constructor(){}config=new Jm;of={};server=!1;get connectTo(){return Ey}get connectToNet(){return Cy}get disconnect(){return _y}get serve(){return Iy}get serveNet(){return ky}get log(){return Sy}set connectTo(e){return Ey}set connectToNet(e){return Cy}set disconnect(e){return _y}set serve(e){return Iy}set serveNet(e){return ky}set log(e){return Sy}}function Sy(...e){if(!this.config.silent){for(let t=0,n=e.length;t<n;t++)"object"==typeof e[t]&&(e[t]=c.inspect(e[t],{depth:this.config.logDepth,colors:this.config.logInColor}));this.config.logger(e.join(" "))}}function _y(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 Iy(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=xy),this.server=new uy(e,this.config,Sy),this.server.on("start",t)}function xy(){}function ky(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=xy),this.server=new uy(e,this.config,Sy,t),n&&(this.server[n]=!0,"udp4"===n&&"::1"===e&&(this.server.path="127.0.0.1")),this.server.on("start",r)}function Ey(e,t,n){if("function"==typeof t&&(n=t,t=!1),n||(n=xy),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 sy(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 Cy(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=xy),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 sy(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 Oy=new class extends wy{constructor(){super()}IPC=wy};var $y={id:"widgets",retry:1500,silent:!0,rawBuffer:!0,appspace:"kemu.",encoding:"hex"};const My=Object.values({protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8}).reduce(((e,t)=>e+t),0),Ny=e=>{try{return JSON.parse(e)}catch(e){return null}},Ty="undefined"!=typeof window,Ay={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},Py={protocolPrefix:4,txtLength:4},Dy=Object.values(Ay).reduce(((e,t)=>e+t),0),Ly=Object.values(Py).reduce(((e,t)=>e+t),0),jy=["width","height","colorSpace"],Ry=(e,t)=>{const n={},r=[];let i=0,s=Array.isArray(e)?[]:{};const o=(e,s)=>{const a=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,i=e instanceof Uint8Array,s=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":i?"Uint8Array":s?"Int8Array":null})(e);if(!a){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=o(e[n],`${s}[${n}]`);return t}if("object"==typeof e){const t={},n=(e=>{const t=e instanceof Int16Array,n=e instanceof Uint16Array,r=e instanceof Int32Array,i=e instanceof Uint32Array,s=e instanceof Float32Array,o=e instanceof Float64Array,a=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":i?"Uint32Array":s?"Float32Array":o?"Float64Array":a?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${s}"`);for(const n in e)Object.hasOwn(e,n)||jy.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${s}`),t[n]=o(e[n],`${s.length?`${s}.`:""}${n}`);return t}return e}n[s]={index:i,length:e.byteLength,binaryType:a},"Buffer"===t?r.push(Buffer.from(e)):"ArrayBuffer"===a?r.push(e):r.push(e.buffer),i+=e.byteLength};s=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:s}:null},Fy=(e,t,n)=>{const r=t.match(/(\[\d+\])|([^[\].]+)/g)||[];let i=e;for(let e=0;e<r.length;e++){let t=r[e];const s=t.startsWith("[")&&t.endsWith("]"),o=e===r.length-1;if(s){t=t.slice(1,-1);const s=parseInt(t,10);if(!Array.isArray(i))throw new Error(`Expected an array at key "${r.slice(0,e).join(".")}" but found an object.`);o?i[s]=n:(i[s]||(i[s]=r[e+1].startsWith("[")?[]:{}),i=i[s])}else o?i[t]=n:(i[t]||(i[t]=r[e+1].startsWith("[")?[]:{}),i=i[t])}return e},By=(e,t,n)=>{const r="undefined"!=typeof Buffer,i=t instanceof Uint8Array;for(const s in n)if(Object.hasOwn(n,s)){const{index:o,length:a,binaryType:c}=n[s];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=i?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a):t.slice(o,o+a);break;case"Uint8Array":l=i?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&&Fy(e,s,l)}return e},Uy=e=>Nl(e),Wy="KMSG",Yy="KCMD",Gy=Uy("klProtocol");var Hy={encode:(e,t,n)=>{const r={json:e.json},i=Ry(r.json,"Buffer"),s=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const o=s?s.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),l=c.byteLength,u=Ay.protocolPrefix+Ay.protocolVersion+Ay.jsonLength+Ay.binaryLength+Ay.fromServiceId+Ay.toServiceId+Ay.sentAt+l+o,d=Buffer.alloc(u),h=Date.now();let f=0;return d.write(Wy,f),f+=Ay.protocolPrefix,d.writeUInt8(1,f),f+=Ay.protocolVersion,d.writeUInt32LE(l,f),f+=Ay.jsonLength,d.writeUInt32LE(o,f),f+=Ay.binaryLength,d.writeUInt32LE(t,f),f+=Ay.fromServiceId,d.writeUInt32LE(n,f),f+=Ay.toServiceId,d.writeBigInt64LE(BigInt(h),f),f+=Ay.sentAt,c.copy(d,f),f+=l,s&&o&&s.copy(d,f),d},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,Ay.protocolPrefix);if(t+=Ay.protocolPrefix,n!==Wy)return null;if(e.byteLength<Dy)return Gy(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=Ay.protocolVersion;const i=e.readUInt32LE(t);t+=Ay.jsonLength;const s=e.readUInt32LE(t);t+=Ay.binaryLength;const o=e.readUInt32LE(t);t+=Ay.fromServiceId;const a=e.readUInt32LE(t);t+=Ay.toServiceId;const c=e.readBigInt64LE(t);t+=Ay.sentAt;const l=i+s,u=e.subarray(t,t+l),d=e.subarray(0,Dy);let h=null;return e.byteLength-Dy-i-s>0&&(h=e.subarray(Dy+i+s)),{header:{protocolVersion:r,jsonLength:i,binaryLength:s,fromServiceId:o,toServiceId:a,sentAt:new Date(Number(c)),packages:[u],headerPackage:d},remaining:h}},decodeFullKlMessage:e=>{const t=Buffer.concat(e.packages),n=t.subarray(0,e.jsonLength).toString(),r=t.subarray(e.jsonLength,e.jsonLength+e.binaryLength),i=Ny(n);if(!i?.json)return Gy("Invalid JSON in KL message"),null;i.jsonBinaryMap&&r.byteLength&&By(i.json,r,i.jsonBinaryMap);const s=Buffer.concat([e.headerPackage,t]);let o=s,a=null;const c=Dy+e.jsonLength+e.binaryLength;return s.byteLength>c&&(a=s.subarray(c),o=s.subarray(0,c)),{message:{json:i.json,rawMessage:o},remaining:a}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Dy)return Gy("Invalid Header Size"),e;let n=0;return n+=Ay.protocolPrefix,n+=Ay.protocolVersion,n+=Ay.jsonLength,n+=Ay.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=Ay.fromServiceId,void 0!==t.toServiceId&&e.writeUInt32LE(t.toServiceId,n),e},encodeCommand:e=>{let t=0;const n=Buffer.from(e),r=n.byteLength,i=Ly+r,s=Buffer.alloc(i);return s.write(Yy,t),t+=Py.protocolPrefix,s.writeUint32LE(r,t),t+=Py.txtLength,n.copy(s,t),s},decodeCommand:e=>{let t=0;if(e.byteLength<Ly)return{command:null};const n=e.toString("utf-8",t,Py.protocolPrefix);if(t+=Py.protocolPrefix,n!==Yy)return{command:null};const r=e.readUInt32LE(t);t+=Py.txtLength;const i=e.toString("utf-8",t,t+r),s=e.byteLength-Ly-r;let o=null;s>0&&(o=e.subarray(Ly+r));let a=0;return s<0&&(a=Math.abs(s)),{command:i,remainingData:o,missing:a}}};const Vy="KMSG",zy="KCMD",qy=Uy("klProtocol"),Jy=new TextEncoder;var Ky={encode:(e,t,n)=>{const r={json:e.json},i=Ry(e.json,"ArrayBuffer"),s=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const o=s?s.byteLength:0,a=JSON.stringify(r),c=Jy.encode(a),l=c.byteLength,u=new ArrayBuffer(Ay.protocolPrefix+Ay.protocolVersion+Ay.jsonLength+Ay.binaryLength+Ay.fromServiceId+Ay.toServiceId+Ay.sentAt+l+o),d=new DataView(u),h=new Uint8Array(u),f=Date.now();let p=0;for(let e=0;e<4;++e)h[p++]=Vy.charCodeAt(e);return d.setUint8(p,1),p+=Ay.protocolVersion,d.setUint32(p,l,!0),p+=Ay.jsonLength,d.setUint32(p,o,!0),p+=Ay.binaryLength,d.setUint32(p,t,!0),p+=Ay.fromServiceId,d.setUint32(p,n,!0),p+=Ay.toServiceId,d.setBigInt64(p,BigInt(f),!0),p+=Ay.sentAt,h.set(c,p),p+=l,s&&o&&h.set(new Uint8Array(s),p),u},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<Ay.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Vy)return null;if(e.byteLength<Dy)return qy.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const i=t.getUint8(n);n+=Ay.protocolVersion;const s=t.getUint32(n,!0);n+=Ay.jsonLength;const o=t.getUint32(n,!0);n+=Ay.binaryLength;const a=t.getUint32(n,!0);n+=Ay.fromServiceId;const c=t.getUint32(n,!0);n+=Ay.toServiceId;const l=t.getBigInt64(n,!0);n+=Ay.sentAt;const u=s+o,d=e.slice(n,n+u),h=new Uint8Array(e,0,Dy);let f=null;if(e.byteLength-Dy-s-o>0){f=new Uint8Array(e,Dy+s+o).slice().buffer}return{header:{protocolVersion:i,jsonLength:s,binaryLength:o,fromServiceId:a,toServiceId:c,sentAt:new Date(Number(l)),packages:[d],headerPackage:h.slice().buffer},remaining:f}},decodeFullKlMessage:e=>{const t=e.packages.reduce(((e,t)=>e+t.byteLength),0),n=new Uint8Array(t);let r,i=0;for(const t of e.packages)r=new Uint8Array(t),n.set(r,i),i+=r.byteLength;const s=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),o=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=Ny(s);if(!a?.json)return qy.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&o.byteLength&&By(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=Dy+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<Dy)return qy("Invalid Header Size"),e;let n=0;n+=Ay.protocolPrefix,n+=Ay.protocolVersion,n+=Ay.jsonLength,n+=Ay.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=Ay.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=Jy.encode(e),r=n.byteLength,i=new ArrayBuffer(Ly+r),s=new DataView(i),o=new Uint8Array(i);for(let e=0;e<4;++e)o[t++]=zy.charCodeAt(e);return s.setUint32(t,r,!0),t+=Py.txtLength,o.set(n,t),i},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<Ly)return{command:null};let r="";for(let e=0;e<Py.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==zy)return{command:null};const i=t.getUint32(n,!0);n+=Py.txtLength;const s=e.byteLength-Ly-i,o=new Uint8Array(e,n,Math.min(i,e.byteLength-Ly)),a=(new TextDecoder).decode(o);let c=null;s>0&&(c=e.slice(Ly+i));let l=0;return s<0&&(l=Math.abs(s)),{command:a,remainingData:c,missing:l}}};const Zy=Uy("klTransmissionManager"),Xy=()=>{const e=(t,n,r,i)=>{let s=n,o=null;const a=t instanceof ArrayBuffer;if(Zy(`RAW: ${t.toString()}`),!s||s.partialHeaderData){let c;if(a?(c=s?.partialHeaderData?new Uint8Array([...new Uint8Array(s.partialHeaderData),...new Uint8Array(t)]).buffer:t,o=Ky.decodeHeader(c)):(c=s?.partialHeaderData?Buffer.concat([s.partialHeaderData,t]):t,o=Hy.decodeHeader(c)),!o){const{command:t,missing:s,remainingData:o}=a?Ky.decodeCommand(c):Hy.decodeCommand(c);return t?i({command:t,complete:!0,rawMessage:c}):Zy(s?`ERROR: Missing ${s} 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?(Zy(`${o.byteLength} bytes remain after processing command. Re-analyzing...`),e(o,n,r,i)):void 0}if(o.partialHeader)return s={firstPackageAt:Date.now(),partialHeaderData:c},r(s);if(!o.header)return Zy(`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${c.byteLength} bytes`);const l=o.header;s={firstPackageAt:Date.now(),header:{...l,totalBytesReceived:l.packages[0].byteLength,totalBytesExpected:l.binaryLength+l.jsonLength,remaining:o.remaining}},r(s)}else s.header&&s.header.totalBytesReceived<s.header.totalBytesExpected&&(s.header.packages.push(t),s.header.totalBytesReceived+=t.byteLength,r(s));if(s.header&&s.header.totalBytesReceived>=s.header.totalBytesExpected){const t=Date.now()-s.header.sentAt.getTime(),n=Date.now()-s.firstPackageAt;Zy(`Received ${s.header.totalBytesReceived} of ${s.header.totalBytesExpected} expected in ${t} ms, elapsed since first package: ${n}ms`);const o=a?Ky.decodeFullKlMessage(s.header):Hy.decodeFullKlMessage(s.header),c=s.header.totalBytesReceived,l=s.header.remaining;r(null),o&&i({klMessage:o.message,complete:!0,sourceServiceId:s.header.fromServiceId,targetServiceId:s.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),i=new Uint8Array(e),s=new Uint8Array(t),o=new Uint8Array(r);return o.set(i),o.set(s,i.length),r})(l,o.remaining):o.remaining:l?Buffer.concat([l,o.remaining]):o.remaining),u)return Zy(`${u.byteLength} bytes remaining after processing message with ${c} bytes of data. Re-analyzing...`),e(u,null,r,i)}};return e};Oy.config={...Oy.config,...$y};const Qy={info:Tl("ipcServer:info"),data:Tl("ipcServer:data")};let ev,tv,nv,rv,iv={};const sv=Xy(),ov=e=>{iv[e]&&(Qy.info(`Client disconnected [${e}]`),delete iv[e],tv&&tv(e))};var av=e=>(e?.ipcId&&(Oy.config.id=e.ipcId),e?.ipcAppSpace&&(Oy.config.appspace=e.ipcAppSpace),new Promise((e=>{Oy.serve((()=>{Qy.info("IPC Server Initiated"),Oy.server.on("data",((e,t)=>{const n=iv[t.id];n?(Qy.data(`IPC Socket [${t.id}] data ${e.byteLength} bytes`),sv(e,n.activeMessage,(e=>n.activeMessage=e),(e=>{if(!e.complete)return;const n=e=>{t.write(e)};if(e.command)return Qy.data(`Received command from client [${t.id}]: ${e.command}`),void(nv&&nv(t.id,e.command,n));e.klMessage&&rv&&rv({send:n,transmission:{sourceServiceId:e.sourceServiceId??-1,targetServiceId:e.targetServiceId??-1,rawMessage:e.rawMessage},json:e.klMessage.json})}))):Qy.data(`Received data from unknown client [${t.id}]. Ignoring.`)})),Oy.server.on("connect",(e=>{const t=fm();Qy.info(`New client connected. Registered as "${t}"`),e.id=t,iv[t]={socket:e,activeMessage:null,disconnectHandler:()=>ov(t)},e.on("close",iv[t].disconnectHandler),ev&&ev(t)})),Oy.server.on("disconnect",(e=>{ov(e.id)})),Oy.server.on("error",(e=>{console.log(`IPC Server Error: ${e}`)})),e()})),Oy.server.start()}))),cv=e=>{ev=e},lv=e=>{tv=e},uv=e=>rv=e,dv=(e,t)=>{const n=iv[e];if(!n)return Qy.info(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=My)return Qy.info("Message is too long to be a command. Use sendMessage instead."),!1;const r=Hy.encodeCommand(t);return n.socket.write(r),!0},hv=(e,t)=>{const n=iv[e];return!!n&&(Qy.info(`Renaming socket id [${e}] to [${t}]`),delete iv[e],n.socket.id=t,iv[t]=n,n.socket.removeListener("close",n.disconnectHandler),n.disconnectHandler=()=>ov(t),n.socket.on("close",n.disconnectHandler),!0)},fv=e=>{nv=e};let pv=Hy;Ty&&(pv=Ky);var gv,mv=pv;!function(e){e.FunctionNotFound="FNC_NOT_FOUND",e.ParentEventCallbackError="PARENT_EVENT_CALLBACK_ERROR"}(gv||(gv={}));let yv=Math.ceil(Date.now()/1e3);var vv={exports:{}};const bv=["nodebuffer","arraybuffer","fragments"],wv="undefined"!=typeof Blob;wv&&bv.push("blob");var Sv={BINARY_TYPES:bv,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:wv,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:_v}=Sv,Iv=Buffer[Symbol.species];function xv(e,t,n,r,i){for(let s=0;s<i;s++)n[r+s]=e[s]^t[3&s]}function kv(e,t){for(let n=0;n<e.length;n++)e[n]^=t[3&n]}if(vv.exports={concat:function(e,t){if(0===e.length)return _v;if(1===e.length)return e[0];const n=Buffer.allocUnsafe(t);let r=0;for(let t=0;t<e.length;t++){const i=e[t];n.set(i,r),r+=i.length}return r<t?new Iv(n.buffer,n.byteOffset,r):n},mask:xv,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 Iv(t):ArrayBuffer.isView(t)?n=new Iv(t.buffer,t.byteOffset,t.byteLength):(n=Buffer.from(t),e.readOnly=!1),n},unmask:kv},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");vv.exports.mask=function(t,n,r,i,s){s<48?xv(t,n,r,i,s):e.mask(t,n,r,i,s)},vv.exports.unmask=function(t,n){t.length<32?kv(t,n):e.unmask(t,n)}}catch(e){}var Ev=vv.exports;const Cv=Symbol("kDone"),Ov=Symbol("kRun");const $v=L,Mv=Ev,Nv=class{constructor(e){this[Cv]=()=>{this.pending--,this[Ov]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ov]()}[Ov](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[Cv])}}},{kStatusCode:Tv}=Sv,Av=Buffer[Symbol.species],Pv=Buffer.from([0,0,255,255]),Dv=Symbol("permessage-deflate"),Lv=Symbol("total-length"),jv=Symbol("callback"),Rv=Symbol("buffers"),Fv=Symbol("error");let Bv;var Uv=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,!Bv){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;Bv=new Nv(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[jv];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){Bv.add((r=>{this._decompress(e,t,((e,t)=>{r(),n(e,t)}))}))}compress(e,t,n){Bv.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]?$v.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=$v.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[Dv]=this,this._inflate[Lv]=0,this._inflate[Rv]=[],this._inflate.on("error",Gv),this._inflate.on("data",Yv)}this._inflate[jv]=n,this._inflate.write(e),t&&this._inflate.write(Pv),this._inflate.flush((()=>{const e=this._inflate[Fv];if(e)return this._inflate.close(),this._inflate=null,void n(e);const i=Mv.concat(this._inflate[Rv],this._inflate[Lv]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Lv]=0,this._inflate[Rv]=[],t&&this.params[`${r}_no_context_takeover`]&&this._inflate.reset()),n(null,i)}))}_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]?$v.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=$v.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[Lv]=0,this._deflate[Rv]=[],this._deflate.on("data",Wv)}this._deflate[jv]=n,this._deflate.write(e),this._deflate.flush($v.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=Mv.concat(this._deflate[Rv],this._deflate[Lv]);t&&(e=new Av(e.buffer,e.byteOffset,e.length-4)),this._deflate[jv]=null,this._deflate[Lv]=0,this._deflate[Rv]=[],t&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),n(null,e)}))}};function Wv(e){this[Rv].push(e),this[Lv]+=e.length}function Yv(e){this[Lv]+=e.length,this[Dv]._maxPayload<1||this[Lv]<=this[Dv]._maxPayload?this[Rv].push(e):(this[Fv]=new RangeError("Max payload size exceeded"),this[Fv].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Fv][Tv]=1009,this.removeListener("data",Yv),this.reset())}function Gv(e){this[Dv]._inflate=null,e[Tv]=1007,this[jv](e)}var Hv={exports:{}};const{isUtf8:Vv}=T,{hasBlob:zv}=Sv;function qv(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(Hv.exports={isBlob:function(e){return zv&&"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:qv,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]},Vv)Hv.exports.isValidUTF8=function(e){return e.length<24?qv(e):Vv(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");Hv.exports.isValidUTF8=function(t){return t.length<32?qv(t):e(t)}}catch(e){}var Jv=Hv.exports;const{Writable:Kv}=N,Zv=Uv,{BINARY_TYPES:Xv,EMPTY_BUFFER:Qv,kStatusCode:eb,kWebSocket:tb}=Sv,{concat:nb,toArrayBuffer:rb,unmask:ib}=Ev,{isValidStatusCode:sb,isValidUTF8:ob}=Jv,ab=Buffer[Symbol.species];var cb=class extends Kv{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||Xv[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[tb]=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 ab(t.buffer,t.byteOffset+e,t.length-e),new ab(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 ab(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[Zv.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=Qv;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]&&ib(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[Zv.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?nb(n,t):"arraybuffer"===this._binaryType?rb(nb(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=nb(n,t);if(!this._skipUTF8Validation&&!ob(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,Qv),this.end();else{const n=e.readUInt16BE(0);if(!sb(n)){const e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const r=new ab(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!ob(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,i){this._loop=!1,this._errored=!0;const s=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(s,this.createError),s.code=i,s[eb]=r,s}};const{randomFillSync:lb}=u,ub=Uv,{EMPTY_BUFFER:db,kWebSocket:hb,NOOP:fb}=Sv,{isBlob:pb,isValidStatusCode:gb}=Jv,{mask:mb,toBuffer:yb}=Ev,vb=Symbol("kByteLength"),bb=Buffer.alloc(4),wb=8192;let Sb,_b=wb;var Ib=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=fb,this[hb]=void 0}static frame(e,t){let n,r,i=!1,s=2,o=!1;t.mask&&(n=t.maskBuffer||bb,t.generateMask?t.generateMask(n):(_b===wb&&(void 0===Sb&&(Sb=Buffer.alloc(wb)),lb(Sb,0,wb),_b=0),n[0]=Sb[_b++],n[1]=Sb[_b++],n[2]=Sb[_b++],n[3]=Sb[_b++]),o=!(n[0]|n[1]|n[2]|n[3]),s=6),"string"==typeof e?r=t.mask&&!o||void 0===t[vb]?(e=Buffer.from(e)).length:t[vb]:(r=e.length,i=t.mask&&t.readOnly&&!o);let a=r;r>=65536?(s+=8,a=127):r>125&&(s+=2,a=126);const c=Buffer.allocUnsafe(i?r+s:s);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[s-4]=n[0],c[s-3]=n[1],c[s-2]=n[2],c[s-1]=n[3],o?[c,e]:i?(mb(e,n,c,s,r),[c]):(mb(e,n,e,0,r),[c,e])):[c,e]}close(t,n,r,i){let s;if(void 0===t)s=db;else{if("number"!=typeof t||!gb(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");s=Buffer.allocUnsafe(2+e),s.writeUInt16BE(t,0),"string"==typeof n?s.write(n,2):s.set(n,2)}else s=Buffer.allocUnsafe(2),s.writeUInt16BE(t,0)}const o={[vb]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,s,!1,o,i]):this.sendFrame(e.frame(s,o),i)}ping(t,n,r){let i,s;if("string"==typeof t?(i=Buffer.byteLength(t),s=!1):pb(t)?(i=t.size,s=!1):(i=(t=yb(t)).length,s=yb.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[vb]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};pb(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 i,s;if("string"==typeof t?(i=Buffer.byteLength(t),s=!1):pb(t)?(i=t.size,s=!1):(i=(t=yb(t)).length,s=yb.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[vb]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};pb(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[ub.extensionName];let i,s,o=t.binary?2:1,a=t.compress;"string"==typeof e?(i=Buffer.byteLength(e),s=!1):pb(e)?(i=e.size,s=!1):(i=(e=yb(e)).length,s=yb.readOnly),this._firstFragment?(this._firstFragment=!1,a&&r&&r.params[r._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=i>=r._threshold),this._compress=a):(a=!1,o=0),t.fin&&(this._firstFragment=!0);const c={[vb]:i,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:s,rsv1:a};pb(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,i){this._bufferedBytes+=r[vb],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(xb,this,e,i)}this._bufferedBytes-=r[vb];const s=yb(t);n?this.dispatch(s,n,r,i):(this._state=0,this.sendFrame(e.frame(s,r),i),this.dequeue())})).catch((e=>{process.nextTick(kb,this,e,i)}))}dispatch(t,n,r,i){if(!n)return void this.sendFrame(e.frame(t,r),i);const s=this._extensions[ub.extensionName];this._bufferedBytes+=r[vb],this._state=1,s.compress(t,r.fin,((t,n)=>{if(this._socket.destroyed){xb(this,new Error("The socket was closed while data was being compressed"),i)}else this._bufferedBytes-=r[vb],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),i),this.dequeue()}))}dequeue(){for(;0===this._state&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][vb],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][vb],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 xb(e,t,n){"function"==typeof n&&n(t);for(let n=0;n<e._queue.length;n++){const r=e._queue[n],i=r[r.length-1];"function"==typeof i&&i(t)}}function kb(e,t,n){xb(e,t,n),e.onerror(t)}const{kForOnEventAttribute:Eb,kListener:Cb}=Sv,Ob=Symbol("kCode"),$b=Symbol("kData"),Mb=Symbol("kError"),Nb=Symbol("kMessage"),Tb=Symbol("kReason"),Ab=Symbol("kTarget"),Pb=Symbol("kType"),Db=Symbol("kWasClean");class Lb{constructor(e){this[Ab]=null,this[Pb]=e}get target(){return this[Ab]}get type(){return this[Pb]}}Object.defineProperty(Lb.prototype,"target",{enumerable:!0}),Object.defineProperty(Lb.prototype,"type",{enumerable:!0});class jb extends Lb{constructor(e,t={}){super(e),this[Ob]=void 0===t.code?0:t.code,this[Tb]=void 0===t.reason?"":t.reason,this[Db]=void 0!==t.wasClean&&t.wasClean}get code(){return this[Ob]}get reason(){return this[Tb]}get wasClean(){return this[Db]}}Object.defineProperty(jb.prototype,"code",{enumerable:!0}),Object.defineProperty(jb.prototype,"reason",{enumerable:!0}),Object.defineProperty(jb.prototype,"wasClean",{enumerable:!0});class Rb extends Lb{constructor(e,t={}){super(e),this[Mb]=void 0===t.error?null:t.error,this[Nb]=void 0===t.message?"":t.message}get error(){return this[Mb]}get message(){return this[Nb]}}Object.defineProperty(Rb.prototype,"error",{enumerable:!0}),Object.defineProperty(Rb.prototype,"message",{enumerable:!0});class Fb extends Lb{constructor(e,t={}){super(e),this[$b]=void 0===t.data?null:t.data}get data(){return this[$b]}}Object.defineProperty(Fb.prototype,"data",{enumerable:!0});const Bb={addEventListener(e,t,n={}){for(const r of this.listeners(e))if(!n[Eb]&&r[Cb]===t&&!r[Eb])return;let r;if("message"===e)r=function(e,n){const r=new Fb("message",{data:n?e:e.toString()});r[Ab]=this,Wb(t,this,r)};else if("close"===e)r=function(e,n){const r=new jb("close",{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[Ab]=this,Wb(t,this,r)};else if("error"===e)r=function(e){const n=new Rb("error",{error:e,message:e.message});n[Ab]=this,Wb(t,this,n)};else{if("open"!==e)return;r=function(){const e=new Lb("open");e[Ab]=this,Wb(t,this,e)}}r[Eb]=!!n[Eb],r[Cb]=t,n.once?this.once(e,r):this.on(e,r)},removeEventListener(e,t){for(const n of this.listeners(e))if(n[Cb]===t&&!n[Eb]){this.removeListener(e,n);break}}};var Ub={CloseEvent:jb,ErrorEvent:Rb,Event:Lb,EventTarget:Bb,MessageEvent:Fb};function Wb(e,t,n){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}const{tokenChars:Yb}=Jv;function Gb(e,t,n){void 0===e[t]?e[t]=[n]:e[t].push(n)}var Hb={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,i=Object.create(null),s=!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===Yb[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?(Gb(t,r,i),i=Object.create(null)):n=r,c=u=-1}}else-1===u&&-1!==c&&(u=d);else if(void 0===r)if(-1===u&&1===Yb[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),Gb(i,e.slice(c,u),!0),44===l&&(Gb(t,n,i),i=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!==Yb[l])throw new SyntaxError(`Unexpected character at index ${d}`);-1===c?c=d:s||(s=!0),o=!1}else if(a)if(1===Yb[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===Yb[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);s&&(o=o.replace(/\\/g,""),s=!1),Gb(i,r,o),44===l&&(Gb(t,n,i),i=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 h=e.slice(c,u);return void 0===n?Gb(t,h,i):(void 0===r?Gb(i,h,!0):Gb(i,r,s?h.replace(/\\/g,""):h),Gb(t,n,i)),t}};const Vb=A,zb=F,qb=R,Jb=B,Kb=U,{randomBytes:Zb,createHash:Xb}=u,{URL:Qb}=Y,ew=Uv,tw=cb,nw=Ib,{isBlob:rw}=Jv,{BINARY_TYPES:iw,EMPTY_BUFFER:sw,GUID:ow,kForOnEventAttribute:aw,kListener:cw,kStatusCode:lw,kWebSocket:uw,NOOP:dw}=Sv,{EventTarget:{addEventListener:hw,removeEventListener:fw}}=Ub,{format:pw,parse:gw}=Hb,{toBuffer:mw}=Ev,yw=3e4,vw=Symbol("kAborted"),bw=[8,13],ww=["CONNECTING","OPEN","CLOSING","CLOSED"],Sw=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;let _w=class e extends Vb{constructor(t,n,r){super(),this._binaryType=iw[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=sw,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]),xw(this,t,n,r)):(this._autoPong=r.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){iw.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 i=new tw({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),s=new nw(t,this._extensions,r.generateMask);this._receiver=i,this._sender=s,this._socket=t,i[uw]=this,s[uw]=this,t[uw]=this,i.on("conclude",Mw),i.on("drain",Nw),i.on("error",Tw),i.on("message",Pw),i.on("ping",Dw),i.on("pong",Lw),s.onerror=Rw,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on("close",Bw),t.on("data",Uw),t.on("end",Ww),t.on("error",Yw),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[ew.extensionName]&&this._extensions[ew.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())})),Fw(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";Ow(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||sw,n,r)):$w(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||sw,n,r)):$w(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 $w(this,t,r);const i={binary:"string"!=typeof t,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[ew.extensionName]||(i.compress=!1),this._sender.send(t||sw,i,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";Ow(this,this._req,e)}}};Object.defineProperty(_w,"CONNECTING",{enumerable:!0,value:ww.indexOf("CONNECTING")}),Object.defineProperty(_w.prototype,"CONNECTING",{enumerable:!0,value:ww.indexOf("CONNECTING")}),Object.defineProperty(_w,"OPEN",{enumerable:!0,value:ww.indexOf("OPEN")}),Object.defineProperty(_w.prototype,"OPEN",{enumerable:!0,value:ww.indexOf("OPEN")}),Object.defineProperty(_w,"CLOSING",{enumerable:!0,value:ww.indexOf("CLOSING")}),Object.defineProperty(_w.prototype,"CLOSING",{enumerable:!0,value:ww.indexOf("CLOSING")}),Object.defineProperty(_w,"CLOSED",{enumerable:!0,value:ww.indexOf("CLOSED")}),Object.defineProperty(_w.prototype,"CLOSED",{enumerable:!0,value:ww.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(_w.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(_w.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[aw])return t[cw];return null},set(t){for(const t of this.listeners(e))if(t[aw]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[aw]:!0})}})})),_w.prototype.addEventListener=hw,_w.prototype.removeEventListener=fw;var Iw=_w;function xw(e,t,n,r){const i={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:bw[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=i.autoPong,!bw.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${bw.join(", ")})`);let s;if(t instanceof Qb)s=t;else try{s=new Qb(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}"http:"===s.protocol?s.protocol="ws:":"https:"===s.protocol&&(s.protocol="wss:"),e._url=s.href;const o="wss:"===s.protocol,a="ws+unix:"===s.protocol;let c;if("ws:"===s.protocol||o||a?a&&!s.pathname?c="The URL's pathname is empty":s.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 kw(e,t)}const l=o?443:80,u=Zb(16).toString("base64"),d=o?zb.request:qb.request,h=new Set;let f,p;if(i.createConnection=i.createConnection||(o?Cw:Ew),i.defaultPort=i.defaultPort||l,i.port=s.port||l,i.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},i.path=s.pathname+s.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(f=new ew(!0!==i.perMessageDeflate?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=pw({[ew.extensionName]:f.offer()})),n.length){for(const e of n){if("string"!=typeof e||!Sw.test(e)||h.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(e)}i.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(s.username||s.password)&&(i.auth=`${s.username}:${s.password}`),a){const e=i.path.split(":");i.socketPath=e[0],i.path=e[1]}if(i.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=o,e._originalHostOrSocketPath=a?i.socketPath:s.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&&i.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&s.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!o)&&(delete i.headers.authorization,delete i.headers.cookie,t||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),p=e._req=d(i),e._redirects&&e.emit("redirect",e.url,p)}else p=e._req=d(i);i.timeout&&p.on("timeout",(()=>{Ow(e,p,"Opening handshake has timed out")})),p.on("error",(t=>{null===p||p[vw]||(p=e._req=null,kw(e,t))})),p.on("response",(s=>{const o=s.headers.location,a=s.statusCode;if(o&&i.followRedirects&&a>=300&&a<400){if(++e._redirects>i.maxRedirects)return void Ow(e,p,"Maximum redirects exceeded");let s;p.abort();try{s=new Qb(o,t)}catch(t){const n=new SyntaxError(`Invalid URL: ${o}`);return void kw(e,n)}xw(e,s,n,r)}else e.emit("unexpected-response",p,s)||Ow(e,p,`Unexpected server response: ${s.statusCode}`)})),p.on("upgrade",((t,n,r)=>{if(e.emit("upgrade",t),e.readyState!==_w.CONNECTING)return;p=e._req=null;const s=t.headers.upgrade;if(void 0===s||"websocket"!==s.toLowerCase())return void Ow(e,n,"Invalid Upgrade header");const o=Xb("sha1").update(u+ow).digest("base64");if(t.headers["sec-websocket-accept"]!==o)return void Ow(e,n,"Invalid Sec-WebSocket-Accept header");const a=t.headers["sec-websocket-protocol"];let c;if(void 0!==a?h.size?h.has(a)||(c="Server sent an invalid subprotocol"):c="Server sent a subprotocol but none was requested":h.size&&(c="Server sent no subprotocol"),c)return void Ow(e,n,c);a&&(e._protocol=a);const l=t.headers["sec-websocket-extensions"];if(void 0!==l){if(!f){return void Ow(e,n,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=gw(l)}catch(t){return void Ow(e,n,"Invalid Sec-WebSocket-Extensions header")}const r=Object.keys(t);if(1!==r.length||r[0]!==ew.extensionName){return void Ow(e,n,"Server indicated an extension that was not requested")}try{f.accept(t[ew.extensionName])}catch(t){return void Ow(e,n,"Invalid Sec-WebSocket-Extensions header")}e._extensions[ew.extensionName]=f}e.setSocket(n,r,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})})),i.finishRequest?i.finishRequest(p,e):p.end()}function kw(e,t){e._readyState=_w.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function Ew(e){return e.path=e.socketPath,Jb.connect(e)}function Cw(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=Jb.isIP(e.host)?"":e.host),Kb.connect(e)}function Ow(e,t,n){e._readyState=_w.CLOSING;const r=new Error(n);Error.captureStackTrace(r,Ow),t.setHeader?(t[vw]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(kw,e,r)):(t.destroy(r),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function $w(e,t,n){if(t){const n=rw(t)?t.size:mw(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${ww[e.readyState]})`);process.nextTick(n,t)}}function Mw(e,t){const n=this[uw];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,void 0!==n._socket[uw]&&(n._socket.removeListener("data",Uw),process.nextTick(jw,n._socket),1005===e?n.close():n.close(e,t))}function Nw(){const e=this[uw];e.isPaused||e._socket.resume()}function Tw(e){const t=this[uw];void 0!==t._socket[uw]&&(t._socket.removeListener("data",Uw),process.nextTick(jw,t._socket),t.close(e[lw])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function Aw(){this[uw].emitClose()}function Pw(e,t){this[uw].emit("message",e,t)}function Dw(e){const t=this[uw];t._autoPong&&t.pong(e,!this._isServer,dw),t.emit("ping",e)}function Lw(e){this[uw].emit("pong",e)}function jw(e){e.resume()}function Rw(e){const t=this[uw];t.readyState!==_w.CLOSED&&(t.readyState===_w.OPEN&&(t._readyState=_w.CLOSING,Fw(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function Fw(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),yw)}function Bw(){const e=this[uw];let t;this.removeListener("close",Bw),this.removeListener("data",Uw),this.removeListener("end",Ww),e._readyState=_w.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[uw]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Aw),e._receiver.on("finish",Aw))}function Uw(e){this[uw]._receiver.write(e)||this.pause()}function Ww(){const e=this[uw];e._readyState=_w.CLOSING,e._receiver.end(),this.end()}function Yw(){const e=this[uw];this.removeListener("error",Yw),this.on("error",dw),e&&(e._readyState=_w.CLOSING,this.destroy())}const{tokenChars:Gw}=Jv;var Hw={parse:function(e){const t=new Set;let n=-1,r=-1,i=0;for(;i<e.length;i++){const s=e.charCodeAt(i);if(-1===r&&1===Gw[s])-1===n&&(n=i);else if(0===i||32!==s&&9!==s){if(44!==s)throw new SyntaxError(`Unexpected character at index ${i}`);{if(-1===n)throw new SyntaxError(`Unexpected character at index ${i}`);-1===r&&(r=i);const s=e.slice(n,r);if(t.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);t.add(s),n=r=-1}}else-1===r&&-1!==n&&(r=i)}if(-1===n||-1!==r)throw new SyntaxError("Unexpected end of input");const s=e.slice(n,i);if(t.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return t.add(s),t}};const Vw=A,zw=R,{createHash:qw}=u,Jw=Hb,Kw=Uv,Zw=Hw,Xw=Iw,{GUID:Qw,kWebSocket:eS}=Sv,tS=/^[+/0-9A-Za-z]{22}==$/;var nS=class extends Vw{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:Xw,...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=zw.createServer(((e,t)=>{const n=zw.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(rS,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(rS,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{rS(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",iS);const i=e.headers["sec-websocket-key"],s=e.headers.upgrade,o=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void oS(this,e,t,405,"Invalid HTTP method")}if(void 0===s||"websocket"!==s.toLowerCase()){return void oS(this,e,t,400,"Invalid Upgrade header")}if(void 0===i||!tS.test(i)){return void oS(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(8!==o&&13!==o){return void oS(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header")}if(!this.shouldHandle(e))return void sS(t,400);const a=e.headers["sec-websocket-protocol"];let c=new Set;if(void 0!==a)try{c=Zw.parse(a)}catch(n){return void oS(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 Kw(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=Jw.parse(l);e[Kw.extensionName]&&(n.accept(e[Kw.extensionName]),u[Kw.extensionName]=n)}catch(n){return void oS(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const s={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(s,((s,o,a,l)=>{if(!s)return sS(t,o||401,a,l);this.completeUpgrade(u,i,c,e,t,n,r)}));if(!this.options.verifyClient(s))return sS(t,401)}this.completeUpgrade(u,i,c,e,t,n,r)}completeUpgrade(e,t,n,r,i,s,o){if(!i.readable||!i.writable)return i.destroy();if(i[eS])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return sS(i,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${qw("sha1").update(t+Qw).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[Kw.extensionName]){const t=e[Kw.extensionName].params,n=Jw.format({[Kw.extensionName]:[t]});a.push(`Sec-WebSocket-Extensions: ${n}`),c._extensions=e}this.emit("headers",a,r),i.write(a.concat("\r\n").join("\r\n")),i.removeListener("error",iS),c.setSocket(i,s,{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(rS,this)}))),o(c,r)}};function rS(e){e._state=2,e.emit("close")}function iS(){this.destroy()}function sS(e,t,n,r){n=n||zw.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} ${zw.STATUS_CODES[t]}\r\n`+Object.keys(r).map((e=>`${e}: ${r[e]}`)).join("\r\n")+"\r\n\r\n"+n)}function oS(e,t,n,r,i){if(e.listenerCount("wsClientError")){const r=new Error(i);Error.captureStackTrace(r,oS),e.emit("wsClientError",r,n,t)}else sS(n,r,i)}var aS=fl(nS);const cS=Tl("websocketServer"),lS={},uS=Xy();let dS,hS,fS,pS,gS;const mS=e=>{const t=lS[e];t&&t.socket.close()};var yS={startServer:e=>{gS=new aS({port:e,maxPayload:1048576e3}),gS.on("connection",(e=>{const t=fm();cS(`New client connected. Registered as "${t}"`),e.id=t,lS[t]={socket:e,activeMessage:null},dS&&dS(t),e.on("message",(t=>{if(t instanceof Buffer){const n=lS[e.id];uS(t,n.activeMessage,(e=>n.activeMessage=e),(t=>{if(!t.complete)return;const r=t=>{e.send(t),cS(`Writing ${t.byteLength} bytes to socket [${n.socket.id}]: ${t.toString()}`)},i=()=>{mS(n.socket.id)};if(t.command)return cS(`Received command from client [${n.socket.id}]: ${t.command}`),void(fS&&fS(n.socket.id,t.command,r,i));t.klMessage&&pS&&pS({send:r,terminateWebsocket:i,websocketId:n.socket.id,transmission:{sourceServiceId:t.sourceServiceId??-1,targetServiceId:t.targetServiceId??-1,rawMessage:t.rawMessage},json:t.klMessage.json})}))}})),e.on("close",(()=>{cS(`Client disconnected: ${e.id}`),hS&&hS(e.id),delete lS[e.id]})),e.on("error",(()=>{cS(`Error on client connection: ${e.id}`)}))})),console.log(`WebSocket server is running on port ${e}`)},stopServer:()=>{gS.close((()=>{console.log("WebSocket server stopped")}))},onClientConnected:e=>{dS=e},onClientDisconnected:e=>{hS=e},onClientCommand:e=>{fS=e},sendCommand:(e,t)=>{const n=lS[e];if(!n)return cS(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=My)return cS("Message is too long to be a command. Use sendMessage instead."),!1;const r=Hy.encodeCommand(t);return n.socket.send(r),!0},onMessageReceived:e=>pS=e,terminateConnection:mS};const vS=Tl("stopService"),bS=async e=>{const t=e.args[0];if(!t)return e.reply({error:"No service name provided"});const n=qm.getAllServiceVersions(t);vS(`Stopping ${n.length} services with name: ${t}`);for(const e of n)await qm.stopService({serviceName:e.info.name,version:e.info.version});const r=n.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[r]})},wS=Tl("removeService"),SS=async e=>{const t=e.args[0],n=e.args[1];if(!t)return e.reply({error:"No service name provided"});let r=qm.getAllServiceVersions(t);n&&(r=r.filter((e=>e.info.version===n))),wS(`Removing ${r.length} service(s) with name: ${t}`);for(const e of r)await qm.uninstallService(e.info.name,e.info.version);const i=r.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[i]})},_S=Tl("launchService"),IS=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 i=Em();_S(`Loading service ${t}@${n} from ${i}`);const{errorMsg:s,service:o,errorCode:a}=await qm.loadAndLaunch(i,r,!1);if(s||"started"!==o?.status)return e.reply({error:`Failed to launch service ${t}@${n}: ${s||"error-not-provided"}`,errCode:a});const c=Date.now(),l=3e4,u=async()=>{const r=o.status;return"running"===r?(_S(`Service ${t}@${n} loaded and started`),e.reply({success:[]})):(_S(`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"}):(_S("Retrying in 1 second..."),void setTimeout(u,1e3)))};u()}catch(r){return _S(`Error loading service ${t}@${n}: ${r?.message||r}`),e.reply({error:r?.message||"There was an error loading the service"})}},xS=Tl("getMatchingServices"),kS=async e=>{const t=e.args[0],n=[],r=[];xS(`Checking for matching services: ${t.map((e=>e.name)).join(", ")}`);for(const{name:e,version:i}of t){const t=qm.getMatchingService(e,i);t?n.push({name:e,version:i,installationPath:qm.getServiceRootDirectory(t)}):r.push({name:e,version:i})}xS(`Found ${n.length} available services and ${r.length} missing services.`),e.reply({success:[{available:n,missing:r}]})},ES=Tl("getSecretsValues");let CS;var OS=async e=>{const t=e.args[0].services;if(!CS)throw new Error("getSecretValuesFn is not set. Please call setGetSecretValuesFunction before using this function.");ES(`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 CS({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})},$S=e=>{CS=e};const MS=Tl("getMappedSecrets");let NS;var TS=async e=>{const t=e.args[0].services;MS(`Getting mapped secrets for services: ${t.map((e=>`${e.name}@${e.version}`)).join(", ")}`);const n=await NS(t),r=[{services:t.map((e=>({name:e.name,version:e.version,secrets:n[e.name]||[]})))}];e.reply({success:r})},AS=e=>{NS=e};const PS=Tl("getServiceContents"),DS=({reply:e,args:t})=>{const[n]=t;PS(`Received GetServiceContents request for service ${n.serviceName} v${n.version}`);const r=qm.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}]})}PS(`Service ${n.serviceName} v${n.version} not found`),e({error:`Service ${n.serviceName} v${n.version} not found`})};let LS={globalApiKey:void 0};const jS=()=>({...LS}),RS=()=>{const e=jS();if(!e.serviceUrl)throw new Error("Unknown server URL. Please call `edgeConfig.setEdgeConfig` before using the APIs.");return e.serviceUrl},FS=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}}},BS={},US=async e=>{const t=(e=>{const t=BS[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:i}=await(async e=>{const{data:t,error:n}=await FS(`${RS()}/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"}})(e);return n&&(BS[e]={features:r,lastCheckedAt:new Date}),{valid:n,features:r,error:i}},WS=Tl("activeClients");let YS={},GS={};const HS=(e,t)=>`${e}_${t}`,VS=e=>YS[e]||null,zS=(e,t)=>{const n=HS(e,t);return GS[n]||[]},qS=()=>{for(const e in YS){const t=YS[e];if(t?.transport===Jc.WS){const e=Hy.encodeCommand(Vc.ServicesListChanged);t.send(e)}}},JS=async e=>{const t=[],{serviceSessionId:n,transport:r,send:i,terminateFn:s,extraInfo:o,isDevClient:a}=e,c=e=>{console.warn(e),s&&s()};if(r===Jc.WS){if(!o.user?.wsApiKey)return void c(`Attempted to register a WebSocket client without an API key. SessionId: ${n}`);const{valid:e,error:t}=await US(o.user?.wsApiKey);if(!e&&!t)return void c(`Attempted to register a WebSocket client with an invalid API key. SessionId: ${n}`);t&&(o.user?.wsApiKey&&Mm.captureError({error:new Error(t),message:`Error validating api key "${o.user?.wsApiKey}"`,data:o}),WS(`Unable to validate API Key, usage will be limited. SessionId: ${n}`))}YS[n]={serviceSessionId:n,transport:r,isDevClient:!!a,broadcastSubscriptions:t,send:i,extraInfo:o,terminate:()=>{s&&s()},addSubscription:e=>{if(!t.some((t=>t.targetService.serviceName===e.serviceName&&t.targetService.version===e.version))){t.push({targetService:e});const r=HS(e.serviceName,e.version);GS[r]=GS[r]||[];return GS[r].some((e=>e.serviceId===n))||GS[r].push({sendFn:i,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 i=HS(e.serviceName,e.version),s=GS[i]?.findIndex((e=>e.serviceId===n));if(-1!==s&&(GS[i]?.splice(s,1),!GS[i]?.length)){const t=qm.getMatchingService(e.serviceName,e.version);if(t?.info.eventEmitter&&"running"===t.status){const e=VS(t.info.sessionId);e?.extraInfo.ipcSocketId&&dv(e?.extraInfo.ipcSocketId,Vc.BroadcastEnd)}}}},removeAllSubscriptions:()=>{for(const e of t){const t=HS(e.targetService.serviceName,e.targetService.version),r=GS[t]?.findIndex((e=>e.serviceId===n));-1!==r&&GS[t]?.splice(r,1)}t.length=0}},r===Jc.IPC&&(qS(),ZS(n))},KS=()=>{const e=Object.values(YS);for(const t of e)if(t.transport===Jc.IPC){const e=t.extraInfo.ipcSocketId,n=qm.getServiceBySessionId(t.serviceSessionId);if(n?.info.eventEmitter){zS(n.info.name,n.info.version).length||e&&dv(e,Vc.BroadcastEnd)}}},ZS=e=>{const t=qm.getServiceBySessionId(e);if(t?.info.eventEmitter){if(zS(t.info.name,t.info.version).length){const t=VS(e);t?.extraInfo.ipcSocketId&&dv(t?.extraInfo.ipcSocketId,Vc.BroadcastStart)}}},XS=e=>{const t=YS[e];delete YS[e],t?.transport===Jc.IPC?qS():(t?.removeAllSubscriptions(),KS())},QS=Tl("ipc:handleIpcClientCommand"),e_=(e,t,n)=>{const r=((e,t)=>{if(e.startsWith(Vc.AcknowledgeResponse)){const n=e.split(":"),r=parseInt(n[1]),i=parseInt(n[2]);return t&&t(r,isNaN(i)?void 0:i),!0}return!1})(t,((e,t)=>{if(!e)return void QS(`Ignoring ACK response from IPC service ${e} with no service id`);QS(`Received ACK from IPC service ${e}. Marking as running.`);let r=e;t&&e&&e!==t&&(hv(e,t),r=t);let i=!1;t&&(i=qm.setServiceStatus(t,"running")),i?JS({serviceSessionId:t||e,transport:Jc.IPC,send:n,extraInfo:{ipcSocketId:t}}):dv(r,Vc.SendManifest)}));!r&&QS(`Received unknown command [${t}] from service ${e}`)};let t_={};H.platform();const n_=async e=>{const t=e.args[0];if(t_.chooseDirectory)try{const n=await t_.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"})},r_=async e=>{const t=e.args[0];if(t_.chooseFile)try{const n=await t_.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"})},i_=e=>{t_=e};var s_={},o_={},a_={};function c_(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function l_(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function u_(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function d_(e,...t){if(!u_(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 h_(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");c_(e.outputLen),c_(e.blockLen)}function f_(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 p_(e,t){d_(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}Object.defineProperty(a_,"__esModule",{value:!0}),a_.output=a_.exists=a_.hash=a_.bytes=a_.bool=a_.number=a_.isBytes=void 0,a_.number=c_,a_.bool=l_,a_.isBytes=u_,a_.bytes=d_,a_.hash=h_,a_.exists=f_,a_.output=p_;const g_={number:c_,bool:l_,bytes:d_,hash:h_,exists:f_,output:p_};a_.default=g_;var m_={};Object.defineProperty(m_,"__esModule",{value:!0}),m_.add5L=m_.add5H=m_.add4H=m_.add4L=m_.add3H=m_.add3L=m_.add=m_.rotlBL=m_.rotlBH=m_.rotlSL=m_.rotlSH=m_.rotr32L=m_.rotr32H=m_.rotrBL=m_.rotrBH=m_.rotrSL=m_.rotrSH=m_.shrSL=m_.shrSH=m_.toBig=m_.split=m_.fromBig=void 0;const y_=BigInt(2**32-1),v_=BigInt(32);function b_(e,t=!1){return t?{h:Number(e&y_),l:Number(e>>v_&y_)}:{h:0|Number(e>>v_&y_),l:0|Number(e&y_)}}function w_(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let i=0;i<e.length;i++){const{h:s,l:o}=b_(e[i],t);[n[i],r[i]]=[s,o]}return[n,r]}m_.fromBig=b_,m_.split=w_;const S_=(e,t)=>BigInt(e>>>0)<<v_|BigInt(t>>>0);m_.toBig=S_;const __=(e,t,n)=>e>>>n;m_.shrSH=__;const I_=(e,t,n)=>e<<32-n|t>>>n;m_.shrSL=I_;const x_=(e,t,n)=>e>>>n|t<<32-n;m_.rotrSH=x_;const k_=(e,t,n)=>e<<32-n|t>>>n;m_.rotrSL=k_;const E_=(e,t,n)=>e<<64-n|t>>>n-32;m_.rotrBH=E_;const C_=(e,t,n)=>e>>>n-32|t<<64-n;m_.rotrBL=C_;const O_=(e,t)=>t;m_.rotr32H=O_;const $_=e=>e;m_.rotr32L=$_;const M_=(e,t,n)=>e<<n|t>>>32-n;m_.rotlSH=M_;const N_=(e,t,n)=>t<<n|e>>>32-n;m_.rotlSL=N_;const T_=(e,t,n)=>t<<n-32|e>>>64-n;m_.rotlBH=T_;const A_=(e,t,n)=>e<<n-32|t>>>64-n;function P_(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:0|i}}m_.rotlBL=A_,m_.add=P_;const D_=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0);m_.add3L=D_;const L_=(e,t,n,r)=>t+n+r+(e/2**32|0)|0;m_.add3H=L_;const j_=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0);m_.add4L=j_;const R_=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0;m_.add4H=R_;const F_=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0);m_.add5L=F_;const B_=(e,t,n,r,i,s)=>t+n+r+i+s+(e/2**32|0)|0;m_.add5H=B_;const U_={fromBig:b_,split:w_,toBig:S_,shrSH:__,shrSL:I_,rotrSH:x_,rotrSL:k_,rotrBH:E_,rotrBL:C_,rotr32H:O_,rotr32L:$_,rotlSH:M_,rotlSL:N_,rotlBH:T_,rotlBL:A_,add:P_,add3L:D_,add3H:L_,add4L:j_,add4H:R_,add5H:B_,add5L:F_};m_.default=U_;var W_={},Y_={};Object.defineProperty(Y_,"__esModule",{value:!0}),Y_.crypto=void 0,Y_.crypto="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,function(e){
|
|
2
11
|
/*! 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=um,n=Af;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 i={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function s(e){return e>=i._0&&e<=i._9?e-i._0:e>=i._A&&e<=i._F?e-(i._A-10):e>=i._a&&e<=i._f?e-(i._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,i=0;t<n;t++,i+=2){const n=s(e.charCodeAt(i)),o=s(e.charCodeAt(i+1));if(void 0===n||void 0===o){const t=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+i)}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 i=Date.now();for(let s=0;s<t;s++){r(s);const t=Date.now()-i;t>=0&&t<n||(await(0,e.nextTick)(),i+=t)}},e.utf8ToBytes=o,e.toBytes=a,e.concatBytes=function(...e){let t=0;for(let r=0;r<e.length;r++){const i=e[r];(0,n.bytes)(i),t+=i.length}const r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const i=e[t];r.set(i,n),n+=i.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")}}(dm),Object.defineProperty(xf,"__esModule",{value:!0}),xf.shake256=xf.shake128=xf.keccak_512=xf.keccak_384=xf.keccak_256=xf.keccak_224=xf.sha3_512=xf.sha3_384=xf.sha3_256=xf.sha3_224=xf.Keccak=xf.keccakP=void 0;const pm=Af,gm=Uf,hm=dm,fm=[],mm=[],ym=[],vm=BigInt(0),bm=BigInt(1),Sm=BigInt(2),wm=BigInt(7),Im=BigInt(256),_m=BigInt(113);for(let e=0,t=bm,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],fm.push(2*(5*r+n)),mm.push((e+1)*(e+2)/2%64);let i=vm;for(let e=0;e<7;e++)t=(t<<bm^(t>>wm)*_m)%Im,t&Sm&&(i^=bm<<(bm<<BigInt(e))-bm);ym.push(i)}const[$m,Cm]=(0,gm.split)(ym,!0),km=(e,t,n)=>n>32?(0,gm.rotlBH)(e,t,n):(0,gm.rotlSH)(e,t,n),Em=(e,t,n)=>n>32?(0,gm.rotlBL)(e,t,n):(0,gm.rotlSL)(e,t,n);function xm(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,i=(t+2)%10,s=n[i],o=n[i+1],a=km(s,o,1)^n[r],c=Em(s,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],i=e[3];for(let n=0;n<24;n++){const r=mm[n],s=km(t,i,r),o=Em(t,i,r),a=fm[n];t=e[a],i=e[a+1],e[a]=s,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]^=$m[r],e[1]^=Cm[r]}n.fill(0)}xf.keccakP=xm;class Am extends hm.Hash{constructor(e,t,n,r=!1,i=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=r,this.rounds=i,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,(0,pm.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,hm.u32)(this.state)}keccak(){hm.isLE||(0,hm.byteSwap32)(this.state32),xm(this.state32,this.rounds),hm.isLE||(0,hm.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,pm.exists)(this);const{blockLen:t,state:n}=this,r=(e=(0,hm.toBytes)(e)).length;for(let i=0;i<r;){const s=Math.min(t-this.pos,r-i);for(let t=0;t<s;t++)n[this.pos++]^=e[i++];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,pm.exists)(this,!1),(0,pm.bytes)(e),this.finish();const t=this.state,{blockLen:n}=this;for(let r=0,i=e.length;r<i;){this.posOut>=n&&this.keccak();const s=Math.min(n-this.posOut,i-r);e.set(t.subarray(this.posOut,this.posOut+s),r),this.posOut+=s,r+=s}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,pm.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,pm.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:i,enableXOF:s}=this;return e||(e=new Am(t,n,r,s,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=n,e.outputLen=r,e.enableXOF=s,e.destroyed=this.destroyed,e}}xf.Keccak=Am;const Nm=(e,t,n)=>(0,hm.wrapConstructor)((()=>new Am(t,e,n)));xf.sha3_224=Nm(6,144,28),xf.sha3_256=Nm(6,136,32),xf.sha3_384=Nm(6,104,48),xf.sha3_512=Nm(6,72,64),xf.keccak_224=Nm(1,144,28),xf.keccak_256=Nm(1,136,32),xf.keccak_384=Nm(1,104,48),xf.keccak_512=Nm(1,72,64);const Pm=(e,t,n)=>(0,hm.wrapXOFConstructorWithOpts)(((r={})=>new Am(t,e,void 0===r.dkLen?n:r.dkLen,!0)));xf.shake128=Pm(31,168,16),xf.shake256=Pm(31,136,32);const{sha3_512:Om}=xf,Tm=(e=4,t=Math.random)=>{let n="";for(;n.length<e;)n+=Math.floor(36*t()).toString(36);return n};function Lm(e){let t=0n;for(const n of e.values()){t=(t<<8n)+BigInt(n)}return t}const Bm=(e="")=>Lm(Om(e)).toString(36).slice(1),Dm=Array.from({length:26},((e,t)=>String.fromCharCode(t+97))),jm=({globalObj:e=(void 0!==ml?ml:"undefined"!=typeof window?window:{}),random:t=Math.random}={})=>{const n=Object.keys(e).toString(),r=n.length?n+Tm(32,t):Tm(32,t);return Bm(r).substring(0,32)},Um=e=>()=>e++,Rm=({random:e=Math.random,counter:t=Um(Math.floor(476782367*e())),length:n=24,fingerprint:r=jm({random:e})}={})=>function(){const i=(e=>Dm[Math.floor(e()*Dm.length)])(e),s=Date.now().toString(36),o=t().toString(36),a=Tm(n,e);return`${i+Bm(`${s+a+o+r}`).substring(1,n)}`},Fm=Rm();Ef.getConstants=()=>({defaultLength:24,bigLength:32}),Ef.init=Rm,Ef.createId=Fm,Ef.bufToBigInt=Lm,Ef.createCounter=Um,Ef.createFingerprint=jm,Ef.isCuid=(e,{minLength:t=2,maxLength:n=32}={})=>{const r=e.length,i=/^[0-9a-z]+$/;try{if("string"==typeof e&&r>=t&&r<=n&&i.test(e))return!0}finally{}return!1};const{createId:Mm,init:Wm,getConstants:Gm,isCuid:Vm}=Ef;var Hm=Mm;const zm=Bl("getUniqueId"),qm=({reply:e,sourceServiceId:t})=>{zm(`Generating unique id for service "${t}"`);return e({success:[Hm()]})},Km=Bl("getActiveServices"),Jm=async({transport:e,sourceServiceId:t,reply:n})=>{if(Km(`Received GetServices request from ${e} [${t}]`),e===Qc.WS){let e=fd.getActiveServices();const r=hf(t);if(!r)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});let i=[];if(r.transport===Qc.WS){if(!r?.extraInfo.wsApiKey)return n({error:"Client does not have an API key",errCode:"CLIENT_NO_API_KEY"});const t=e.filter(fd.isInternalKemuService),s=e.filter((e=>e.devMode&&fd.isNotInternalKemuService(e))),o=e.filter((e=>fd.isOfficialKemuService(e)&&fd.isNotInternalKemuService(e)&&fd.isNotDevService(e))).sort(((e,t)=>e.name.localeCompare(t.name))),a=await(async e=>{const{features:t}=await lf(e);return t})(r.extraInfo.wsApiKey),c=a?.hub_services??0,l=o.slice(0,-1!==c?c:o.length);i=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,...s,...l]}const s=fd.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:fd.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:s,installed:i}]})}};let Ym="runtime",Xm=null;const Zm=()=>Ym,Qm=Bl("getSystemInfo"),ey=async({reply:e})=>{Qm("Received GetSystemInfo request");e({success:[await(async()=>({platformArch:`${"win32"===process.platform?"win":"darwin"===process.platform?"osx":""}-${(()=>{switch(process.arch){case"x64":return"x64";case"ia32":return"x86";case"arm":return"arm";case"arm64":return"arm64";default:return""}})()}`,isDesktopHub:"desktop"===Zm(),isRuntimeHub:"runtime"===Zm(),hubVersion:Wl,...Xm?{updateAvailable:Xm}:{}}))()]})},ty=Bl("removeService"),ny=async({args:e,sourceServiceId:t,reply:n})=>{const r=e[0],i=r.serviceName,s=r.version;if(!i)return n({error:"No service name provided"});if(!s)return n({error:"No service version provided"});const o=fd.getAllServiceVersions(i),a=o.find((e=>e.info.version===s));if(!a)return n({error:"Service not found"});ty(`Removing ${o.length} service(s) with name: ${i}`);const c=a.info.publicationId;let l;if(await fd.uninstallService(a.info.name,a.info.version),c){const e=hf(t);if(!e)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});const r=e.extraInfo.wsApiKey;if(!r)return n({error:"Client does not have an API key",errCode:"CLIENT_NO_API_KEY"});ty(`Updating license details for "${c}"`);const i=await(async e=>{const{data:t,error:n}=await af(`${of()}/v1/validate/uninstall_hub_service`,e);if(n)throw new Error(n);return t})({apiKey:r,hubService:{id:c}}).catch((e=>(ty(`Error updating license details for "${c}": ${e}`),{error:e.message,remaining:void 0})));l=i?.remaining}n({success:[{remaining:l,service:{name:i,version:s}}]})},ry=Bl("getDecryptedEdgeApiKey"),iy=({reply:e})=>{ry("Getting decrypted edge API key");return e({success:[sf().globalApiKey]})},sy=v(W(import.meta.url)),oy=Bl("hub"),ay=new function(e){const t={};let n=console.log;const r={};let i=e||String(Date.now());const s={},o=e=>!s[e],a=(e,t,n,r,i,s)=>{let a=Qd?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:s.success?s.success:[s],messageId:t,type:s.success?"response":"error"}};return o(r)&&(a=ju.encode(c,n,r)),i(a,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{n=e},processMessage:(e,i,s,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,s.targetServiceId,s.sourceServiceId,i,e)};t({transport:e,args:c.args,reply:n,messageId:c.messageId,sourceServiceId:s.sourceServiceId,send:i})}else{const e=`Function "${c.functionName}" not found.`;n&&n(e),a(c.functionName,c.messageId,s.targetServiceId,s.sourceServiceId,i,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(e,r,s,a,c,l)=>{if(!s){const e="No send buffer function provided.";throw n&&n(e),e}Uu+=1;const d=`${i}-${Uu}-exec-${e.substring(0,10)}`,u={messageId:d,functionName:e,send:s,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};u.promise=new Promise(((e,t)=>{u.resolve=e,u.reject=t}));let p=Qd?new ArrayBuffer(0):Buffer.alloc(0);const g={json:{functionName:e,args:r,messageId:d,type:"execute"}};o(c)&&(p=ju.encode(g,a,c)),t[d]=u,n&&n(`Calling remote function "${e}" with message id "${d}"`);const h="true"===process.env.NO_INVOKE_TIMEOUT;return l?.async?(u.fulfilled=!0,u.resolve([void 0]),delete t[d]):0===l?.timeout||h||(u.timer=setTimeout((()=>{n&&n(`Remote function ${d} timed out`);const r=t[d];r&&!r.fulfilled&&(r.fulfilled=!0,u.reject(`Function ${e} Timed out`)),delete t[d]}),l?.timeout||3e4)),s(p,{sourceServiceId:a,targetServiceId:c,msg:g}),u.promise},sendResponse:a,registerFunction:(e,t)=>{r[e]=t},getTransportSendFunction:e=>{const n=t[e];return n?n.send:null},setServiceName:e=>{i=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,s)=>{Uu+=1;const a=`${i}-${Uu}-multicast-${e.substring(0,10)}`;let c=Qd?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:t,messageId:a,type:"execute"}};let d=o(r[0].serviceId);d&&(c=ju.encode(l,s,r[0].serviceId));for(let t=0;t<r.length;t++)try{const i=r[t];n&&n(`Broadcasting function "${e}" with message id "${a}" to client [${i.serviceId}]`),0!==t&&(d=o(i.serviceId),d&&(c=ju.patchEncodedHeader(c,{toServiceId:i.serviceId}))),i.sendFn(c,{msg:l,sourceServiceId:s,targetServiceId:i.serviceId})}catch(e){n&&n(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{s[e]=t}}}("hub");ay.setLogger(oy);const cy={[Xc.RebootToInstallUpdate]:null,[Xc.GetFileContentFromCacheId]:null},ly=(e,t)=>{const{transmission:n}=t;if(0!==n.targetServiceId){const r=hf(n.targetServiceId);if(!r)return oy(`Service [${e}] ${n.sourceServiceId} is sending data to an unknown service ["${n.targetServiceId}"]`),!0;r.transport,Qc.IPC;const i=t.json?.messageId;return oy(`Forwarding message from ${n.sourceServiceId} to ${n.targetServiceId}, msgId: ${i}`),r.send(n.rawMessage,{sourceServiceId:n.sourceServiceId,targetServiceId:n.targetServiceId,msg:{json:t.json}}),!0}return!1},dy=({sourceServiceId:e,args:t})=>{const n=fd.getServiceBySessionId(e);if(n){const r=ff(n.info.name,n.info.version),i=ff(n.info.name,"*");if(!r.length&&!i.length)return;const s=[...r,...i],o={...t[0],source:{serviceName:n.info.name,serviceVersion:n.info.version,sessionId:e}};ay.broadcast(Xc.BroadcastEvent,[o],s,0)}},uy=e=>{const{send:t,transmission:n,json:r}=e;oy(`Raw message Id received from WS: ${r?.messageId}`);ly(Qc.WS,e)||ay.processMessage(Qc.WS,t,n,r)},py=e=>{const t=(n=e,`${Yc.SocketAcknowledge}${n}`);var n;Uh.sendCommand(e,t)},gy=(e,t)=>{oy(`Received unknown command [${t}] from service ${e}`)},hy=async e=>{const{args:t,sourceServiceId:n,send:r,reply:i}=e,s=n,o=sf().globalApiKey||t[0]?.apiKey;await yf({serviceSessionId:n,transport:Qc.WS,send:r,terminateFn:()=>{Uh.terminateConnection(n)},extraInfo:{websocketId:s,wsApiKey:o}}),i({success:[]})},fy=e=>{oy(`WS Client ${e} disconnected`),Sf(e)},my=async({sourceServiceId:e,args:t,transport:n,send:r})=>{if(n!==Qc.IPC){var i;oy(`Received manifest from non IPC service ${e}.`)}else{const n=t[0];if(n.devMode){const t=fd.getMatchingDevService(n.name,n.version,"stopped");if(t){oy(`Found matching previous service ${t.info.name} (${t.info.version}). Reactivating previous client with session id ${t.info.sessionId}`);const s=hf(t.info.sessionId);if(!s)return void oy(`Could not find previous client instance for ${t.info.name} (${t.info.version}). Aborting manifest injection`);s.send=r,uf[i=e]?delete uf[i]:df(`Could not find source client with session id ${i}`),Tu(e,t.info.sessionId);const o=await ql(n,n.path);t.info={...t.info,...o},oy(`Updating manifest for dev service ${t.info.sessionId}`),fd.setServiceManifest(t.info.sessionId,o,"running"),oy(`Asking service ${e} to assume previous session id ${t.info.sessionId}`),Ou(t.info.sessionId,(e=>`${Yc.AssumeSession}${e}`)(t.info.sessionId)),(e=>{const t=uf[e];t?t.isDevClient?(t.disconnected=!1,t.transport===Qc.IPC&&(mf(),bf(e))):df(`Client with session id ${e} is not a dev client`):df(`Could not find source client with session id ${e}`)})(t.info.sessionId)}else{fd.addDevService(e,n,"running");const t=hf(e);t?t.isDevClient=!0:yf({serviceSessionId:e,transport:Qc.IPC,send:r,extraInfo:{ipcSocketId:e},isDevClient:!0})}return}oy(`Received manifest from non dev service ${e} [${n.name}@(${n.version})]. Ignoring...`)}};var yy=async e=>{var t;oy("Starting Kemu Hub..."),t=e.desktopMode?"desktop":"runtime",Ym=t;const n=e?.ipc?.appSpace||"kemu.",r=e?.ipc?.id||"widgets";if(!e.serviceUrl)throw new Error("Missing service url, please set the `apiUrl` option.");(e=>{rf={...rf,...e}})({serviceUrl:e.serviceUrl,globalApiKey:e.globalApiKey}),ay.registerFunction(Xc.GetServiceContents,nf),ay.registerFunction(Xc.GetServices,Jm),ay.registerFunction(Xc.GetSystemInfo,ey),ay.registerFunction(Xc.ShowSecretsConfigScreen,(async({args:t,reply:n})=>{const[{name:r,version:i}]=t;e?.onShowSecretsScreen?(await e.onShowSecretsScreen(r,i),n({success:[]})):n({error:"This hub does not support showing secrets configuration screens",errCode:"GUI_NOT_SUPPORTED"})})),ay.registerFunction(Xc.UnsubscribeFromService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===Qc.WS){const[e]=n,i=hf(r);if(!i)return t({error:`Session id "${r}" not found`});oy(`Service ${r} unsubscribing from "${e.targetService.serviceName} (${e.targetService.version})"`),t({success:[]}),i?.removeSubscription({serviceName:e.targetService.serviceName,version:e.targetService.version})}})),ay.registerFunction(Xc.SubscribeToService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===Qc.WS){const[e]=n,i=hf(r),s=e.targetService;if(!i)return t({error:`Session id "${r}" not found`});if(oy(`Service ${r} subscribing to "${s.serviceName} (${s.version})"`),"hub"===s.serviceName)return i.addSubscription(s),void t({success:[]});if(!i.addSubscription(s))return oy(`Service ${r} already subscribed to "${s.serviceName} (${s.version})", ignoring request.`),t({success:[]});const o=fd.getMatchingService(s.serviceName,s.version);if(!o)return oy(`Service ${s.serviceName} ${s.version} not active yet`),t({success:[]});if(!o.info.eventEmitter)return oy(`Service ${s.serviceName} ${s.version} does not have an event emitter, removing subscription`),i.removeSubscription(s),t({error:`Service "${s.serviceName} (${s.version})" does not produce events`});const a=hf(o.info.sessionId);return a?.extraInfo.ipcSocketId&&(oy(`Sending Broadcast START command to service ${o.info.sessionId}`),Ou(a?.extraInfo.ipcSocketId,Yc.BroadcastStart)),t({success:[]})}})),ay.registerFunction("stopService",Fh),ay.registerFunction("removeService",Wh),ay.registerFunction("launchService",Vh),ay.registerFunction("getMatchingServices",zh),ay.registerFunction("getSecretsValues",Jh),ay.registerFunction(Xc.GetMappedSecrets,Qh),ay.registerFunction(Xc.BroadcastEvent,dy),ay.registerFunction(Xc.ServiceManifest,my),ay.registerFunction(Xc.ChooseDirectoryDialog,$f),ay.registerFunction(Xc.ChooseFileDialog,Cf),ay.registerFunction(Xc.GetUniqueId,qm),ay.registerFunction(Xc.GetDecryptedEdgeApiKey,iy),ay.registerFunction(Xc.SocketAckResponse,hy),ay.registerFunction(Xc.UninstallService,ny),Object.entries(cy).forEach((([e,t])=>{t?ay.registerFunction(e,t):(oy(`Skipping registration of "${e}" because it's not implemented`),ay.registerFunction(e,(({reply:t})=>{t({error:`This hub does not support "${e}"`,errCode:"FUNCTION_NOT_SUPPORTED"})})))})),Pu((e=>{const{send:t,transmission:n,json:r}=e;oy(`Raw message Id received from IPC: ${r?.messageId}`);ly(Qc.IPC,e)||ay.processMessage(Qc.IPC,t,n,r)})),Uh.onMessageReceived(uy),Uh.onClientConnected(py),Uh.onClientCommand(gy),Uh.onClientDisconnected(fy),Lu(If),Au((e=>{const t=(e=>`${Yc.IpcAcknowledge}${e}`)(e);Ou(e,t)})),Nu((e=>{oy(`IPC socket [${e}] disconnected`);const t=hf(e);if(t){oy(`Found matching service for disconnected socket. SessionId: ${t.serviceSessionId}`);const e=fd.getServiceBySessionId(t.serviceSessionId);fd.setServiceStatus(t.serviceSessionId,"stopped"),e?.devMode?(t.disconnected=!0,mf()):Sf(t.serviceSessionId)}})),await xu({ipcAppSpace:n,ipcId:r}),e?.ws?.disabled||await Uh.startServer(e?.ws?.port||5368);const i=e?.defaultServicesPath||m.resolve(sy,"defaultServices"),s=process.env.DEV_SESSION_ID;fd.setHubIpcConfig({recipePath:e?.recipeRootPath,appSpace:n,id:r}),e?.servicesInstallPath&&(e=>{Jl=e})(e.servicesInstallPath),e?.testServicesInstallPath&&(e=>{Yl=e})(e.testServicesInstallPath);const o=Xl(),a=Yl||Fl,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=sf().serviceUrl,t},l=async e=>e.reduce(((e,t)=>({...e,[t.name]:[]})),{});e?.getServiceSecretsFn?(fd.setGetSecretsFunction(e.getServiceSecretsFn),Yh(e.getServiceSecretsFn)):(fd.setGetSecretsFunction(c),Yh(c)),ef(e?.getMappedSecretsFn?e.getMappedSecretsFn:l),fd.setSpawnNodeFunction(e?.spawnFn?e.spawnFn:({args:e,options:t})=>{const n={...process.env};return V("node",e||[],{...t,env:{...n,...t?.env}})}),e?.noDefaultServices||await fd.loadServices(i,{fixedSession:s?parseInt(s):void 0,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,internalServices:!0}),null!==e?.servicesInstallPath&&(await Kl(o)||await S(o,{recursive:!0}),await fd.loadServices(o,{internalServices:!1,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME}));const d=process.env.DEV_NO_SPAWN_LIST?.split(",");await fd.launchServices({noSpawningList:d||[]}),oy("Kemu Hub started"),(e?.onChooseDirectory||e?.onChooseFile)&&kf({chooseDirectory:e.onChooseDirectory,chooseFile:e.onChooseFile})},vy=e=>{if(e===Qc.WS)return{handleWebsocketConnectionEvent:py,handleWebsocketClientDisconnectionEvent:fy,handleWebsocketMessage:uy,handleWebsocketClientCommand:gy,getRemoteInvoke:()=>ay}},by=(e=[])=>{let t;const n=new Promise((n=>{const r=()=>{if(fd.getAllServices().every((e=>"running"===e.status))){if(e.every((e=>"running"===fd.getMatchingService(e.name,e.version)?.status)))return n()}t=setTimeout(r,100)};r()}));return n.abort=()=>{t&&clearTimeout(t)},n};let Sy;const wy=ec("run"),Iy=nl(),_y=1e3,$y=k(process.argv.slice(2));global.ImageData=K,$e({createCanvas:(e,t)=>Y(e,t),loadImage:async e=>{const t=await J(e),n=Y(t.width,t.height).getContext("2d");n.drawImage(t,0,0,t.width,t.height);return n.getImageData(0,0,t.width,t.height)}});const Cy={createImageDataLike:(e,t,n,r="srgb")=>{let i;return i=e instanceof Uint8ClampedArray?e:new Uint8ClampedArray(e),{data:i,width:t,height:n,colorSpace:r,_kemuType:da.ImageData}},loadImageFile:async e=>{const t=await J(e),n=Y(t.width,t.height).getContext("2d");n.drawImage(t,0,0,t.width,t.height);return n.getImageData(0,0,t.width,t.height)},encodeImageData:async(e,t="jpeg",n)=>{const r=Y(e.width,e.height);let i;return r.getContext("2d").putImageData(e,0,0),i="png"===t?await r.encode(t):await r.encode(t,n),i}};var ky={start:async r=>{r=r||{};const i=r?.recipePath||$y.recipePath||process.env.KEMU_EDGE_RECIPE_PATH||process.cwd();if(!i)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:H(z(i),".env")});const s=r.apiKey||process.env.KEMU_API_KEY;if(!s)throw new Error("Missing API key. Please provide it via config.apiKey or KEMU_API_KEY environment variable.");const o=i.endsWith(".json")||i.endsWith(".kemu"),a=o?q(i):i,c=o?i:H(a,"recipe.kemu"),l=(e=>{try{return JSON.parse(e||"")}catch(e){return null}})(await t(z(c),"utf-8"));if(!l)throw new Error("Failed to parse recipe file");const{serviceUrl:d,apiKey:u}=((e,t)=>{const n=ca(e,t),r=Buffer.from(n,"base64").toString("utf8"),[i,s]=r.split("<@>");if(!s||!i)throw new Error("Invalid API key.");return{serviceUrl:s,apiKey:i}})(l,s);await ks();const p={id:l.id||String(Date.now()),version:1,author:""};(e=>{Or=e})(console);const g=vy(we.WS),h=(e,t)=>{if(t)g?.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;g?.handleWebsocketClientCommand(_y,t)}},f=(Ma={instanceServiceId:_y,sendBuf:h,sendCmd:h,triggerOnCommand:(...e)=>Wa(...e),triggerOnConnected:()=>Ga(),triggerOnDisconnected:()=>Va(),triggerOnMessageReceived:(...e)=>Ha(...e)},Ma);const m=(e,t)=>{if(t)f.triggerOnMessageReceived({send:h,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg.json});else{const t=e instanceof Buffer?e.toString():e;f.triggerOnCommand(t)}},y=il(),v=g.getRemoteInvoke();y.disableServiceEncoding(0,!0),v.disableServiceEncoding(_y,!0);const b=Object.values(l.blocks[ge].gates).filter((e=>e.type===ze.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=H(a,"services"),I=await n(w).then((()=>!0)).catch((()=>!1));await yy({globalApiKey:u,serviceUrl:d,recipeRootPath:a,servicesInstallPath:I?H(a,"services"):null,noDefaultServices:!0,ws:{disabled:!0},ipc:{appSpace:"kemu-runner.",id:p.id}}),wy("Waiting for services to run"),await by(S),wy("All services are running"),ia(Iy);const _=await ta(l,"runner",p.version,p.author,Vo.Desktop);return Sy=_,rl(_),await el(u),new Promise(((e,t)=>{var n;tl("acknowledged",(async()=>{await Iy.getServices();const{failed:n,sendToInputWidget:r,invokeRecipeLoadedWidgets:i}=await ra(_);if(n.length>0){const e=`Some widgets failed to initialize: ${n.join(", ")}`;return t(e)}await i().catch((e=>{console.error("Error invoking recipe loaded widgets: ",e)})),wy("Recipe started"),e({sendToInputWidget:(e,t)=>"number"==typeof t?r(e,{type:fe.Number,value:t}):"string"==typeof t?r(e,{type:fe.String,value:t}):"boolean"==typeof t?r(e,{type:fe.Boolean,value:t}):Array.isArray(t)?r(e,{type:fe.Array,value:t}):r(e,t)})})),f.triggerOnConnected(),f.triggerOnCommand((n=_y,`${ve.SocketAcknowledge}${n}`))}))},terminate:async()=>{Sy&&await na(Sy)},onVariableChange:(e,t)=>kr(e,t)};void 0===typeof process.env.BLOCKS_INSTALL_DIR&&console.warn("Missing `BLOCKS_INSTALL_DIR` env var");process.env.BLOCKS_INSTALL_DIR;export{fe as DataType,ky as default,Cy as utils};
|
|
12
|
+
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=Y_,n=a_;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 i={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function s(e){return e>=i._0&&e<=i._9?e-i._0:e>=i._A&&e<=i._F?e-(i._A-10):e>=i._a&&e<=i._f?e-(i._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,i=0;t<n;t++,i+=2){const n=s(e.charCodeAt(i)),o=s(e.charCodeAt(i+1));if(void 0===n||void 0===o){const t=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+i)}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 i=Date.now();for(let s=0;s<t;s++){r(s);const t=Date.now()-i;t>=0&&t<n||(await(0,e.nextTick)(),i+=t)}},e.utf8ToBytes=o,e.toBytes=a,e.concatBytes=function(...e){let t=0;for(let r=0;r<e.length;r++){const i=e[r];(0,n.bytes)(i),t+=i.length}const r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const i=e[t];r.set(i,n),n+=i.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")}}(W_),Object.defineProperty(o_,"__esModule",{value:!0}),o_.shake256=o_.shake128=o_.keccak_512=o_.keccak_384=o_.keccak_256=o_.keccak_224=o_.sha3_512=o_.sha3_384=o_.sha3_256=o_.sha3_224=o_.Keccak=o_.keccakP=void 0;const G_=a_,H_=m_,V_=W_,z_=[],q_=[],J_=[],K_=BigInt(0),Z_=BigInt(1),X_=BigInt(2),Q_=BigInt(7),eI=BigInt(256),tI=BigInt(113);for(let e=0,t=Z_,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],z_.push(2*(5*r+n)),q_.push((e+1)*(e+2)/2%64);let i=K_;for(let e=0;e<7;e++)t=(t<<Z_^(t>>Q_)*tI)%eI,t&X_&&(i^=Z_<<(Z_<<BigInt(e))-Z_);J_.push(i)}const[nI,rI]=(0,H_.split)(J_,!0),iI=(e,t,n)=>n>32?(0,H_.rotlBH)(e,t,n):(0,H_.rotlSH)(e,t,n),sI=(e,t,n)=>n>32?(0,H_.rotlBL)(e,t,n):(0,H_.rotlSL)(e,t,n);function oI(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,i=(t+2)%10,s=n[i],o=n[i+1],a=iI(s,o,1)^n[r],c=sI(s,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],i=e[3];for(let n=0;n<24;n++){const r=q_[n],s=iI(t,i,r),o=sI(t,i,r),a=z_[n];t=e[a],i=e[a+1],e[a]=s,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]^=nI[r],e[1]^=rI[r]}n.fill(0)}o_.keccakP=oI;class aI extends V_.Hash{constructor(e,t,n,r=!1,i=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=r,this.rounds=i,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,(0,G_.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,V_.u32)(this.state)}keccak(){V_.isLE||(0,V_.byteSwap32)(this.state32),oI(this.state32,this.rounds),V_.isLE||(0,V_.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,G_.exists)(this);const{blockLen:t,state:n}=this,r=(e=(0,V_.toBytes)(e)).length;for(let i=0;i<r;){const s=Math.min(t-this.pos,r-i);for(let t=0;t<s;t++)n[this.pos++]^=e[i++];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,G_.exists)(this,!1),(0,G_.bytes)(e),this.finish();const t=this.state,{blockLen:n}=this;for(let r=0,i=e.length;r<i;){this.posOut>=n&&this.keccak();const s=Math.min(n-this.posOut,i-r);e.set(t.subarray(this.posOut,this.posOut+s),r),this.posOut+=s,r+=s}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,G_.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,G_.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:i,enableXOF:s}=this;return e||(e=new aI(t,n,r,s,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=n,e.outputLen=r,e.enableXOF=s,e.destroyed=this.destroyed,e}}o_.Keccak=aI;const cI=(e,t,n)=>(0,V_.wrapConstructor)((()=>new aI(t,e,n)));o_.sha3_224=cI(6,144,28),o_.sha3_256=cI(6,136,32),o_.sha3_384=cI(6,104,48),o_.sha3_512=cI(6,72,64),o_.keccak_224=cI(1,144,28),o_.keccak_256=cI(1,136,32),o_.keccak_384=cI(1,104,48),o_.keccak_512=cI(1,72,64);const lI=(e,t,n)=>(0,V_.wrapXOFConstructorWithOpts)(((r={})=>new aI(t,e,void 0===r.dkLen?n:r.dkLen,!0)));o_.shake128=lI(31,168,16),o_.shake256=lI(31,136,32);const{sha3_512:uI}=o_,dI=(e=4,t=Math.random)=>{let n="";for(;n.length<e;)n+=Math.floor(36*t()).toString(36);return n};function hI(e){let t=0n;for(const n of e.values()){t=(t<<8n)+BigInt(n)}return t}const fI=(e="")=>hI(uI(e)).toString(36).slice(1),pI=Array.from({length:26},((e,t)=>String.fromCharCode(t+97))),gI=({globalObj:e=(void 0!==hl?hl:"undefined"!=typeof window?window:{}),random:t=Math.random}={})=>{const n=Object.keys(e).toString(),r=n.length?n+dI(32,t):dI(32,t);return fI(r).substring(0,32)},mI=e=>()=>e++,yI=({random:e=Math.random,counter:t=mI(Math.floor(476782367*e())),length:n=24,fingerprint:r=gI({random:e})}={})=>function(){const i=(e=>pI[Math.floor(e()*pI.length)])(e),s=Date.now().toString(36),o=t().toString(36),a=dI(n,e);return`${i+fI(`${s+a+o+r}`).substring(1,n)}`},vI=yI();s_.getConstants=()=>({defaultLength:24,bigLength:32}),s_.init=yI,s_.createId=vI,s_.bufToBigInt=hI,s_.createCounter=mI,s_.createFingerprint=gI,s_.isCuid=(e,{minLength:t=2,maxLength:n=32}={})=>{const r=e.length,i=/^[0-9a-z]+$/;try{if("string"==typeof e&&r>=t&&r<=n&&i.test(e))return!0}finally{}return!1};const{createId:bI,init:wI,getConstants:SI,isCuid:_I}=s_;var II=bI;const xI=Tl("getUniqueId"),kI=({reply:e,sourceServiceId:t})=>{xI(`Generating unique id for service "${t}"`);return e({success:[II()]})},EI=Tl("getActiveServices"),CI=async({transport:e,sourceServiceId:t,reply:n})=>{if(EI(`Received GetServices request from ${e} [${t}]`),e===Jc.WS){let e=qm.getActiveServices();const r=VS(t);if(!r)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});let i=[];if(r.transport===Jc.WS){if(!r?.extraInfo.user?.wsApiKey)return n({error:"Client does not have an API key",errCode:"CLIENT_NO_API_KEY"});const t=e.filter(qm.isInternalKemuService),s=e.filter((e=>e.devMode&&qm.isNotInternalKemuService(e))),o=e.filter((e=>qm.isOfficialKemuService(e)&&qm.isNotInternalKemuService(e)&&qm.isNotDevService(e))).sort(((e,t)=>e.name.localeCompare(t.name))),a=await(async e=>{const{features:t}=await US(e);return t})(r.extraInfo.user?.wsApiKey),c=a?.hub_services??0,l=o.slice(0,-1!==c?c:o.length);i=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,...s,...l]}const s=qm.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:qm.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:s,installed:i}]})}};let OI="runtime",$I=null;const MI=()=>OI,NI=Tl("getSystemInfo"),TI=async({reply:e})=>{NI("Received GetSystemInfo request");e({success:[await(async()=>({platformArch:`${"win32"===process.platform?"win":"darwin"===process.platform?"osx":""}-${(()=>{switch(process.arch){case"x64":return"x64";case"ia32":return"x86";case"arm":return"arm";case"arm64":return"arm64";default:return""}})()}`,isDesktopHub:"desktop"===MI(),isRuntimeHub:"runtime"===MI(),hubVersion:ym,...$I?{updateAvailable:$I}:{}}))()]})},AI=Tl("removeService"),PI=async({args:e,sourceServiceId:t,reply:n})=>{const r=e[0],i=r.serviceName,s=r.version;if(!i)return n({error:"No service name provided"});if(!s)return n({error:"No service version provided"});const o=qm.getAllServiceVersions(i),a=o.find((e=>e.info.version===s));if(!a)return n({error:"Service not found"});AI(`Removing ${o.length} service(s) with name: ${i}`);const c=a.info.publicationId;let l;if(await qm.uninstallService(a.info.name,a.info.version),c){const e=VS(t);if(!e)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});const r=e.extraInfo.user?.wsApiKey;if(!r)return n({error:"Client does not have an API key",errCode:"CLIENT_NO_API_KEY"});AI(`Updating license details for "${c}"`);const i=await(async e=>{const{data:t,error:n}=await FS(`${RS()}/v1/validate/uninstall_hub_service`,e);if(n)throw new Error(n);return t})({apiKey:r,hubService:{id:c}}).catch((e=>(AI(`Error updating license details for "${c}": ${e}`),{error:e.message,remaining:void 0})));l=i?.remaining}n({success:[{remaining:l,service:{name:i,version:s}}]})},DI=Tl("getDecryptedEdgeApiKey"),LI=({reply:e})=>{DI("Getting decrypted edge API key");return e({success:[jS().globalApiKey]})},jI=v(G(import.meta.url));let RI=null;const FI=Tl("hub"),BI=new function(e){const t={};let n=console.log;const r={};let i=e||String(Date.now());const s={},o=e=>!s[e],a=(e,t,n,r,i,s)=>{let a=Ty?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:s.success?s.success:[s],messageId:t,type:s.success?"response":"error"}};return o(r)&&(a=mv.encode(c,n,r)),i(a,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{n=e},processMessage:(e,i,s,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,s.targetServiceId,s.sourceServiceId,i,e)};t({transport:e,args:c.args,reply:n,messageId:c.messageId,sourceServiceId:s.sourceServiceId,send:i})}else{const e=`Function "${c.functionName}" not found.`;n&&n(e),a(c.functionName,c.messageId,s.targetServiceId,s.sourceServiceId,i,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(e,r,s,a,c,l)=>{if(!s){const e="No send buffer function provided.";throw n&&n(e),e}yv+=1;const u=`${i}-${yv}-exec-${e.substring(0,10)}`,d={messageId:u,functionName:e,send:s,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};d.promise=new Promise(((e,t)=>{d.resolve=e,d.reject=t}));let h=Ty?new ArrayBuffer(0):Buffer.alloc(0);const f={json:{functionName:e,args:r,messageId:u,type:"execute"}};o(c)&&(h=mv.encode(f,a,c)),t[u]=d,n&&n(`Calling remote function "${e}" with message id "${u}"`);const p="true"===process.env.NO_INVOKE_TIMEOUT;return l?.async?(d.fulfilled=!0,d.resolve([void 0]),delete t[u]):0===l?.timeout||p||(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)),s(h,{sourceServiceId:a,targetServiceId:c,msg:f}),d.promise},sendResponse:a,registerFunction:(e,t)=>{r[e]=t},getTransportSendFunction:e=>{const n=t[e];return n?n.send:null},setServiceName:e=>{i=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,s)=>{yv+=1;const a=`${i}-${yv}-multicast-${e.substring(0,10)}`;let c=Ty?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=mv.encode(l,s,r[0].serviceId));for(let t=0;t<r.length;t++)try{const i=r[t];n&&n(`Broadcasting function "${e}" with message id "${a}" to client [${i.serviceId}]`),0!==t&&(u=o(i.serviceId),u&&(c=mv.patchEncodedHeader(c,{toServiceId:i.serviceId}))),i.sendFn(c,{msg:l,sourceServiceId:s,targetServiceId:i.serviceId})}catch(e){n&&n(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{s[e]=t}}}("hub");BI.setLogger(FI);const UI={[zc.RebootToInstallUpdate]:null,[zc.GetFileContentFromCacheId]:null},WI=(e,t)=>{const{transmission:n}=t;if(0!==n.targetServiceId){const r=VS(n.targetServiceId);if(!r)return FI(`Service [${e}] ${n.sourceServiceId} is sending data to an unknown service ["${n.targetServiceId}"]`),!0;r.transport,Jc.IPC;const i=t.json?.messageId;return FI(`Forwarding message from ${n.sourceServiceId} to ${n.targetServiceId}, msgId: ${i}`),r.send(n.rawMessage,{sourceServiceId:n.sourceServiceId,targetServiceId:n.targetServiceId,msg:{json:t.json}}),!0}return!1},YI=({sourceServiceId:e,args:t})=>{const n=qm.getServiceBySessionId(e);if(n){const r=zS(n.info.name,n.info.version),i=zS(n.info.name,"*");if(!r.length&&!i.length)return;const s=[...r,...i],o={...t[0],source:{serviceName:n.info.name,serviceVersion:n.info.version,sessionId:e}};BI.broadcast(zc.BroadcastEvent,[o],s,0)}},GI=e=>{const{send:t,transmission:n,json:r}=e;FI(`Raw message Id received from WS: ${r?.messageId}`);WI(Jc.WS,e)||BI.processMessage(Jc.WS,t,n,r)},HI=e=>{const t=(n=e,`${Vc.SocketAcknowledge}${n}`);var n;yS.sendCommand(e,t)},VI=(e,t)=>{FI(`Received unknown command [${t}] from service ${e}`)},zI=async e=>{const{args:t,sourceServiceId:n,send:r,reply:i}=e,s=n,o=t[0],a=o?.user?.apiKey||jS().globalApiKey;if(!a)return FI(`Received ACK from WS service ${n} but no API key was provided`),i({error:"No API key was provided",errCode:"MISSING_API_KEY"});o.user?.id&&Mm.setGlobalUserId(o.user?.id),await JS({serviceSessionId:n,transport:Jc.WS,send:r,terminateFn:()=>{yS.terminateConnection(n)},extraInfo:{websocketId:s,user:{wsApiKey:a,userEmail:o.user?.email,userId:o.user?.id}}}),i({success:[]})},qI=e=>{FI(`WS Client ${e} disconnected`),XS(e)},JI=async({sourceServiceId:e,args:t,transport:n,send:r})=>{if(n!==Jc.IPC){var i;FI(`Received manifest from non IPC service ${e}.`)}else{const n=t[0];if(n.devMode){const t=qm.getMatchingDevService(n.name,n.version,"stopped");if(t){FI(`Found matching previous service ${t.info.name} (${t.info.version}). Reactivating previous client with session id ${t.info.sessionId}`);const s=VS(t.info.sessionId);if(!s)return void FI(`Could not find previous client instance for ${t.info.name} (${t.info.version}). Aborting manifest injection`);s.send=r,YS[i=e]?delete YS[i]:WS(`Could not find source client with session id ${i}`),hv(e,t.info.sessionId);const o=await _m(n,n.path);t.info={...t.info,...o},FI(`Updating manifest for dev service ${t.info.sessionId}`),qm.setServiceManifest(t.info.sessionId,o,"running"),FI(`Asking service ${e} to assume previous session id ${t.info.sessionId}`),dv(t.info.sessionId,(e=>`${Vc.AssumeSession}${e}`)(t.info.sessionId)),(e=>{const t=YS[e];t?t.isDevClient?(t.disconnected=!1,t.transport===Jc.IPC&&(qS(),ZS(e))):WS(`Client with session id ${e} is not a dev client`):WS(`Could not find source client with session id ${e}`)})(t.info.sessionId)}else{qm.addDevService(e,n,"running");const t=VS(e);t?t.isDevClient=!0:JS({serviceSessionId:e,transport:Jc.IPC,send:r,extraInfo:{ipcSocketId:e},isDevClient:!0})}return}FI(`Received manifest from non dev service ${e} [${n.name}@(${n.version})]. Ignoring...`)}};var KI=async e=>{var t;FI("Starting Kemu Hub..."),t=e.desktopMode?"desktop":"runtime",OI=t;const n=e?.ipc?.appSpace||"kemu.",r=e?.ipc?.id||"widgets";if(!e.serviceUrl)throw new Error("Missing service url, please set the `apiUrl` option.");e.errorTracker&&Mm.setTracker(e.errorTracker),(e=>{LS={...LS,...e}})({serviceUrl:e.serviceUrl,globalApiKey:e.globalApiKey}),BI.registerFunction(zc.GetServiceContents,DS),BI.registerFunction(zc.GetServices,CI),BI.registerFunction(zc.GetSystemInfo,TI),BI.registerFunction(zc.ShowSecretsConfigScreen,(async({args:t,reply:n})=>{const[{name:r,version:i}]=t;e?.onShowSecretsScreen?(await e.onShowSecretsScreen(r,i),n({success:[]})):n({error:"This hub does not support showing secrets configuration screens",errCode:"GUI_NOT_SUPPORTED"})})),BI.registerFunction(zc.UnsubscribeFromService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===Jc.WS){const[e]=n,i=VS(r);if(!i)return t({error:`Session id "${r}" not found`});FI(`Service ${r} unsubscribing from "${e.targetService.serviceName} (${e.targetService.version})"`),t({success:[]}),i?.removeSubscription({serviceName:e.targetService.serviceName,version:e.targetService.version})}})),BI.registerFunction(zc.SubscribeToService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===Jc.WS){const[e]=n,i=VS(r),s=e.targetService;if(!i)return t({error:`Session id "${r}" not found`});if(FI(`Service ${r} subscribing to "${s.serviceName} (${s.version})"`),"hub"===s.serviceName)return i.addSubscription(s),void t({success:[]});if(!i.addSubscription(s))return FI(`Service ${r} already subscribed to "${s.serviceName} (${s.version})", ignoring request.`),t({success:[]});const o=qm.getMatchingService(s.serviceName,s.version);if(!o)return FI(`Service ${s.serviceName} ${s.version} not active yet`),t({success:[]});if(!o.info.eventEmitter)return FI(`Service ${s.serviceName} ${s.version} does not have an event emitter, removing subscription`),i.removeSubscription(s),t({error:`Service "${s.serviceName} (${s.version})" does not produce events`});const a=VS(o.info.sessionId);return a?.extraInfo.ipcSocketId&&(FI(`Sending Broadcast START command to service ${o.info.sessionId}`),dv(a?.extraInfo.ipcSocketId,Vc.BroadcastStart)),t({success:[]})}})),BI.registerFunction("stopService",bS),BI.registerFunction("removeService",SS),BI.registerFunction("launchService",IS),BI.registerFunction("getMatchingServices",kS),BI.registerFunction("getSecretsValues",OS),BI.registerFunction(zc.GetMappedSecrets,TS),BI.registerFunction(zc.BroadcastEvent,YI),BI.registerFunction(zc.ServiceManifest,JI),BI.registerFunction(zc.ChooseDirectoryDialog,n_),BI.registerFunction(zc.ChooseFileDialog,r_),BI.registerFunction(zc.GetUniqueId,kI),BI.registerFunction(zc.GetDecryptedEdgeApiKey,LI),BI.registerFunction(zc.SocketAckResponse,zI),BI.registerFunction(zc.UninstallService,PI),Object.entries(UI).forEach((([e,t])=>{t?BI.registerFunction(e,t):(FI(`Skipping registration of "${e}" because it's not implemented`),BI.registerFunction(e,(({reply:t})=>{t({error:`This hub does not support "${e}"`,errCode:"FUNCTION_NOT_SUPPORTED"})})))})),uv((e=>{const{send:t,transmission:n,json:r}=e;FI(`Raw message Id received from IPC: ${r?.messageId}`);WI(Jc.IPC,e)||BI.processMessage(Jc.IPC,t,n,r)})),yS.onMessageReceived(GI),yS.onClientConnected(HI),yS.onClientCommand(VI),yS.onClientDisconnected(qI),fv(e_),cv((e=>{const t=(e=>`${Vc.IpcAcknowledge}${e}`)(e);dv(e,t)})),lv((e=>{FI(`IPC socket [${e}] disconnected`);const t=VS(e);if(t){FI(`Found matching service for disconnected socket. SessionId: ${t.serviceSessionId}`);const e=qm.getServiceBySessionId(t.serviceSessionId);qm.setServiceStatus(t.serviceSessionId,"stopped"),e?.devMode?(t.disconnected=!0,qS()):XS(t.serviceSessionId)}})),await av({ipcAppSpace:n,ipcId:r}),e?.ws?.disabled||await yS.startServer(e?.ws?.port||5368);const i=e?.defaultServicesPath||m.resolve(jI,"defaultServices");RI=i;const s=process.env.DEV_SESSION_ID;qm.setHubIpcConfig({recipePath:e?.recipeRootPath,appSpace:n,id:r}),e?.servicesInstallPath&&(e=>{xm=e})(e.servicesInstallPath),e?.testServicesInstallPath&&(e=>{km=e})(e.testServicesInstallPath);const o=Em(),a=Cm(),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=jS().serviceUrl,t},l=async e=>e.reduce(((e,t)=>({...e,[t.name]:[]})),{});e?.getServiceSecretsFn?(qm.setGetSecretsFunction(e.getServiceSecretsFn),$S(e.getServiceSecretsFn)):(qm.setGetSecretsFunction(c),$S(c)),AS(e?.getMappedSecretsFn?e.getMappedSecretsFn:l),qm.setSpawnNodeFunction(e?.spawnFn?e.spawnFn:({args:e,options:t})=>{const n={...process.env};return V("node",e||[],{...t,env:{...n,...t?.env}})}),e?.noDefaultServices||await qm.loadServices(i,{fixedSession:s?parseInt(s):void 0,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,internalServices:!0,enableLogs:!0}),null!==e?.servicesInstallPath&&(await Im(o)||await S(o,{recursive:!0}),await qm.loadServices(o,{internalServices:!1,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,enableLogs:!!e?.enableServiceLogs}));const u=process.env.DEV_NO_SPAWN_LIST?.split(",");await qm.launchServices({noSpawningList:u||[]}),FI("Kemu Hub started"),(e?.onChooseDirectory||e?.onChooseFile)&&i_({chooseDirectory:e.onChooseDirectory,chooseFile:e.onChooseFile})},ZI=e=>{if(e===Jc.WS)return{handleWebsocketConnectionEvent:HI,handleWebsocketClientDisconnectionEvent:qI,handleWebsocketMessage:GI,handleWebsocketClientCommand:VI,getRemoteInvoke:()=>BI}},XI=(e=[])=>{let t;const n=new Promise((n=>{const r=()=>{if(qm.getAllServices().every((e=>"running"===e.status))){if(e.every((e=>"running"===qm.getMatchingService(e.name,e.version)?.status)))return n()}t=setTimeout(r,100)};r()}));return n.abort=()=>{t&&clearTimeout(t)},n};let QI;const ex=Ka("run"),tx=Xc(),nx=1e3,rx=C(process.argv.slice(2));global.ImageData=K,Ee({createCanvas:(e,t)=>X(e,t),loadImage:async e=>{const t=await Z(e),n=X(t.width,t.height).getContext("2d");n.drawImage(t,0,0,t.width,t.height);return n.getImageData(0,0,t.width,t.height)}});const ix={createImageDataLike:(e,t,n,r="srgb")=>{let i;return i=e instanceof Uint8ClampedArray?e:new Uint8ClampedArray(e),{data:i,width:t,height:n,colorSpace:r,_kemuType:ye.ImageData}},loadImageFile:async e=>{const t=await Z(e),n=X(t.width,t.height).getContext("2d");n.drawImage(t,0,0,t.width,t.height);return n.getImageData(0,0,t.width,t.height)},encodeImageData:async(e,t="jpeg",n)=>{const r=X(e.width,e.height);let i;return r.getContext("2d").putImageData(e,0,0),i="png"===t?await r.encode(t):await r.encode(t,n),i}};var sx={start:async r=>{r=r||{};const i=r?.recipePath||rx.recipePath||process.env.KEMU_EDGE_RECIPE_PATH||process.cwd();if(!i)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:z(q(i),".env")});const s=r.apiKey||process.env.KEMU_API_KEY;if(!s)throw new Error("Missing API key. Please provide it via config.apiKey or KEMU_API_KEY environment variable.");const o=i.endsWith(".json")||i.endsWith(".kemu"),a=o?J(i):i,c=o?i:z(a,"recipe.kemu"),l=(e=>{try{return JSON.parse(e||"")}catch(e){return null}})(await t(q(c),"utf-8"));if(!l)throw new Error("Failed to parse recipe file");const{serviceUrl:u,apiKey:d}=((e,t)=>{const n=ha(e,t),r=Buffer.from(n,"base64").toString("utf8"),[i,s]=r.split("<@>");if(!s||!i)throw new Error("Invalid API key.");return{serviceUrl:s,apiKey:i}})(l,s);await Ms();const h={id:l.id||String(Date.now()),version:1,author:""};(e=>{Pr=e})(console);const f=ZI(Ie.WS),p=(e,t)=>{if(t)f?.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;f?.handleWebsocketClientCommand(nx,t)}},g=(ja={instanceServiceId:nx,sendBuf:p,sendCmd:p,triggerOnCommand:(...e)=>Ra(...e),triggerOnConnected:()=>Fa(),triggerOnDisconnected:()=>Ba(),triggerOnMessageReceived:(...e)=>Ua(...e)},ja);const m=(e,t)=>{if(t)g.triggerOnMessageReceived({send:p,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)}},y=el(),v=f.getRemoteInvoke();y.disableServiceEncoding(0,!0),v.disableServiceEncoding(nx,!0);const b=Object.values(l.blocks[ge].gates).filter((e=>e.type===qe.hubService&&e.state.service&&!0!==e.state.service?.webOnly)),w=b.map((e=>{const t=e.state.service;return{name:t.name,version:t.version}})),S=z(a,"services"),_=await n(S).then((()=>!0)).catch((()=>!1));await KI({globalApiKey:d,serviceUrl:u,recipeRootPath:a,servicesInstallPath:_?z(a,"services"):null,noDefaultServices:!0,ws:{disabled:!0},ipc:{appSpace:"kemu-runner.",id:h.id}}),ex("Waiting for services to run"),await XI(w),ex("All services are running"),ca(tx);const I=await sa(l,"runner",h.version,h.author,qo.Desktop);return QI=I,Qc(I),await Kc(d),new Promise(((e,t)=>{var n;Zc("acknowledged",(async()=>{await tx.getServices();const{failed:n,sendToInputWidget:r,invokeRecipeLoadedWidgets:i}=await aa(I);if(n.length>0){const e=`Some widgets failed to initialize: ${n.join(", ")}`;return t(e)}await i().catch((e=>{console.error("Error invoking recipe loaded widgets: ",e)})),ex("Recipe started"),e({sendToInputWidget:(e,t)=>"number"==typeof t?r(e,{type:ye.Number,value:t}):"string"==typeof t?r(e,{type:ye.String,value:t}):"boolean"==typeof t?r(e,{type:ye.Boolean,value:t}):Array.isArray(t)?r(e,{type:ye.Array,value:t}):r(e,t)})})),g.triggerOnConnected(),g.triggerOnCommand((n=nx,`${we.SocketAcknowledge}${n}`))}))},terminate:async()=>{QI&&await oa(QI)},onVariableChange:(e,t)=>Or(e,t)};void 0===typeof process.env.BLOCKS_INSTALL_DIR&&console.warn("Missing `BLOCKS_INSTALL_DIR` env var");process.env.BLOCKS_INSTALL_DIR;export{ye as DataType,sx as default,ix as utils};
|