@kemu-io/edge-runtime 1.12.3 → 1.13.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 +1 -1
- package/runner.d.ts +5 -0
- package/runner.js +2 -2
package/package.json
CHANGED
package/runner.d.ts
CHANGED
|
@@ -183,6 +183,11 @@ declare const _default$1: {
|
|
|
183
183
|
* If not provided, `node` will be used by default.
|
|
184
184
|
**/
|
|
185
185
|
runtimeCommand?: string;
|
|
186
|
+
/**
|
|
187
|
+
* Names of the hub's default internal services allowed to run.
|
|
188
|
+
* Defaults to an empty list to preserve the current edge-runtime behavior.
|
|
189
|
+
**/
|
|
190
|
+
defaultServicesAllowList?: string[];
|
|
186
191
|
}) => Promise<{
|
|
187
192
|
/**
|
|
188
193
|
* use it to send data to input widgets
|
package/runner.js
CHANGED
|
@@ -7,6 +7,6 @@ r.version="2.30.1",function(e){t=e}(Rt),r.fn=An,r.min=function(){return Ft("isBe
|
|
|
7
7
|
* Copyright(c) 2017 Roger C.
|
|
8
8
|
* MIT Licensed
|
|
9
9
|
*/
|
|
10
|
-
var e=x,t=b,n=My(),r=R,o=T,s={};Ty=s;var a=["daily","test","m","h","custom"],c="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||c;let i=r?n.utc():n().local();if(e&&-1!==a.indexOf(e.type))switch(e.type){case"m":var o=Math.floor(i.minutes()/e.digit)*e.digit;return i.minutes(o).format(t);case"h":var s=Math.floor(i.hour()/e.digit)*e.digit;return i.hour(s).format(t);case"daily":case"custom":case"test":return i.format(t)}return i.format(t)},s.setAuditLog=function(n,r,i){var o=null;if(n){var s=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);o=JSON.parse(e.readFileSync(l,{encoding:"utf-8"}))}else l=t.resolve(c+"/.audit.json"),o=JSON.parse(e.readFileSync(l,{encoding:"utf-8"}))}catch(n){if("ENOENT"!==n.code)return null;o={keep:{days:!1,amount:Number(a[1])},auditLog:r||c+"/.audit.json",files:[]}}o.keep={days:"d"===s,amount:Number(a[1])}}}return o},s.writeAuditLog=function(t,n){try{u(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){if(-1!==t.files.findIndex((function(t){return t.name===e})))return t;var a=Date.now();if(t.files.push({date:a,name:e,hash:r.createHash(t.hashType).update(e+"LOG_FILE"+a).digest("hex")}),t.keep.days){var c=n().subtract(t.keep.amount,"days").valueOf(),u=t.files.filter((function(e){return e.date>c||(e.hashType=t.hashType,l(e,o),i.emit("logRemoved",e),!1)}));t.files=u}else{var d=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=d}s.writeAuditLog(t,o)}return t},s.getStream=function(r){var l=null,h=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||c;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&&(h=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+(h?"."+h:"");if(b.match(/%DATE%/)&&(S=b.replace(/%DATE%/g,h||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),u(S);var C=r.file_options||{flags:"a"},$=e.createWriteStream(S,C);if(h&&l&&a.indexOf(l.type)>-1||g>0){f.verbose&&console.log(new Date,"[FileStreamRotator] Rotating file: ",l?l.type:"",g?"size: "+g:"");var N,O=new o;return O.auditLog=p,O.end=function(){$.end.apply($,arguments)},d($,O),O.on("close",(function(){N&&N.close()})),O.on("new",(function(n){O.auditLog=f.addLogToAudit(n,O.auditLog,O,f.verbose),r.create_symlink&&function(n,r,i){let o=r||"current.log",s=t.dirname(n),a=t.basename(n),c=s+"/"+o;try{e.lstatSync(c).isSymbolicLink()&&(e.unlinkSync(c),e.symlinkSync(a,c))}catch(n){if(n&&"ENOENT"==n.code)try{e.symlinkSync(a,c)}catch(n){i&&console.error(new Date,"[FileStreamRotator] Could not create symlink file: ",c," -> ",a)}}}(n,r.symlink_name,f.verbose),r.watch_log&&O.emit("addWatcher",n)})),O.on("addWatcher",(function(t){N&&N.close(),r.watch_log&&(N=function(t,n){if(!t)return null;try{return e.lstatSync(t),e.watch(t,(function(n){if("rename"==n)try{e.lstatSync(t)}catch(e){!function(e,t){O.emit("createLog",t)}(0,t)}}))}catch(e){n&&console.log(new Date,"[FileStreamRotator] Could not add watcher for "+t)}}(t,f.verbose))})),O.on("createLog",(function(t){try{e.lstatSync(t)}catch(n){$&&"function"==$.end&&$.end(),$=e.createWriteStream(t,C),O.emit("new",t),d($,O)}})),O.write=function(t,n){var o=l?this.getDate(l,v,r.utc):h;if(o!=h||g&&y>g){var s=b+(h&&l?"."+o:"");b.match(/%DATE%/)&&h&&(s=b.replace(/%DATE%/g,o)),g&&y>g?s+="."+ ++m+r.extension:(m=0,s+=r.extension),y=0,f.verbose&&console.log(new Date,i.format("[FileStreamRotator] Changing logs from %s to %s",S,s)),h=o,w=S,S=s,!0===r.end_stream?$.end():$.destroy(),u(S),$=e.createWriteStream(s,C),O.emit("new",s),O.emit("rotate",w,s),d($,O)}$.write(t,n),y+=Buffer.byteLength(t,n)}.bind(this),process.nextTick((function(){O.emit("new",S)})),O.emit("new",S),O}return f.verbose&&console.log(new Date,"[FileStreamRotator] File won't be rotated: ",r.frequency,r.size),process.nextTick((function(){$.emit("new",S)})),$};var u=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(n){if("EEXIST"!==n.code)throw n}return n}),"")},d=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 Ty}const Ry=x,jy=E,Ly=b,Fy=i,Uy=A,By=Ny.exports,Wy=gh.MESSAGE,Gy=N.PassThrough,Vy=Bp,Hy={json:!1,colorize:!1,eol:jy.EOL,logstash:null,prettyPrint:!1,label:null,stringify:!1,depth:null,showLevel:!0,timestamp:()=>(new Date).toISOString()},Yy=function(e){if(e=e||{},Vy.call(this,e),this.options=Object.assign({},Hy,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 Gy,this.logStream.pipe(e.stream);else{if(this.filename=e.filename?Ly.basename(e.filename):"winston.log",this.dirname=e.dirname||Ly.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=Dy().getStream({filename:Ly.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:Ly.join(this.dirname,"."+By(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{Ry.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(!Ry.existsSync(e))return}catch(t){return t.message=`Error occurred while checking existence of ${e}: ${t.message}`,void this.emit("error",t)}try{if(Ry.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=Uy.createGzip(),n=Ry.createReadStream(e);n.on("error",(t=>{t.message=`Error occurred while reading ${e}: ${t.message}`,this.emit("error",t)}));const r=Ry.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{Ry.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 zy=Yy;Fy.inherits(Yy,Vy),Yy.prototype.name="dailyRotateFile";const qy=function(){};Yy.prototype.log=function(e,t){t=t||qy,this.logStream.write(e[Wy]+this.options.eol),this.emit("logged",e),t(null,!0)},Yy.prototype.close=function(){this.logStream&&this.logStream.end((()=>{this.emit("finish")}))},Yy.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 Ry.readdirSync(this.dirname).filter((t=>Ly.basename(t).match(e)))})();0===r.length&&t&&t(null,n);const i=o=>{if(!o)return;const s=Ly.join(this.dirname,o);let a,c="";if(o.endsWith(".gz")){a=new Gy;const e=Ry.createReadStream(s);e.on("error",(e=>{e.message=`Error occurred while reading ${s}: ${e.message}`,a.emit("error",e)})),e.pipe(Uy.createGunzip()).pipe(a)}else a=Ry.createReadStream(s,{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 Ky=zy;jd.transports.DailyRotateFile=Ky;var Jy=bd(Ky);const Zy=Date.now();let Xy=Math.ceil(Zy/1e3);var Qy=()=>Xy+=1;const ev=w(C(),"kemu-user-services"),tv=w(C(),"kemu-test-services"),nv="KMU-CB-v1",rv=process.env.HUB_PKG_VERSION||'"1.12.4"';var iv;!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"}(iv||(iv={}));const ov=e=>({...e,type:Array.isArray(e.type)?e.type.map((e=>qu[e])):qu[e.type]}),sv=async e=>{try{return await y(e,"utf-8")}catch(e){return null}},av=e=>{if(e&&e.startsWith(nv)){const t=e.slice(9),n=decodeURI(t);return sd(n)}return null},cv=async(e,t,n)=>{let r=[];e.variants?.length&&(r=e.variants.map((e=>({...e,...e.inputs?{inputs:e.inputs.map(ov)}:{},...e.outputs?{outputs:e.outputs.map(ov)}:{}}))));const i={...e,path:t,customWidgets:[],...e.inputs?{inputs:e.inputs.map(ov)}:{inputs:[]},...e.outputs?{outputs:e.outputs.map(ov)}:{outputs:[]},variants:r,...e.widgetUI&&n?.widgetUIContents?{widgetUIContents:n.widgetUIContents}:{}},o=await(async(e,t,n=console.log)=>{const r=[];if(t.customWidgets?.length)for(const i of t.customWidgets){const t=await sv(w(e,i));if(!t){n(`Error loading custom widget file ${i}`);continue}const o=t.startsWith(nv)?t:`${nv}${t}`,s=av(o);if(!s){n(`Custom widget file "${i}" is not a valid Kemu Clipboard item`);continue}const a=Object.values(s).filter((e=>e.type===iv.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:o,rootGroupId:c.id,icon:l.icon,protocolVersion:l.protocolVersion||"2"};r.push(u)}return r})(t,e,n?.log);if(o.length?i.customWidgets=o:delete i.customWidgets,i.variants?.length)for(const e of i.variants)if(e.svgIcon)try{const n=await y(w(t,e.svgIcon),"utf-8");e.svgIcon=n}catch(t){n?.log&&n?.log(`Error loading svgIcon for variant ${e.id}: ${t}`)}return i},lv=async e=>{try{return await f(e,p.F_OK),!0}catch{return!1}};let uv=null,dv=null;const hv=()=>uv||ev,fv=()=>dv||tv;let pv=null;const gv={setGlobalUserId:e=>pv?.setGlobalUserId?.(e),captureError:e=>pv?.captureError?.(e),flushMessages:async()=>pv?.flushMessages?.(),isEnabled:()=>!!pv};var mv={...gv,setTracker:e=>{pv=e}};const yv=Rd("servicesManager"),vv={};let bv=null,wv=null,Sv=null,_v=!1;class Iv extends Error{code;originalError;constructor(e,t,n){super(e),this.code=t,this.originalError=n,this.name="ServiceError"}}const xv=async e=>{try{return await f(e),!0}catch{return!1}},kv=async e=>{if(!bv)throw new Error('IPC config not set, call "setHubIpcConfig" first.');let t;if(e.info.internal)if("linux"===$()){const n=process.env.XDG_STATE_HOME||b.join(C(),".local","state");t=b.join(n,"kemu-hub","service-logs",e.info.name);try{await h(t,{recursive:!0})}catch(n){yv(`Failed to create log directory ${t}, falling back to service path`),t=e.info.path}}else t=e.info.path;else t=b.join(e.info.path,"..");const n=e.logsEnabled?((e,t)=>{const n=$y.createLogger({level:"info",format:$y.format.combine($y.format.timestamp(),$y.format.errors({stack:!0}),$y.format.json()),defaultMeta:{service:e},transports:[new Jy({filename:b.join(t,"service-%DATE%.log"),datePattern:"YYYY-MM-DD",maxSize:"5m",maxFiles:"5d",auditFile:b.join(t,".service-log-audit.json")})]});return n.getLastLogs=async(n=100)=>{try{const r=b.join(t,".service-log-audit.json"),i=await d.readFile(r,"utf-8"),o=sd(i);if(!o)return console.warn(`Missing audit file for ${e}, skipping log retrieval.`),[];const s=async e=>(await d.readFile(e,"utf-8")).split("\n").filter((e=>e.trim())),a=[],c=[...o.files].reverse();for(const e of c){const t=await s(e.name);if(a.push(...t),a.length>=n)break}return a}catch(t){return console.warn(`Failed to read service logs for ${e}: `,t),[]}},n})(e.info.name,t):null,r=t=>{if(!e.devMode){const{childProcess:r,...i}=e;mv.isEnabled()&&mv.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===Ju.Javascript){yv(`Spawning service ${e.info.name} with sessionId ${e.info.sessionId}`);const t=b.join(e.info.path,"processor.js"),i=b.join(e.info.path,"processor.mjs"),o=await xv(t)?t:i,s=[`--sessionId=${e.info.sessionId.toString()}`,`--ipcSpace=${bv.appSpace}`,`--ipcId=${bv?.id}`,`--recipePath=${bv.recipePath||""}`];if(e.info.internal&&s.push("--internal=true"),!Sv)throw new Error('Get secrets function not set, call "setGetSecretsFunction" first.');const a=await Sv({name:e.info.name,version:e.info.version,requiredSecrets:e.info.requiredSecrets||{}}),c=Object.entries(e.info.requiredSecrets||{}).filter((([e,t])=>null==a[e]&&!t.optional)).map((([e])=>e));if(c?.length)throw new Iv(`Missing required environment variables: ${c.join(", ")}`,"MISSING_REQUIRED_SECRETS");return new Promise(((t,i)=>{if(!wv)throw new Error('Spawn function not set, call "setSpawnNodeFunction" first.');const c=wv({args:[o,...s],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),yv(`[${e.info.name}] - stdout: ${r}`))})),c.stderr.on("data",(t=>{const i=t.toString().trim();i&&(n?.error(i),r(new Error(i)),yv(`[${e.info.name}] - stderr: ${i}`))})),c.on("exit",(t=>{const r=`exited with code ${t}`;n?.info(r,{code:t}),yv(`[${e.info.name}] ${r}`)})),c.on("spawn",(()=>{const r=`spawned with PID ${c.pid}`;n?.info(r,{pid:c.pid}),yv(`[${e.info.name}] ${r}`),t(c)})),c.on("error",(t=>{n?.error(`[${e.info.name}] error`,t),yv(`[${e.info.name}] error: ${t}`),r(t),i(new Iv(`Error spawning service ${e.info.name}: ${t}`,"SPAWN_ERROR"))}))}))}throw`Unsupported processor type ${e.info.processor}`}catch(t){if(r(t),t instanceof Iv)throw t;throw`Error spawning service ${e.info.name}: ${t}`}},Ev=e=>e?.name?e?.version?e?.description?e?.processor?[Ju.Javascript,Ju.Executable,Ju.Python].includes(e?.processor)?null:"Invalid processor":"Missing processor":"Missing description":"Missing version":"Missing name",Cv=async(e,t)=>{const n=b.join(e,"manifest.json");if(!await xv(n)){const t=`Missing manifest for service ${e}. Aborting.`;return yv(t),{error:t}}const r=await y(n,"utf-8"),i=sd(r),o=Ev(i);if(!i||o){const t=`Invalid service manifest [${e}]: ${o}. Aborting.`;return yv(t),{error:t}}let s;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{s=await y(b.join(e,"widgetUI.js"))}catch(e){const t=`Error loading widgetUI file ${i.name}: ${e}`;return yv(t),{error:t}}})(),(async()=>{if(i.svgIcon){const t=await sv(b.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=b.join(e,t),{error:r,service:o}=await Cv(n);r?yv(`Error loading sub-service ${t}: ${r}`):o&&(o.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 y(b.join(e,t.svgIcon),"utf-8");t.svgIcon=n}catch(e){yv(`Error loading svgIcon for variant ${t.id}: ${e}`)}})()]);const a=Qy(),c=t?.fixedSession||a;yv(`Loaded service ${i.name} with sessionId ${c}`);const l=await cv(i,e,{widgetUIContents:s});return $v(l),vv[c]={info:{...l,path:e,sessionId:c},status:"loaded",childProcess:null,logsEnabled:t?.logsEnabled},{service:vv[c]}},$v=e=>{e.widgetUIContents?e.uiContentChecksum=(e=>{const t=j("sha256");return t.update(e),t.digest("hex")})(e.widgetUIContents):e.uiContentChecksum=void 0},Nv=async e=>{try{return e.childProcess=await kv(e),e.status="started",e.errorMsg=void 0,e.errorCode=void 0,!0}catch(t){return yv(`Service [${e.info.name}] error: ${t}`),e.status="error",t instanceof Iv?(e.errorMsg=t.message,e.errorCode=t.code):(e.errorMsg="string"==typeof t?t:JSON.stringify(t),e.errorCode="UNKNOWN_ERROR"),!1}},Ov=e=>{const{path:t,...n}=e.info;return{...n}},Tv=()=>Object.values(vv).filter((e=>"running"===e.status)).map(Ov),Av=e=>{if(!e?.kill)return yv(`Failed to kill service ${e?.pid} because it is not a child process`),!1;let t=e.kill("SIGINT");return t||(yv(`Failed to send SIGINT to service ${e.pid} using SIGINT`),t=e.kill("SIGTERM"),t||(yv(`Failed to send SIGTERM to service ${e.pid} using SIGTERM`),t=e.kill("SIGKILL"),t||yv(`Failed to send SIGKILL to service ${e.pid} using SIGKILL`))),t},Pv=async e=>{const{serviceName:t,version:n,force:r,timeout:i=15e3}=e,o=Object.values(vv).find((t=>t.info.name===e.serviceName&&t.info.version===e.version));if(!o)return null;if(o.info.internal&&!r)throw`Cannot stop internal service ${t}`;if(o.childProcess){yv(`Stopping service "${t} (v${n})"`);const r=new Promise(((e,n)=>{const r=setTimeout((()=>{n(new Error(`Timeout waiting for service ${t} to stop after ${i}ms`))}),i);o.childProcess.once("exit",((n,i)=>{clearTimeout(r),yv(`Service ${t} process exited with code ${n} and signal ${i}`),e()})),o.childProcess.once("error",(n=>{clearTimeout(r),yv(`Service ${t} process error: ${n.message}`),e()}))}));Av(o.childProcess);try{await r,yv(`Service ${t} process successfully terminated`)}catch(e){yv(`Warning: ${e instanceof Error?e.message:"Unknown error"} while waiting for service ${t} to stop`)}}return o.status="stopped",yv(`Service ${t} stopped`),o},Mv=e=>e.info.internal?e.info.path:b.join(e.info.path,".."),Dv=e=>!!e.internal;var Rv={isOfficialKemuService:e=>e.name.startsWith("kemu.io"),loadServices:async(e,t)=>{if(!await lv(e))return void yv(`Failed to load services from "${e}". Directory does not exist.`);const n=(await g(e,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name));yv(`Found ${n.length} services in "${e}"`);for(let r=0;r<n.length;r++){const i=n[r],o=b.join(e,i),{error:s,service:a}=await Cv(`${o}${t?.internalServices?"":"/dist"}`,{...t,logsEnabled:Array.isArray(t?.enableLogs)?t?.enableLogs.includes(i):t?.enableLogs});s&&yv(`Failed to load service ${o}. Please check logs`),a&&t?.internalServices&&(a.info.internal=!0)}},launchServices:async e=>{if(yv("Initializing services"),!bv)throw new Error('IPC config not set, call "setHubIpcConfig" first.');for(const t in vv){const n=vv[t];e.noSpawningList&&e.noSpawningList.includes(n.info.name)?yv(`Service ${n.info.name} is in the noSpawningList. Skipping.`):Nv(n)}yv("Services initialized")},setServiceStatus:(e,t)=>{const n=vv[e];return n?(n.status=t,!0):(yv(`Service with serviceId ${e} not found`),!1)},getActiveServices:Tv,getMatchingService:(e,t)=>{const n=Object.values(vv).filter((e=>"running"===e.status));for(const r of n)if(r.info.name===e){if(r.info.version===t)return r;if(pd(r.info.version,t,">="))return r}return null},getServiceBySessionId:e=>vv[e]||null,killAllServices:async(e=5e3)=>{const t=[];for(const n in vv){const r=vv[n];if(r.childProcess&&r.childProcess.pid)try{yv(`Killing service ${r.info.name} with PID ${r.childProcess.pid}`);const n=new Promise((t=>{const n=setTimeout((()=>{yv(`Timeout waiting for service ${r.info.name} to exit`),t()}),e);r.childProcess?.once("exit",(()=>{clearTimeout(n),yv(`Service ${r.info.name} exited successfully`),t()}))}));Av(r.childProcess),t.push(n)}catch(e){yv(`Error killing service ${r.info.name}: ${e}`)}}await Promise.allSettled(t),yv("All services killed")},addDevService:async(e,t,n)=>{const r={info:{...await cv(t,t.path),sessionId:e},status:n,startedAt:new Date,devMode:!0,childProcess:null};vv[e]=r,$v(vv[e].info)},setServiceManifest:(e,t,n)=>{const r=vv[e];if(!r)return yv(`Service with sessionId ${e} not found`),!1;const i=Ev(t);if(i)return yv(`Invalid manifest for service ${r.info.name}: ${i}`),!1;$v(t),r.info={...r.info,...t},n&&(r.status=n)},getMatchingDevService:(e,t,n)=>{const r=Object.values(vv).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:()=>Tv().filter((e=>e.internal)),getAllServices:()=>Object.values(vv),stopService:Pv,uninstallService:async(e,t)=>{yv(`Uninstalling service ${e} v${t}`);const n=await Pv({serviceName:e,version:t});if(!n)return!1;yv(`Service ${e} stopped. Removing from disk...`);const r=Mv(n),i=hv();return r.startsWith(i)?(await m(r,{recursive:!0,force:!0,maxRetries:3}),yv(`Service ${e} successfully removed from disk`),(e=>{vv[e],delete vv[e]})(n.info.sessionId),!0):(yv(`Service ${e} is not installed in the user services directory. Aborting.`),!1)},getAllServiceVersions:e=>Object.values(vv).filter((t=>t.info.name===e)),setHubIpcConfig:e=>{bv={...e}},setEnableServiceLogsConfig:e=>{_v=e},loadAndLaunch:async(e,t,n)=>{const r=_(e,t),{error:i,service:o}=await Cv(r,{logsEnabled:_v});if(i||!o)return{errorMsg:i};try{o.info.internal=!!n,o.childProcess=await kv(o),o.status="started"}catch(e){o.status="error",e instanceof Iv?(yv(`Service spawning error: ${e.message} (${e.code})`),o.errorMsg=e.message,o.errorCode=e.code):(yv(`Error launching service ${o.info.name}: ${e}`),o.errorMsg="string"==typeof e?e:JSON.stringify(e))}return{service:o,errorCode:o.errorCode,errorMsg:o.errorMsg}},getServiceRootDirectory:Mv,setSpawnNodeFunction:e=>{wv=e},setGetSecretsFunction:e=>{Sv=e},restartService:async(e,t)=>{yv(`Restarting service ${e} v${t}`);const n=await Pv({serviceName:e,version:t,force:!0});return!!n&&Nv(n)},getFailedServices:()=>Object.values(vv).filter((e=>"error"===e.status)).map((e=>({...Ov(e),errorMsg:e.errorMsg||"",errorCode:e.errorCode,status:e.status}))),isInternalKemuService:Dv,isNotInternalKemuService:e=>!Dv(e),isNotDevService:e=>!e.devMode};class jv{constructor(){}appspace="app.";socketRoot="/tmp/";id=E.hostname();encoding="utf8";rawBuffer=!1;sync=!1;unlink=!0;delimiter="\f";silent=!1;logDepth=5;logInColor=!0;logger=console.log.bind(console);maxConnections=100;retry=500;maxRetries=1/0;stopRetrying=!1;IPType=function(){const e=E.networkInterfaces();let t="";return e&&Array.isArray(e)&&e.length>0&&(t=e[Object.keys(e)[0]][0].family),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 Lv{constructor(e){e||(e=new jv),this.delimiter=e.delimiter}format(e){return e.data||!1===e.data||0===e.data||(e.data={}),e.data._maxListeners&&(e.data={}),e.JSON+this.delimiter}parse(e){let t=e.split(this.delimiter);return t.pop(),t}}var Fv=bd((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={}})),Uv=bd((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(){t=!0,e.length<1||this.stop?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 Bv{}class Wv{}const Gv=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 Bv,t=Wv){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 Bv}}())}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 Vv{constructor(){}on(e,t,n=!1){return Gv.string(e),Gv.function(t),Gv.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(Gv.string(e),e!=this.#e.toString()&&"*"!=e||(e=this.#e),!this.#t[e])return this;if("*"==t)return delete this.#t[e],this;Gv.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){Gv.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)=>{Gv.string(e),Gv.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 Hv=new Lv;class Yv extends Vv{constructor(e,t){super(),this.config=e,this.log=t,this.publish=super.emit,e.maxRetries&&(this.retriesRemaining=e.maxRetries),Hv=new Lv(this.config)}Client=Yv;queue=new Uv;socket=!1;connect=Kv;emit=zv;retriesRemaining=0;explicitlyDisconnected=!1}function zv(e,t){this.log("dispatching event to ",this.id,this.path," : ",e,",",t);let n=new Fv;n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Hv.format(n),this.config.sync?this.queue.add(qv.bind(this,n)):this.socket.write(n)}function qv(e){this.log("dispatching event to ",this.id,this.path," : ",e),this.socket.write(e)}function Kv(){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=x.readFileSync(e.config.tls.private)),e.config.tls.public&&(e.config.tls.cert=x.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(x.readFileSync(e.config.tls.trustedConnections[t]))}Object.assign(e.config.tls,t),e.socket=F.connect(e.config.tls)}else e.log("Connecting client via TCP to",t),e.socket=L.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=L.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)!=Hv.delimiter||-1==t.indexOf(Hv.delimiter))return void e.log("Messages are large, You may want to consider smaller messages.");this.ipcBuffer="";const n=Hv.parse(t),r=n.length;for(let t=0;t<r;t++){let r=new Fv;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 Jv=new Lv;class Zv extends Vv{constructor(e,t,n,r){super(),this.config=t,this.path=e,this.port=r,this.log=n,this.publish=super.emit,Jv=new Lv(this.config),this.on("close",eb.bind(this))}udp4=!1;udp6=!1;server=!1;sockets=[];emit=Xv;broadcast=Qv;onStart(e){this.publish("start",e)}stop(){this.server.close()}start(){this.path?this.config.unlink?x.unlink(this.path,ib.bind(this)):ib.bind(this)():this.log("Socket Server Path not specified, refusing to start")}}function Xv(e,t,n){this.log("dispatching event to socket"," : ",t,n);let r=new Fv;if(r.type=t,r.data=n,this.config.rawBuffer?(this.log(this.config.encoding),r=Buffer.from(t,this.config.encoding)):r=Jv.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 Qv(e,t){this.log("broadcasting event to all known sockets listening to ",this.path," : ",this.port?this.port:"",e,t);let n=new Fv;if(n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Jv.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 eb(){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 tb(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)==Jv.delimiter&&-1!=t.indexOf(Jv.delimiter))for(r.ipcBuffer="",t=Jv.parse(t);t.length>0;){let e=new Fv;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 nb(e){this.publish("close",e)}function rb(e){this.sockets.push(e),e.setEncoding&&e.setEncoding(this.config.encoding),this.log("## socket connection to server detected ##"),e.on("close",nb.bind(this)),e.on("error",function(e){this.log("server socket error",e),this.publish("error",e)}.bind(this)),e.on("data",tb.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 ib(){return this.log("starting server on ",this.path,this.port?`:${this.port}`:""),this.udp4||this.udp6?(this.server=U.createSocket(this.udp4?"udp4":"udp6"),this.server.write=sb.bind(this),this.server.on("listening",function(){rb.bind(this)(this.server)}.bind(this))):(this.log("starting TLS server",this.config.tls),this.config.tls?ob.bind(this)():this.server=L.createServer(rb.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 ob(){if(this.log("starting TLS server",this.config.tls),this.config.tls.private?this.config.tls.key=x.readFileSync(this.config.tls.private):this.config.tls.key=x.readFileSync(`${__dirname}/../local-node-ipc-certs/private/server.key`),this.config.tls.public?this.config.tls.cert=x.readFileSync(this.config.tls.public):this.config.tls.cert=x.readFileSync(`${__dirname}/../local-node-ipc-certs/server.pub`),this.config.tls.dhparam&&(this.config.tls.dhparam=x.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(x.readFileSync(this.config.tls.trustedConnections[e]))}this.server=F.createServer(this.config.tls,rb.bind(this))}function sb(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 ab{constructor(){}config=new jv;of={};server=!1;get connectTo(){return fb}get connectToNet(){return pb}get disconnect(){return lb}get serve(){return ub}get serveNet(){return hb}get log(){return cb}set connectTo(e){return fb}set connectToNet(e){return pb}set disconnect(e){return lb}set serve(e){return ub}set serveNet(e){return hb}set log(e){return cb}}function cb(...e){if(!this.config.silent){for(let t=0,n=e.length;t<n;t++)"object"==typeof e[t]&&(e[t]=i.inspect(e[t],{depth:this.config.logDepth,colors:this.config.logInColor}));this.config.logger(e.join(" "))}}function lb(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 ub(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=db),this.server=new Zv(e,this.config,cb),this.server.on("start",t)}function db(){}function hb(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=db),this.server=new Zv(e,this.config,cb,t),n&&(this.server[n]=!0,"udp4"===n&&"::1"===e&&(this.server.path="127.0.0.1")),this.server.on("start",r)}function fb(e,t,n){if("function"==typeof t&&(n=t,t=!1),n||(n=db),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 Yv(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 pb(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=db),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 Yv(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 gb=new class extends ab{constructor(){super()}IPC=ab};const mb=Object.values({protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8}).reduce(((e,t)=>e+t),0),yb=e=>{try{return JSON.parse(e)}catch(e){return null}},vb="undefined"!=typeof window,bb={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},wb={protocolPrefix:4,txtLength:4},Sb=Object.values(bb).reduce(((e,t)=>e+t),0),_b=Object.values(wb).reduce(((e,t)=>e+t),0),Ib=["width","height","colorSpace"],xb=(e,t)=>{const n={},r=[];let i=0,o=Array.isArray(e)?[]:{};const s=(e,o)=>{const a=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,i=e instanceof Uint8Array,o=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":i?"Uint8Array":o?"Int8Array":null})(e);if(!a){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=s(e[n],`${o}[${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,o=e instanceof Float32Array,s=e instanceof Float64Array,a=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":i?"Uint32Array":o?"Float32Array":s?"Float64Array":a?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${o}"`);for(const n in e)Object.hasOwn(e,n)||Ib.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${o}`),t[n]=s(e[n],`${o.length?`${o}.`:""}${n}`);return t}return e}n[o]={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};o=s(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:o}:null},kb=(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 o=t.startsWith("[")&&t.endsWith("]"),s=e===r.length-1;if(o){t=t.slice(1,-1);const o=parseInt(t,10);if(!Array.isArray(i))throw new Error(`Expected an array at key "${r.slice(0,e).join(".")}" but found an object.`);s?i[o]=n:(i[o]||(i[o]=r[e+1].startsWith("[")?[]:{}),i=i[o])}else s?i[t]=n:(i[t]||(i[t]=r[e+1].startsWith("[")?[]:{}),i=i[t])}return e},Eb=(e,t,n)=>{const r="undefined"!=typeof Buffer,i=t instanceof Uint8Array;for(const o in n)if(Object.hasOwn(n,o)){const{index:s,length:a,binaryType:c}=n[o];let l=null;if(r&&t instanceof Buffer)switch(c){case"Buffer":l=t.subarray(s,s+a);break;case"ArrayBuffer":l=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(s,s+a);break;case"Uint8Array":l=new Uint8Array(t.subarray(s,s+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.subarray(s,s+a));break;case"Int8Array":l=new Int8Array(t.subarray(s,s+a))}else if(t instanceof ArrayBuffer||t instanceof Uint8Array)switch(c){case"Buffer":if(r){l=Buffer.from(t.slice(s,s+a));break}case"ArrayBuffer":l=i?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(s,s+a):t.slice(s,s+a);break;case"Uint8Array":l=i?t.slice(s,s+a):new Uint8Array(t.slice(s,s+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.slice(s,s+a));break;case"Int8Array":l=new Int8Array(t.slice(s,s+a))}l&&kb(e,o,l)}return e},Cb=e=>Dd(e),$b="KMSG",Nb="KCMD",Ob=Cb("klProtocol");var Tb={encode:(e,t,n)=>{const r={json:e.json},i=xb(r.json,"Buffer"),o=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const s=o?o.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),l=c.byteLength,u=bb.protocolPrefix+bb.protocolVersion+bb.jsonLength+bb.binaryLength+bb.fromServiceId+bb.toServiceId+bb.sentAt+l+s,d=Buffer.alloc(u),h=Date.now();let f=0;return d.write($b,f),f+=bb.protocolPrefix,d.writeUInt8(1,f),f+=bb.protocolVersion,d.writeUInt32LE(l,f),f+=bb.jsonLength,d.writeUInt32LE(s,f),f+=bb.binaryLength,d.writeUInt32LE(t,f),f+=bb.fromServiceId,d.writeUInt32LE(n,f),f+=bb.toServiceId,d.writeBigInt64LE(BigInt(h),f),f+=bb.sentAt,c.copy(d,f),f+=l,o&&s&&o.copy(d,f),d},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,bb.protocolPrefix);if(t+=bb.protocolPrefix,n!==$b)return null;if(e.byteLength<Sb)return Ob(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=bb.protocolVersion;const i=e.readUInt32LE(t);t+=bb.jsonLength;const o=e.readUInt32LE(t);t+=bb.binaryLength;const s=e.readUInt32LE(t);t+=bb.fromServiceId;const a=e.readUInt32LE(t);t+=bb.toServiceId;const c=e.readBigInt64LE(t);t+=bb.sentAt;const l=i+o,u=e.subarray(t,t+l),d=e.subarray(0,Sb);let h=null;return e.byteLength-Sb-i-o>0&&(h=e.subarray(Sb+i+o)),{header:{protocolVersion:r,jsonLength:i,binaryLength:o,fromServiceId:s,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=yb(n);if(!i?.json)return Ob("Invalid JSON in KL message"),null;i.jsonBinaryMap&&r.byteLength&&Eb(i.json,r,i.jsonBinaryMap);const o=Buffer.concat([e.headerPackage,t]);let s=o,a=null;const c=Sb+e.jsonLength+e.binaryLength;return o.byteLength>c&&(a=o.subarray(c),s=o.subarray(0,c)),{message:{json:i.json,rawMessage:s},remaining:a}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Sb)return Ob("Invalid Header Size"),e;let n=0;return n+=bb.protocolPrefix,n+=bb.protocolVersion,n+=bb.jsonLength,n+=bb.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=bb.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=_b+r,o=Buffer.alloc(i);return o.write(Nb,t),t+=wb.protocolPrefix,o.writeUint32LE(r,t),t+=wb.txtLength,n.copy(o,t),o},decodeCommand:e=>{let t=0;if(e.byteLength<_b)return{command:null};const n=e.toString("utf-8",t,wb.protocolPrefix);if(t+=wb.protocolPrefix,n!==Nb)return{command:null};const r=e.readUInt32LE(t);t+=wb.txtLength;const i=e.toString("utf-8",t,t+r),o=e.byteLength-_b-r;let s=null;o>0&&(s=e.subarray(_b+r));let a=0;return o<0&&(a=Math.abs(o)),{command:i,remainingData:s,missing:a}}};const Ab="KMSG",Pb="KCMD",Mb=Cb("klProtocol"),Db=new TextEncoder;var Rb={encode:(e,t,n)=>{const r={json:e.json},i=xb(e.json,"ArrayBuffer"),o=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const s=o?o.byteLength:0,a=JSON.stringify(r),c=Db.encode(a),l=c.byteLength,u=new ArrayBuffer(bb.protocolPrefix+bb.protocolVersion+bb.jsonLength+bb.binaryLength+bb.fromServiceId+bb.toServiceId+bb.sentAt+l+s),d=new DataView(u),h=new Uint8Array(u),f=Date.now();let p=0;for(let e=0;e<4;++e)h[p++]=Ab.charCodeAt(e);return d.setUint8(p,1),p+=bb.protocolVersion,d.setUint32(p,l,!0),p+=bb.jsonLength,d.setUint32(p,s,!0),p+=bb.binaryLength,d.setUint32(p,t,!0),p+=bb.fromServiceId,d.setUint32(p,n,!0),p+=bb.toServiceId,d.setBigInt64(p,BigInt(f),!0),p+=bb.sentAt,h.set(c,p),p+=l,o&&s&&h.set(new Uint8Array(o),p),u},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<bb.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Ab)return null;if(e.byteLength<Sb)return Mb.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const i=t.getUint8(n);n+=bb.protocolVersion;const o=t.getUint32(n,!0);n+=bb.jsonLength;const s=t.getUint32(n,!0);n+=bb.binaryLength;const a=t.getUint32(n,!0);n+=bb.fromServiceId;const c=t.getUint32(n,!0);n+=bb.toServiceId;const l=t.getBigInt64(n,!0);n+=bb.sentAt;const u=o+s,d=e.slice(n,n+u),h=new Uint8Array(e,0,Sb);let f=null;return e.byteLength-Sb-o-s>0&&(f=new Uint8Array(e,Sb+o+s).slice().buffer),{header:{protocolVersion:i,jsonLength:o,binaryLength:s,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 o=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),s=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=yb(o);if(!a?.json)return Mb.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&s.byteLength&&Eb(a.json,s,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=Sb+e.jsonLength+e.binaryLength;return c.byteLength>d&&(u=c.subarray(d),l=c.subarray(0,d)),{message:{json:a.json,...s.length?{binaryData:s.buffer}:{},rawMessage:l.buffer},remaining:u?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Sb)return Mb("Invalid Header Size"),e;let n=0;n+=bb.protocolPrefix,n+=bb.protocolVersion,n+=bb.jsonLength,n+=bb.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=bb.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=Db.encode(e),r=n.byteLength,i=new ArrayBuffer(_b+r),o=new DataView(i),s=new Uint8Array(i);for(let e=0;e<4;++e)s[t++]=Pb.charCodeAt(e);return o.setUint32(t,r,!0),t+=wb.txtLength,s.set(n,t),i},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<_b)return{command:null};let r="";for(let e=0;e<wb.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Pb)return{command:null};const i=t.getUint32(n,!0);n+=wb.txtLength;const o=e.byteLength-_b-i,s=new Uint8Array(e,n,Math.min(i,e.byteLength-_b)),a=(new TextDecoder).decode(s);let c=null;o>0&&(c=e.slice(_b+i));let l=0;return o<0&&(l=Math.abs(o)),{command:a,remainingData:c,missing:l}}};const jb=Cb("klTransmissionManager"),Lb=()=>{const e=(t,n,r,i)=>{let o=n,s=null;const a=t instanceof ArrayBuffer;if(jb(`RAW: ${t.toString()}`),!o||o.partialHeaderData){let c;if(a?(c=o?.partialHeaderData?new Uint8Array([...new Uint8Array(o.partialHeaderData),...new Uint8Array(t)]).buffer:t,s=Rb.decodeHeader(c)):(c=o?.partialHeaderData?Buffer.concat([o.partialHeaderData,t]):t,s=Tb.decodeHeader(c)),!s){const{command:t,missing:o,remainingData:s}=a?Rb.decodeCommand(c):Tb.decodeCommand(c);return t?i({command:t,complete:!0,rawMessage:c}):jb(o?`ERROR: Missing ${o} 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`),s?(jb(`${s.byteLength} bytes remain after processing command. Re-analyzing...`),e(s,n,r,i)):void 0}if(s.partialHeader)return o={firstPackageAt:Date.now(),partialHeaderData:c},r(o);if(!s.header)return jb(`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${c.byteLength} bytes`);const l=s.header;o={firstPackageAt:Date.now(),header:{...l,totalBytesReceived:l.packages[0].byteLength,totalBytesExpected:l.binaryLength+l.jsonLength,remaining:s.remaining}},r(o)}else o.header&&o.header.totalBytesReceived<o.header.totalBytesExpected&&(o.header.packages.push(t),o.header.totalBytesReceived+=t.byteLength,r(o));if(o.header&&o.header.totalBytesReceived>=o.header.totalBytesExpected){const t=Date.now()-o.header.sentAt.getTime(),n=Date.now()-o.firstPackageAt;jb(`Received ${o.header.totalBytesReceived} of ${o.header.totalBytesExpected} expected in ${t} ms, elapsed since first package: ${n}ms`);const s=a?Rb.decodeFullKlMessage(o.header):Tb.decodeFullKlMessage(o.header),c=o.header.totalBytesReceived,l=o.header.remaining;r(null),s&&i({klMessage:s.message,complete:!0,sourceServiceId:o.header.fromServiceId,targetServiceId:o.header.toServiceId,rawMessage:s.message.rawMessage});let u=l;if(s?.remaining&&(u=a?l?((e,t)=>{const n=e.byteLength+t.byteLength,r=new ArrayBuffer(n),i=new Uint8Array(e),o=new Uint8Array(t),s=new Uint8Array(r);return s.set(i),s.set(o,i.length),r})(l,s.remaining):s.remaining:l?Buffer.concat([l,s.remaining]):s.remaining),u)return jb(`${u.byteLength} bytes remaining after processing message with ${c} bytes of data. Re-analyzing...`),e(u,null,r,i)}};return e};gb.config={...gb.config,id:"widgets",retry:1500,silent:!0,rawBuffer:!0,appspace:"kemu.",encoding:"hex"};const Fb={info:Rd("ipcServer:info"),data:Rd("ipcServer:data")};let Ub,Bb,Wb,Gb,Vb={};const Hb=Lb(),Yb=e=>{Vb[e]&&(Fb.info(`Client disconnected [${e}]`),delete Vb[e],Bb&&Bb(e))};var zb=(e,t)=>{const n=Vb[e];if(!n)return Fb.info(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=mb)return Fb.info("Message is too long to be a command. Use sendMessage instead."),!1;const r=Tb.encodeCommand(t);return n.socket.write(r),!0},qb=(e,t)=>{const n=Vb[e];return!!n&&(Fb.info(`Renaming socket id [${e}] to [${t}]`),delete Vb[e],n.socket.id=t,Vb[t]=n,n.socket.removeListener("close",n.disconnectHandler),n.disconnectHandler=()=>Yb(t),n.socket.on("close",n.disconnectHandler),!0)};let Kb=Tb;vb&&(Kb=Rb);var Jb,Zb=Kb;!function(e){e.FunctionNotFound="FNC_NOT_FOUND",e.FunctionNotAllowed="FNC_NOT_ALLOWED",e.ParentEventCallbackError="PARENT_EVENT_CALLBACK_ERROR"}(Jb||(Jb={}));let Xb=Math.ceil(Date.now()/1e3);var Qb={exports:{}};const ew=["nodebuffer","arraybuffer","fragments"],tw="undefined"!=typeof Blob;tw&&ew.push("blob");var nw={BINARY_TYPES:ew,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:tw,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:rw}=nw,iw=Buffer[Symbol.species];function ow(e,t,n,r,i){for(let o=0;o<i;o++)n[r+o]=e[o]^t[3&o]}function sw(e,t){for(let n=0;n<e.length;n++)e[n]^=t[3&n]}if(Qb.exports={concat:function(e,t){if(0===e.length)return rw;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 iw(n.buffer,n.byteOffset,r):n},mask:ow,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 iw(t):ArrayBuffer.isView(t)?n=new iw(t.buffer,t.byteOffset,t.byteLength):(n=Buffer.from(t),e.readOnly=!1),n},unmask:sw},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");Qb.exports.mask=function(t,n,r,i,o){o<48?ow(t,n,r,i,o):e.mask(t,n,r,i,o)},Qb.exports.unmask=function(t,n){t.length<32?sw(t,n):e.unmask(t,n)}}catch(b){}var aw=Qb.exports;const cw=Symbol("kDone"),lw=Symbol("kRun"),uw=A,dw=aw,hw=class{constructor(e){this[cw]=()=>{this.pending--,this[lw]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[lw]()}[lw](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[cw])}}},{kStatusCode:fw}=nw,pw=Buffer[Symbol.species],gw=Buffer.from([0,0,255,255]),mw=Symbol("permessage-deflate"),yw=Symbol("total-length"),vw=Symbol("callback"),bw=Symbol("buffers"),ww=Symbol("error");let Sw;var _w=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,!Sw){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;Sw=new hw(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[vw];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){Sw.add((r=>{this._decompress(e,t,((e,t)=>{r(),n(e,t)}))}))}compress(e,t,n){Sw.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]?uw.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=uw.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[mw]=this,this._inflate[yw]=0,this._inflate[bw]=[],this._inflate.on("error",kw),this._inflate.on("data",xw)}this._inflate[vw]=n,this._inflate.write(e),t&&this._inflate.write(gw),this._inflate.flush((()=>{const e=this._inflate[ww];if(e)return this._inflate.close(),this._inflate=null,void n(e);const i=dw.concat(this._inflate[bw],this._inflate[yw]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[yw]=0,this._inflate[bw]=[],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]?uw.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=uw.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[yw]=0,this._deflate[bw]=[],this._deflate.on("data",Iw)}this._deflate[vw]=n,this._deflate.write(e),this._deflate.flush(uw.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=dw.concat(this._deflate[bw],this._deflate[yw]);t&&(e=new pw(e.buffer,e.byteOffset,e.length-4)),this._deflate[vw]=null,this._deflate[yw]=0,this._deflate[bw]=[],t&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),n(null,e)}))}};function Iw(e){this[bw].push(e),this[yw]+=e.length}function xw(e){this[yw]+=e.length,this[mw]._maxPayload<1||this[yw]<=this[mw]._maxPayload?this[bw].push(e):(this[ww]=new RangeError("Max payload size exceeded"),this[ww].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ww][fw]=1009,this.removeListener("data",xw),this.reset())}function kw(e){this[mw]._inflate=null,e[fw]=1007,this[vw](e)}var Ew={exports:{}};const{isUtf8:Cw}=O,{hasBlob:$w}=nw;function Nw(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(Ew.exports={isBlob:function(e){return $w&&"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:Nw,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]},Cw)Ew.exports.isValidUTF8=function(e){return e.length<24?Nw(e):Cw(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");Ew.exports.isValidUTF8=function(t){return t.length<32?Nw(t):e(t)}}catch(b){}var Ow=Ew.exports;const{Writable:Tw}=N,Aw=_w,{BINARY_TYPES:Pw,EMPTY_BUFFER:Mw,kStatusCode:Dw,kWebSocket:Rw}=nw,{concat:jw,toArrayBuffer:Lw,unmask:Fw}=aw,{isValidStatusCode:Uw,isValidUTF8:Bw}=Ow,Ww=Buffer[Symbol.species];const{randomFillSync:Gw}=R,Vw=_w,{EMPTY_BUFFER:Hw,kWebSocket:Yw,NOOP:zw}=nw,{isBlob:qw,isValidStatusCode:Kw}=Ow,{mask:Jw,toBuffer:Zw}=aw,Xw=Symbol("kByteLength"),Qw=Buffer.alloc(4),eS=8192;let tS,nS=eS;function rS(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 iS(e,t,n){rS(e,t,n),e.onerror(t)}const{kForOnEventAttribute:oS,kListener:sS}=nw,aS=Symbol("kCode"),cS=Symbol("kData"),lS=Symbol("kError"),uS=Symbol("kMessage"),dS=Symbol("kReason"),hS=Symbol("kTarget"),fS=Symbol("kType"),pS=Symbol("kWasClean");class gS{constructor(e){this[hS]=null,this[fS]=e}get target(){return this[hS]}get type(){return this[fS]}}Object.defineProperty(gS.prototype,"target",{enumerable:!0}),Object.defineProperty(gS.prototype,"type",{enumerable:!0});class mS extends gS{constructor(e,t={}){super(e),this[aS]=void 0===t.code?0:t.code,this[dS]=void 0===t.reason?"":t.reason,this[pS]=void 0!==t.wasClean&&t.wasClean}get code(){return this[aS]}get reason(){return this[dS]}get wasClean(){return this[pS]}}Object.defineProperty(mS.prototype,"code",{enumerable:!0}),Object.defineProperty(mS.prototype,"reason",{enumerable:!0}),Object.defineProperty(mS.prototype,"wasClean",{enumerable:!0});class yS extends gS{constructor(e,t={}){super(e),this[lS]=void 0===t.error?null:t.error,this[uS]=void 0===t.message?"":t.message}get error(){return this[lS]}get message(){return this[uS]}}Object.defineProperty(yS.prototype,"error",{enumerable:!0}),Object.defineProperty(yS.prototype,"message",{enumerable:!0});class vS extends gS{constructor(e,t={}){super(e),this[cS]=void 0===t.data?null:t.data}get data(){return this[cS]}}Object.defineProperty(vS.prototype,"data",{enumerable:!0});const bS={addEventListener(e,t,n={}){for(const r of this.listeners(e))if(!n[oS]&&r[sS]===t&&!r[oS])return;let r;if("message"===e)r=function(e,n){const r=new vS("message",{data:n?e:e.toString()});r[hS]=this,SS(t,this,r)};else if("close"===e)r=function(e,n){const r=new mS("close",{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[hS]=this,SS(t,this,r)};else if("error"===e)r=function(e){const n=new yS("error",{error:e,message:e.message});n[hS]=this,SS(t,this,n)};else{if("open"!==e)return;r=function(){const e=new gS("open");e[hS]=this,SS(t,this,e)}}r[oS]=!!n[oS],r[sS]=t,n.once?this.once(e,r):this.on(e,r)},removeEventListener(e,t){for(const n of this.listeners(e))if(n[sS]===t&&!n[oS]){this.removeListener(e,n);break}}};var wS={CloseEvent:mS,ErrorEvent:yS,Event:gS,EventTarget:bS,MessageEvent:vS};function SS(e,t,n){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}const{tokenChars:_S}=Ow;function IS(e,t,n){void 0===e[t]?e[t]=[n]:e[t].push(n)}var xS={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),o=!1,s=!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===_S[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?(IS(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===_S[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),IS(i,e.slice(c,u),!0),44===l&&(IS(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(s){if(1!==_S[l])throw new SyntaxError(`Unexpected character at index ${d}`);-1===c?c=d:o||(o=!0),s=!1}else if(a)if(1===_S[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}`);s=!0}else if(34===l&&61===e.charCodeAt(d-1))a=!0;else if(-1===u&&1===_S[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 s=e.slice(c,u);o&&(s=s.replace(/\\/g,""),o=!1),IS(i,r,s),44===l&&(IS(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?IS(t,h,i):(void 0===r?IS(i,h,!0):IS(i,r,o?h.replace(/\\/g,""):h),IS(t,n,i)),t}};const kS=T,ES=D,CS=M,$S=L,NS=F,{randomBytes:OS,createHash:TS}=R,{URL:AS}=B,PS=_w,MS=class extends Tw{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||Pw[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Rw]=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 Ww(t.buffer,t.byteOffset+e,t.length-e),new Ww(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 Ww(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[Aw.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);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")):(this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e))}haveLength(e){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")):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=Mw;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]&&Fw(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[Aw.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?jw(n,t):"arraybuffer"===this._binaryType?Lw(jw(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=jw(n,t);if(!this._skipUTF8Validation&&!Bw(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,Mw),this.end();else{const n=e.readUInt16BE(0);if(!Uw(n)){const e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const r=new Ww(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Bw(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 o=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[Dw]=r,o}},DS=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=zw,this[Yw]=void 0}static frame(e,t){let n,r,i=!1,o=2,s=!1;t.mask&&(n=t.maskBuffer||Qw,t.generateMask?t.generateMask(n):(nS===eS&&(void 0===tS&&(tS=Buffer.alloc(eS)),Gw(tS,0,eS),nS=0),n[0]=tS[nS++],n[1]=tS[nS++],n[2]=tS[nS++],n[3]=tS[nS++]),s=!(n[0]|n[1]|n[2]|n[3]),o=6),"string"==typeof e?r=t.mask&&!s||void 0===t[Xw]?(e=Buffer.from(e)).length:t[Xw]:(r=e.length,i=t.mask&&t.readOnly&&!s);let a=r;r>=65536?(o+=8,a=127):r>125&&(o+=2,a=126);const c=Buffer.allocUnsafe(i?r+o:o);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[o-4]=n[0],c[o-3]=n[1],c[o-2]=n[2],c[o-1]=n[3],s?[c,e]:i?(Jw(e,n,c,o,r),[c]):(Jw(e,n,e,0,r),[c,e])):[c,e]}close(t,n,r,i){let o;if(void 0===t)o=Hw;else{if("number"!=typeof t||!Kw(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");o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),"string"==typeof n?o.write(n,2):o.set(n,2)}else o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0)}const s={[Xw]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,o,!1,s,i]):this.sendFrame(e.frame(o,s),i)}ping(t,n,r){let i,o;if("string"==typeof t?(i=Buffer.byteLength(t),o=!1):qw(t)?(i=t.size,o=!1):(i=(t=Zw(t)).length,o=Zw.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const s={[Xw]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};qw(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,s,r]):this.getBlobData(t,!1,s,r):0!==this._state?this.enqueue([this.dispatch,t,!1,s,r]):this.sendFrame(e.frame(t,s),r)}pong(t,n,r){let i,o;if("string"==typeof t?(i=Buffer.byteLength(t),o=!1):qw(t)?(i=t.size,o=!1):(i=(t=Zw(t)).length,o=Zw.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const s={[Xw]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};qw(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,s,r]):this.getBlobData(t,!1,s,r):0!==this._state?this.enqueue([this.dispatch,t,!1,s,r]):this.sendFrame(e.frame(t,s),r)}send(e,t,n){const r=this._extensions[Vw.extensionName];let i,o,s=t.binary?2:1,a=t.compress;"string"==typeof e?(i=Buffer.byteLength(e),o=!1):qw(e)?(i=e.size,o=!1):(i=(e=Zw(e)).length,o=Zw.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,s=0),t.fin&&(this._firstFragment=!0);const c={[Xw]:i,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:o,rsv1:a};qw(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[Xw],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(rS,this,e,i)}this._bufferedBytes-=r[Xw];const o=Zw(t);n?this.dispatch(o,n,r,i):(this._state=0,this.sendFrame(e.frame(o,r),i),this.dequeue())})).catch((e=>{process.nextTick(iS,this,e,i)}))}dispatch(t,n,r,i){if(!n)return void this.sendFrame(e.frame(t,r),i);const o=this._extensions[Vw.extensionName];this._bufferedBytes+=r[Xw],this._state=1,o.compress(t,r.fin,((t,n)=>{this._socket.destroyed?rS(this,new Error("The socket was closed while data was being compressed"),i):(this._bufferedBytes-=r[Xw],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][Xw],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Xw],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)}},{isBlob:RS}=Ow,{BINARY_TYPES:jS,EMPTY_BUFFER:LS,GUID:FS,kForOnEventAttribute:US,kListener:BS,kStatusCode:WS,kWebSocket:GS,NOOP:VS}=nw,{EventTarget:{addEventListener:HS,removeEventListener:YS}}=wS,{format:zS,parse:qS}=xS,{toBuffer:KS}=aw,JS=3e4,ZS=Symbol("kAborted"),XS=[8,13],QS=["CONNECTING","OPEN","CLOSING","CLOSED"],e_=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;let t_=class e extends kS{constructor(t,n,r){super(),this._binaryType=jS[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=LS,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]),r_(this,t,n,r)):(this._autoPong=r.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){jS.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 MS({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),o=new DS(t,this._extensions,r.generateMask);this._receiver=i,this._sender=o,this._socket=t,i[GS]=this,o[GS]=this,t[GS]=this,i.on("conclude",l_),i.on("drain",u_),i.on("error",d_),i.on("message",f_),i.on("ping",p_),i.on("pong",g_),o.onerror=y_,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on("close",b_),t.on("data",w_),t.on("end",S_),t.on("error",__),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[PS.extensionName]&&this._extensions[PS.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())})),v_(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";a_(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||LS,n,r)):c_(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||LS,n,r)):c_(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 c_(this,t,r);const i={binary:"string"!=typeof t,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[PS.extensionName]||(i.compress=!1),this._sender.send(t||LS,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";a_(this,this._req,e)}}};Object.defineProperty(t_,"CONNECTING",{enumerable:!0,value:QS.indexOf("CONNECTING")}),Object.defineProperty(t_.prototype,"CONNECTING",{enumerable:!0,value:QS.indexOf("CONNECTING")}),Object.defineProperty(t_,"OPEN",{enumerable:!0,value:QS.indexOf("OPEN")}),Object.defineProperty(t_.prototype,"OPEN",{enumerable:!0,value:QS.indexOf("OPEN")}),Object.defineProperty(t_,"CLOSING",{enumerable:!0,value:QS.indexOf("CLOSING")}),Object.defineProperty(t_.prototype,"CLOSING",{enumerable:!0,value:QS.indexOf("CLOSING")}),Object.defineProperty(t_,"CLOSED",{enumerable:!0,value:QS.indexOf("CLOSED")}),Object.defineProperty(t_.prototype,"CLOSED",{enumerable:!0,value:QS.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(t_.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(t_.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[US])return t[BS];return null},set(t){for(const t of this.listeners(e))if(t[US]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[US]:!0})}})})),t_.prototype.addEventListener=HS,t_.prototype.removeEventListener=YS;var n_=t_;function r_(e,t,n,r){const i={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:XS[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,!XS.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${XS.join(", ")})`);let o;if(t instanceof AS)o=t;else try{o=new AS(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}"http:"===o.protocol?o.protocol="ws:":"https:"===o.protocol&&(o.protocol="wss:"),e._url=o.href;const s="wss:"===o.protocol,a="ws+unix:"===o.protocol;let c;if("ws:"===o.protocol||s||a?a&&!o.pathname?c="The URL's pathname is empty":o.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 i_(e,t)}const l=s?443:80,u=OS(16).toString("base64"),d=s?ES.request:CS.request,h=new Set;let f,p;if(i.createConnection=i.createConnection||(s?s_:o_),i.defaultPort=i.defaultPort||l,i.port=o.port||l,i.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},i.path=o.pathname+o.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(f=new PS(!0!==i.perMessageDeflate?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=zS({[PS.extensionName]:f.offer()})),n.length){for(const e of n){if("string"!=typeof e||!e_.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),(o.username||o.password)&&(i.auth=`${o.username}:${o.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=s,e._originalHostOrSocketPath=a?i.socketPath:o.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&&o.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!s)&&(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",(()=>{a_(e,p,"Opening handshake has timed out")})),p.on("error",(t=>{null===p||p[ZS]||(p=e._req=null,i_(e,t))})),p.on("response",(o=>{const s=o.headers.location,a=o.statusCode;if(s&&i.followRedirects&&a>=300&&a<400){if(++e._redirects>i.maxRedirects)return void a_(e,p,"Maximum redirects exceeded");let o;p.abort();try{o=new AS(s,t)}catch(t){const n=new SyntaxError(`Invalid URL: ${s}`);return void i_(e,n)}r_(e,o,n,r)}else e.emit("unexpected-response",p,o)||a_(e,p,`Unexpected server response: ${o.statusCode}`)})),p.on("upgrade",((t,n,r)=>{if(e.emit("upgrade",t),e.readyState!==t_.CONNECTING)return;p=e._req=null;const o=t.headers.upgrade;if(void 0===o||"websocket"!==o.toLowerCase())return void a_(e,n,"Invalid Upgrade header");const s=TS("sha1").update(u+FS).digest("base64");if(t.headers["sec-websocket-accept"]!==s)return void a_(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 a_(e,n,c);a&&(e._protocol=a);const l=t.headers["sec-websocket-extensions"];if(void 0!==l){if(!f)return void a_(e,n,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");let r;try{r=qS(l)}catch(t){return void a_(e,n,"Invalid Sec-WebSocket-Extensions header")}const i=Object.keys(r);if(1!==i.length||i[0]!==PS.extensionName)return void a_(e,n,"Server indicated an extension that was not requested");try{f.accept(r[PS.extensionName])}catch(t){return void a_(e,n,"Invalid Sec-WebSocket-Extensions header")}e._extensions[PS.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 i_(e,t){e._readyState=t_.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function o_(e){return e.path=e.socketPath,$S.connect(e)}function s_(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=$S.isIP(e.host)?"":e.host),NS.connect(e)}function a_(e,t,n){e._readyState=t_.CLOSING;const r=new Error(n);Error.captureStackTrace(r,a_),t.setHeader?(t[ZS]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(i_,e,r)):(t.destroy(r),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function c_(e,t,n){if(t){const n=RS(t)?t.size:KS(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${QS[e.readyState]})`);process.nextTick(n,t)}}function l_(e,t){const n=this[GS];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,void 0!==n._socket[GS]&&(n._socket.removeListener("data",w_),process.nextTick(m_,n._socket),1005===e?n.close():n.close(e,t))}function u_(){const e=this[GS];e.isPaused||e._socket.resume()}function d_(e){const t=this[GS];void 0!==t._socket[GS]&&(t._socket.removeListener("data",w_),process.nextTick(m_,t._socket),t.close(e[WS])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function h_(){this[GS].emitClose()}function f_(e,t){this[GS].emit("message",e,t)}function p_(e){const t=this[GS];t._autoPong&&t.pong(e,!this._isServer,VS),t.emit("ping",e)}function g_(e){this[GS].emit("pong",e)}function m_(e){e.resume()}function y_(e){const t=this[GS];t.readyState!==t_.CLOSED&&(t.readyState===t_.OPEN&&(t._readyState=t_.CLOSING,v_(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function v_(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),JS)}function b_(){const e=this[GS];let t;this.removeListener("close",b_),this.removeListener("data",w_),this.removeListener("end",S_),e._readyState=t_.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[GS]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",h_),e._receiver.on("finish",h_))}function w_(e){this[GS]._receiver.write(e)||this.pause()}function S_(){const e=this[GS];e._readyState=t_.CLOSING,e._receiver.end(),this.end()}function __(){const e=this[GS];this.removeListener("error",__),this.on("error",VS),e&&(e._readyState=t_.CLOSING,this.destroy())}const{tokenChars:I_}=Ow;var x_={parse:function(e){const t=new Set;let n=-1,r=-1,i=0;for(;i<e.length;i++){const o=e.charCodeAt(i);if(-1===r&&1===I_[o])-1===n&&(n=i);else if(0===i||32!==o&&9!==o){if(44!==o)throw new SyntaxError(`Unexpected character at index ${i}`);{if(-1===n)throw new SyntaxError(`Unexpected character at index ${i}`);-1===r&&(r=i);const o=e.slice(n,r);if(t.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);t.add(o),n=r=-1}}else-1===r&&-1!==n&&(r=i)}if(-1===n||-1!==r)throw new SyntaxError("Unexpected end of input");const o=e.slice(n,i);if(t.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}};const k_=T,E_=M,{createHash:C_}=R,$_=xS,N_=_w,O_=x_,T_=n_,{GUID:A_,kWebSocket:P_}=nw,M_=/^[+/0-9A-Za-z]{22}==$/;function D_(e){e._state=2,e.emit("close")}function R_(){this.destroy()}function j_(e,t,n,r){n=n||E_.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} ${E_.STATUS_CODES[t]}\r\n`+Object.keys(r).map((e=>`${e}: ${r[e]}`)).join("\r\n")+"\r\n\r\n"+n)}function L_(e,t,n,r,i){if(e.listenerCount("wsClientError")){const r=new Error(i);Error.captureStackTrace(r,L_),e.emit("wsClientError",r,n,t)}else j_(n,r,i)}var F_=bd(class extends k_{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:T_,...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=E_.createServer(((e,t)=>{const n=E_.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(D_,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(D_,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{D_(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",R_);const i=e.headers["sec-websocket-key"],o=e.headers.upgrade,s=+e.headers["sec-websocket-version"];if("GET"!==e.method)return void L_(this,e,t,405,"Invalid HTTP method");if(void 0===o||"websocket"!==o.toLowerCase())return void L_(this,e,t,400,"Invalid Upgrade header");if(void 0===i||!M_.test(i))return void L_(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");if(8!==s&&13!==s)return void L_(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header");if(!this.shouldHandle(e))return void j_(t,400);const a=e.headers["sec-websocket-protocol"];let c=new Set;if(void 0!==a)try{c=O_.parse(a)}catch(n){return void L_(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 r=new N_(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=$_.parse(l);e[N_.extensionName]&&(r.accept(e[N_.extensionName]),u[N_.extensionName]=r)}catch(n){return void L_(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const o={origin:e.headers[8===s?"sec-websocket-origin":"origin"],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(o,((o,s,a,l)=>{if(!o)return j_(t,s||401,a,l);this.completeUpgrade(u,i,c,e,t,n,r)}));if(!this.options.verifyClient(o))return j_(t,401)}this.completeUpgrade(u,i,c,e,t,n,r)}completeUpgrade(e,t,n,r,i,o,s){if(!i.readable||!i.writable)return i.destroy();if(i[P_])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return j_(i,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${C_("sha1").update(t+A_).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[N_.extensionName]){const t=e[N_.extensionName].params,n=$_.format({[N_.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",R_),c.setSocket(i,o,{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(D_,this)}))),s(c,r)}});const U_=Rd("websocketServer"),B_={},W_=Lb();let G_,V_,H_,Y_,z_;const q_=["https://app.kemu.io","https://dev.kemu.io","https://stage.kemu.io","https://local.kemu.io:3003"],K_=e=>{const t=B_[e];t&&t.socket.close()};var J_=e=>{z_=new F_({port:e,maxPayload:1048576e3,verifyClient:(e,t)=>{const n=e.req.headers.origin;n&&q_.includes(n)?t(!0):t(!1,401,"Origin not allowed")}}),z_.on("connection",(e=>{const t=Qy();U_(`New client connected. Registered as "${t}"`),e.id=t,B_[t]={socket:e,activeMessage:null},G_&&G_(t),e.on("message",(t=>{if(t instanceof Buffer){const n=B_[e.id];W_(t,n.activeMessage,(e=>n.activeMessage=e),(t=>{if(!t.complete)return;const r=t=>{e.send(t),U_(`Writing ${t.byteLength} bytes to socket [${n.socket.id}]: ${t.toString()}`)},i=()=>{K_(n.socket.id)};if(t.command)return U_(`Received command from client [${n.socket.id}]: ${t.command}`),void(H_&&H_(n.socket.id,t.command,r,i));t.klMessage&&Y_&&Y_({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",(()=>{U_(`Client disconnected: ${e.id}`),V_&&V_(e.id),delete B_[e.id]})),e.on("error",(()=>{U_(`Error on client connection: ${e.id}`)}))})),console.log(`WebSocket server is running on port ${e}`)},Z_=e=>{G_=e},X_=e=>{V_=e},Q_=e=>{H_=e},eI=(e,t)=>{const n=B_[e];if(!n)return U_(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=mb)return U_("Message is too long to be a command. Use sendMessage instead."),!1;const r=Tb.encodeCommand(t);return n.socket.send(r),!0},tI=e=>Y_=e,nI=K_;const rI=Rd("stopService"),iI=async e=>{const t=e.args[0];if(!t)return e.reply({error:"No service name provided"});const n=Rv.getAllServiceVersions(t);rI(`Stopping ${n.length} services with name: ${t}`);for(const e of n)await Rv.stopService({serviceName:e.info.name,version:e.info.version});const r=n.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[r]})},oI=Rd("removeService"),sI=async e=>{const t=e.args[0],n=e.args[1];if(!t)return e.reply({error:"No service name provided"});let r=Rv.getAllServiceVersions(t);n&&(r=r.filter((e=>e.info.version===n))),oI(`Removing ${r.length} service(s) with name: ${t}`);for(const e of r)await Rv.uninstallService(e.info.name,e.info.version);const i=r.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[i]})},aI=Rd("launchService"),cI=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=hv();aI(`Loading service ${t}@${n} from ${i}`);const{errorMsg:o,service:s,errorCode:a}=await Rv.loadAndLaunch(i,r,!1);if(o||"started"!==s?.status)return e.reply({error:`Failed to launch service ${t}@${n}: ${o||"error-not-provided"}`,errCode:a});const c=Date.now(),l=3e4,u=async()=>{const r=s.status;return"running"===r?(aI(`Service ${t}@${n} loaded and started`),e.reply({success:[]})):(aI(`Service ${t}@${n} not yet started, status: ${r}`),"stopped"===r||"error"===r?e.reply({error:`Error launching service: "${s.errorMsg||"failed to initiate"}"`}):Date.now()-c>l?e.reply({error:"Timeout waiting for service to start"}):(aI("Retrying in 1 second..."),void setTimeout(u,1e3)))};u()}catch(r){return aI(`Error loading service ${t}@${n}: ${r?.message||r}`),e.reply({error:r?.message||"There was an error loading the service"})}},lI=Rd("getMatchingServices"),uI=async e=>{const t=e.args[0],n=[],r=[];lI(`Checking for matching services: ${t.map((e=>e.name)).join(", ")}`);for(const{name:e,version:i}of t){const t=Rv.getMatchingService(e,i);t?n.push({name:e,version:i,installationPath:Rv.getServiceRootDirectory(t)}):r.push({name:e,version:i})}lI(`Found ${n.length} available services and ${r.length} missing services.`),e.reply({success:[{available:n,missing:r}]})},dI=Rd("getSecretsValues");let hI;var fI=async e=>{const t=e.args[0].services;if(!hI)throw new Error("getSecretValuesFn is not set. Please call setGetSecretValuesFunction before using this function.");dI(`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 hI({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})},pI=e=>{hI=e};const gI=Rd("getMappedSecrets");let mI;var yI=async e=>{const t=e.args[0].services;gI(`Getting mapped secrets for services: ${t.map((e=>`${e.name}@${e.version}`)).join(", ")}`);const n=await mI(t),r=[{services:t.map((e=>({name:e.name,version:e.version,secrets:n[e.name]||[]})))}];e.reply({success:r})};const vI=Rd("getServiceContents"),bI=({reply:e,args:t})=>{const[n]=t;vI(`Received GetServiceContents request for service ${n.serviceName} v${n.version}`);const r=Rv.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}]});vI(`Service ${n.serviceName} v${n.version} not found`),e({error:`Service ${n.serviceName} v${n.version} not found`})};let wI={globalApiKey:void 0,environment:"production"};const SI=()=>({...wI}),_I=Rd("apis"),II=()=>{const e=SI();if(!e.serviceUrl)throw new Error("Unknown server URL. Please call `edgeConfig.setEdgeConfig` before using the APIs.");return e.serviceUrl},xI=async(e,t,n={})=>{try{const r=await fetch(e,{method:"POST",body:JSON.stringify(t),headers:{...n}});return r.ok?{data:await r.json(),statusCode:r.status,success:!0}:{statusCode:r.status,error:await r.text(),success:!1}}catch(e){return{statusCode:500,error:e instanceof Error?e.message:"Internal server error",success:!1}}},kI=async e=>{const{data:t,error:n}=await xI(`${II()}/v1/organization/validate/apiKey`,{apiKey:e},{"Content-Type":"application/json"});return n?(_I(`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"}},EI={},CI={},$I=e=>{const t=EI[e],n=Date.now()-(t?.lastCheckedAt.getTime()??0);return t&&n<3e5?t.features:null};function NI(e){return"number"==typeof e||!!/^0x[0-9a-f]+$/i.test(e)||/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(e)}function OI(e,t){return"constructor"===t&&"function"==typeof e[t]||"__proto__"===t}var TI=bd((function(e,t){t||(t={});var n={bools:{},strings:{},unknownFn:null};"function"==typeof t.unknown&&(n.unknownFn=t.unknown),"boolean"==typeof t.boolean&&t.boolean?n.allBools=!0:[].concat(t.boolean).filter(Boolean).forEach((function(e){n.bools[e]=!0}));var r={};function i(e){return r[e].some((function(e){return n.bools[e]}))}Object.keys(t.alias||{}).forEach((function(e){r[e]=[].concat(t.alias[e]),r[e].forEach((function(t){r[t]=[e].concat(r[e].filter((function(e){return t!==e})))}))})),[].concat(t.string).filter(Boolean).forEach((function(e){n.strings[e]=!0,r[e]&&[].concat(r[e]).forEach((function(e){n.strings[e]=!0}))}));var o=t.default||{},s={_:[]};function a(e,t,r){for(var i=e,o=0;o<t.length-1;o++){var s=t[o];if(OI(i,s))return;void 0===i[s]&&(i[s]={}),i[s]!==Object.prototype&&i[s]!==Number.prototype&&i[s]!==String.prototype||(i[s]={}),i[s]===Array.prototype&&(i[s]=[]),i=i[s]}var a=t[t.length-1];OI(i,a)||(i!==Object.prototype&&i!==Number.prototype&&i!==String.prototype||(i={}),i===Array.prototype&&(i=[]),void 0===i[a]||n.bools[a]||"boolean"==typeof i[a]?i[a]=r:Array.isArray(i[a])?i[a].push(r):i[a]=[i[a],r])}function c(e,t,i){if(!i||!n.unknownFn||function(e,t){return n.allBools&&/^--[^=]+$/.test(t)||n.strings[e]||n.bools[e]||r[e]}(e,i)||!1!==n.unknownFn(i)){var o=!n.strings[e]&&NI(t)?Number(t):t;a(s,e.split("."),o),(r[e]||[]).forEach((function(e){a(s,e.split("."),o)}))}}Object.keys(n.bools).forEach((function(e){c(e,void 0!==o[e]&&o[e])}));var l=[];-1!==e.indexOf("--")&&(l=e.slice(e.indexOf("--")+1),e=e.slice(0,e.indexOf("--")));for(var u=0;u<e.length;u++){var d,h,f=e[u];if(/^--.+=/.test(f)){var p=f.match(/^--([^=]+)=([\s\S]*)$/);d=p[1];var g=p[2];n.bools[d]&&(g="false"!==g),c(d,g,f)}else if(/^--no-.+/.test(f))c(d=f.match(/^--no-(.+)/)[1],!1,f);else if(/^--.+/.test(f))d=f.match(/^--(.+)/)[1],void 0===(h=e[u+1])||/^(-|--)[^-]/.test(h)||n.bools[d]||n.allBools||r[d]&&i(d)?/^(true|false)$/.test(h)?(c(d,"true"===h,f),u+=1):c(d,!n.strings[d]||"",f):(c(d,h,f),u+=1);else if(/^-[^-]+/.test(f)){for(var m=f.slice(1,-1).split(""),y=!1,v=0;v<m.length;v++)if("-"!==(h=f.slice(v+2))){if(/[A-Za-z]/.test(m[v])&&"="===h[0]){c(m[v],h.slice(1),f),y=!0;break}if(/[A-Za-z]/.test(m[v])&&/-?\d+(\.\d*)?(e-?\d+)?$/.test(h)){c(m[v],h,f),y=!0;break}if(m[v+1]&&m[v+1].match(/\W/)){c(m[v],f.slice(v+2),f),y=!0;break}c(m[v],!n.strings[m[v]]||"",f)}else c(m[v],h,f);d=f.slice(-1)[0],y||"-"===d||(!e[u+1]||/^(-|--)[^-]/.test(e[u+1])||n.bools[d]||r[d]&&i(d)?e[u+1]&&/^(true|false)$/.test(e[u+1])?(c(d,"true"===e[u+1],f),u+=1):c(d,!n.strings[d]||"",f):(c(d,e[u+1],f),u+=1))}else if(n.unknownFn&&!1===n.unknownFn(f)||s._.push(n.strings._||!NI(f)?f:Number(f)),t.stopEarly){s._.push.apply(s._,e.slice(u+1));break}}return Object.keys(o).forEach((function(e){var t,n,i;t=s,n=e.split("."),i=t,n.slice(0,-1).forEach((function(e){i=i[e]||{}})),n[n.length-1]in i||(a(s,e.split("."),o[e]),(r[e]||[]).forEach((function(t){a(s,t.split("."),o[e])})))})),t["--"]?s["--"]=l.slice():l.forEach((function(e){s._.push(e)})),s}));Cb("ipcClient"),Cb("kemuWidgetService"),TI(process.argv.slice(2));const AI=Rd("activeClients");let PI,MI={},DI={};const RI=(e,t)=>`${e}_${t}`,jI=e=>MI[e]||null,LI=(e,t)=>{const n=RI(e,t);return DI[n]||[]},FI=()=>{for(const e in MI){const t=MI[e];if(t?.transport===ed.WS){const e=Tb.encodeCommand(Zu.ServicesListChanged);t.send(e)}}},UI=async e=>{const t=[],{serviceSessionId:n,transport:r,send:i,terminateFn:o,extraInfo:s,isDevClient:a}=e;if(r===ed.WS&&!s.recipe?.poolId)return c=`Bad request. Recipe pool id is required. SessionId: ${n}`,console.warn(c),void(o&&o());var c;MI[n]={serviceSessionId:n,transport:r,isDevClient:!!a,broadcastSubscriptions:t,send:i,extraInfo:s,terminate:()=>{o&&o()},addSubscription:e=>{if(!t.some((t=>t.targetService.serviceName===e.serviceName&&t.targetService.version===e.version))){t.push({targetService:e});const r=RI(e.serviceName,e.version);return DI[r]=DI[r]||[],DI[r].some((e=>e.serviceId===n))||DI[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=RI(e.serviceName,e.version),o=DI[i]?.findIndex((e=>e.serviceId===n));if(-1!==o&&(DI[i]?.splice(o,1),!DI[i]?.length)){const t=Rv.getMatchingService(e.serviceName,e.version);if(t?.info.eventEmitter&&"running"===t.status){const e=jI(t.info.sessionId);e?.extraInfo.ipcSocketId&&zb(e?.extraInfo.ipcSocketId,Zu.BroadcastEnd)}}}},removeAllSubscriptions:()=>{for(const e of t){const t=RI(e.targetService.serviceName,e.targetService.version),r=DI[t]?.findIndex((e=>e.serviceId===n));-1!==r&&DI[t]?.splice(r,1)}t.length=0}},r===ed.IPC&&(FI(),BI(n))},BI=e=>{const t=Rv.getServiceBySessionId(e);if(t?.info.eventEmitter&&LI(t.info.name,t.info.version).length){const t=jI(e);t?.extraInfo.ipcSocketId&&zb(t?.extraInfo.ipcSocketId,Zu.BroadcastStart)}},WI=e=>{const t=MI[e];var n;t?.transport===ed.IPC?FI():(t?.removeAllSubscriptions(),(()=>{const e=Object.values(MI);for(const t of e)if(t.transport===ed.IPC){const e=t.extraInfo.ipcSocketId,n=Rv.getServiceBySessionId(t.serviceSessionId);n?.info.eventEmitter&&(LI(n.info.name,n.info.version).length||e&&zb(e,Zu.BroadcastEnd))}})(),t?.extraInfo.recipe?.poolId&&(n=t.extraInfo.recipe.poolId,delete EI[n],delete CI[n]),(e=>{const t=MI[e];if(t?.transport===ed.WS&&t.extraInfo.recipe){const n=[{recipe:t.extraInfo.recipe}];AI(`Notifying IPC clients that a Kemu Compose client [${t.extraInfo.recipe.name} (${t.extraInfo.recipe.poolId})] has disconnected. ServiceSessionId: ${e}`);for(const e in MI){const t=MI[e];t?.transport===ed.IPC&&PI.execute(Xu.KemuComposerDisconnected,n,t.send,0,t.serviceSessionId,{async:!0}).catch((t=>{AI(`Error notifying IPC client [${e}] that a Kemu Compose client has disconnected: ${t?.message||t}`)}))}}})(e)),delete MI[e]},GI=Rd("ipc:handleIpcClientCommand"),VI=(e,t,n)=>{const r=((e,t)=>{if(e.startsWith(Zu.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 GI(`Ignoring ACK response from IPC service ${e} with no service id`);GI(`Received ACK from IPC service ${e}. Marking as running.`);let r=e;t&&e&&e!==t&&(qb(e,t),r=t);let i=!1;t&&(i=Rv.setServiceStatus(t,"running")),i?UI({serviceSessionId:t||e,transport:ed.IPC,send:n,extraInfo:{ipcSocketId:t}}):zb(r,Zu.SendManifest)}));!r&&GI(`Received unknown command [${t}] from service ${e}`)};let HI={};G.platform();const YI=async e=>{const t=e.args[0];if(HI.chooseDirectory)try{const n=await HI.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"})},zI=async e=>{const t=e.args[0];if(HI.chooseFile)try{const n=await HI.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"})};var qI={},KI={},JI={};function ZI(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function XI(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function QI(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function ex(e,...t){if(!QI(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 tx(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");ZI(e.outputLen),ZI(e.blockLen)}function nx(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 rx(e,t){ex(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}Object.defineProperty(JI,"__esModule",{value:!0}),JI.output=JI.exists=JI.hash=JI.bytes=JI.bool=JI.number=JI.isBytes=void 0,JI.number=ZI,JI.bool=XI,JI.isBytes=QI,JI.bytes=ex,JI.hash=tx,JI.exists=nx,JI.output=rx;const ix={number:ZI,bool:XI,bytes:ex,hash:tx,exists:nx,output:rx};JI.default=ix;var ox={};Object.defineProperty(ox,"__esModule",{value:!0}),ox.add5L=ox.add5H=ox.add4H=ox.add4L=ox.add3H=ox.add3L=ox.add=ox.rotlBL=ox.rotlBH=ox.rotlSL=ox.rotlSH=ox.rotr32L=ox.rotr32H=ox.rotrBL=ox.rotrBH=ox.rotrSL=ox.rotrSH=ox.shrSL=ox.shrSH=ox.toBig=ox.split=ox.fromBig=void 0;const sx=BigInt(2**32-1),ax=BigInt(32);function cx(e,t=!1){return t?{h:Number(e&sx),l:Number(e>>ax&sx)}:{h:0|Number(e>>ax&sx),l:0|Number(e&sx)}}function lx(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let i=0;i<e.length;i++){const{h:o,l:s}=cx(e[i],t);[n[i],r[i]]=[o,s]}return[n,r]}ox.fromBig=cx,ox.split=lx;const ux=(e,t)=>BigInt(e>>>0)<<ax|BigInt(t>>>0);ox.toBig=ux;const dx=(e,t,n)=>e>>>n;ox.shrSH=dx;const hx=(e,t,n)=>e<<32-n|t>>>n;ox.shrSL=hx;const fx=(e,t,n)=>e>>>n|t<<32-n;ox.rotrSH=fx;const px=(e,t,n)=>e<<32-n|t>>>n;ox.rotrSL=px;const gx=(e,t,n)=>e<<64-n|t>>>n-32;ox.rotrBH=gx;const mx=(e,t,n)=>e>>>n-32|t<<64-n;ox.rotrBL=mx;const yx=(e,t)=>t;ox.rotr32H=yx;const vx=e=>e;ox.rotr32L=vx;const bx=(e,t,n)=>e<<n|t>>>32-n;ox.rotlSH=bx;const wx=(e,t,n)=>t<<n|e>>>32-n;ox.rotlSL=wx;const Sx=(e,t,n)=>t<<n-32|e>>>64-n;ox.rotlBH=Sx;const _x=(e,t,n)=>e<<n-32|t>>>64-n;function Ix(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:0|i}}ox.rotlBL=_x,ox.add=Ix;const xx=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0);ox.add3L=xx;const kx=(e,t,n,r)=>t+n+r+(e/2**32|0)|0;ox.add3H=kx;const Ex=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0);ox.add4L=Ex;const Cx=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0;ox.add4H=Cx;const $x=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0);ox.add5L=$x;const Nx=(e,t,n,r,i,o)=>t+n+r+i+o+(e/2**32|0)|0;ox.add5H=Nx;const Ox={fromBig:cx,split:lx,toBig:ux,shrSH:dx,shrSL:hx,rotrSH:fx,rotrSL:px,rotrBH:gx,rotrBL:mx,rotr32H:yx,rotr32L:vx,rotlSH:bx,rotlSL:wx,rotlBH:Sx,rotlBL:_x,add:Ix,add3L:xx,add3H:kx,add4L:Ex,add4H:Cx,add5H:Nx,add5L:$x};ox.default=Ox;var Tx={},Ax={};Object.defineProperty(Ax,"__esModule",{value:!0}),Ax.crypto=void 0,Ax.crypto="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,function(e){
|
|
10
|
+
var e=x,t=b,n=My(),r=R,o=T,s={};Ty=s;var a=["daily","test","m","h","custom"],c="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||c;let i=r?n.utc():n().local();if(e&&-1!==a.indexOf(e.type))switch(e.type){case"m":var o=Math.floor(i.minutes()/e.digit)*e.digit;return i.minutes(o).format(t);case"h":var s=Math.floor(i.hour()/e.digit)*e.digit;return i.hour(s).format(t);case"daily":case"custom":case"test":return i.format(t)}return i.format(t)},s.setAuditLog=function(n,r,i){var o=null;if(n){var s=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);o=JSON.parse(e.readFileSync(l,{encoding:"utf-8"}))}else l=t.resolve(c+"/.audit.json"),o=JSON.parse(e.readFileSync(l,{encoding:"utf-8"}))}catch(n){if("ENOENT"!==n.code)return null;o={keep:{days:!1,amount:Number(a[1])},auditLog:r||c+"/.audit.json",files:[]}}o.keep={days:"d"===s,amount:Number(a[1])}}}return o},s.writeAuditLog=function(t,n){try{u(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){if(-1!==t.files.findIndex((function(t){return t.name===e})))return t;var a=Date.now();if(t.files.push({date:a,name:e,hash:r.createHash(t.hashType).update(e+"LOG_FILE"+a).digest("hex")}),t.keep.days){var c=n().subtract(t.keep.amount,"days").valueOf(),u=t.files.filter((function(e){return e.date>c||(e.hashType=t.hashType,l(e,o),i.emit("logRemoved",e),!1)}));t.files=u}else{var d=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=d}s.writeAuditLog(t,o)}return t},s.getStream=function(r){var l=null,h=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||c;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&&(h=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+(h?"."+h:"");if(b.match(/%DATE%/)&&(S=b.replace(/%DATE%/g,h||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),u(S);var C=r.file_options||{flags:"a"},$=e.createWriteStream(S,C);if(h&&l&&a.indexOf(l.type)>-1||g>0){f.verbose&&console.log(new Date,"[FileStreamRotator] Rotating file: ",l?l.type:"",g?"size: "+g:"");var N,O=new o;return O.auditLog=p,O.end=function(){$.end.apply($,arguments)},d($,O),O.on("close",(function(){N&&N.close()})),O.on("new",(function(n){O.auditLog=f.addLogToAudit(n,O.auditLog,O,f.verbose),r.create_symlink&&function(n,r,i){let o=r||"current.log",s=t.dirname(n),a=t.basename(n),c=s+"/"+o;try{e.lstatSync(c).isSymbolicLink()&&(e.unlinkSync(c),e.symlinkSync(a,c))}catch(n){if(n&&"ENOENT"==n.code)try{e.symlinkSync(a,c)}catch(n){i&&console.error(new Date,"[FileStreamRotator] Could not create symlink file: ",c," -> ",a)}}}(n,r.symlink_name,f.verbose),r.watch_log&&O.emit("addWatcher",n)})),O.on("addWatcher",(function(t){N&&N.close(),r.watch_log&&(N=function(t,n){if(!t)return null;try{return e.lstatSync(t),e.watch(t,(function(n){if("rename"==n)try{e.lstatSync(t)}catch(e){!function(e,t){O.emit("createLog",t)}(0,t)}}))}catch(e){n&&console.log(new Date,"[FileStreamRotator] Could not add watcher for "+t)}}(t,f.verbose))})),O.on("createLog",(function(t){try{e.lstatSync(t)}catch(n){$&&"function"==$.end&&$.end(),$=e.createWriteStream(t,C),O.emit("new",t),d($,O)}})),O.write=function(t,n){var o=l?this.getDate(l,v,r.utc):h;if(o!=h||g&&y>g){var s=b+(h&&l?"."+o:"");b.match(/%DATE%/)&&h&&(s=b.replace(/%DATE%/g,o)),g&&y>g?s+="."+ ++m+r.extension:(m=0,s+=r.extension),y=0,f.verbose&&console.log(new Date,i.format("[FileStreamRotator] Changing logs from %s to %s",S,s)),h=o,w=S,S=s,!0===r.end_stream?$.end():$.destroy(),u(S),$=e.createWriteStream(s,C),O.emit("new",s),O.emit("rotate",w,s),d($,O)}$.write(t,n),y+=Buffer.byteLength(t,n)}.bind(this),process.nextTick((function(){O.emit("new",S)})),O.emit("new",S),O}return f.verbose&&console.log(new Date,"[FileStreamRotator] File won't be rotated: ",r.frequency,r.size),process.nextTick((function(){$.emit("new",S)})),$};var u=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(n){if("EEXIST"!==n.code)throw n}return n}),"")},d=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 Ty}const Ry=x,jy=E,Ly=b,Fy=i,Uy=A,By=Ny.exports,Wy=gh.MESSAGE,Gy=N.PassThrough,Vy=Bp,Hy={json:!1,colorize:!1,eol:jy.EOL,logstash:null,prettyPrint:!1,label:null,stringify:!1,depth:null,showLevel:!0,timestamp:()=>(new Date).toISOString()},Yy=function(e){if(e=e||{},Vy.call(this,e),this.options=Object.assign({},Hy,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 Gy,this.logStream.pipe(e.stream);else{if(this.filename=e.filename?Ly.basename(e.filename):"winston.log",this.dirname=e.dirname||Ly.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=Dy().getStream({filename:Ly.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:Ly.join(this.dirname,"."+By(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{Ry.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(!Ry.existsSync(e))return}catch(t){return t.message=`Error occurred while checking existence of ${e}: ${t.message}`,void this.emit("error",t)}try{if(Ry.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=Uy.createGzip(),n=Ry.createReadStream(e);n.on("error",(t=>{t.message=`Error occurred while reading ${e}: ${t.message}`,this.emit("error",t)}));const r=Ry.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{Ry.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 zy=Yy;Fy.inherits(Yy,Vy),Yy.prototype.name="dailyRotateFile";const qy=function(){};Yy.prototype.log=function(e,t){t=t||qy,this.logStream.write(e[Wy]+this.options.eol),this.emit("logged",e),t(null,!0)},Yy.prototype.close=function(){this.logStream&&this.logStream.end((()=>{this.emit("finish")}))},Yy.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 Ry.readdirSync(this.dirname).filter((t=>Ly.basename(t).match(e)))})();0===r.length&&t&&t(null,n);const i=o=>{if(!o)return;const s=Ly.join(this.dirname,o);let a,c="";if(o.endsWith(".gz")){a=new Gy;const e=Ry.createReadStream(s);e.on("error",(e=>{e.message=`Error occurred while reading ${s}: ${e.message}`,a.emit("error",e)})),e.pipe(Uy.createGunzip()).pipe(a)}else a=Ry.createReadStream(s,{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 Ky=zy;jd.transports.DailyRotateFile=Ky;var Jy=bd(Ky);const Zy=Date.now();let Xy=Math.ceil(Zy/1e3);var Qy=()=>Xy+=1;const ev=w(C(),"kemu-user-services"),tv=w(C(),"kemu-test-services"),nv="KMU-CB-v1",rv=process.env.HUB_PKG_VERSION||'"1.13.1"';var iv;!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"}(iv||(iv={}));const ov=e=>({...e,type:Array.isArray(e.type)?e.type.map((e=>qu[e])):qu[e.type]}),sv=async e=>{try{return await y(e,"utf-8")}catch(e){return null}},av=e=>{if(e&&e.startsWith(nv)){const t=e.slice(9),n=decodeURI(t);return sd(n)}return null},cv=async(e,t,n)=>{let r=[];e.variants?.length&&(r=e.variants.map((e=>({...e,...e.inputs?{inputs:e.inputs.map(ov)}:{},...e.outputs?{outputs:e.outputs.map(ov)}:{}}))));const i={...e,path:t,customWidgets:[],...e.inputs?{inputs:e.inputs.map(ov)}:{inputs:[]},...e.outputs?{outputs:e.outputs.map(ov)}:{outputs:[]},variants:r,...e.widgetUI&&n?.widgetUIContents?{widgetUIContents:n.widgetUIContents}:{}},o=await(async(e,t,n=console.log)=>{const r=[];if(t.customWidgets?.length)for(const i of t.customWidgets){const t=await sv(w(e,i));if(!t){n(`Error loading custom widget file ${i}`);continue}const o=t.startsWith(nv)?t:`${nv}${t}`,s=av(o);if(!s){n(`Custom widget file "${i}" is not a valid Kemu Clipboard item`);continue}const a=Object.values(s).filter((e=>e.type===iv.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:o,rootGroupId:c.id,icon:l.icon,protocolVersion:l.protocolVersion||"2"};r.push(u)}return r})(t,e,n?.log);if(o.length?i.customWidgets=o:delete i.customWidgets,i.variants?.length)for(const e of i.variants)if(e.svgIcon)try{const n=await y(w(t,e.svgIcon),"utf-8");e.svgIcon=n}catch(t){n?.log&&n?.log(`Error loading svgIcon for variant ${e.id}: ${t}`)}return i},lv=async e=>{try{return await f(e,p.F_OK),!0}catch{return!1}};let uv=null,dv=null;const hv=()=>uv||ev,fv=()=>dv||tv;let pv=null;const gv={setGlobalUserId:e=>pv?.setGlobalUserId?.(e),captureError:e=>pv?.captureError?.(e),flushMessages:async()=>pv?.flushMessages?.(),isEnabled:()=>!!pv};var mv={...gv,setTracker:e=>{pv=e}};const yv=Rd("servicesManager"),vv={};let bv=null,wv=null,Sv=null,_v=!1;class Iv extends Error{code;originalError;constructor(e,t,n){super(e),this.code=t,this.originalError=n,this.name="ServiceError"}}const xv=async e=>{try{return await f(e),!0}catch{return!1}},kv=async e=>{if(!bv)throw new Error('IPC config not set, call "setHubIpcConfig" first.');let t;if(e.info.internal)if("linux"===$()){const n=process.env.XDG_STATE_HOME||b.join(C(),".local","state");t=b.join(n,"kemu-hub","service-logs",e.info.name);try{await h(t,{recursive:!0})}catch(n){yv(`Failed to create log directory ${t}, falling back to service path`),t=e.info.path}}else t=e.info.path;else t=b.join(e.info.path,"..");const n=e.logsEnabled?((e,t)=>{const n=$y.createLogger({level:"info",format:$y.format.combine($y.format.timestamp(),$y.format.errors({stack:!0}),$y.format.json()),defaultMeta:{service:e},transports:[new Jy({filename:b.join(t,"service-%DATE%.log"),datePattern:"YYYY-MM-DD",maxSize:"5m",maxFiles:"5d",auditFile:b.join(t,".service-log-audit.json")})]});return n.getLastLogs=async(n=100)=>{try{const r=b.join(t,".service-log-audit.json"),i=await d.readFile(r,"utf-8"),o=sd(i);if(!o)return console.warn(`Missing audit file for ${e}, skipping log retrieval.`),[];const s=async e=>(await d.readFile(e,"utf-8")).split("\n").filter((e=>e.trim())),a=[],c=[...o.files].reverse();for(const e of c){const t=await s(e.name);if(a.push(...t),a.length>=n)break}return a}catch(t){return console.warn(`Failed to read service logs for ${e}: `,t),[]}},n})(e.info.name,t):null,r=t=>{if(!e.devMode){const{childProcess:r,...i}=e;mv.isEnabled()&&mv.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===Ju.Javascript){yv(`Spawning service ${e.info.name} with sessionId ${e.info.sessionId}`);const t=b.join(e.info.path,"processor.js"),i=b.join(e.info.path,"processor.mjs"),o=await xv(t)?t:i,s=[`--sessionId=${e.info.sessionId.toString()}`,`--ipcSpace=${bv.appSpace}`,`--ipcId=${bv?.id}`,`--recipePath=${bv.recipePath||""}`];if(e.info.internal&&s.push("--internal=true"),!Sv)throw new Error('Get secrets function not set, call "setGetSecretsFunction" first.');const a=await Sv({name:e.info.name,version:e.info.version,requiredSecrets:e.info.requiredSecrets||{}}),c=Object.entries(e.info.requiredSecrets||{}).filter((([e,t])=>null==a[e]&&!t.optional)).map((([e])=>e));if(c?.length)throw new Iv(`Missing required environment variables: ${c.join(", ")}`,"MISSING_REQUIRED_SECRETS");return new Promise(((t,i)=>{if(!wv)throw new Error('Spawn function not set, call "setSpawnNodeFunction" first.');const c=wv({args:[o,...s],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),yv(`[${e.info.name}] - stdout: ${r}`))})),c.stderr.on("data",(t=>{const i=t.toString().trim();i&&(n?.error(i),r(new Error(i)),yv(`[${e.info.name}] - stderr: ${i}`))})),c.on("exit",(t=>{const r=`exited with code ${t}`;n?.info(r,{code:t}),yv(`[${e.info.name}] ${r}`)})),c.on("spawn",(()=>{const r=`spawned with PID ${c.pid}`;n?.info(r,{pid:c.pid}),yv(`[${e.info.name}] ${r}`),t(c)})),c.on("error",(t=>{n?.error(`[${e.info.name}] error`,t),yv(`[${e.info.name}] error: ${t}`),r(t),i(new Iv(`Error spawning service ${e.info.name}: ${t}`,"SPAWN_ERROR"))}))}))}throw`Unsupported processor type ${e.info.processor}`}catch(t){if(r(t),t instanceof Iv)throw t;throw`Error spawning service ${e.info.name}: ${t}`}},Ev=e=>e?.name?e?.version?e?.description?e?.processor?[Ju.Javascript,Ju.Executable,Ju.Python].includes(e?.processor)?null:"Invalid processor":"Missing processor":"Missing description":"Missing version":"Missing name",Cv=async(e,t)=>{const n=b.join(e,"manifest.json");if(!await xv(n)){const t=`Missing manifest for service ${e}. Aborting.`;return yv(t),{error:t}}const r=await y(n,"utf-8"),i=sd(r),o=Ev(i);if(!i||o){const t=`Invalid service manifest [${e}]: ${o}. Aborting.`;return yv(t),{error:t}}let s;if(delete i.internal,t?.singleServiceName&&i.name!==t.singleServiceName)return{error:`Skipping service ${i.name} as it does not match the singleServiceName option`};if(t?.allowedServiceNames&&!t.allowedServiceNames.includes(i.name))return{error:`[SKIPPED] Skipping service ${i.name} as it is not included in the allowedServiceNames option`};await Promise.all([(async()=>{if(i.widgetUI)try{s=await y(b.join(e,"widgetUI.js"))}catch(e){const t=`Error loading widgetUI file ${i.name}: ${e}`;return yv(t),{error:t}}})(),(async()=>{if(i.svgIcon){const t=await sv(b.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=b.join(e,t),{error:r,service:o}=await Cv(n);r?yv(`Error loading sub-service ${t}: ${r}`):o&&(o.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 y(b.join(e,t.svgIcon),"utf-8");t.svgIcon=n}catch(e){yv(`Error loading svgIcon for variant ${t.id}: ${e}`)}})()]);const a=Qy(),c=t?.fixedSession||a;yv(`Loaded service ${i.name} with sessionId ${c}`);const l=await cv(i,e,{widgetUIContents:s});return $v(l),vv[c]={info:{...l,path:e,sessionId:c},status:"loaded",childProcess:null,logsEnabled:t?.logsEnabled},{service:vv[c]}},$v=e=>{e.widgetUIContents?e.uiContentChecksum=(e=>{const t=j("sha256");return t.update(e),t.digest("hex")})(e.widgetUIContents):e.uiContentChecksum=void 0},Nv=async e=>{try{return e.childProcess=await kv(e),e.status="started",e.errorMsg=void 0,e.errorCode=void 0,!0}catch(t){return yv(`Service [${e.info.name}] error: ${t}`),e.status="error",t instanceof Iv?(e.errorMsg=t.message,e.errorCode=t.code):(e.errorMsg="string"==typeof t?t:JSON.stringify(t),e.errorCode="UNKNOWN_ERROR"),!1}},Ov=e=>{const{path:t,...n}=e.info;return{...n}},Tv=()=>Object.values(vv).filter((e=>"running"===e.status)).map(Ov),Av=e=>{if(!e?.kill)return yv(`Failed to kill service ${e?.pid} because it is not a child process`),!1;let t=e.kill("SIGINT");return t||(yv(`Failed to send SIGINT to service ${e.pid} using SIGINT`),t=e.kill("SIGTERM"),t||(yv(`Failed to send SIGTERM to service ${e.pid} using SIGTERM`),t=e.kill("SIGKILL"),t||yv(`Failed to send SIGKILL to service ${e.pid} using SIGKILL`))),t},Pv=async e=>{const{serviceName:t,version:n,force:r,timeout:i=15e3}=e,o=Object.values(vv).find((t=>t.info.name===e.serviceName&&t.info.version===e.version));if(!o)return null;if(o.info.internal&&!r)throw`Cannot stop internal service ${t}`;if(o.childProcess){yv(`Stopping service "${t} (v${n})"`);const r=new Promise(((e,n)=>{const r=setTimeout((()=>{n(new Error(`Timeout waiting for service ${t} to stop after ${i}ms`))}),i);o.childProcess.once("exit",((n,i)=>{clearTimeout(r),yv(`Service ${t} process exited with code ${n} and signal ${i}`),e()})),o.childProcess.once("error",(n=>{clearTimeout(r),yv(`Service ${t} process error: ${n.message}`),e()}))}));Av(o.childProcess);try{await r,yv(`Service ${t} process successfully terminated`)}catch(e){yv(`Warning: ${e instanceof Error?e.message:"Unknown error"} while waiting for service ${t} to stop`)}}return o.status="stopped",yv(`Service ${t} stopped`),o},Mv=e=>e.info.internal?e.info.path:b.join(e.info.path,".."),Dv=e=>!!e.internal;var Rv={isOfficialKemuService:e=>e.name.startsWith("kemu.io"),loadServices:async(e,t)=>{if(!await lv(e))return void yv(`Failed to load services from "${e}". Directory does not exist.`);const n=(await g(e,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name));yv(`Found ${n.length} services in "${e}"`);for(let r=0;r<n.length;r++){const i=n[r],o=b.join(e,i),{error:s,service:a}=await Cv(`${o}${t?.internalServices?"":"/dist"}`,{...t,logsEnabled:Array.isArray(t?.enableLogs)?t?.enableLogs.includes(i):t?.enableLogs});s&&!s.startsWith("[SKIPPED]")&&yv(`Failed to load service ${o}. Please check logs`),a&&t?.internalServices&&(a.info.internal=!0)}},launchServices:async e=>{if(yv("Initializing services"),!bv)throw new Error('IPC config not set, call "setHubIpcConfig" first.');for(const t in vv){const n=vv[t];e.noSpawningList&&e.noSpawningList.includes(n.info.name)?yv(`Service ${n.info.name} is in the noSpawningList. Skipping.`):Nv(n)}yv("Services initialized")},setServiceStatus:(e,t)=>{const n=vv[e];return n?(n.status=t,!0):(yv(`Service with serviceId ${e} not found`),!1)},getActiveServices:Tv,getMatchingService:(e,t)=>{const n=Object.values(vv).filter((e=>"running"===e.status));for(const r of n)if(r.info.name===e){if(r.info.version===t)return r;if(pd(r.info.version,t,">="))return r}return null},getServiceBySessionId:e=>vv[e]||null,killAllServices:async(e=5e3)=>{const t=[];for(const n in vv){const r=vv[n];if(r.childProcess&&r.childProcess.pid)try{yv(`Killing service ${r.info.name} with PID ${r.childProcess.pid}`);const n=new Promise((t=>{const n=setTimeout((()=>{yv(`Timeout waiting for service ${r.info.name} to exit`),t()}),e);r.childProcess?.once("exit",(()=>{clearTimeout(n),yv(`Service ${r.info.name} exited successfully`),t()}))}));Av(r.childProcess),t.push(n)}catch(e){yv(`Error killing service ${r.info.name}: ${e}`)}}await Promise.allSettled(t),yv("All services killed")},addDevService:async(e,t,n)=>{const r={info:{...await cv(t,t.path),sessionId:e},status:n,startedAt:new Date,devMode:!0,childProcess:null};vv[e]=r,$v(vv[e].info)},setServiceManifest:(e,t,n)=>{const r=vv[e];if(!r)return yv(`Service with sessionId ${e} not found`),!1;const i=Ev(t);if(i)return yv(`Invalid manifest for service ${r.info.name}: ${i}`),!1;$v(t),r.info={...r.info,...t},n&&(r.status=n)},getMatchingDevService:(e,t,n)=>{const r=Object.values(vv).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:()=>Tv().filter((e=>e.internal)),getAllServices:()=>Object.values(vv),stopService:Pv,uninstallService:async(e,t)=>{yv(`Uninstalling service ${e} v${t}`);const n=await Pv({serviceName:e,version:t});if(!n)return!1;yv(`Service ${e} stopped. Removing from disk...`);const r=Mv(n),i=hv();return r.startsWith(i)?(await m(r,{recursive:!0,force:!0,maxRetries:3}),yv(`Service ${e} successfully removed from disk`),(e=>{vv[e],delete vv[e]})(n.info.sessionId),!0):(yv(`Service ${e} is not installed in the user services directory. Aborting.`),!1)},getAllServiceVersions:e=>Object.values(vv).filter((t=>t.info.name===e)),setHubIpcConfig:e=>{bv={...e}},setEnableServiceLogsConfig:e=>{_v=e},loadAndLaunch:async(e,t,n)=>{const r=_(e,t),{error:i,service:o}=await Cv(r,{logsEnabled:_v});if(i||!o)return{errorMsg:i};try{o.info.internal=!!n,o.childProcess=await kv(o),o.status="started"}catch(e){o.status="error",e instanceof Iv?(yv(`Service spawning error: ${e.message} (${e.code})`),o.errorMsg=e.message,o.errorCode=e.code):(yv(`Error launching service ${o.info.name}: ${e}`),o.errorMsg="string"==typeof e?e:JSON.stringify(e))}return{service:o,errorCode:o.errorCode,errorMsg:o.errorMsg}},getServiceRootDirectory:Mv,setSpawnNodeFunction:e=>{wv=e},setGetSecretsFunction:e=>{Sv=e},restartService:async(e,t)=>{yv(`Restarting service ${e} v${t}`);const n=await Pv({serviceName:e,version:t,force:!0});return!!n&&Nv(n)},getFailedServices:()=>Object.values(vv).filter((e=>"error"===e.status)).map((e=>({...Ov(e),errorMsg:e.errorMsg||"",errorCode:e.errorCode,status:e.status}))),isInternalKemuService:Dv,isNotInternalKemuService:e=>!Dv(e),isNotDevService:e=>!e.devMode};class jv{constructor(){}appspace="app.";socketRoot="/tmp/";id=E.hostname();encoding="utf8";rawBuffer=!1;sync=!1;unlink=!0;delimiter="\f";silent=!1;logDepth=5;logInColor=!0;logger=console.log.bind(console);maxConnections=100;retry=500;maxRetries=1/0;stopRetrying=!1;IPType=function(){const e=E.networkInterfaces();let t="";return e&&Array.isArray(e)&&e.length>0&&(t=e[Object.keys(e)[0]][0].family),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 Lv{constructor(e){e||(e=new jv),this.delimiter=e.delimiter}format(e){return e.data||!1===e.data||0===e.data||(e.data={}),e.data._maxListeners&&(e.data={}),e.JSON+this.delimiter}parse(e){let t=e.split(this.delimiter);return t.pop(),t}}var Fv=bd((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={}})),Uv=bd((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(){t=!0,e.length<1||this.stop?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 Bv{}class Wv{}const Gv=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 Bv,t=Wv){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 Bv}}())}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 Vv{constructor(){}on(e,t,n=!1){return Gv.string(e),Gv.function(t),Gv.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(Gv.string(e),e!=this.#e.toString()&&"*"!=e||(e=this.#e),!this.#t[e])return this;if("*"==t)return delete this.#t[e],this;Gv.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){Gv.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)=>{Gv.string(e),Gv.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 Hv=new Lv;class Yv extends Vv{constructor(e,t){super(),this.config=e,this.log=t,this.publish=super.emit,e.maxRetries&&(this.retriesRemaining=e.maxRetries),Hv=new Lv(this.config)}Client=Yv;queue=new Uv;socket=!1;connect=Kv;emit=zv;retriesRemaining=0;explicitlyDisconnected=!1}function zv(e,t){this.log("dispatching event to ",this.id,this.path," : ",e,",",t);let n=new Fv;n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Hv.format(n),this.config.sync?this.queue.add(qv.bind(this,n)):this.socket.write(n)}function qv(e){this.log("dispatching event to ",this.id,this.path," : ",e),this.socket.write(e)}function Kv(){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=x.readFileSync(e.config.tls.private)),e.config.tls.public&&(e.config.tls.cert=x.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(x.readFileSync(e.config.tls.trustedConnections[t]))}Object.assign(e.config.tls,t),e.socket=F.connect(e.config.tls)}else e.log("Connecting client via TCP to",t),e.socket=L.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=L.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)!=Hv.delimiter||-1==t.indexOf(Hv.delimiter))return void e.log("Messages are large, You may want to consider smaller messages.");this.ipcBuffer="";const n=Hv.parse(t),r=n.length;for(let t=0;t<r;t++){let r=new Fv;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 Jv=new Lv;class Zv extends Vv{constructor(e,t,n,r){super(),this.config=t,this.path=e,this.port=r,this.log=n,this.publish=super.emit,Jv=new Lv(this.config),this.on("close",eb.bind(this))}udp4=!1;udp6=!1;server=!1;sockets=[];emit=Xv;broadcast=Qv;onStart(e){this.publish("start",e)}stop(){this.server.close()}start(){this.path?this.config.unlink?x.unlink(this.path,ib.bind(this)):ib.bind(this)():this.log("Socket Server Path not specified, refusing to start")}}function Xv(e,t,n){this.log("dispatching event to socket"," : ",t,n);let r=new Fv;if(r.type=t,r.data=n,this.config.rawBuffer?(this.log(this.config.encoding),r=Buffer.from(t,this.config.encoding)):r=Jv.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 Qv(e,t){this.log("broadcasting event to all known sockets listening to ",this.path," : ",this.port?this.port:"",e,t);let n=new Fv;if(n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Jv.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 eb(){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 tb(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)==Jv.delimiter&&-1!=t.indexOf(Jv.delimiter))for(r.ipcBuffer="",t=Jv.parse(t);t.length>0;){let e=new Fv;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 nb(e){this.publish("close",e)}function rb(e){this.sockets.push(e),e.setEncoding&&e.setEncoding(this.config.encoding),this.log("## socket connection to server detected ##"),e.on("close",nb.bind(this)),e.on("error",function(e){this.log("server socket error",e),this.publish("error",e)}.bind(this)),e.on("data",tb.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 ib(){return this.log("starting server on ",this.path,this.port?`:${this.port}`:""),this.udp4||this.udp6?(this.server=U.createSocket(this.udp4?"udp4":"udp6"),this.server.write=sb.bind(this),this.server.on("listening",function(){rb.bind(this)(this.server)}.bind(this))):(this.log("starting TLS server",this.config.tls),this.config.tls?ob.bind(this)():this.server=L.createServer(rb.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 ob(){if(this.log("starting TLS server",this.config.tls),this.config.tls.private?this.config.tls.key=x.readFileSync(this.config.tls.private):this.config.tls.key=x.readFileSync(`${__dirname}/../local-node-ipc-certs/private/server.key`),this.config.tls.public?this.config.tls.cert=x.readFileSync(this.config.tls.public):this.config.tls.cert=x.readFileSync(`${__dirname}/../local-node-ipc-certs/server.pub`),this.config.tls.dhparam&&(this.config.tls.dhparam=x.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(x.readFileSync(this.config.tls.trustedConnections[e]))}this.server=F.createServer(this.config.tls,rb.bind(this))}function sb(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 ab{constructor(){}config=new jv;of={};server=!1;get connectTo(){return fb}get connectToNet(){return pb}get disconnect(){return lb}get serve(){return ub}get serveNet(){return hb}get log(){return cb}set connectTo(e){return fb}set connectToNet(e){return pb}set disconnect(e){return lb}set serve(e){return ub}set serveNet(e){return hb}set log(e){return cb}}function cb(...e){if(!this.config.silent){for(let t=0,n=e.length;t<n;t++)"object"==typeof e[t]&&(e[t]=i.inspect(e[t],{depth:this.config.logDepth,colors:this.config.logInColor}));this.config.logger(e.join(" "))}}function lb(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 ub(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=db),this.server=new Zv(e,this.config,cb),this.server.on("start",t)}function db(){}function hb(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=db),this.server=new Zv(e,this.config,cb,t),n&&(this.server[n]=!0,"udp4"===n&&"::1"===e&&(this.server.path="127.0.0.1")),this.server.on("start",r)}function fb(e,t,n){if("function"==typeof t&&(n=t,t=!1),n||(n=db),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 Yv(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 pb(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=db),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 Yv(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 gb=new class extends ab{constructor(){super()}IPC=ab};const mb=Object.values({protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8}).reduce(((e,t)=>e+t),0),yb=e=>{try{return JSON.parse(e)}catch(e){return null}},vb="undefined"!=typeof window,bb={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},wb={protocolPrefix:4,txtLength:4},Sb=Object.values(bb).reduce(((e,t)=>e+t),0),_b=Object.values(wb).reduce(((e,t)=>e+t),0),Ib=["width","height","colorSpace"],xb=(e,t)=>{const n={},r=[];let i=0,o=Array.isArray(e)?[]:{};const s=(e,o)=>{const a=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,i=e instanceof Uint8Array,o=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":i?"Uint8Array":o?"Int8Array":null})(e);if(!a){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=s(e[n],`${o}[${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,o=e instanceof Float32Array,s=e instanceof Float64Array,a=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":i?"Uint32Array":o?"Float32Array":s?"Float64Array":a?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${o}"`);for(const n in e)Object.hasOwn(e,n)||Ib.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${o}`),t[n]=s(e[n],`${o.length?`${o}.`:""}${n}`);return t}return e}n[o]={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};o=s(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:o}:null},kb=(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 o=t.startsWith("[")&&t.endsWith("]"),s=e===r.length-1;if(o){t=t.slice(1,-1);const o=parseInt(t,10);if(!Array.isArray(i))throw new Error(`Expected an array at key "${r.slice(0,e).join(".")}" but found an object.`);s?i[o]=n:(i[o]||(i[o]=r[e+1].startsWith("[")?[]:{}),i=i[o])}else s?i[t]=n:(i[t]||(i[t]=r[e+1].startsWith("[")?[]:{}),i=i[t])}return e},Eb=(e,t,n)=>{const r="undefined"!=typeof Buffer,i=t instanceof Uint8Array;for(const o in n)if(Object.hasOwn(n,o)){const{index:s,length:a,binaryType:c}=n[o];let l=null;if(r&&t instanceof Buffer)switch(c){case"Buffer":l=t.subarray(s,s+a);break;case"ArrayBuffer":l=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(s,s+a);break;case"Uint8Array":l=new Uint8Array(t.subarray(s,s+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.subarray(s,s+a));break;case"Int8Array":l=new Int8Array(t.subarray(s,s+a))}else if(t instanceof ArrayBuffer||t instanceof Uint8Array)switch(c){case"Buffer":if(r){l=Buffer.from(t.slice(s,s+a));break}case"ArrayBuffer":l=i?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(s,s+a):t.slice(s,s+a);break;case"Uint8Array":l=i?t.slice(s,s+a):new Uint8Array(t.slice(s,s+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.slice(s,s+a));break;case"Int8Array":l=new Int8Array(t.slice(s,s+a))}l&&kb(e,o,l)}return e},Cb=e=>Dd(e),$b="KMSG",Nb="KCMD",Ob=Cb("klProtocol");var Tb={encode:(e,t,n)=>{const r={json:e.json},i=xb(r.json,"Buffer"),o=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const s=o?o.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),l=c.byteLength,u=bb.protocolPrefix+bb.protocolVersion+bb.jsonLength+bb.binaryLength+bb.fromServiceId+bb.toServiceId+bb.sentAt+l+s,d=Buffer.alloc(u),h=Date.now();let f=0;return d.write($b,f),f+=bb.protocolPrefix,d.writeUInt8(1,f),f+=bb.protocolVersion,d.writeUInt32LE(l,f),f+=bb.jsonLength,d.writeUInt32LE(s,f),f+=bb.binaryLength,d.writeUInt32LE(t,f),f+=bb.fromServiceId,d.writeUInt32LE(n,f),f+=bb.toServiceId,d.writeBigInt64LE(BigInt(h),f),f+=bb.sentAt,c.copy(d,f),f+=l,o&&s&&o.copy(d,f),d},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,bb.protocolPrefix);if(t+=bb.protocolPrefix,n!==$b)return null;if(e.byteLength<Sb)return Ob(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=bb.protocolVersion;const i=e.readUInt32LE(t);t+=bb.jsonLength;const o=e.readUInt32LE(t);t+=bb.binaryLength;const s=e.readUInt32LE(t);t+=bb.fromServiceId;const a=e.readUInt32LE(t);t+=bb.toServiceId;const c=e.readBigInt64LE(t);t+=bb.sentAt;const l=i+o,u=e.subarray(t,t+l),d=e.subarray(0,Sb);let h=null;return e.byteLength-Sb-i-o>0&&(h=e.subarray(Sb+i+o)),{header:{protocolVersion:r,jsonLength:i,binaryLength:o,fromServiceId:s,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=yb(n);if(!i?.json)return Ob("Invalid JSON in KL message"),null;i.jsonBinaryMap&&r.byteLength&&Eb(i.json,r,i.jsonBinaryMap);const o=Buffer.concat([e.headerPackage,t]);let s=o,a=null;const c=Sb+e.jsonLength+e.binaryLength;return o.byteLength>c&&(a=o.subarray(c),s=o.subarray(0,c)),{message:{json:i.json,rawMessage:s},remaining:a}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Sb)return Ob("Invalid Header Size"),e;let n=0;return n+=bb.protocolPrefix,n+=bb.protocolVersion,n+=bb.jsonLength,n+=bb.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=bb.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=_b+r,o=Buffer.alloc(i);return o.write(Nb,t),t+=wb.protocolPrefix,o.writeUint32LE(r,t),t+=wb.txtLength,n.copy(o,t),o},decodeCommand:e=>{let t=0;if(e.byteLength<_b)return{command:null};const n=e.toString("utf-8",t,wb.protocolPrefix);if(t+=wb.protocolPrefix,n!==Nb)return{command:null};const r=e.readUInt32LE(t);t+=wb.txtLength;const i=e.toString("utf-8",t,t+r),o=e.byteLength-_b-r;let s=null;o>0&&(s=e.subarray(_b+r));let a=0;return o<0&&(a=Math.abs(o)),{command:i,remainingData:s,missing:a}}};const Ab="KMSG",Pb="KCMD",Mb=Cb("klProtocol"),Db=new TextEncoder;var Rb={encode:(e,t,n)=>{const r={json:e.json},i=xb(e.json,"ArrayBuffer"),o=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const s=o?o.byteLength:0,a=JSON.stringify(r),c=Db.encode(a),l=c.byteLength,u=new ArrayBuffer(bb.protocolPrefix+bb.protocolVersion+bb.jsonLength+bb.binaryLength+bb.fromServiceId+bb.toServiceId+bb.sentAt+l+s),d=new DataView(u),h=new Uint8Array(u),f=Date.now();let p=0;for(let e=0;e<4;++e)h[p++]=Ab.charCodeAt(e);return d.setUint8(p,1),p+=bb.protocolVersion,d.setUint32(p,l,!0),p+=bb.jsonLength,d.setUint32(p,s,!0),p+=bb.binaryLength,d.setUint32(p,t,!0),p+=bb.fromServiceId,d.setUint32(p,n,!0),p+=bb.toServiceId,d.setBigInt64(p,BigInt(f),!0),p+=bb.sentAt,h.set(c,p),p+=l,o&&s&&h.set(new Uint8Array(o),p),u},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<bb.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Ab)return null;if(e.byteLength<Sb)return Mb.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const i=t.getUint8(n);n+=bb.protocolVersion;const o=t.getUint32(n,!0);n+=bb.jsonLength;const s=t.getUint32(n,!0);n+=bb.binaryLength;const a=t.getUint32(n,!0);n+=bb.fromServiceId;const c=t.getUint32(n,!0);n+=bb.toServiceId;const l=t.getBigInt64(n,!0);n+=bb.sentAt;const u=o+s,d=e.slice(n,n+u),h=new Uint8Array(e,0,Sb);let f=null;return e.byteLength-Sb-o-s>0&&(f=new Uint8Array(e,Sb+o+s).slice().buffer),{header:{protocolVersion:i,jsonLength:o,binaryLength:s,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 o=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),s=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=yb(o);if(!a?.json)return Mb.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&s.byteLength&&Eb(a.json,s,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=Sb+e.jsonLength+e.binaryLength;return c.byteLength>d&&(u=c.subarray(d),l=c.subarray(0,d)),{message:{json:a.json,...s.length?{binaryData:s.buffer}:{},rawMessage:l.buffer},remaining:u?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Sb)return Mb("Invalid Header Size"),e;let n=0;n+=bb.protocolPrefix,n+=bb.protocolVersion,n+=bb.jsonLength,n+=bb.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=bb.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=Db.encode(e),r=n.byteLength,i=new ArrayBuffer(_b+r),o=new DataView(i),s=new Uint8Array(i);for(let e=0;e<4;++e)s[t++]=Pb.charCodeAt(e);return o.setUint32(t,r,!0),t+=wb.txtLength,s.set(n,t),i},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<_b)return{command:null};let r="";for(let e=0;e<wb.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Pb)return{command:null};const i=t.getUint32(n,!0);n+=wb.txtLength;const o=e.byteLength-_b-i,s=new Uint8Array(e,n,Math.min(i,e.byteLength-_b)),a=(new TextDecoder).decode(s);let c=null;o>0&&(c=e.slice(_b+i));let l=0;return o<0&&(l=Math.abs(o)),{command:a,remainingData:c,missing:l}}};const jb=Cb("klTransmissionManager"),Lb=()=>{const e=(t,n,r,i)=>{let o=n,s=null;const a=t instanceof ArrayBuffer;if(jb(`RAW: ${t.toString()}`),!o||o.partialHeaderData){let c;if(a?(c=o?.partialHeaderData?new Uint8Array([...new Uint8Array(o.partialHeaderData),...new Uint8Array(t)]).buffer:t,s=Rb.decodeHeader(c)):(c=o?.partialHeaderData?Buffer.concat([o.partialHeaderData,t]):t,s=Tb.decodeHeader(c)),!s){const{command:t,missing:o,remainingData:s}=a?Rb.decodeCommand(c):Tb.decodeCommand(c);return t?i({command:t,complete:!0,rawMessage:c}):jb(o?`ERROR: Missing ${o} 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`),s?(jb(`${s.byteLength} bytes remain after processing command. Re-analyzing...`),e(s,n,r,i)):void 0}if(s.partialHeader)return o={firstPackageAt:Date.now(),partialHeaderData:c},r(o);if(!s.header)return jb(`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${c.byteLength} bytes`);const l=s.header;o={firstPackageAt:Date.now(),header:{...l,totalBytesReceived:l.packages[0].byteLength,totalBytesExpected:l.binaryLength+l.jsonLength,remaining:s.remaining}},r(o)}else o.header&&o.header.totalBytesReceived<o.header.totalBytesExpected&&(o.header.packages.push(t),o.header.totalBytesReceived+=t.byteLength,r(o));if(o.header&&o.header.totalBytesReceived>=o.header.totalBytesExpected){const t=Date.now()-o.header.sentAt.getTime(),n=Date.now()-o.firstPackageAt;jb(`Received ${o.header.totalBytesReceived} of ${o.header.totalBytesExpected} expected in ${t} ms, elapsed since first package: ${n}ms`);const s=a?Rb.decodeFullKlMessage(o.header):Tb.decodeFullKlMessage(o.header),c=o.header.totalBytesReceived,l=o.header.remaining;r(null),s&&i({klMessage:s.message,complete:!0,sourceServiceId:o.header.fromServiceId,targetServiceId:o.header.toServiceId,rawMessage:s.message.rawMessage});let u=l;if(s?.remaining&&(u=a?l?((e,t)=>{const n=e.byteLength+t.byteLength,r=new ArrayBuffer(n),i=new Uint8Array(e),o=new Uint8Array(t),s=new Uint8Array(r);return s.set(i),s.set(o,i.length),r})(l,s.remaining):s.remaining:l?Buffer.concat([l,s.remaining]):s.remaining),u)return jb(`${u.byteLength} bytes remaining after processing message with ${c} bytes of data. Re-analyzing...`),e(u,null,r,i)}};return e};gb.config={...gb.config,id:"widgets",retry:1500,silent:!0,rawBuffer:!0,appspace:"kemu.",encoding:"hex"};const Fb={info:Rd("ipcServer:info"),data:Rd("ipcServer:data")};let Ub,Bb,Wb,Gb,Vb={};const Hb=Lb(),Yb=e=>{Vb[e]&&(Fb.info(`Client disconnected [${e}]`),delete Vb[e],Bb&&Bb(e))};var zb=(e,t)=>{const n=Vb[e];if(!n)return Fb.info(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=mb)return Fb.info("Message is too long to be a command. Use sendMessage instead."),!1;const r=Tb.encodeCommand(t);return n.socket.write(r),!0},qb=(e,t)=>{const n=Vb[e];return!!n&&(Fb.info(`Renaming socket id [${e}] to [${t}]`),delete Vb[e],n.socket.id=t,Vb[t]=n,n.socket.removeListener("close",n.disconnectHandler),n.disconnectHandler=()=>Yb(t),n.socket.on("close",n.disconnectHandler),!0)};let Kb=Tb;vb&&(Kb=Rb);var Jb,Zb=Kb;!function(e){e.FunctionNotFound="FNC_NOT_FOUND",e.FunctionNotAllowed="FNC_NOT_ALLOWED",e.ParentEventCallbackError="PARENT_EVENT_CALLBACK_ERROR"}(Jb||(Jb={}));let Xb=Math.ceil(Date.now()/1e3);var Qb={exports:{}};const ew=["nodebuffer","arraybuffer","fragments"],tw="undefined"!=typeof Blob;tw&&ew.push("blob");var nw={BINARY_TYPES:ew,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:tw,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:rw}=nw,iw=Buffer[Symbol.species];function ow(e,t,n,r,i){for(let o=0;o<i;o++)n[r+o]=e[o]^t[3&o]}function sw(e,t){for(let n=0;n<e.length;n++)e[n]^=t[3&n]}if(Qb.exports={concat:function(e,t){if(0===e.length)return rw;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 iw(n.buffer,n.byteOffset,r):n},mask:ow,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 iw(t):ArrayBuffer.isView(t)?n=new iw(t.buffer,t.byteOffset,t.byteLength):(n=Buffer.from(t),e.readOnly=!1),n},unmask:sw},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");Qb.exports.mask=function(t,n,r,i,o){o<48?ow(t,n,r,i,o):e.mask(t,n,r,i,o)},Qb.exports.unmask=function(t,n){t.length<32?sw(t,n):e.unmask(t,n)}}catch(b){}var aw=Qb.exports;const cw=Symbol("kDone"),lw=Symbol("kRun"),uw=A,dw=aw,hw=class{constructor(e){this[cw]=()=>{this.pending--,this[lw]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[lw]()}[lw](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[cw])}}},{kStatusCode:fw}=nw,pw=Buffer[Symbol.species],gw=Buffer.from([0,0,255,255]),mw=Symbol("permessage-deflate"),yw=Symbol("total-length"),vw=Symbol("callback"),bw=Symbol("buffers"),ww=Symbol("error");let Sw;var _w=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,!Sw){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;Sw=new hw(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[vw];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){Sw.add((r=>{this._decompress(e,t,((e,t)=>{r(),n(e,t)}))}))}compress(e,t,n){Sw.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]?uw.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=uw.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[mw]=this,this._inflate[yw]=0,this._inflate[bw]=[],this._inflate.on("error",kw),this._inflate.on("data",xw)}this._inflate[vw]=n,this._inflate.write(e),t&&this._inflate.write(gw),this._inflate.flush((()=>{const e=this._inflate[ww];if(e)return this._inflate.close(),this._inflate=null,void n(e);const i=dw.concat(this._inflate[bw],this._inflate[yw]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[yw]=0,this._inflate[bw]=[],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]?uw.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=uw.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[yw]=0,this._deflate[bw]=[],this._deflate.on("data",Iw)}this._deflate[vw]=n,this._deflate.write(e),this._deflate.flush(uw.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=dw.concat(this._deflate[bw],this._deflate[yw]);t&&(e=new pw(e.buffer,e.byteOffset,e.length-4)),this._deflate[vw]=null,this._deflate[yw]=0,this._deflate[bw]=[],t&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),n(null,e)}))}};function Iw(e){this[bw].push(e),this[yw]+=e.length}function xw(e){this[yw]+=e.length,this[mw]._maxPayload<1||this[yw]<=this[mw]._maxPayload?this[bw].push(e):(this[ww]=new RangeError("Max payload size exceeded"),this[ww].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ww][fw]=1009,this.removeListener("data",xw),this.reset())}function kw(e){this[mw]._inflate=null,e[fw]=1007,this[vw](e)}var Ew={exports:{}};const{isUtf8:Cw}=O,{hasBlob:$w}=nw;function Nw(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(Ew.exports={isBlob:function(e){return $w&&"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:Nw,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]},Cw)Ew.exports.isValidUTF8=function(e){return e.length<24?Nw(e):Cw(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");Ew.exports.isValidUTF8=function(t){return t.length<32?Nw(t):e(t)}}catch(b){}var Ow=Ew.exports;const{Writable:Tw}=N,Aw=_w,{BINARY_TYPES:Pw,EMPTY_BUFFER:Mw,kStatusCode:Dw,kWebSocket:Rw}=nw,{concat:jw,toArrayBuffer:Lw,unmask:Fw}=aw,{isValidStatusCode:Uw,isValidUTF8:Bw}=Ow,Ww=Buffer[Symbol.species];const{randomFillSync:Gw}=R,Vw=_w,{EMPTY_BUFFER:Hw,kWebSocket:Yw,NOOP:zw}=nw,{isBlob:qw,isValidStatusCode:Kw}=Ow,{mask:Jw,toBuffer:Zw}=aw,Xw=Symbol("kByteLength"),Qw=Buffer.alloc(4),eS=8192;let tS,nS=eS;function rS(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 iS(e,t,n){rS(e,t,n),e.onerror(t)}const{kForOnEventAttribute:oS,kListener:sS}=nw,aS=Symbol("kCode"),cS=Symbol("kData"),lS=Symbol("kError"),uS=Symbol("kMessage"),dS=Symbol("kReason"),hS=Symbol("kTarget"),fS=Symbol("kType"),pS=Symbol("kWasClean");class gS{constructor(e){this[hS]=null,this[fS]=e}get target(){return this[hS]}get type(){return this[fS]}}Object.defineProperty(gS.prototype,"target",{enumerable:!0}),Object.defineProperty(gS.prototype,"type",{enumerable:!0});class mS extends gS{constructor(e,t={}){super(e),this[aS]=void 0===t.code?0:t.code,this[dS]=void 0===t.reason?"":t.reason,this[pS]=void 0!==t.wasClean&&t.wasClean}get code(){return this[aS]}get reason(){return this[dS]}get wasClean(){return this[pS]}}Object.defineProperty(mS.prototype,"code",{enumerable:!0}),Object.defineProperty(mS.prototype,"reason",{enumerable:!0}),Object.defineProperty(mS.prototype,"wasClean",{enumerable:!0});class yS extends gS{constructor(e,t={}){super(e),this[lS]=void 0===t.error?null:t.error,this[uS]=void 0===t.message?"":t.message}get error(){return this[lS]}get message(){return this[uS]}}Object.defineProperty(yS.prototype,"error",{enumerable:!0}),Object.defineProperty(yS.prototype,"message",{enumerable:!0});class vS extends gS{constructor(e,t={}){super(e),this[cS]=void 0===t.data?null:t.data}get data(){return this[cS]}}Object.defineProperty(vS.prototype,"data",{enumerable:!0});const bS={addEventListener(e,t,n={}){for(const r of this.listeners(e))if(!n[oS]&&r[sS]===t&&!r[oS])return;let r;if("message"===e)r=function(e,n){const r=new vS("message",{data:n?e:e.toString()});r[hS]=this,SS(t,this,r)};else if("close"===e)r=function(e,n){const r=new mS("close",{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[hS]=this,SS(t,this,r)};else if("error"===e)r=function(e){const n=new yS("error",{error:e,message:e.message});n[hS]=this,SS(t,this,n)};else{if("open"!==e)return;r=function(){const e=new gS("open");e[hS]=this,SS(t,this,e)}}r[oS]=!!n[oS],r[sS]=t,n.once?this.once(e,r):this.on(e,r)},removeEventListener(e,t){for(const n of this.listeners(e))if(n[sS]===t&&!n[oS]){this.removeListener(e,n);break}}};var wS={CloseEvent:mS,ErrorEvent:yS,Event:gS,EventTarget:bS,MessageEvent:vS};function SS(e,t,n){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}const{tokenChars:_S}=Ow;function IS(e,t,n){void 0===e[t]?e[t]=[n]:e[t].push(n)}var xS={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),o=!1,s=!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===_S[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?(IS(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===_S[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),IS(i,e.slice(c,u),!0),44===l&&(IS(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(s){if(1!==_S[l])throw new SyntaxError(`Unexpected character at index ${d}`);-1===c?c=d:o||(o=!0),s=!1}else if(a)if(1===_S[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}`);s=!0}else if(34===l&&61===e.charCodeAt(d-1))a=!0;else if(-1===u&&1===_S[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 s=e.slice(c,u);o&&(s=s.replace(/\\/g,""),o=!1),IS(i,r,s),44===l&&(IS(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?IS(t,h,i):(void 0===r?IS(i,h,!0):IS(i,r,o?h.replace(/\\/g,""):h),IS(t,n,i)),t}};const kS=T,ES=D,CS=M,$S=L,NS=F,{randomBytes:OS,createHash:TS}=R,{URL:AS}=B,PS=_w,MS=class extends Tw{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||Pw[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Rw]=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 Ww(t.buffer,t.byteOffset+e,t.length-e),new Ww(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 Ww(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[Aw.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);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")):(this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e))}haveLength(e){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")):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=Mw;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]&&Fw(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[Aw.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?jw(n,t):"arraybuffer"===this._binaryType?Lw(jw(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=jw(n,t);if(!this._skipUTF8Validation&&!Bw(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,Mw),this.end();else{const n=e.readUInt16BE(0);if(!Uw(n)){const e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const r=new Ww(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Bw(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 o=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[Dw]=r,o}},DS=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=zw,this[Yw]=void 0}static frame(e,t){let n,r,i=!1,o=2,s=!1;t.mask&&(n=t.maskBuffer||Qw,t.generateMask?t.generateMask(n):(nS===eS&&(void 0===tS&&(tS=Buffer.alloc(eS)),Gw(tS,0,eS),nS=0),n[0]=tS[nS++],n[1]=tS[nS++],n[2]=tS[nS++],n[3]=tS[nS++]),s=!(n[0]|n[1]|n[2]|n[3]),o=6),"string"==typeof e?r=t.mask&&!s||void 0===t[Xw]?(e=Buffer.from(e)).length:t[Xw]:(r=e.length,i=t.mask&&t.readOnly&&!s);let a=r;r>=65536?(o+=8,a=127):r>125&&(o+=2,a=126);const c=Buffer.allocUnsafe(i?r+o:o);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[o-4]=n[0],c[o-3]=n[1],c[o-2]=n[2],c[o-1]=n[3],s?[c,e]:i?(Jw(e,n,c,o,r),[c]):(Jw(e,n,e,0,r),[c,e])):[c,e]}close(t,n,r,i){let o;if(void 0===t)o=Hw;else{if("number"!=typeof t||!Kw(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");o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),"string"==typeof n?o.write(n,2):o.set(n,2)}else o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0)}const s={[Xw]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,o,!1,s,i]):this.sendFrame(e.frame(o,s),i)}ping(t,n,r){let i,o;if("string"==typeof t?(i=Buffer.byteLength(t),o=!1):qw(t)?(i=t.size,o=!1):(i=(t=Zw(t)).length,o=Zw.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const s={[Xw]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};qw(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,s,r]):this.getBlobData(t,!1,s,r):0!==this._state?this.enqueue([this.dispatch,t,!1,s,r]):this.sendFrame(e.frame(t,s),r)}pong(t,n,r){let i,o;if("string"==typeof t?(i=Buffer.byteLength(t),o=!1):qw(t)?(i=t.size,o=!1):(i=(t=Zw(t)).length,o=Zw.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const s={[Xw]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};qw(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,s,r]):this.getBlobData(t,!1,s,r):0!==this._state?this.enqueue([this.dispatch,t,!1,s,r]):this.sendFrame(e.frame(t,s),r)}send(e,t,n){const r=this._extensions[Vw.extensionName];let i,o,s=t.binary?2:1,a=t.compress;"string"==typeof e?(i=Buffer.byteLength(e),o=!1):qw(e)?(i=e.size,o=!1):(i=(e=Zw(e)).length,o=Zw.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,s=0),t.fin&&(this._firstFragment=!0);const c={[Xw]:i,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:o,rsv1:a};qw(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[Xw],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(rS,this,e,i)}this._bufferedBytes-=r[Xw];const o=Zw(t);n?this.dispatch(o,n,r,i):(this._state=0,this.sendFrame(e.frame(o,r),i),this.dequeue())})).catch((e=>{process.nextTick(iS,this,e,i)}))}dispatch(t,n,r,i){if(!n)return void this.sendFrame(e.frame(t,r),i);const o=this._extensions[Vw.extensionName];this._bufferedBytes+=r[Xw],this._state=1,o.compress(t,r.fin,((t,n)=>{this._socket.destroyed?rS(this,new Error("The socket was closed while data was being compressed"),i):(this._bufferedBytes-=r[Xw],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][Xw],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Xw],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)}},{isBlob:RS}=Ow,{BINARY_TYPES:jS,EMPTY_BUFFER:LS,GUID:FS,kForOnEventAttribute:US,kListener:BS,kStatusCode:WS,kWebSocket:GS,NOOP:VS}=nw,{EventTarget:{addEventListener:HS,removeEventListener:YS}}=wS,{format:zS,parse:qS}=xS,{toBuffer:KS}=aw,JS=3e4,ZS=Symbol("kAborted"),XS=[8,13],QS=["CONNECTING","OPEN","CLOSING","CLOSED"],e_=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;let t_=class e extends kS{constructor(t,n,r){super(),this._binaryType=jS[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=LS,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]),r_(this,t,n,r)):(this._autoPong=r.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){jS.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 MS({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),o=new DS(t,this._extensions,r.generateMask);this._receiver=i,this._sender=o,this._socket=t,i[GS]=this,o[GS]=this,t[GS]=this,i.on("conclude",l_),i.on("drain",u_),i.on("error",d_),i.on("message",f_),i.on("ping",p_),i.on("pong",g_),o.onerror=y_,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on("close",b_),t.on("data",w_),t.on("end",S_),t.on("error",__),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[PS.extensionName]&&this._extensions[PS.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())})),v_(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";a_(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||LS,n,r)):c_(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||LS,n,r)):c_(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 c_(this,t,r);const i={binary:"string"!=typeof t,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[PS.extensionName]||(i.compress=!1),this._sender.send(t||LS,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";a_(this,this._req,e)}}};Object.defineProperty(t_,"CONNECTING",{enumerable:!0,value:QS.indexOf("CONNECTING")}),Object.defineProperty(t_.prototype,"CONNECTING",{enumerable:!0,value:QS.indexOf("CONNECTING")}),Object.defineProperty(t_,"OPEN",{enumerable:!0,value:QS.indexOf("OPEN")}),Object.defineProperty(t_.prototype,"OPEN",{enumerable:!0,value:QS.indexOf("OPEN")}),Object.defineProperty(t_,"CLOSING",{enumerable:!0,value:QS.indexOf("CLOSING")}),Object.defineProperty(t_.prototype,"CLOSING",{enumerable:!0,value:QS.indexOf("CLOSING")}),Object.defineProperty(t_,"CLOSED",{enumerable:!0,value:QS.indexOf("CLOSED")}),Object.defineProperty(t_.prototype,"CLOSED",{enumerable:!0,value:QS.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(t_.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(t_.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[US])return t[BS];return null},set(t){for(const t of this.listeners(e))if(t[US]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[US]:!0})}})})),t_.prototype.addEventListener=HS,t_.prototype.removeEventListener=YS;var n_=t_;function r_(e,t,n,r){const i={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:XS[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,!XS.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${XS.join(", ")})`);let o;if(t instanceof AS)o=t;else try{o=new AS(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}"http:"===o.protocol?o.protocol="ws:":"https:"===o.protocol&&(o.protocol="wss:"),e._url=o.href;const s="wss:"===o.protocol,a="ws+unix:"===o.protocol;let c;if("ws:"===o.protocol||s||a?a&&!o.pathname?c="The URL's pathname is empty":o.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 i_(e,t)}const l=s?443:80,u=OS(16).toString("base64"),d=s?ES.request:CS.request,h=new Set;let f,p;if(i.createConnection=i.createConnection||(s?s_:o_),i.defaultPort=i.defaultPort||l,i.port=o.port||l,i.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},i.path=o.pathname+o.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(f=new PS(!0!==i.perMessageDeflate?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=zS({[PS.extensionName]:f.offer()})),n.length){for(const e of n){if("string"!=typeof e||!e_.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),(o.username||o.password)&&(i.auth=`${o.username}:${o.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=s,e._originalHostOrSocketPath=a?i.socketPath:o.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&&o.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!s)&&(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",(()=>{a_(e,p,"Opening handshake has timed out")})),p.on("error",(t=>{null===p||p[ZS]||(p=e._req=null,i_(e,t))})),p.on("response",(o=>{const s=o.headers.location,a=o.statusCode;if(s&&i.followRedirects&&a>=300&&a<400){if(++e._redirects>i.maxRedirects)return void a_(e,p,"Maximum redirects exceeded");let o;p.abort();try{o=new AS(s,t)}catch(t){const n=new SyntaxError(`Invalid URL: ${s}`);return void i_(e,n)}r_(e,o,n,r)}else e.emit("unexpected-response",p,o)||a_(e,p,`Unexpected server response: ${o.statusCode}`)})),p.on("upgrade",((t,n,r)=>{if(e.emit("upgrade",t),e.readyState!==t_.CONNECTING)return;p=e._req=null;const o=t.headers.upgrade;if(void 0===o||"websocket"!==o.toLowerCase())return void a_(e,n,"Invalid Upgrade header");const s=TS("sha1").update(u+FS).digest("base64");if(t.headers["sec-websocket-accept"]!==s)return void a_(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 a_(e,n,c);a&&(e._protocol=a);const l=t.headers["sec-websocket-extensions"];if(void 0!==l){if(!f)return void a_(e,n,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");let r;try{r=qS(l)}catch(t){return void a_(e,n,"Invalid Sec-WebSocket-Extensions header")}const i=Object.keys(r);if(1!==i.length||i[0]!==PS.extensionName)return void a_(e,n,"Server indicated an extension that was not requested");try{f.accept(r[PS.extensionName])}catch(t){return void a_(e,n,"Invalid Sec-WebSocket-Extensions header")}e._extensions[PS.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 i_(e,t){e._readyState=t_.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function o_(e){return e.path=e.socketPath,$S.connect(e)}function s_(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=$S.isIP(e.host)?"":e.host),NS.connect(e)}function a_(e,t,n){e._readyState=t_.CLOSING;const r=new Error(n);Error.captureStackTrace(r,a_),t.setHeader?(t[ZS]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(i_,e,r)):(t.destroy(r),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function c_(e,t,n){if(t){const n=RS(t)?t.size:KS(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${QS[e.readyState]})`);process.nextTick(n,t)}}function l_(e,t){const n=this[GS];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,void 0!==n._socket[GS]&&(n._socket.removeListener("data",w_),process.nextTick(m_,n._socket),1005===e?n.close():n.close(e,t))}function u_(){const e=this[GS];e.isPaused||e._socket.resume()}function d_(e){const t=this[GS];void 0!==t._socket[GS]&&(t._socket.removeListener("data",w_),process.nextTick(m_,t._socket),t.close(e[WS])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function h_(){this[GS].emitClose()}function f_(e,t){this[GS].emit("message",e,t)}function p_(e){const t=this[GS];t._autoPong&&t.pong(e,!this._isServer,VS),t.emit("ping",e)}function g_(e){this[GS].emit("pong",e)}function m_(e){e.resume()}function y_(e){const t=this[GS];t.readyState!==t_.CLOSED&&(t.readyState===t_.OPEN&&(t._readyState=t_.CLOSING,v_(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function v_(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),JS)}function b_(){const e=this[GS];let t;this.removeListener("close",b_),this.removeListener("data",w_),this.removeListener("end",S_),e._readyState=t_.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[GS]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",h_),e._receiver.on("finish",h_))}function w_(e){this[GS]._receiver.write(e)||this.pause()}function S_(){const e=this[GS];e._readyState=t_.CLOSING,e._receiver.end(),this.end()}function __(){const e=this[GS];this.removeListener("error",__),this.on("error",VS),e&&(e._readyState=t_.CLOSING,this.destroy())}const{tokenChars:I_}=Ow;var x_={parse:function(e){const t=new Set;let n=-1,r=-1,i=0;for(;i<e.length;i++){const o=e.charCodeAt(i);if(-1===r&&1===I_[o])-1===n&&(n=i);else if(0===i||32!==o&&9!==o){if(44!==o)throw new SyntaxError(`Unexpected character at index ${i}`);{if(-1===n)throw new SyntaxError(`Unexpected character at index ${i}`);-1===r&&(r=i);const o=e.slice(n,r);if(t.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);t.add(o),n=r=-1}}else-1===r&&-1!==n&&(r=i)}if(-1===n||-1!==r)throw new SyntaxError("Unexpected end of input");const o=e.slice(n,i);if(t.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}};const k_=T,E_=M,{createHash:C_}=R,$_=xS,N_=_w,O_=x_,T_=n_,{GUID:A_,kWebSocket:P_}=nw,M_=/^[+/0-9A-Za-z]{22}==$/;function D_(e){e._state=2,e.emit("close")}function R_(){this.destroy()}function j_(e,t,n,r){n=n||E_.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} ${E_.STATUS_CODES[t]}\r\n`+Object.keys(r).map((e=>`${e}: ${r[e]}`)).join("\r\n")+"\r\n\r\n"+n)}function L_(e,t,n,r,i){if(e.listenerCount("wsClientError")){const r=new Error(i);Error.captureStackTrace(r,L_),e.emit("wsClientError",r,n,t)}else j_(n,r,i)}var F_=bd(class extends k_{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:T_,...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=E_.createServer(((e,t)=>{const n=E_.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(D_,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(D_,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{D_(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",R_);const i=e.headers["sec-websocket-key"],o=e.headers.upgrade,s=+e.headers["sec-websocket-version"];if("GET"!==e.method)return void L_(this,e,t,405,"Invalid HTTP method");if(void 0===o||"websocket"!==o.toLowerCase())return void L_(this,e,t,400,"Invalid Upgrade header");if(void 0===i||!M_.test(i))return void L_(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");if(8!==s&&13!==s)return void L_(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header");if(!this.shouldHandle(e))return void j_(t,400);const a=e.headers["sec-websocket-protocol"];let c=new Set;if(void 0!==a)try{c=O_.parse(a)}catch(n){return void L_(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 r=new N_(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=$_.parse(l);e[N_.extensionName]&&(r.accept(e[N_.extensionName]),u[N_.extensionName]=r)}catch(n){return void L_(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const o={origin:e.headers[8===s?"sec-websocket-origin":"origin"],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(o,((o,s,a,l)=>{if(!o)return j_(t,s||401,a,l);this.completeUpgrade(u,i,c,e,t,n,r)}));if(!this.options.verifyClient(o))return j_(t,401)}this.completeUpgrade(u,i,c,e,t,n,r)}completeUpgrade(e,t,n,r,i,o,s){if(!i.readable||!i.writable)return i.destroy();if(i[P_])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return j_(i,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${C_("sha1").update(t+A_).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[N_.extensionName]){const t=e[N_.extensionName].params,n=$_.format({[N_.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",R_),c.setSocket(i,o,{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(D_,this)}))),s(c,r)}});const U_=Rd("websocketServer"),B_={},W_=Lb();let G_,V_,H_,Y_,z_;const q_=["https://app.kemu.io","https://dev.kemu.io","https://stage.kemu.io","https://local.kemu.io:3003"],K_=e=>{const t=B_[e];t&&t.socket.close()};var J_=e=>{z_=new F_({port:e,maxPayload:1048576e3,verifyClient:(e,t)=>{const n=e.req.headers.origin;n&&q_.includes(n)?t(!0):t(!1,401,"Origin not allowed")}}),z_.on("connection",(e=>{const t=Qy();U_(`New client connected. Registered as "${t}"`),e.id=t,B_[t]={socket:e,activeMessage:null},G_&&G_(t),e.on("message",(t=>{if(t instanceof Buffer){const n=B_[e.id];W_(t,n.activeMessage,(e=>n.activeMessage=e),(t=>{if(!t.complete)return;const r=t=>{e.send(t),U_(`Writing ${t.byteLength} bytes to socket [${n.socket.id}]: ${t.toString()}`)},i=()=>{K_(n.socket.id)};if(t.command)return U_(`Received command from client [${n.socket.id}]: ${t.command}`),void(H_&&H_(n.socket.id,t.command,r,i));t.klMessage&&Y_&&Y_({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",(()=>{U_(`Client disconnected: ${e.id}`),V_&&V_(e.id),delete B_[e.id]})),e.on("error",(()=>{U_(`Error on client connection: ${e.id}`)}))})),console.log(`WebSocket server is running on port ${e}`)},Z_=e=>{G_=e},X_=e=>{V_=e},Q_=e=>{H_=e},eI=(e,t)=>{const n=B_[e];if(!n)return U_(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=mb)return U_("Message is too long to be a command. Use sendMessage instead."),!1;const r=Tb.encodeCommand(t);return n.socket.send(r),!0},tI=e=>Y_=e,nI=K_;const rI=Rd("stopService"),iI=async e=>{const t=e.args[0];if(!t)return e.reply({error:"No service name provided"});const n=Rv.getAllServiceVersions(t);rI(`Stopping ${n.length} services with name: ${t}`);for(const e of n)await Rv.stopService({serviceName:e.info.name,version:e.info.version});const r=n.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[r]})},oI=Rd("removeService"),sI=async e=>{const t=e.args[0],n=e.args[1];if(!t)return e.reply({error:"No service name provided"});let r=Rv.getAllServiceVersions(t);n&&(r=r.filter((e=>e.info.version===n))),oI(`Removing ${r.length} service(s) with name: ${t}`);for(const e of r)await Rv.uninstallService(e.info.name,e.info.version);const i=r.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[i]})},aI=Rd("launchService"),cI=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=hv();aI(`Loading service ${t}@${n} from ${i}`);const{errorMsg:o,service:s,errorCode:a}=await Rv.loadAndLaunch(i,r,!1);if(o||"started"!==s?.status)return e.reply({error:`Failed to launch service ${t}@${n}: ${o||"error-not-provided"}`,errCode:a});const c=Date.now(),l=3e4,u=async()=>{const r=s.status;return"running"===r?(aI(`Service ${t}@${n} loaded and started`),e.reply({success:[]})):(aI(`Service ${t}@${n} not yet started, status: ${r}`),"stopped"===r||"error"===r?e.reply({error:`Error launching service: "${s.errorMsg||"failed to initiate"}"`}):Date.now()-c>l?e.reply({error:"Timeout waiting for service to start"}):(aI("Retrying in 1 second..."),void setTimeout(u,1e3)))};u()}catch(r){return aI(`Error loading service ${t}@${n}: ${r?.message||r}`),e.reply({error:r?.message||"There was an error loading the service"})}},lI=Rd("getMatchingServices"),uI=async e=>{const t=e.args[0],n=[],r=[];lI(`Checking for matching services: ${t.map((e=>e.name)).join(", ")}`);for(const{name:e,version:i}of t){const t=Rv.getMatchingService(e,i);t?n.push({name:e,version:i,installationPath:Rv.getServiceRootDirectory(t)}):r.push({name:e,version:i})}lI(`Found ${n.length} available services and ${r.length} missing services.`),e.reply({success:[{available:n,missing:r}]})},dI=Rd("getSecretsValues");let hI;var fI=async e=>{const t=e.args[0].services;if(!hI)throw new Error("getSecretValuesFn is not set. Please call setGetSecretValuesFunction before using this function.");dI(`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 hI({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})},pI=e=>{hI=e};const gI=Rd("getMappedSecrets");let mI;var yI=async e=>{const t=e.args[0].services;gI(`Getting mapped secrets for services: ${t.map((e=>`${e.name}@${e.version}`)).join(", ")}`);const n=await mI(t),r=[{services:t.map((e=>({name:e.name,version:e.version,secrets:n[e.name]||[]})))}];e.reply({success:r})};const vI=Rd("getServiceContents"),bI=({reply:e,args:t})=>{const[n]=t;vI(`Received GetServiceContents request for service ${n.serviceName} v${n.version}`);const r=Rv.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}]});vI(`Service ${n.serviceName} v${n.version} not found`),e({error:`Service ${n.serviceName} v${n.version} not found`})};let wI={globalApiKey:void 0,environment:"production"};const SI=()=>({...wI}),_I=Rd("apis"),II=()=>{const e=SI();if(!e.serviceUrl)throw new Error("Unknown server URL. Please call `edgeConfig.setEdgeConfig` before using the APIs.");return e.serviceUrl},xI=async(e,t,n={})=>{try{const r=await fetch(e,{method:"POST",body:JSON.stringify(t),headers:{...n}});return r.ok?{data:await r.json(),statusCode:r.status,success:!0}:{statusCode:r.status,error:await r.text(),success:!1}}catch(e){return{statusCode:500,error:e instanceof Error?e.message:"Internal server error",success:!1}}},kI=async e=>{const{data:t,error:n}=await xI(`${II()}/v1/organization/validate/apiKey`,{apiKey:e},{"Content-Type":"application/json"});return n?(_I(`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"}},EI={},CI={},$I=e=>{const t=EI[e],n=Date.now()-(t?.lastCheckedAt.getTime()??0);return t&&n<3e5?t.features:null};function NI(e){return"number"==typeof e||!!/^0x[0-9a-f]+$/i.test(e)||/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(e)}function OI(e,t){return"constructor"===t&&"function"==typeof e[t]||"__proto__"===t}var TI=bd((function(e,t){t||(t={});var n={bools:{},strings:{},unknownFn:null};"function"==typeof t.unknown&&(n.unknownFn=t.unknown),"boolean"==typeof t.boolean&&t.boolean?n.allBools=!0:[].concat(t.boolean).filter(Boolean).forEach((function(e){n.bools[e]=!0}));var r={};function i(e){return r[e].some((function(e){return n.bools[e]}))}Object.keys(t.alias||{}).forEach((function(e){r[e]=[].concat(t.alias[e]),r[e].forEach((function(t){r[t]=[e].concat(r[e].filter((function(e){return t!==e})))}))})),[].concat(t.string).filter(Boolean).forEach((function(e){n.strings[e]=!0,r[e]&&[].concat(r[e]).forEach((function(e){n.strings[e]=!0}))}));var o=t.default||{},s={_:[]};function a(e,t,r){for(var i=e,o=0;o<t.length-1;o++){var s=t[o];if(OI(i,s))return;void 0===i[s]&&(i[s]={}),i[s]!==Object.prototype&&i[s]!==Number.prototype&&i[s]!==String.prototype||(i[s]={}),i[s]===Array.prototype&&(i[s]=[]),i=i[s]}var a=t[t.length-1];OI(i,a)||(i!==Object.prototype&&i!==Number.prototype&&i!==String.prototype||(i={}),i===Array.prototype&&(i=[]),void 0===i[a]||n.bools[a]||"boolean"==typeof i[a]?i[a]=r:Array.isArray(i[a])?i[a].push(r):i[a]=[i[a],r])}function c(e,t,i){if(!i||!n.unknownFn||function(e,t){return n.allBools&&/^--[^=]+$/.test(t)||n.strings[e]||n.bools[e]||r[e]}(e,i)||!1!==n.unknownFn(i)){var o=!n.strings[e]&&NI(t)?Number(t):t;a(s,e.split("."),o),(r[e]||[]).forEach((function(e){a(s,e.split("."),o)}))}}Object.keys(n.bools).forEach((function(e){c(e,void 0!==o[e]&&o[e])}));var l=[];-1!==e.indexOf("--")&&(l=e.slice(e.indexOf("--")+1),e=e.slice(0,e.indexOf("--")));for(var u=0;u<e.length;u++){var d,h,f=e[u];if(/^--.+=/.test(f)){var p=f.match(/^--([^=]+)=([\s\S]*)$/);d=p[1];var g=p[2];n.bools[d]&&(g="false"!==g),c(d,g,f)}else if(/^--no-.+/.test(f))c(d=f.match(/^--no-(.+)/)[1],!1,f);else if(/^--.+/.test(f))d=f.match(/^--(.+)/)[1],void 0===(h=e[u+1])||/^(-|--)[^-]/.test(h)||n.bools[d]||n.allBools||r[d]&&i(d)?/^(true|false)$/.test(h)?(c(d,"true"===h,f),u+=1):c(d,!n.strings[d]||"",f):(c(d,h,f),u+=1);else if(/^-[^-]+/.test(f)){for(var m=f.slice(1,-1).split(""),y=!1,v=0;v<m.length;v++)if("-"!==(h=f.slice(v+2))){if(/[A-Za-z]/.test(m[v])&&"="===h[0]){c(m[v],h.slice(1),f),y=!0;break}if(/[A-Za-z]/.test(m[v])&&/-?\d+(\.\d*)?(e-?\d+)?$/.test(h)){c(m[v],h,f),y=!0;break}if(m[v+1]&&m[v+1].match(/\W/)){c(m[v],f.slice(v+2),f),y=!0;break}c(m[v],!n.strings[m[v]]||"",f)}else c(m[v],h,f);d=f.slice(-1)[0],y||"-"===d||(!e[u+1]||/^(-|--)[^-]/.test(e[u+1])||n.bools[d]||r[d]&&i(d)?e[u+1]&&/^(true|false)$/.test(e[u+1])?(c(d,"true"===e[u+1],f),u+=1):c(d,!n.strings[d]||"",f):(c(d,e[u+1],f),u+=1))}else if(n.unknownFn&&!1===n.unknownFn(f)||s._.push(n.strings._||!NI(f)?f:Number(f)),t.stopEarly){s._.push.apply(s._,e.slice(u+1));break}}return Object.keys(o).forEach((function(e){var t,n,i;t=s,n=e.split("."),i=t,n.slice(0,-1).forEach((function(e){i=i[e]||{}})),n[n.length-1]in i||(a(s,e.split("."),o[e]),(r[e]||[]).forEach((function(t){a(s,t.split("."),o[e])})))})),t["--"]?s["--"]=l.slice():l.forEach((function(e){s._.push(e)})),s}));Cb("ipcClient"),Cb("kemuWidgetService"),TI(process.argv.slice(2));const AI=Rd("activeClients");let PI,MI={},DI={};const RI=(e,t)=>`${e}_${t}`,jI=e=>MI[e]||null,LI=(e,t)=>{const n=RI(e,t);return DI[n]||[]},FI=()=>{for(const e in MI){const t=MI[e];if(t?.transport===ed.WS){const e=Tb.encodeCommand(Zu.ServicesListChanged);t.send(e)}}},UI=async e=>{const t=[],{serviceSessionId:n,transport:r,send:i,terminateFn:o,extraInfo:s,isDevClient:a}=e;if(r===ed.WS&&!s.recipe?.poolId)return c=`Bad request. Recipe pool id is required. SessionId: ${n}`,console.warn(c),void(o&&o());var c;MI[n]={serviceSessionId:n,transport:r,isDevClient:!!a,broadcastSubscriptions:t,send:i,extraInfo:s,terminate:()=>{o&&o()},addSubscription:e=>{if(!t.some((t=>t.targetService.serviceName===e.serviceName&&t.targetService.version===e.version))){t.push({targetService:e});const r=RI(e.serviceName,e.version);return DI[r]=DI[r]||[],DI[r].some((e=>e.serviceId===n))||DI[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=RI(e.serviceName,e.version),o=DI[i]?.findIndex((e=>e.serviceId===n));if(-1!==o&&(DI[i]?.splice(o,1),!DI[i]?.length)){const t=Rv.getMatchingService(e.serviceName,e.version);if(t?.info.eventEmitter&&"running"===t.status){const e=jI(t.info.sessionId);e?.extraInfo.ipcSocketId&&zb(e?.extraInfo.ipcSocketId,Zu.BroadcastEnd)}}}},removeAllSubscriptions:()=>{for(const e of t){const t=RI(e.targetService.serviceName,e.targetService.version),r=DI[t]?.findIndex((e=>e.serviceId===n));-1!==r&&DI[t]?.splice(r,1)}t.length=0}},r===ed.IPC&&(FI(),BI(n))},BI=e=>{const t=Rv.getServiceBySessionId(e);if(t?.info.eventEmitter&&LI(t.info.name,t.info.version).length){const t=jI(e);t?.extraInfo.ipcSocketId&&zb(t?.extraInfo.ipcSocketId,Zu.BroadcastStart)}},WI=e=>{const t=MI[e];var n;t?.transport===ed.IPC?FI():(t?.removeAllSubscriptions(),(()=>{const e=Object.values(MI);for(const t of e)if(t.transport===ed.IPC){const e=t.extraInfo.ipcSocketId,n=Rv.getServiceBySessionId(t.serviceSessionId);n?.info.eventEmitter&&(LI(n.info.name,n.info.version).length||e&&zb(e,Zu.BroadcastEnd))}})(),t?.extraInfo.recipe?.poolId&&(n=t.extraInfo.recipe.poolId,delete EI[n],delete CI[n]),(e=>{const t=MI[e];if(t?.transport===ed.WS&&t.extraInfo.recipe){const n=[{recipe:t.extraInfo.recipe}];AI(`Notifying IPC clients that a Kemu Compose client [${t.extraInfo.recipe.name} (${t.extraInfo.recipe.poolId})] has disconnected. ServiceSessionId: ${e}`);for(const e in MI){const t=MI[e];t?.transport===ed.IPC&&PI.execute(Xu.KemuComposerDisconnected,n,t.send,0,t.serviceSessionId,{async:!0}).catch((t=>{AI(`Error notifying IPC client [${e}] that a Kemu Compose client has disconnected: ${t?.message||t}`)}))}}})(e)),delete MI[e]},GI=Rd("ipc:handleIpcClientCommand"),VI=(e,t,n)=>{const r=((e,t)=>{if(e.startsWith(Zu.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 GI(`Ignoring ACK response from IPC service ${e} with no service id`);GI(`Received ACK from IPC service ${e}. Marking as running.`);let r=e;t&&e&&e!==t&&(qb(e,t),r=t);let i=!1;t&&(i=Rv.setServiceStatus(t,"running")),i?UI({serviceSessionId:t||e,transport:ed.IPC,send:n,extraInfo:{ipcSocketId:t}}):zb(r,Zu.SendManifest)}));!r&&GI(`Received unknown command [${t}] from service ${e}`)};let HI={};G.platform();const YI=async e=>{const t=e.args[0];if(HI.chooseDirectory)try{const n=await HI.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"})},zI=async e=>{const t=e.args[0];if(HI.chooseFile)try{const n=await HI.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"})};var qI={},KI={},JI={};function ZI(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function XI(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function QI(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function ex(e,...t){if(!QI(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 tx(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");ZI(e.outputLen),ZI(e.blockLen)}function nx(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 rx(e,t){ex(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}Object.defineProperty(JI,"__esModule",{value:!0}),JI.output=JI.exists=JI.hash=JI.bytes=JI.bool=JI.number=JI.isBytes=void 0,JI.number=ZI,JI.bool=XI,JI.isBytes=QI,JI.bytes=ex,JI.hash=tx,JI.exists=nx,JI.output=rx;const ix={number:ZI,bool:XI,bytes:ex,hash:tx,exists:nx,output:rx};JI.default=ix;var ox={};Object.defineProperty(ox,"__esModule",{value:!0}),ox.add5L=ox.add5H=ox.add4H=ox.add4L=ox.add3H=ox.add3L=ox.add=ox.rotlBL=ox.rotlBH=ox.rotlSL=ox.rotlSH=ox.rotr32L=ox.rotr32H=ox.rotrBL=ox.rotrBH=ox.rotrSL=ox.rotrSH=ox.shrSL=ox.shrSH=ox.toBig=ox.split=ox.fromBig=void 0;const sx=BigInt(2**32-1),ax=BigInt(32);function cx(e,t=!1){return t?{h:Number(e&sx),l:Number(e>>ax&sx)}:{h:0|Number(e>>ax&sx),l:0|Number(e&sx)}}function lx(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let i=0;i<e.length;i++){const{h:o,l:s}=cx(e[i],t);[n[i],r[i]]=[o,s]}return[n,r]}ox.fromBig=cx,ox.split=lx;const ux=(e,t)=>BigInt(e>>>0)<<ax|BigInt(t>>>0);ox.toBig=ux;const dx=(e,t,n)=>e>>>n;ox.shrSH=dx;const hx=(e,t,n)=>e<<32-n|t>>>n;ox.shrSL=hx;const fx=(e,t,n)=>e>>>n|t<<32-n;ox.rotrSH=fx;const px=(e,t,n)=>e<<32-n|t>>>n;ox.rotrSL=px;const gx=(e,t,n)=>e<<64-n|t>>>n-32;ox.rotrBH=gx;const mx=(e,t,n)=>e>>>n-32|t<<64-n;ox.rotrBL=mx;const yx=(e,t)=>t;ox.rotr32H=yx;const vx=e=>e;ox.rotr32L=vx;const bx=(e,t,n)=>e<<n|t>>>32-n;ox.rotlSH=bx;const wx=(e,t,n)=>t<<n|e>>>32-n;ox.rotlSL=wx;const Sx=(e,t,n)=>t<<n-32|e>>>64-n;ox.rotlBH=Sx;const _x=(e,t,n)=>e<<n-32|t>>>64-n;function Ix(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:0|i}}ox.rotlBL=_x,ox.add=Ix;const xx=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0);ox.add3L=xx;const kx=(e,t,n,r)=>t+n+r+(e/2**32|0)|0;ox.add3H=kx;const Ex=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0);ox.add4L=Ex;const Cx=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0;ox.add4H=Cx;const $x=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0);ox.add5L=$x;const Nx=(e,t,n,r,i,o)=>t+n+r+i+o+(e/2**32|0)|0;ox.add5H=Nx;const Ox={fromBig:cx,split:lx,toBig:ux,shrSH:dx,shrSL:hx,rotrSH:fx,rotrSL:px,rotrBH:gx,rotrBL:mx,rotr32H:yx,rotr32L:vx,rotlSH:bx,rotlSL:wx,rotlBH:Sx,rotlBL:_x,add:Ix,add3L:xx,add3H:kx,add4L:Ex,add4H:Cx,add5H:Nx,add5L:$x};ox.default=Ox;var Tx={},Ax={};Object.defineProperty(Ax,"__esModule",{value:!0}),Ax.crypto=void 0,Ax.crypto="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,function(e){
|
|
11
11
|
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
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=Ax,n=JI;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=48,o=57,s=65,a=70,c=97,l=102;function u(e){return e>=i&&e<=o?e-i:e>=s&&e<=a?e-(s-10):e>=c&&e<=l?e-(c-10):void 0}function d(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}function h(e){return"string"==typeof e&&(e=d(e)),(0,n.bytes)(e),e}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=u(e.charCodeAt(i)),o=u(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},e.nextTick=async()=>{},e.asyncLoop=async function(t,n,r){let i=Date.now();for(let o=0;o<t;o++){r(o);const t=Date.now()-i;t>=0&&t<n||(await(0,e.nextTick)(),i+=t)}},e.utf8ToBytes=d,e.toBytes=h,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 f={}.toString;e.checkOpts=function(e,t){if(void 0!==t&&"[object Object]"!==f.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(h(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(h(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(h(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")}}(Tx),Object.defineProperty(KI,"__esModule",{value:!0}),KI.shake256=KI.shake128=KI.keccak_512=KI.keccak_384=KI.keccak_256=KI.keccak_224=KI.sha3_512=KI.sha3_384=KI.sha3_256=KI.sha3_224=KI.Keccak=KI.keccakP=void 0;const Px=JI,Mx=ox,Dx=Tx,Rx=[],jx=[],Lx=[],Fx=BigInt(0),Ux=BigInt(1),Bx=BigInt(2),Wx=BigInt(7),Gx=BigInt(256),Vx=BigInt(113);for(let e=0,t=Ux,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],Rx.push(2*(5*r+n)),jx.push((e+1)*(e+2)/2%64);let i=Fx;for(let e=0;e<7;e++)t=(t<<Ux^(t>>Wx)*Vx)%Gx,t&Bx&&(i^=Ux<<(Ux<<BigInt(e))-Ux);Lx.push(i)}const[Hx,Yx]=(0,Mx.split)(Lx,!0),zx=(e,t,n)=>n>32?(0,Mx.rotlBH)(e,t,n):(0,Mx.rotlSH)(e,t,n),qx=(e,t,n)=>n>32?(0,Mx.rotlBL)(e,t,n):(0,Mx.rotlSL)(e,t,n);function Kx(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,o=n[i],s=n[i+1],a=zx(o,s,1)^n[r],c=qx(o,s,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=jx[n],o=zx(t,i,r),s=qx(t,i,r),a=Rx[n];t=e[a],i=e[a+1],e[a]=o,e[a+1]=s}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]^=Hx[r],e[1]^=Yx[r]}n.fill(0)}KI.keccakP=Kx;class Jx extends Dx.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,Px.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,Dx.u32)(this.state)}keccak(){Dx.isLE||(0,Dx.byteSwap32)(this.state32),Kx(this.state32,this.rounds),Dx.isLE||(0,Dx.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,Px.exists)(this);const{blockLen:t,state:n}=this,r=(e=(0,Dx.toBytes)(e)).length;for(let i=0;i<r;){const o=Math.min(t-this.pos,r-i);for(let t=0;t<o;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,Px.exists)(this,!1),(0,Px.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 o=Math.min(n-this.posOut,i-r);e.set(t.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}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,Px.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,Px.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:o}=this;return e||(e=new Jx(t,n,r,o,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=o,e.destroyed=this.destroyed,e}}KI.Keccak=Jx;const Zx=(e,t,n)=>(0,Dx.wrapConstructor)((()=>new Jx(t,e,n)));KI.sha3_224=Zx(6,144,28),KI.sha3_256=Zx(6,136,32),KI.sha3_384=Zx(6,104,48),KI.sha3_512=Zx(6,72,64),KI.keccak_224=Zx(1,144,28),KI.keccak_256=Zx(1,136,32),KI.keccak_384=Zx(1,104,48),KI.keccak_512=Zx(1,72,64);const Xx=(e,t,n)=>(0,Dx.wrapXOFConstructorWithOpts)(((r={})=>new Jx(t,e,void 0===r.dkLen?n:r.dkLen,!0)));KI.shake128=Xx(31,168,16),KI.shake256=Xx(31,136,32);const{sha3_512:Qx}=KI,ek=(e=4,t=Math.random)=>{let n="";for(;n.length<e;)n+=Math.floor(36*t()).toString(36);return n};function tk(e){let t=0n;for(const n of e.values())t=(t<<8n)+BigInt(n);return t}const nk=(e="")=>tk(Qx(e)).toString(36).slice(1),rk=Array.from({length:26},((e,t)=>String.fromCharCode(t+97))),ik=({globalObj:e=(void 0!==vd?vd:"undefined"!=typeof window?window:{}),random:t=Math.random}={})=>{const n=Object.keys(e).toString(),r=n.length?n+ek(32,t):ek(32,t);return nk(r).substring(0,32)},ok=e=>()=>e++,sk=({random:e=Math.random,counter:t=ok(Math.floor(476782367*e())),length:n=24,fingerprint:r=ik({random:e})}={})=>function(){const i=(e=>rk[Math.floor(e()*rk.length)])(e),o=Date.now().toString(36),s=t().toString(36),a=ek(n,e);return`${i+nk(`${o+a+s+r}`).substring(1,n)}`},ak=sk();qI.getConstants=()=>({defaultLength:24,bigLength:32}),qI.init=sk,qI.createId=ak,qI.bufToBigInt=tk,qI.createCounter=ok,qI.createFingerprint=ik,qI.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:ck,init:lk,getConstants:uk,isCuid:dk}=qI;var hk=ck;const fk=Rd("getUniqueId"),pk=({reply:e,sourceServiceId:t})=>(fk(`Generating unique id for service "${t}"`),e({success:[hk()]})),gk=Rd("getActiveServices"),mk=async({transport:e,sourceServiceId:t,reply:n})=>{if(gk(`Received GetServices request from ${e} [${t}]`),e===ed.WS){let e=Rv.getActiveServices();const r=jI(t);if(!r)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});let i=[];if(r.transport===ed.WS){const t=e.filter(Rv.isInternalKemuService),n=e.filter((e=>e.devMode&&Rv.isNotInternalKemuService(e))),o=e.filter((e=>Rv.isOfficialKemuService(e)&&Rv.isNotInternalKemuService(e)&&Rv.isNotDevService(e))).sort(((e,t)=>e.name.localeCompare(t.name))),s=e.filter((e=>Rv.isNotDevService(e)&&Rv.isNotInternalKemuService(e)&&!Rv.isOfficialKemuService(e))),a=SI();let c=null;c=a.globalApiKey?await(async(e,t)=>{const{features:n}=await(async e=>{const{apiKey:t,recipePoolId:n}=e,r=$I(n);if(r)return{valid:!0,features:r,error:null};const{valid:i,features:o,error:s}=await kI(t);return i&&(EI[n]={features:o,lastCheckedAt:new Date}),{valid:i,features:o,error:s}})({apiKey:e,recipePoolId:t});return n})(a.globalApiKey,r.extraInfo.recipe?.poolId):await(async e=>{const t=$I(e);if(t)return t;const n=CI[e];if(n)return await n;const r=(async()=>{try{const{features:t}=await kI("free");return EI[e]={features:t,lastCheckedAt:new Date},t}finally{delete CI[e]}})();return CI[e]=r,await r})(r.extraInfo.recipe?.poolId);const l=c?.hub_services??0,u=o.slice(0,-1!==l?l:o.length);-1!==l&&(i=o.slice(l).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,...n,...u,...s]}const o=Rv.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:Rv.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:o,installed:i}]})}};let yk="runtime",vk=null;const bk=()=>yk,wk=Rd("getSystemInfo"),Sk=async({reply:e})=>{wk("Received GetSystemInfo request"),e({success:[await(async()=>{const e=SI().globalApiKey;return{platformArch:ad(),isDesktopHub:"desktop"===bk(),isRuntimeHub:"runtime"===bk(),hubVersion:rv,hasValidApiKeyConfigured:!!e,...vk?{updateAvailable:vk}:{}}})()]})},_k=Rd("removeService"),Ik=async({args:e,sourceServiceId:t,reply:n})=>{const r=e[0],i=r.serviceName,o=r.version;if(!i)return n({error:"No service name provided"});if(!o)return n({error:"No service version provided"});const s=Rv.getAllServiceVersions(i),a=s.find((e=>e.info.version===o));if(!a)return n({error:"Service not found"});_k(`Removing ${s.length} service(s) with name: ${i}`);const c=a.info.publicationId;let l;if(await Rv.uninstallService(a.info.name,a.info.version),c){if(!jI(t))return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});const e=SI();if(!e.globalApiKey)return n({error:"Global API key is not set",errCode:"GLOBAL_API_KEY_NOT_SET"});const r=e.globalApiKey;_k(`Updating license details for "${c}"`);const i=await(async e=>{const{data:t,error:n}=await xI(`${II()}/v1/organization/validate/uninstall_hub_service`,e,{"Content-Type":"application/json"});if(n)throw new Error(n);return t})({apiKey:r,hubService:{id:c}}).catch((e=>(_k(`Error updating license details for "${c}": ${e}`),{error:e.message,remaining:void 0})));l=i?.remaining}n({success:[{remaining:l,service:{name:i,version:o}}]})},xk=Rd("getDecryptedEdgeApiKey"),kk=({reply:e})=>(xk("Getting decrypted edge API key"),e({success:[SI().globalApiKey]})),Ek=({reply:e})=>{xk("Getting hub config");const t=SI();return e({success:[{kemuApiKey:t.globalApiKey,environment:t.environment}]})};let Ck,$k,Nk,Ok,Tk;const Ak=e=>e.transport===ed.IPC&&(e.reply({error:"Transport is not allowed to call this function"}),!0);var Pk=async e=>{const t=e.args,n=t[0].recipeUuid,r=t[0].secretNames;if(!r||!n)return e.reply({error:"Invalid request parameters"});if(!Ck)return e.reply({error:"Get recipe secrets function not set"});const i=await Ck({...t[0]}),o={};for(const e of r)o[e]=e in i?i[e]:null;const s=[{secrets:o}];e.reply({success:s})},Mk=async e=>{const t=e.args,n=t[0].recipeUuid,r=t[0].secretsMap;if(Ak(e))return;if(!$k)return e.reply({error:"Add recipe secret mapping function not set"});if(!r||!n)return e.reply({error:"Invalid request parameters"});const i=[{secrets:await $k({recipeUuid:n,secretsMap:r})}];e.reply({success:i})},Dk=async e=>{const t=e.args,n=t[0].recipeUuid,r=t[0].secretName;if(Ak(e))return;if(!Nk)return e.reply({error:"Delete recipe secret mapping function not set"});if(!r||!n)return e.reply({error:"Invalid request parameters"});const i=[{secrets:await Nk({recipeUuid:n,secretName:r})}];e.reply({success:i})},Rk=async e=>{const t=e.args[0].recipeUuid;if(!Ok)return e.reply({error:"Get recipe secret mappings function not set"});if(!t)return e.reply({error:"Invalid request parameters"});const n=[{secrets:await Ok({recipeUuid:t})}];e.reply({success:n})},jk=async e=>{const t=e.args,n=t[0].hubServiceName,r=t[0].secrets;return Tk?n&&r?Array.isArray(r)?(await Tk({hubServiceName:n,secrets:r}),void e.reply({success:[]})):e.reply({error:'Expected "secrets" to be an array'}):e.reply({error:"Invalid request parameters"}):e.reply({error:"Add service secret function not set"})};let Lk,Fk,Uk;const Bk=e=>e.transport===ed.IPC&&(e.reply({error:"You are not allowed to manage secrets using this transport"}),!0);var Wk=async e=>{if(e.args,Bk(e))return;if(!Uk)return e.reply({error:"Get hub secrets function not set"});const t=[{contexts:await Uk()}];e.reply({success:t})},Gk=async e=>{const t=e.args;if(Bk(e))return;if(!Lk)return e.reply({error:"Add hub secret function not set"});const n=[{contexts:await Lk(t[0])}];e.reply({success:n})},Vk=async e=>{const t=e.args;if(Bk(e))return;if(!Fk)return e.reply({error:"Delete hub secret function not set"});const n=[{contexts:await Fk(t[0])}];e.reply({success:n})};const Hk=S(W(import.meta.url));let Yk=null;const zk=Rd("hub"),qk=new function(){const e={};let t,n=console.log;const r={};let i="hub";const o={},s=e=>!o[e],a=(e,t,n,r,i,o)=>{let a=vb?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:o.success?o.success:[o],messageId:t,type:o.success?"response":"error"}};return s(r)&&(a=Zb.encode(c,n,r)),i(a,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{n=e},processMessage:(i,o,s,c)=>{if(!c)return!1;const l=c;if(e[l.messageId]){const t=e[l.messageId];return t&&(clearTimeout(t.timer),t.fulfilled||(t.fulfilled=!0,"response"===l.type?t.resolve(l.args):"error"===l.type&&t.reject(l.args[0])),delete e[l.messageId]),!0}if("execute"!==l.type&&n&&n(`No pending execution found for message id "${l.messageId}"`),"execute"===l.type){const e=r[l.functionName];if(e){const r=e=>{a(l.functionName,l.messageId,s.targetServiceId,s.sourceServiceId,o,e)};if(t&&!t({args:l.args,functionName:l.functionName,transport:i,messageId:l.messageId,sourceServiceId:s.sourceServiceId,reply:r,send:o}))return n&&n(`Function "${l.functionName}" not allowed to be invoked by client [${s.sourceServiceId}]`),r({error:"Function not allowed",errCode:"FNC_NOT_ALLOWED"}),!0;e({transport:i,args:l.args,reply:r,messageId:l.messageId,sourceServiceId:s.sourceServiceId,send:o})}else{const e=`Function "${l.functionName}" not found.`;n&&n(e),a(l.functionName,l.messageId,s.targetServiceId,s.sourceServiceId,o,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(t,r,o,a,c,l)=>{if(!o){const e="No send buffer function provided.";throw n&&n(e),e}Xb+=1;const u=`${i}-${Xb}-exec-${t.substring(0,10)}`,d={messageId:u,functionName:t,send:o,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};d.promise=new Promise(((e,t)=>{d.resolve=e,d.reject=t}));let h=vb?new ArrayBuffer(0):Buffer.alloc(0);const f={json:{functionName:t,args:r,messageId:u,type:"execute"}};s(c)&&(h=Zb.encode(f,a,c)),e[u]=d,n&&n(`Calling remote function "${t}" with message id "${u}"`);const p="true"===process.env.NO_INVOKE_TIMEOUT;return l?.async?(d.fulfilled=!0,d.resolve([void 0]),delete e[u]):0===l?.timeout||p||(d.timer=setTimeout((()=>{n&&n(`Remote function ${u} timed out`);const r=e[u];r&&!r.fulfilled&&(r.fulfilled=!0,d.reject(`Function ${t} Timed out`)),delete e[u]}),l?.timeout||3e4)),o(h,{sourceServiceId:a,targetServiceId:c,msg:f}),d.promise},sendResponse:a,registerFunction:(e,t)=>{r[e]=t},registerFunctionsMiddleware:e=>{t=e},unregisterAllFunctions:()=>{Object.keys(r).forEach((e=>{delete r[e]}))},getTransportSendFunction:t=>{const n=e[t];return n?n.send:null},setServiceName:e=>{i=e},getPendingExecutions:()=>e,rejectAllPending:t=>{Object.keys(e).forEach((n=>{const r=e[n];r&&!r.fulfilled&&(clearTimeout(r.timer),r.fulfilled=!0,r.reject(t),delete e[n])}))},broadcast:(e,t,r,o)=>{Xb+=1;const a=`${i}-${Xb}-multicast-${e.substring(0,10)}`;let c=vb?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:t,messageId:a,type:"execute"}};let u=s(r[0].serviceId);u&&(c=Zb.encode(l,o,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=s(i.serviceId),u&&(c=Zb.patchEncodedHeader(c,{toServiceId:i.serviceId}))),i.sendFn(c,{msg:l,sourceServiceId:o,targetServiceId:i.serviceId})}catch(e){n&&n(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{o[e]=t}}}("hub");PI=qk,qk.setLogger(zk);const Kk={[Xu.RebootToInstallUpdate]:null,[Xu.GetFileContentFromCacheId]:null,[Xu.SaveRecipeToFile]:null},Jk=(e,t)=>{const{transmission:n}=t;if(0!==n.targetServiceId){const r=jI(n.targetServiceId);if(!r)return zk(`Service [${e}] ${n.sourceServiceId} is sending data to an unknown service ["${n.targetServiceId}"]`),!0;r.transport,ed.IPC;const i=t.json?.messageId;return zk(`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},Zk=({sourceServiceId:e,args:t})=>{const n=Rv.getServiceBySessionId(e);if(n){const r=LI(n.info.name,n.info.version),i=LI(n.info.name,"*");if(!r.length&&!i.length)return;const o=[...r,...i],s={...t[0],source:{serviceName:n.info.name,serviceVersion:n.info.version,sessionId:e}};qk.broadcast(Xu.BroadcastEvent,[s],o,0)}},Xk=async({args:e,reply:t})=>{const n=e[0];if(!n)return zk("Invalid config for SendToRecipe"),t({error:"Invalid config for SendToRecipe"});const r=(i=n.recipePoolId,Object.values(MI).find((e=>e.extraInfo.recipe?.poolId===i))||null);var i;if(!r)return zk(`No client found for recipe pool id ${n.recipePoolId}`),t({error:`No client found for recipe pool id "${n.recipePoolId}"`});try{const e=qk.execute(Xu.SendToRecipe,[n],r.send,0,r.serviceSessionId,{async:!n.waitForResponse,timeout:n.timeout});n.waitForResponse?t({success:await e}):t({success:[]})}catch(e){return zk(`Error sending to recipe ${n.recipePoolId}: ${e?.message||e}`),t({error:e?.message||"There was an error sending to the recipe"})}},Qk=e=>{const{send:t,transmission:n,json:r}=e;zk(`Raw message Id received from WS: ${r?.messageId}`),Jk(ed.WS,e)||qk.processMessage(ed.WS,t,n,r)},eE=e=>{const t=(n=e,`${Zu.SocketAcknowledge}${n}`);var n;eI(e,t)},tE=(e,t)=>{zk(`Received unknown command [${t}] from service ${e}`)},nE=async e=>{const{args:t,sourceServiceId:n,send:r,reply:i}=e,o=n,s=t[0];s.user?.id&&mv.setGlobalUserId(s.user?.id),await UI({serviceSessionId:n,transport:ed.WS,send:r,terminateFn:()=>{nI(n)},extraInfo:{websocketId:o,recipe:s.recipe,user:{userEmail:s.user?.email,userId:s.user?.id}}}),i({success:[]})},rE=e=>{zk(`WS Client ${e} disconnected`),WI(e)},iE=e=>{if(1===e.sourceServiceId)return e.functionName===Xu.GetFileContentFromCacheId;if(e.functionName===Xu.GetHubConfig){const t=Rv.getServiceBySessionId(e.sourceServiceId);if(!t||!Rv.isOfficialKemuService(t.info)&&Rv.isNotDevService(t.info))return zk(`Service "${e.sourceServiceId}" attempting to get hub config but is not an official Kemu service`),!1}return e.functionName===Xu.SocketAckResponse||e.functionName===Xu.ServiceManifest||e.functionName===Xu.SubscribeToService||(!!jI(e.sourceServiceId)||(e.reply({error:`Session id "${e.sourceServiceId}" not found. Please acknowledge the session first.`}),!1))},oE=async({sourceServiceId:e,args:t,transport:n,send:r})=>{if(n!==ed.IPC){var i;zk(`Received manifest from non IPC service ${e}.`)}else{const n=t[0];if(n.devMode){const t=Rv.getMatchingDevService(n.name,n.version,"stopped");if(t){zk(`Found matching previous service ${t.info.name} (${t.info.version}). Reactivating previous client with session id ${t.info.sessionId}`);const o=jI(t.info.sessionId);if(!o)return void zk(`Could not find previous client instance for ${t.info.name} (${t.info.version}). Aborting manifest injection`);o.send=r,MI[i=e]?delete MI[i]:AI(`Could not find source client with session id ${i}`),qb(e,t.info.sessionId);const s=await cv(n,n.path);t.info={...t.info,...s},zk(`Updating manifest for dev service ${t.info.sessionId}`),Rv.setServiceManifest(t.info.sessionId,s,"running"),zk(`Asking service ${e} to assume previous session id ${t.info.sessionId}`),zb(t.info.sessionId,(e=>`${Zu.AssumeSession}${e}`)(t.info.sessionId)),(e=>{const t=MI[e];t?t.isDevClient?(t.disconnected=!1,t.transport===ed.IPC&&(FI(),BI(e))):AI(`Client with session id ${e} is not a dev client`):AI(`Could not find source client with session id ${e}`)})(t.info.sessionId)}else{Rv.addDevService(e,n,"running");const t=jI(e);t?t.isDevClient=!0:UI({serviceSessionId:e,transport:ed.IPC,send:r,extraInfo:{ipcSocketId:e},isDevClient:!0})}return}zk(`Received manifest from non dev service ${e} [${n.name}@(${n.version})]. Ignoring...`)}};var sE=async e=>{var t;zk("Starting Kemu Hub..."),t=e.desktopMode?"desktop":"runtime",yk=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&&mv.setTracker(e.errorTracker),(e=>{wI={...wI,...e}})({serviceUrl:e.serviceUrl,globalApiKey:e.globalApiKey,environment:e.environment}),qk.registerFunctionsMiddleware(iE),e.secrets?.serviceSecrets&&(e=>{Tk=e})(e.secrets.serviceSecrets.addServiceSecretFn),e.secrets?.recipeSecrets&&((e=>{Ck=e})(e.secrets.recipeSecrets.getRecipeDecryptedSecretsFn),(e=>{$k=e})(e.secrets.recipeSecrets.addRecipeSecretFn),(e=>{Nk=e})(e.secrets.recipeSecrets.deleteRecipeSecretFn),(e=>{Ok=e})(e.secrets.recipeSecrets.getRecipeSecretMappingsFn)),e.secrets?.hubSecrets&&((e=>{Uk=e})(e.secrets.hubSecrets.getHubSecretsFn),(e=>{Lk=e})(e.secrets.hubSecrets.addHubSecretsFn),(e=>{Fk=e})(e.secrets.hubSecrets.deleteHubSecretFn)),qk.registerFunction(Xu.GetServiceContents,bI),qk.registerFunction(Xu.GetServices,mk),qk.registerFunction(Xu.GetSystemInfo,Sk),qk.registerFunction(Xu.ShowHubScreen,(async({args:t,reply:n})=>{const[{screenName:r,context:i}]=t;if(e?.onShowHubScreen)try{await e.onShowHubScreen(r,i),n({success:[]})}catch(t){n({error:`Failed to show hub screen "${r}": ${t}`,errCode:"FAILED_TO_SHOW_HUB_SCREEN"})}else n({error:"This hub does not support showing hub screens",errCode:"FUNCTION_NOT_SUPPORTED"})})),qk.registerFunction(Xu.RestartApp,(({reply:t})=>{e?.onRestartApp?(e.onRestartApp(),t({success:[]})):t({error:"This hub does not support restarting the app",errCode:"FUNCTION_NOT_SUPPORTED"})})),qk.registerFunction(Xu.ExchangeSessionTokenForApiKey,(async({args:t,reply:n})=>{const[{sessionToken:r}]=t;if(e?.onFetchApiKeyFromCode){const t=await e.onFetchApiKeyFromCode({sessionToken:r});n({success:[{success:t.success??!1,error:t.error??void 0}]})}else n({error:"This hub does not support fetching API key from code",errCode:"FUNCTION_NOT_SUPPORTED"})})),qk.registerFunction(Xu.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"})})),qk.registerFunction(Xu.UnsubscribeFromService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===ed.WS){const[e]=n,i=jI(r);if(!i)return t({error:`Session id "${r}" not found`});zk(`Service ${r} unsubscribing from "${e.targetService.serviceName} (${e.targetService.version})"`),t({success:[]}),i?.removeSubscription({serviceName:e.targetService.serviceName,version:e.targetService.version})}})),qk.registerFunction(Xu.SubscribeToService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===ed.WS){const[e]=n,i=jI(r),o=e.targetService;if(!i)return t({error:`Session id "${r}" not found`});if(zk(`Service ${r} subscribing to "${o.serviceName} (${o.version})"`),"hub"===o.serviceName)return i.addSubscription(o),void t({success:[]});if(!i.addSubscription(o))return zk(`Service ${r} already subscribed to "${o.serviceName} (${o.version})", ignoring request.`),t({success:[]});const s=Rv.getMatchingService(o.serviceName,o.version);if(!s)return zk(`Service ${o.serviceName} ${o.version} not active yet`),t({success:[]});if(!s.info.eventEmitter)return zk(`Service ${o.serviceName} ${o.version} does not have an event emitter, removing subscription`),i.removeSubscription(o),t({error:`Service "${o.serviceName} (${o.version})" does not produce events`});const a=jI(s.info.sessionId);return a?.extraInfo.ipcSocketId&&(zk(`Sending Broadcast START command to service ${s.info.sessionId}`),zb(a?.extraInfo.ipcSocketId,Zu.BroadcastStart)),t({success:[]})}})),qk.registerFunction("stopService",iI),qk.registerFunction("removeService",sI),qk.registerFunction("launchService",cI),qk.registerFunction("getMatchingServices",uI),qk.registerFunction("getSecretsValues",fI),qk.registerFunction(Xu.GetMappedSecrets,yI),qk.registerFunction(Xu.BroadcastEvent,Zk),qk.registerFunction(Xu.ServiceManifest,oE),qk.registerFunction(Xu.ChooseDirectoryDialog,YI),qk.registerFunction(Xu.ChooseFileDialog,zI),qk.registerFunction(Xu.GetUniqueId,pk),qk.registerFunction(Xu.SendToRecipe,Xk),qk.registerFunction(Xu.GetDecryptedEdgeApiKey,kk),qk.registerFunction(Xu.GetHubConfig,Ek),qk.registerFunction(Xu.SocketAckResponse,nE),qk.registerFunction(Xu.UninstallService,Ik),qk.registerFunction(Xu.GetRecipeDecryptedSecretsValues,Pk),qk.registerFunction(Xu.GetRecipeSecretMappings,Rk),qk.registerFunction(Xu.AddRecipeSecretMapping,Mk),qk.registerFunction(Xu.DeleteRecipeSecretMapping,Dk),qk.registerFunction(Xu.GetHubSecrets,Wk),qk.registerFunction(Xu.AddHubSecrets,Gk),qk.registerFunction(Xu.DeleteHubSecret,Vk),qk.registerFunction(Xu.AddServiceSecret,jk),Object.entries(Kk).forEach((([e,t])=>{t?qk.registerFunction(e,t):(zk(`Skipping registration of "${e}" because it's not implemented`),qk.registerFunction(e,(({reply:t})=>{t({error:`This hub does not support "${e}"`,errCode:"FUNCTION_NOT_SUPPORTED"})})))})),(e=>{Gb=e})((e=>{const{send:t,transmission:n,json:r}=e;zk(`Raw message Id received from IPC: ${r?.messageId}`),Jk(ed.IPC,e)||qk.processMessage(ed.IPC,t,n,r)})),tI(Qk),Z_(eE),Q_(tE),X_(rE),(e=>{Wb=e})(VI),(e=>{Ub=e})((e=>{const t=(e=>`${Zu.IpcAcknowledge}${e}`)(e);zb(e,t)})),(e=>{Bb=e})((e=>{zk(`IPC socket [${e}] disconnected`);const t=jI(e);if(t){zk(`Found matching service for disconnected socket. SessionId: ${t.serviceSessionId}`);const e=Rv.getServiceBySessionId(t.serviceSessionId);Rv.setServiceStatus(t.serviceSessionId,"stopped"),e?.devMode?(t.disconnected=!0,FI()):WI(t.serviceSessionId)}})),await(e=>(e?.ipcId&&(gb.config.id=e.ipcId),e?.ipcAppSpace&&(gb.config.appspace=e.ipcAppSpace),new Promise((e=>{gb.serve((()=>{Fb.info("IPC Server Initiated"),gb.server.on("data",((e,t)=>{const n=Vb[t.id];n?(Fb.data(`IPC Socket [${t.id}] data ${e.byteLength} bytes`),Hb(e,n.activeMessage,(e=>n.activeMessage=e),(e=>{if(!e.complete)return;const n=e=>{t.write(e)};if(e.command)return Fb.data(`Received command from client [${t.id}]: ${e.command}`),void(Wb&&Wb(t.id,e.command,n));e.klMessage&&Gb&&Gb({send:n,transmission:{sourceServiceId:e.sourceServiceId??-1,targetServiceId:e.targetServiceId??-1,rawMessage:e.rawMessage},json:e.klMessage.json})}))):Fb.data(`Received data from unknown client [${t.id}]. Ignoring.`)})),gb.server.on("connect",(e=>{const t=Qy();Fb.info(`New client connected. Registered as "${t}"`),e.id=t,Vb[t]={socket:e,activeMessage:null,disconnectHandler:()=>Yb(t)},e.on("close",Vb[t].disconnectHandler),Ub&&Ub(t)})),gb.server.on("disconnect",(e=>{Yb(e.id)})),gb.server.on("error",(e=>{console.log(`IPC Server Error: ${e}`)})),e()})),gb.server.start()}))))({ipcAppSpace:n,ipcId:r}),e?.ws?.disabled||await J_(e?.ws?.port||5368);const i=e?.defaultServicesPath||b.resolve(Hk,"defaultServices");Yk=i;const o=process.env.DEV_SESSION_ID;Rv.setHubIpcConfig({recipePath:e?.recipeRootPath,appSpace:n,id:r}),Rv.setEnableServiceLogsConfig(!!e?.enableServiceLogs),e?.servicesInstallPath&&(e=>{uv=e})(e.servicesInstallPath),e?.testServicesInstallPath&&(e=>{dv=e})(e.testServicesInstallPath);const s=hv(),a=fv(),c=async({requiredSecrets:e})=>{const t=Object.keys(e).reduce(((e,t)=>({...e,[t]:process.env[t]})),{});return t.__KEMU_USER_SERVICES_PATH=s,t.__KEMU_USER_TEST_SERVICES_PATH=a,t.__KEMU_SERVICE_URL=SI().serviceUrl,t.__KEMU_ENVIRONMENT=SI().environment,t};e?.getServiceSecretsFn?(Rv.setGetSecretsFunction(e.getServiceSecretsFn),pI(e.getServiceSecretsFn)):(Rv.setGetSecretsFunction(c),pI(c)),(e=>{mI=e})(e?.getMappedSecretsFn?e.getMappedSecretsFn:async e=>e.reduce(((e,t)=>({...e,[t.name]:[]})),{})),Rv.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 Rv.loadServices(i,{fixedSession:o?parseInt(o):void 0,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,internalServices:!0,enableLogs:!0}),null!==e?.servicesInstallPath&&(await lv(s)||await h(s,{recursive:!0}),await Rv.loadServices(s,{internalServices:!1,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,enableLogs:!!e?.enableServiceLogs}));const l=process.env.DEV_NO_SPAWN_LIST?.split(",");await Rv.launchServices({noSpawningList:l||[]}),!1!==e.autoRegisterCleanupHandlers&&(()=>{zk("Registering automatic cleanup handlers for process signals");const e=async e=>{zk(`Received ${e}, cleaning up services...`);try{await Rv.killAllServices(),zk("Services cleaned up successfully"),process.exit(0)}catch(e){zk(`Error during cleanup: ${e}`),process.exit(1)}},t=async e=>{const t=e instanceof Error?e.message:String(e);zk(`Uncaught error: ${t}, cleaning up services...`);try{await Rv.killAllServices(),zk("Services cleaned up after crash")}catch(e){zk(`Error during crash cleanup: ${e}`)}process.exit(1)};process.on("SIGINT",(()=>e("SIGINT"))),process.on("SIGTERM",(()=>e("SIGTERM"))),process.on("uncaughtException",t),process.on("unhandledRejection",(e=>{t(new Error(`Unhandled rejection: ${e}`))}))})(),zk("Kemu Hub started"),(e?.onChooseDirectory||e?.onChooseFile)&&(e=>{HI=e})({chooseDirectory:e.onChooseDirectory,chooseFile:e.onChooseFile})},aE=e=>{if(e===ed.WS)return{handleWebsocketConnectionEvent:eE,handleWebsocketClientDisconnectionEvent:rE,handleWebsocketMessage:Qk,handleWebsocketClientCommand:tE,getRemoteInvoke:()=>qk}},cE=(e=[])=>{let t;const n=new Promise((n=>{const r=()=>{if(Rv.getAllServices().every((e=>"running"===e.status))&&e.every((e=>"running"===Rv.getMatchingService(e.name,e.version)?.status)))return n();t=setTimeout(r,100)};r()}));return n.abort=()=>{t&&clearTimeout(t)},n};const lE=Hl("processManager"),uE=new Set;let dE=!1,hE=[];const fE=()=>{for(const e of uE)if(!e.killed&&e.pid)try{e.kill("SIGTERM")}catch(t){console.error(`Failed to kill process ${e.pid}:`,t)}uE.clear()},pE=e=>{const{onCleanup:t,onEmergencyCleanup:n}=e||{};if(dE){for(const{event:e,handler:t}of hE)process.removeListener(e,t);hE=[],dE=!1}let r=!1,i=!1;const o=async e=>{if(r)lE("Cleanup already in progress, ignoring duplicate signal");else{r=!0;try{if(t)try{await t()}catch(e){console.error("Error during cleanup:",e)}fE(),e&&(await new Promise((e=>{setTimeout((()=>{e()}),100)})),process.exit(0))}finally{r=!1}}},s=async()=>{if(i||r)console.error("Cleanup already in progress, ignoring duplicate error handler");else{i=!0;try{if(n)try{await n()}catch(e){console.error("Error during emergency cleanup:",e)}fE()}finally{i=!1}}};let a=null;const c=(e,t)=>{process.on(e,t),hE.push({event:e,handler:t})};c("SIGINT",(async()=>{lE("Received SIGINT, cleaning up..."),await o("SIGINT")})),c("SIGTERM",(async()=>{lE("Received SIGTERM, cleaning up..."),await o("SIGTERM")})),c("SIGHUP",(async()=>{lE("Received SIGHUP, cleaning up..."),await o("SIGHUP")})),c("uncaughtException",(async e=>{console.error("Uncaught exception:",e),await s(),process.exit(1)})),c("unhandledRejection",(async(e,t)=>{console.error("Unhandled rejection at:",t,"reason:",e),await s(),process.exit(1)})),c("beforeExit",(()=>{a||(a=(async()=>{if(t)try{await t()}catch(e){console.error("Error during cleanup:",e)}fE()})(),a.catch((e=>{console.error("Error in beforeExit handler:",e),fE()})))})),dE=!0};let gE;const mE=Hl("run"),yE=rd(),vE=1e3,bE=v(process.argv.slice(2)),wE=e=>"number"==typeof e?{type:me.Number,value:e}:"string"==typeof e?{type:me.String,value:e}:"boolean"==typeof e?{type:me.Boolean,value:e}:Array.isArray(e)?{type:me.Array,value:e}:e;global.ImageData=q;const SE=e=>e&&"string"==typeof e.format&&e.data&&e.data instanceof ArrayBuffer;ke({createCanvas:(e,t)=>J(e,t),loadImage:async e=>{let t=e;if(SE(e)){const n=e;t=Buffer.from(n.data)}const n=await K(t),r=J(n.width,n.height).getContext("2d");r.drawImage(n,0,0,n.width,n.height);return r.getImageData(0,0,n.width,n.height)}});const _E=(e,t)=>"*"===e?ho.onAnyGlobalVariableChange(t):ho.onGlobalVariableChange(e,t),IE=(e,t,n)=>ho.setGlobalVariable({name:e,value:t,disableChangeNotifications:n?.disableChangeNotifications||!1,disableDefineNotifications:n?.disableDefineNotifications||!1,doNotOverrideExisting:n?.doNotOverrideExisting||!1}),xE=e=>{ho.deleteGlobalVariable({name:e})},kE=()=>ho.getAllVariables(),EE=e=>ho.getGlobalVariable(e),CE=e=>Yi(e),$E=e=>async()=>{throw new Error(`${e} not implemented`)},NE={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:me.ImageData}},loadImageFile:async e=>{const t=await K(e),n=J(t.width,t.height).getContext("2d");n.drawImage(t,0,0,t.width,t.height);return n.getImageData(0,0,t.width,t.height)},encodeImageData:async(e,t="jpeg",n)=>{const r=J(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 OE={start:async r=>{r=r||{};const i=r?.runtimeCommand?.trim()||process.env.KEMU_EDGE_RUNTIME_COMMAND?.trim(),o=r?.recipePath||bE.recipePath||process.env.KEMU_EDGE_RECIPE_PATH||process.cwd();if(!o)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].");const s=o.endsWith(".json")||o.endsWith(".kemu"),a=s?H(o):o,c=s?o:Y(a,"recipe.kemu"),{parsed:l,error:u}=await e({path:Y(z(a),".env")});u&&console.warn(`Failed to load .env file: ${u.message}. This is not an error, it just means that the .env file is not present or is not readable.`);const d=r.apiKey||process.env.KEMU_API_KEY,h=process.env.KEMU_CONFIG;if(!d)throw new Error("Missing API key. Please provide it via config.apiKey or KEMU_API_KEY environment variable.");if(r.envConfig){const{serviceUrl:e,environment:t}=r.envConfig;if(!e||!t)throw new Error("Missing server URL or environment in config.envConfig")}else if(!h)throw new Error("Missing server URL or environment in config.envConfig");const f=(e=>{try{return JSON.parse(e||"")}catch(e){return null}})(await t(z(c),"utf-8"));if(!f)throw new Error("Failed to parse recipe file");if(!f.author?.id)throw new Error("Missing required author ID in recipe file.");const{serviceUrl:p,environment:g}=r.envConfig||(e=>{const t=Buffer.from(e,"base64").toString("utf8"),[n,r]=t.split("<@>");if(!n||!r)throw new Error("Invalid configuration.");return{serviceUrl:n,environment:r}})(h);await vc();const m={id:f.uuid||String(Date.now()),version:1,author:f.author.id};(e=>{yo=e})(console);const y=aE(_e.WS),v=(e,t)=>{if(t)y?.handleWebsocketMessage({send:w,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg?.json});else{const t=e instanceof Buffer?e.toString():e;y?.handleWebsocketClientCommand(vE,t)}},b=(Tl={instanceServiceId:vE,sendBuf:v,sendCmd:v,triggerOnCommand:(...e)=>Al(...e),triggerOnConnected:()=>Pl(),triggerOnDisconnected:()=>Ml(),triggerOnMessageReceived:(...e)=>Dl(...e)},Tl);const w=(e,t)=>{if(t)b.triggerOnMessageReceived({send:v,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg.json});else{const t=e instanceof Buffer?e.toString():e;b.triggerOnCommand(t)}},S=od(),_=y.getRemoteInvoke();S.disableServiceEncoding(0,!0),_.disableServiceEncoding(vE,!0);const I=Object.values(f.blocks[pe].gates).filter((e=>e.type===Je.hubService&&e.state.service&&!0!==e.state.service?.webOnly)),x=I.map((e=>{const t=e.state.service;return{name:t.name,version:t.version}})),k=Y(a,"services"),E=await n(k).then((()=>!0)).catch((()=>!1));if(x.length>0&&!E)throw new Error("Services directory not found but required services are defined in the recipe. Please make sure there is a `services` directory in the recipe root and add the services you want to use to it.");pE();await sE({globalApiKey:d,serviceUrl:p,spawnFn:i?({args:e,options:t,serviceInfo:n})=>{if(!i)throw new Error("Runtime command not provided. Please specify it in the config object, via a command line argument [--runtimeCommand] or as an environment variable [KEMU_EDGE_RUNTIME_COMMAND].");console.log(`Spawning service: "${n.name}" with command: "${i} ${e?.join(" ")}"`);const r=i.split(" ").filter(Boolean),o=Z(r[0],r.slice(1).concat(e||[]),{...t,env:{...process.env,...t?.env}});return(e=>{uE.add(e),e.on("exit",(()=>{uE.delete(e)}))})(o),o}:null,recipeRootPath:a,servicesInstallPath:E?Y(a,"services"):null,noDefaultServices:!0,environment:g,ws:{disabled:!0},secrets:{recipeSecrets:{getRecipeDecryptedSecretsFn:async()=>({...l}),getRecipeSecretMappingsFn:$E("getRecipeSecretMappingsFn"),addRecipeSecretFn:$E("addRecipeSecretFn"),deleteRecipeSecretFn:$E("deleteRecipeSecretFn")}},ipc:{appSpace:"kemu-runner.",id:m.id}}),mE("Waiting for services to run"),await cE(x),mE("All services are running"),el(yE),il(),Ia.onGlobalProcessingStateChange((e=>{mE("Global processing state changed: ",e)})),f.globalVariables&&(f.globalVariables=await sl(f.globalVariables));const C=await Zc(f,"runner",m.version,m.author,wr.Desktop);return gE=C,pE({onCleanup:async()=>{gE&&await Xc(gE)},onEmergencyCleanup:async()=>{gE&&await Xc(gE)}}),id(C),await td({id:f.author.id}),new Promise(((e,t)=>{var n;nd("acknowledged",(async()=>{await yE.getServices();const{failed:n,sendToInputWidget:r,invokeRecipeLoadedWidgets:i}=await Qc(C);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)})),mE("Recipe started"),e({sendToInputWidgetAndWaitForOutput:(e,t)=>{const n=wE(t);return r({inputName:e,data:n,waitForOutputChild:!0})},sendToInputWidget:(e,t)=>{const n=wE(t);return r({inputName:e,data:n,waitForOutputChild:!1})},globalVariables:{onChange:_E,setValue:IE,getValue:EE,delete:xE,getAll:kE},status:{onChange:CE},edgeFunctions:{register:Za.registerFunctionHandler,unregister:Za.unregisterFunctionHandler,clearAll:Za.clearAllHandlers}})})),b.triggerOnConnected(),b.triggerOnCommand((n=vE,`${be.SocketAcknowledge}${n}`))}))},terminate:async()=>{gE&&await Xc(gE),fE()}};export{me as DataType,OE as default,SE as isBinaryFile,NE 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=Ax,n=JI;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=48,o=57,s=65,a=70,c=97,l=102;function u(e){return e>=i&&e<=o?e-i:e>=s&&e<=a?e-(s-10):e>=c&&e<=l?e-(c-10):void 0}function d(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}function h(e){return"string"==typeof e&&(e=d(e)),(0,n.bytes)(e),e}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=u(e.charCodeAt(i)),o=u(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},e.nextTick=async()=>{},e.asyncLoop=async function(t,n,r){let i=Date.now();for(let o=0;o<t;o++){r(o);const t=Date.now()-i;t>=0&&t<n||(await(0,e.nextTick)(),i+=t)}},e.utf8ToBytes=d,e.toBytes=h,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 f={}.toString;e.checkOpts=function(e,t){if(void 0!==t&&"[object Object]"!==f.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(h(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(h(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(h(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")}}(Tx),Object.defineProperty(KI,"__esModule",{value:!0}),KI.shake256=KI.shake128=KI.keccak_512=KI.keccak_384=KI.keccak_256=KI.keccak_224=KI.sha3_512=KI.sha3_384=KI.sha3_256=KI.sha3_224=KI.Keccak=KI.keccakP=void 0;const Px=JI,Mx=ox,Dx=Tx,Rx=[],jx=[],Lx=[],Fx=BigInt(0),Ux=BigInt(1),Bx=BigInt(2),Wx=BigInt(7),Gx=BigInt(256),Vx=BigInt(113);for(let e=0,t=Ux,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],Rx.push(2*(5*r+n)),jx.push((e+1)*(e+2)/2%64);let i=Fx;for(let e=0;e<7;e++)t=(t<<Ux^(t>>Wx)*Vx)%Gx,t&Bx&&(i^=Ux<<(Ux<<BigInt(e))-Ux);Lx.push(i)}const[Hx,Yx]=(0,Mx.split)(Lx,!0),zx=(e,t,n)=>n>32?(0,Mx.rotlBH)(e,t,n):(0,Mx.rotlSH)(e,t,n),qx=(e,t,n)=>n>32?(0,Mx.rotlBL)(e,t,n):(0,Mx.rotlSL)(e,t,n);function Kx(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,o=n[i],s=n[i+1],a=zx(o,s,1)^n[r],c=qx(o,s,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=jx[n],o=zx(t,i,r),s=qx(t,i,r),a=Rx[n];t=e[a],i=e[a+1],e[a]=o,e[a+1]=s}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]^=Hx[r],e[1]^=Yx[r]}n.fill(0)}KI.keccakP=Kx;class Jx extends Dx.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,Px.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,Dx.u32)(this.state)}keccak(){Dx.isLE||(0,Dx.byteSwap32)(this.state32),Kx(this.state32,this.rounds),Dx.isLE||(0,Dx.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,Px.exists)(this);const{blockLen:t,state:n}=this,r=(e=(0,Dx.toBytes)(e)).length;for(let i=0;i<r;){const o=Math.min(t-this.pos,r-i);for(let t=0;t<o;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,Px.exists)(this,!1),(0,Px.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 o=Math.min(n-this.posOut,i-r);e.set(t.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}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,Px.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,Px.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:o}=this;return e||(e=new Jx(t,n,r,o,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=o,e.destroyed=this.destroyed,e}}KI.Keccak=Jx;const Zx=(e,t,n)=>(0,Dx.wrapConstructor)((()=>new Jx(t,e,n)));KI.sha3_224=Zx(6,144,28),KI.sha3_256=Zx(6,136,32),KI.sha3_384=Zx(6,104,48),KI.sha3_512=Zx(6,72,64),KI.keccak_224=Zx(1,144,28),KI.keccak_256=Zx(1,136,32),KI.keccak_384=Zx(1,104,48),KI.keccak_512=Zx(1,72,64);const Xx=(e,t,n)=>(0,Dx.wrapXOFConstructorWithOpts)(((r={})=>new Jx(t,e,void 0===r.dkLen?n:r.dkLen,!0)));KI.shake128=Xx(31,168,16),KI.shake256=Xx(31,136,32);const{sha3_512:Qx}=KI,ek=(e=4,t=Math.random)=>{let n="";for(;n.length<e;)n+=Math.floor(36*t()).toString(36);return n};function tk(e){let t=0n;for(const n of e.values())t=(t<<8n)+BigInt(n);return t}const nk=(e="")=>tk(Qx(e)).toString(36).slice(1),rk=Array.from({length:26},((e,t)=>String.fromCharCode(t+97))),ik=({globalObj:e=(void 0!==vd?vd:"undefined"!=typeof window?window:{}),random:t=Math.random}={})=>{const n=Object.keys(e).toString(),r=n.length?n+ek(32,t):ek(32,t);return nk(r).substring(0,32)},ok=e=>()=>e++,sk=({random:e=Math.random,counter:t=ok(Math.floor(476782367*e())),length:n=24,fingerprint:r=ik({random:e})}={})=>function(){const i=(e=>rk[Math.floor(e()*rk.length)])(e),o=Date.now().toString(36),s=t().toString(36),a=ek(n,e);return`${i+nk(`${o+a+s+r}`).substring(1,n)}`},ak=sk();qI.getConstants=()=>({defaultLength:24,bigLength:32}),qI.init=sk,qI.createId=ak,qI.bufToBigInt=tk,qI.createCounter=ok,qI.createFingerprint=ik,qI.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:ck,init:lk,getConstants:uk,isCuid:dk}=qI;var hk=ck;const fk=Rd("getUniqueId"),pk=({reply:e,sourceServiceId:t})=>(fk(`Generating unique id for service "${t}"`),e({success:[hk()]})),gk=Rd("getActiveServices"),mk=async({transport:e,sourceServiceId:t,reply:n})=>{if(gk(`Received GetServices request from ${e} [${t}]`),e===ed.WS){let e=Rv.getActiveServices();const r=jI(t);if(!r)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});let i=[];if(r.transport===ed.WS){const t=e.filter(Rv.isInternalKemuService);gk("internalServices",t);const n=e.filter((e=>e.devMode&&Rv.isNotInternalKemuService(e)));gk("devServices",n);const o=e.filter((e=>Rv.isOfficialKemuService(e)&&Rv.isNotInternalKemuService(e)&&Rv.isNotDevService(e))).sort(((e,t)=>e.name.localeCompare(t.name)));gk("kemuServices",o);const s=e.filter((e=>Rv.isNotDevService(e)&&Rv.isNotInternalKemuService(e)&&!Rv.isOfficialKemuService(e))),a=SI();gk("userCustomServices",s);let c=null;a.globalApiKey?(gk("Fetching license features..."),c=await(async(e,t)=>{const{features:n}=await(async e=>{const{apiKey:t,recipePoolId:n}=e,r=$I(n);if(r)return{valid:!0,features:r,error:null};const{valid:i,features:o,error:s}=await kI(t);return i&&(EI[n]={features:o,lastCheckedAt:new Date}),{valid:i,features:o,error:s}})({apiKey:e,recipePoolId:t});return n})(a.globalApiKey,r.extraInfo.recipe?.poolId),gk("features",c)):(gk("Fetching free license features..."),c=await(async e=>{const t=$I(e);if(t)return t;const n=CI[e];if(n)return await n;const r=(async()=>{try{const{features:t}=await kI("free");return EI[e]={features:t,lastCheckedAt:new Date},t}finally{delete CI[e]}})();return CI[e]=r,await r})(r.extraInfo.recipe?.poolId),gk("features",c));const l=c?.hub_services??0,u=o.slice(0,-1!==l?l:o.length);-1!==l&&(i=o.slice(l).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,...n,...u,...s]}const o=Rv.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:Rv.isInternalKemuService(e),svgIcon:e.svgIcon,color:e.color,shortTitle:e.shortTitle}))),s={available:e.map((e=>{const{widgetUIContents:t,...n}=e;return{...n}})),failed:o,installed:i};gk("response",s),n({success:[s]})}};let yk="runtime",vk=null;const bk=()=>yk,wk=Rd("getSystemInfo"),Sk=async({reply:e})=>{wk("Received GetSystemInfo request"),e({success:[await(async()=>{const e=SI().globalApiKey;return{platformArch:ad(),isDesktopHub:"desktop"===bk(),isRuntimeHub:"runtime"===bk(),hubVersion:rv,hasValidApiKeyConfigured:!!e,...vk?{updateAvailable:vk}:{}}})()]})},_k=Rd("removeService"),Ik=async({args:e,sourceServiceId:t,reply:n})=>{const r=e[0],i=r.serviceName,o=r.version;if(!i)return n({error:"No service name provided"});if(!o)return n({error:"No service version provided"});const s=Rv.getAllServiceVersions(i),a=s.find((e=>e.info.version===o));if(!a)return n({error:"Service not found"});_k(`Removing ${s.length} service(s) with name: ${i}`);const c=a.info.publicationId;let l;if(await Rv.uninstallService(a.info.name,a.info.version),c){if(!jI(t))return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});const e=SI();if(!e.globalApiKey)return n({error:"Global API key is not set",errCode:"GLOBAL_API_KEY_NOT_SET"});const r=e.globalApiKey;_k(`Updating license details for "${c}"`);const i=await(async e=>{const{data:t,error:n}=await xI(`${II()}/v1/organization/validate/uninstall_hub_service`,e,{"Content-Type":"application/json"});if(n)throw new Error(n);return t})({apiKey:r,hubService:{id:c}}).catch((e=>(_k(`Error updating license details for "${c}": ${e}`),{error:e.message,remaining:void 0})));l=i?.remaining}n({success:[{remaining:l,service:{name:i,version:o}}]})},xk=Rd("getDecryptedEdgeApiKey"),kk=({reply:e})=>(xk("Getting decrypted edge API key"),e({success:[SI().globalApiKey]})),Ek=({reply:e})=>{xk("Getting hub config");const t=SI();return e({success:[{kemuApiKey:t.globalApiKey,environment:t.environment}]})};let Ck,$k,Nk,Ok,Tk;const Ak=e=>e.transport===ed.IPC&&(e.reply({error:"Transport is not allowed to call this function"}),!0);var Pk=async e=>{const t=e.args,n=t[0].recipeUuid,r=t[0].secretNames;if(!r||!n)return e.reply({error:"Invalid request parameters"});if(!Ck)return e.reply({error:"Get recipe secrets function not set"});const i=await Ck({...t[0]}),o={};for(const e of r)o[e]=e in i?i[e]:null;const s=[{secrets:o}];e.reply({success:s})},Mk=async e=>{const t=e.args,n=t[0].recipeUuid,r=t[0].secretsMap;if(Ak(e))return;if(!$k)return e.reply({error:"Add recipe secret mapping function not set"});if(!r||!n)return e.reply({error:"Invalid request parameters"});const i=[{secrets:await $k({recipeUuid:n,secretsMap:r})}];e.reply({success:i})},Dk=async e=>{const t=e.args,n=t[0].recipeUuid,r=t[0].secretName;if(Ak(e))return;if(!Nk)return e.reply({error:"Delete recipe secret mapping function not set"});if(!r||!n)return e.reply({error:"Invalid request parameters"});const i=[{secrets:await Nk({recipeUuid:n,secretName:r})}];e.reply({success:i})},Rk=async e=>{const t=e.args[0].recipeUuid;if(!Ok)return e.reply({error:"Get recipe secret mappings function not set"});if(!t)return e.reply({error:"Invalid request parameters"});const n=[{secrets:await Ok({recipeUuid:t})}];e.reply({success:n})},jk=async e=>{const t=e.args,n=t[0].hubServiceName,r=t[0].secrets;return Tk?n&&r?Array.isArray(r)?(await Tk({hubServiceName:n,secrets:r}),void e.reply({success:[]})):e.reply({error:'Expected "secrets" to be an array'}):e.reply({error:"Invalid request parameters"}):e.reply({error:"Add service secret function not set"})};let Lk,Fk,Uk;const Bk=e=>e.transport===ed.IPC&&(e.reply({error:"You are not allowed to manage secrets using this transport"}),!0);var Wk=async e=>{if(e.args,Bk(e))return;if(!Uk)return e.reply({error:"Get hub secrets function not set"});const t=[{contexts:await Uk()}];e.reply({success:t})},Gk=async e=>{const t=e.args;if(Bk(e))return;if(!Lk)return e.reply({error:"Add hub secret function not set"});const n=[{contexts:await Lk(t[0])}];e.reply({success:n})},Vk=async e=>{const t=e.args;if(Bk(e))return;if(!Fk)return e.reply({error:"Delete hub secret function not set"});const n=[{contexts:await Fk(t[0])}];e.reply({success:n})};const Hk=S(W(import.meta.url));let Yk=null;const zk=Rd("hub"),qk=new function(){const e={};let t,n=console.log;const r={};let i="hub";const o={},s=e=>!o[e],a=(e,t,n,r,i,o)=>{let a=vb?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:o.success?o.success:[o],messageId:t,type:o.success?"response":"error"}};return s(r)&&(a=Zb.encode(c,n,r)),i(a,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{n=e},processMessage:(i,o,s,c)=>{if(!c)return!1;const l=c;if(e[l.messageId]){const t=e[l.messageId];return t&&(clearTimeout(t.timer),t.fulfilled||(t.fulfilled=!0,"response"===l.type?t.resolve(l.args):"error"===l.type&&t.reject(l.args[0])),delete e[l.messageId]),!0}if("execute"!==l.type&&n&&n(`No pending execution found for message id "${l.messageId}"`),"execute"===l.type){const e=r[l.functionName];if(e){const r=e=>{a(l.functionName,l.messageId,s.targetServiceId,s.sourceServiceId,o,e)};if(t&&!t({args:l.args,functionName:l.functionName,transport:i,messageId:l.messageId,sourceServiceId:s.sourceServiceId,reply:r,send:o}))return n&&n(`Function "${l.functionName}" not allowed to be invoked by client [${s.sourceServiceId}]`),r({error:"Function not allowed",errCode:"FNC_NOT_ALLOWED"}),!0;e({transport:i,args:l.args,reply:r,messageId:l.messageId,sourceServiceId:s.sourceServiceId,send:o})}else{const e=`Function "${l.functionName}" not found.`;n&&n(e),a(l.functionName,l.messageId,s.targetServiceId,s.sourceServiceId,o,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(t,r,o,a,c,l)=>{if(!o){const e="No send buffer function provided.";throw n&&n(e),e}Xb+=1;const u=`${i}-${Xb}-exec-${t.substring(0,10)}`,d={messageId:u,functionName:t,send:o,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};d.promise=new Promise(((e,t)=>{d.resolve=e,d.reject=t}));let h=vb?new ArrayBuffer(0):Buffer.alloc(0);const f={json:{functionName:t,args:r,messageId:u,type:"execute"}};s(c)&&(h=Zb.encode(f,a,c)),e[u]=d,n&&n(`Calling remote function "${t}" with message id "${u}"`);const p="true"===process.env.NO_INVOKE_TIMEOUT;return l?.async?(d.fulfilled=!0,d.resolve([void 0]),delete e[u]):0===l?.timeout||p||(d.timer=setTimeout((()=>{n&&n(`Remote function ${u} timed out`);const r=e[u];r&&!r.fulfilled&&(r.fulfilled=!0,d.reject(`Function ${t} Timed out`)),delete e[u]}),l?.timeout||3e4)),o(h,{sourceServiceId:a,targetServiceId:c,msg:f}),d.promise},sendResponse:a,registerFunction:(e,t)=>{r[e]=t},registerFunctionsMiddleware:e=>{t=e},unregisterAllFunctions:()=>{Object.keys(r).forEach((e=>{delete r[e]}))},getTransportSendFunction:t=>{const n=e[t];return n?n.send:null},setServiceName:e=>{i=e},getPendingExecutions:()=>e,rejectAllPending:t=>{Object.keys(e).forEach((n=>{const r=e[n];r&&!r.fulfilled&&(clearTimeout(r.timer),r.fulfilled=!0,r.reject(t),delete e[n])}))},broadcast:(e,t,r,o)=>{Xb+=1;const a=`${i}-${Xb}-multicast-${e.substring(0,10)}`;let c=vb?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:t,messageId:a,type:"execute"}};let u=s(r[0].serviceId);u&&(c=Zb.encode(l,o,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=s(i.serviceId),u&&(c=Zb.patchEncodedHeader(c,{toServiceId:i.serviceId}))),i.sendFn(c,{msg:l,sourceServiceId:o,targetServiceId:i.serviceId})}catch(e){n&&n(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{o[e]=t}}}("hub");PI=qk,qk.setLogger(zk);const Kk={[Xu.RebootToInstallUpdate]:null,[Xu.GetFileContentFromCacheId]:null,[Xu.SaveRecipeToFile]:null},Jk=(e,t)=>{const{transmission:n}=t;if(0!==n.targetServiceId){const r=jI(n.targetServiceId);if(!r)return zk(`Service [${e}] ${n.sourceServiceId} is sending data to an unknown service ["${n.targetServiceId}"]`),!0;r.transport,ed.IPC;const i=t.json?.messageId;return zk(`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},Zk=({sourceServiceId:e,args:t})=>{const n=Rv.getServiceBySessionId(e);if(n){const r=LI(n.info.name,n.info.version),i=LI(n.info.name,"*");if(!r.length&&!i.length)return;const o=[...r,...i],s={...t[0],source:{serviceName:n.info.name,serviceVersion:n.info.version,sessionId:e}};qk.broadcast(Xu.BroadcastEvent,[s],o,0)}},Xk=async({args:e,reply:t})=>{const n=e[0];if(!n)return zk("Invalid config for SendToRecipe"),t({error:"Invalid config for SendToRecipe"});const r=(i=n.recipePoolId,Object.values(MI).find((e=>e.extraInfo.recipe?.poolId===i))||null);var i;if(!r)return zk(`No client found for recipe pool id ${n.recipePoolId}`),t({error:`No client found for recipe pool id "${n.recipePoolId}"`});try{const e=qk.execute(Xu.SendToRecipe,[n],r.send,0,r.serviceSessionId,{async:!n.waitForResponse,timeout:n.timeout});n.waitForResponse?t({success:await e}):t({success:[]})}catch(e){return zk(`Error sending to recipe ${n.recipePoolId}: ${e?.message||e}`),t({error:e?.message||"There was an error sending to the recipe"})}},Qk=e=>{const{send:t,transmission:n,json:r}=e;zk(`Raw message Id received from WS: ${r?.messageId}`),Jk(ed.WS,e)||qk.processMessage(ed.WS,t,n,r)},eE=e=>{const t=(n=e,`${Zu.SocketAcknowledge}${n}`);var n;eI(e,t)},tE=(e,t)=>{zk(`Received unknown command [${t}] from service ${e}`)},nE=async e=>{const{args:t,sourceServiceId:n,send:r,reply:i}=e,o=n,s=t[0];s.user?.id&&mv.setGlobalUserId(s.user?.id),await UI({serviceSessionId:n,transport:ed.WS,send:r,terminateFn:()=>{nI(n)},extraInfo:{websocketId:o,recipe:s.recipe,user:{userEmail:s.user?.email,userId:s.user?.id}}}),i({success:[]})},rE=e=>{zk(`WS Client ${e} disconnected`),WI(e)},iE=e=>{if(1===e.sourceServiceId)return e.functionName===Xu.GetFileContentFromCacheId;if(e.functionName===Xu.GetHubConfig){const t=Rv.getServiceBySessionId(e.sourceServiceId);if(!t||!Rv.isOfficialKemuService(t.info)&&Rv.isNotDevService(t.info))return zk(`Service "${e.sourceServiceId}" attempting to get hub config but is not an official Kemu service`),!1}return e.functionName===Xu.SocketAckResponse||e.functionName===Xu.ServiceManifest||e.functionName===Xu.SubscribeToService||(!!jI(e.sourceServiceId)||(e.reply({error:`Session id "${e.sourceServiceId}" not found. Please acknowledge the session first.`}),!1))},oE=async({sourceServiceId:e,args:t,transport:n,send:r})=>{if(n!==ed.IPC){var i;zk(`Received manifest from non IPC service ${e}.`)}else{const n=t[0];if(n.devMode){const t=Rv.getMatchingDevService(n.name,n.version,"stopped");if(t){zk(`Found matching previous service ${t.info.name} (${t.info.version}). Reactivating previous client with session id ${t.info.sessionId}`);const o=jI(t.info.sessionId);if(!o)return void zk(`Could not find previous client instance for ${t.info.name} (${t.info.version}). Aborting manifest injection`);o.send=r,MI[i=e]?delete MI[i]:AI(`Could not find source client with session id ${i}`),qb(e,t.info.sessionId);const s=await cv(n,n.path);t.info={...t.info,...s},zk(`Updating manifest for dev service ${t.info.sessionId}`),Rv.setServiceManifest(t.info.sessionId,s,"running"),zk(`Asking service ${e} to assume previous session id ${t.info.sessionId}`),zb(t.info.sessionId,(e=>`${Zu.AssumeSession}${e}`)(t.info.sessionId)),(e=>{const t=MI[e];t?t.isDevClient?(t.disconnected=!1,t.transport===ed.IPC&&(FI(),BI(e))):AI(`Client with session id ${e} is not a dev client`):AI(`Could not find source client with session id ${e}`)})(t.info.sessionId)}else{Rv.addDevService(e,n,"running");const t=jI(e);t?t.isDevClient=!0:UI({serviceSessionId:e,transport:ed.IPC,send:r,extraInfo:{ipcSocketId:e},isDevClient:!0})}return}zk(`Received manifest from non dev service ${e} [${n.name}@(${n.version})]. Ignoring...`)}};var sE=async e=>{var t;zk("Starting Kemu Hub..."),t=e.desktopMode?"desktop":"runtime",yk=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&&mv.setTracker(e.errorTracker),(e=>{wI={...wI,...e}})({serviceUrl:e.serviceUrl,globalApiKey:e.globalApiKey,environment:e.environment}),qk.registerFunctionsMiddleware(iE),e.secrets?.serviceSecrets&&(e=>{Tk=e})(e.secrets.serviceSecrets.addServiceSecretFn),e.secrets?.recipeSecrets&&((e=>{Ck=e})(e.secrets.recipeSecrets.getRecipeDecryptedSecretsFn),(e=>{$k=e})(e.secrets.recipeSecrets.addRecipeSecretFn),(e=>{Nk=e})(e.secrets.recipeSecrets.deleteRecipeSecretFn),(e=>{Ok=e})(e.secrets.recipeSecrets.getRecipeSecretMappingsFn)),e.secrets?.hubSecrets&&((e=>{Uk=e})(e.secrets.hubSecrets.getHubSecretsFn),(e=>{Lk=e})(e.secrets.hubSecrets.addHubSecretsFn),(e=>{Fk=e})(e.secrets.hubSecrets.deleteHubSecretFn)),qk.registerFunction(Xu.GetServiceContents,bI),qk.registerFunction(Xu.GetServices,mk),qk.registerFunction(Xu.GetSystemInfo,Sk),qk.registerFunction(Xu.ShowHubScreen,(async({args:t,reply:n})=>{const[{screenName:r,context:i}]=t;if(e?.onShowHubScreen)try{await e.onShowHubScreen(r,i),n({success:[]})}catch(t){n({error:`Failed to show hub screen "${r}": ${t}`,errCode:"FAILED_TO_SHOW_HUB_SCREEN"})}else n({error:"This hub does not support showing hub screens",errCode:"FUNCTION_NOT_SUPPORTED"})})),qk.registerFunction(Xu.RestartApp,(({reply:t})=>{e?.onRestartApp?(e.onRestartApp(),t({success:[]})):t({error:"This hub does not support restarting the app",errCode:"FUNCTION_NOT_SUPPORTED"})})),qk.registerFunction(Xu.ExchangeSessionTokenForApiKey,(async({args:t,reply:n})=>{const[{sessionToken:r}]=t;if(e?.onFetchApiKeyFromCode){const t=await e.onFetchApiKeyFromCode({sessionToken:r});n({success:[{success:t.success??!1,error:t.error??void 0}]})}else n({error:"This hub does not support fetching API key from code",errCode:"FUNCTION_NOT_SUPPORTED"})})),qk.registerFunction(Xu.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"})})),qk.registerFunction(Xu.UnsubscribeFromService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===ed.WS){const[e]=n,i=jI(r);if(!i)return t({error:`Session id "${r}" not found`});zk(`Service ${r} unsubscribing from "${e.targetService.serviceName} (${e.targetService.version})"`),t({success:[]}),i?.removeSubscription({serviceName:e.targetService.serviceName,version:e.targetService.version})}})),qk.registerFunction(Xu.SubscribeToService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===ed.WS){const[e]=n,i=jI(r),o=e.targetService;if(!i)return t({error:`Session id "${r}" not found`});if(zk(`Service ${r} subscribing to "${o.serviceName} (${o.version})"`),"hub"===o.serviceName)return i.addSubscription(o),void t({success:[]});if(!i.addSubscription(o))return zk(`Service ${r} already subscribed to "${o.serviceName} (${o.version})", ignoring request.`),t({success:[]});const s=Rv.getMatchingService(o.serviceName,o.version);if(!s)return zk(`Service ${o.serviceName} ${o.version} not active yet`),t({success:[]});if(!s.info.eventEmitter)return zk(`Service ${o.serviceName} ${o.version} does not have an event emitter, removing subscription`),i.removeSubscription(o),t({error:`Service "${o.serviceName} (${o.version})" does not produce events`});const a=jI(s.info.sessionId);return a?.extraInfo.ipcSocketId&&(zk(`Sending Broadcast START command to service ${s.info.sessionId}`),zb(a?.extraInfo.ipcSocketId,Zu.BroadcastStart)),t({success:[]})}})),qk.registerFunction("stopService",iI),qk.registerFunction("removeService",sI),qk.registerFunction("launchService",cI),qk.registerFunction("getMatchingServices",uI),qk.registerFunction("getSecretsValues",fI),qk.registerFunction(Xu.GetMappedSecrets,yI),qk.registerFunction(Xu.BroadcastEvent,Zk),qk.registerFunction(Xu.ServiceManifest,oE),qk.registerFunction(Xu.ChooseDirectoryDialog,YI),qk.registerFunction(Xu.ChooseFileDialog,zI),qk.registerFunction(Xu.GetUniqueId,pk),qk.registerFunction(Xu.SendToRecipe,Xk),qk.registerFunction(Xu.GetDecryptedEdgeApiKey,kk),qk.registerFunction(Xu.GetHubConfig,Ek),qk.registerFunction(Xu.SocketAckResponse,nE),qk.registerFunction(Xu.UninstallService,Ik),qk.registerFunction(Xu.GetRecipeDecryptedSecretsValues,Pk),qk.registerFunction(Xu.GetRecipeSecretMappings,Rk),qk.registerFunction(Xu.AddRecipeSecretMapping,Mk),qk.registerFunction(Xu.DeleteRecipeSecretMapping,Dk),qk.registerFunction(Xu.GetHubSecrets,Wk),qk.registerFunction(Xu.AddHubSecrets,Gk),qk.registerFunction(Xu.DeleteHubSecret,Vk),qk.registerFunction(Xu.AddServiceSecret,jk),Object.entries(Kk).forEach((([e,t])=>{t?qk.registerFunction(e,t):(zk(`Skipping registration of "${e}" because it's not implemented`),qk.registerFunction(e,(({reply:t})=>{t({error:`This hub does not support "${e}"`,errCode:"FUNCTION_NOT_SUPPORTED"})})))})),(e=>{Gb=e})((e=>{const{send:t,transmission:n,json:r}=e;zk(`Raw message Id received from IPC: ${r?.messageId}`),Jk(ed.IPC,e)||qk.processMessage(ed.IPC,t,n,r)})),tI(Qk),Z_(eE),Q_(tE),X_(rE),(e=>{Wb=e})(VI),(e=>{Ub=e})((e=>{const t=(e=>`${Zu.IpcAcknowledge}${e}`)(e);zb(e,t)})),(e=>{Bb=e})((e=>{zk(`IPC socket [${e}] disconnected`);const t=jI(e);if(t){zk(`Found matching service for disconnected socket. SessionId: ${t.serviceSessionId}`);const e=Rv.getServiceBySessionId(t.serviceSessionId);Rv.setServiceStatus(t.serviceSessionId,"stopped"),e?.devMode?(t.disconnected=!0,FI()):WI(t.serviceSessionId)}})),await(e=>(e?.ipcId&&(gb.config.id=e.ipcId),e?.ipcAppSpace&&(gb.config.appspace=e.ipcAppSpace),new Promise((e=>{gb.serve((()=>{Fb.info("IPC Server Initiated"),gb.server.on("data",((e,t)=>{const n=Vb[t.id];n?(Fb.data(`IPC Socket [${t.id}] data ${e.byteLength} bytes`),Hb(e,n.activeMessage,(e=>n.activeMessage=e),(e=>{if(!e.complete)return;const n=e=>{t.write(e)};if(e.command)return Fb.data(`Received command from client [${t.id}]: ${e.command}`),void(Wb&&Wb(t.id,e.command,n));e.klMessage&&Gb&&Gb({send:n,transmission:{sourceServiceId:e.sourceServiceId??-1,targetServiceId:e.targetServiceId??-1,rawMessage:e.rawMessage},json:e.klMessage.json})}))):Fb.data(`Received data from unknown client [${t.id}]. Ignoring.`)})),gb.server.on("connect",(e=>{const t=Qy();Fb.info(`New client connected. Registered as "${t}"`),e.id=t,Vb[t]={socket:e,activeMessage:null,disconnectHandler:()=>Yb(t)},e.on("close",Vb[t].disconnectHandler),Ub&&Ub(t)})),gb.server.on("disconnect",(e=>{Yb(e.id)})),gb.server.on("error",(e=>{console.log(`IPC Server Error: ${e}`)})),e()})),gb.server.start()}))))({ipcAppSpace:n,ipcId:r}),e?.ws?.disabled||await J_(e?.ws?.port||5368);const i=e?.defaultServicesPath||b.resolve(Hk,"defaultServices");Yk=i;const o=process.env.DEV_SESSION_ID;Rv.setHubIpcConfig({recipePath:e?.recipeRootPath,appSpace:n,id:r}),Rv.setEnableServiceLogsConfig(!!e?.enableServiceLogs),e?.servicesInstallPath&&(e=>{uv=e})(e.servicesInstallPath),e?.testServicesInstallPath&&(e=>{dv=e})(e.testServicesInstallPath);const s=hv(),a=fv(),c=async({requiredSecrets:e})=>{const t=Object.keys(e).reduce(((e,t)=>({...e,[t]:process.env[t]})),{});return t.__KEMU_USER_SERVICES_PATH=s,t.__KEMU_USER_TEST_SERVICES_PATH=a,t.__KEMU_SERVICE_URL=SI().serviceUrl,t.__KEMU_ENVIRONMENT=SI().environment,t};e?.getServiceSecretsFn?(Rv.setGetSecretsFunction(e.getServiceSecretsFn),pI(e.getServiceSecretsFn)):(Rv.setGetSecretsFunction(c),pI(c)),(e=>{mI=e})(e?.getMappedSecretsFn?e.getMappedSecretsFn:async e=>e.reduce(((e,t)=>({...e,[t.name]:[]})),{})),Rv.setSpawnNodeFunction(e?.spawnFn?e.spawnFn:({args:e,options:t})=>{const n={...process.env};return V("node",e||[],{...t,env:{...n,...t?.env}})}),(void 0!==e?.defaultServicesAllowList||!e?.noDefaultServices)&&await Rv.loadServices(i,{allowedServiceNames:e?.defaultServicesAllowList,fixedSession:o?parseInt(o):void 0,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,internalServices:!0,enableLogs:!0}),null!==e?.servicesInstallPath&&(await lv(s)||await h(s,{recursive:!0}),await Rv.loadServices(s,{internalServices:!1,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,enableLogs:!!e?.enableServiceLogs}));const l=process.env.DEV_NO_SPAWN_LIST?.split(",");await Rv.launchServices({noSpawningList:l||[]}),!1!==e.autoRegisterCleanupHandlers&&(()=>{zk("Registering automatic cleanup handlers for process signals");const e=async e=>{zk(`Received ${e}, cleaning up services...`);try{await Rv.killAllServices(),zk("Services cleaned up successfully"),process.exit(0)}catch(e){zk(`Error during cleanup: ${e}`),process.exit(1)}},t=async e=>{const t=e instanceof Error?e.message:String(e);zk(`Uncaught error: ${t}, cleaning up services...`);try{await Rv.killAllServices(),zk("Services cleaned up after crash")}catch(e){zk(`Error during crash cleanup: ${e}`)}process.exit(1)};process.on("SIGINT",(()=>e("SIGINT"))),process.on("SIGTERM",(()=>e("SIGTERM"))),process.on("uncaughtException",t),process.on("unhandledRejection",(e=>{t(new Error(`Unhandled rejection: ${e}`))}))})(),zk("Kemu Hub started"),(e?.onChooseDirectory||e?.onChooseFile)&&(e=>{HI=e})({chooseDirectory:e.onChooseDirectory,chooseFile:e.onChooseFile})},aE=e=>{if(e===ed.WS)return{handleWebsocketConnectionEvent:eE,handleWebsocketClientDisconnectionEvent:rE,handleWebsocketMessage:Qk,handleWebsocketClientCommand:tE,getRemoteInvoke:()=>qk}},cE=(e=[])=>{let t;const n=new Promise((n=>{const r=()=>{if(Rv.getAllServices().every((e=>"running"===e.status))&&e.every((e=>"running"===Rv.getMatchingService(e.name,e.version)?.status)))return n();t=setTimeout(r,100)};r()}));return n.abort=()=>{t&&clearTimeout(t)},n};const lE=Hl("processManager"),uE=new Set;let dE=!1,hE=[];const fE=()=>{for(const e of uE)if(!e.killed&&e.pid)try{e.kill("SIGTERM")}catch(t){console.error(`Failed to kill process ${e.pid}:`,t)}uE.clear()},pE=e=>{const{onCleanup:t,onEmergencyCleanup:n}=e||{};if(dE){for(const{event:e,handler:t}of hE)process.removeListener(e,t);hE=[],dE=!1}let r=!1,i=!1;const o=async e=>{if(r)lE("Cleanup already in progress, ignoring duplicate signal");else{r=!0;try{if(t)try{await t()}catch(e){console.error("Error during cleanup:",e)}fE(),e&&(await new Promise((e=>{setTimeout((()=>{e()}),100)})),process.exit(0))}finally{r=!1}}},s=async()=>{if(i||r)console.error("Cleanup already in progress, ignoring duplicate error handler");else{i=!0;try{if(n)try{await n()}catch(e){console.error("Error during emergency cleanup:",e)}fE()}finally{i=!1}}};let a=null;const c=(e,t)=>{process.on(e,t),hE.push({event:e,handler:t})};c("SIGINT",(async()=>{lE("Received SIGINT, cleaning up..."),await o("SIGINT")})),c("SIGTERM",(async()=>{lE("Received SIGTERM, cleaning up..."),await o("SIGTERM")})),c("SIGHUP",(async()=>{lE("Received SIGHUP, cleaning up..."),await o("SIGHUP")})),c("uncaughtException",(async e=>{console.error("Uncaught exception:",e),await s(),process.exit(1)})),c("unhandledRejection",(async(e,t)=>{console.error("Unhandled rejection at:",t,"reason:",e),await s(),process.exit(1)})),c("beforeExit",(()=>{a||(a=(async()=>{if(t)try{await t()}catch(e){console.error("Error during cleanup:",e)}fE()})(),a.catch((e=>{console.error("Error in beforeExit handler:",e),fE()})))})),dE=!0};let gE;const mE=Hl("run"),yE=rd(),vE=1e3,bE=v(process.argv.slice(2)),wE=e=>"number"==typeof e?{type:me.Number,value:e}:"string"==typeof e?{type:me.String,value:e}:"boolean"==typeof e?{type:me.Boolean,value:e}:Array.isArray(e)?{type:me.Array,value:e}:e;global.ImageData=q;const SE=e=>e&&"string"==typeof e.format&&e.data&&e.data instanceof ArrayBuffer;ke({createCanvas:(e,t)=>J(e,t),loadImage:async e=>{let t=e;if(SE(e)){const n=e;t=Buffer.from(n.data)}const n=await K(t),r=J(n.width,n.height).getContext("2d");r.drawImage(n,0,0,n.width,n.height);return r.getImageData(0,0,n.width,n.height)}});const _E=(e,t)=>"*"===e?ho.onAnyGlobalVariableChange(t):ho.onGlobalVariableChange(e,t),IE=(e,t,n)=>ho.setGlobalVariable({name:e,value:t,disableChangeNotifications:n?.disableChangeNotifications||!1,disableDefineNotifications:n?.disableDefineNotifications||!1,doNotOverrideExisting:n?.doNotOverrideExisting||!1}),xE=e=>{ho.deleteGlobalVariable({name:e})},kE=()=>ho.getAllVariables(),EE=e=>ho.getGlobalVariable(e),CE=e=>Yi(e),$E=e=>async()=>{throw new Error(`${e} not implemented`)},NE={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:me.ImageData}},loadImageFile:async e=>{const t=await K(e),n=J(t.width,t.height).getContext("2d");n.drawImage(t,0,0,t.width,t.height);return n.getImageData(0,0,t.width,t.height)},encodeImageData:async(e,t="jpeg",n)=>{const r=J(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 OE={start:async r=>{r=r||{};const i=r?.runtimeCommand?.trim()||process.env.KEMU_EDGE_RUNTIME_COMMAND?.trim(),o=r?.recipePath||bE.recipePath||process.env.KEMU_EDGE_RECIPE_PATH||process.cwd();if(!o)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].");const s=o.endsWith(".json")||o.endsWith(".kemu"),a=s?H(o):o,c=s?o:Y(a,"recipe.kemu"),{parsed:l,error:u}=await e({path:Y(z(a),".env")});u&&console.warn(`Failed to load .env file: ${u.message}. This is not an error, it just means that the .env file is not present or is not readable.`);const d=r.apiKey||process.env.KEMU_API_KEY,h=process.env.KEMU_CONFIG;if(!d)throw new Error("Missing API key. Please provide it via config.apiKey or KEMU_API_KEY environment variable.");if(r.envConfig){const{serviceUrl:e,environment:t}=r.envConfig;if(!e||!t)throw new Error("Missing server URL or environment in config.envConfig")}else if(!h)throw new Error("Missing server URL or environment in config.envConfig");const f=(e=>{try{return JSON.parse(e||"")}catch(e){return null}})(await t(z(c),"utf-8"));if(!f)throw new Error("Failed to parse recipe file");if(!f.author?.id)throw new Error("Missing required author ID in recipe file.");const{serviceUrl:p,environment:g}=r.envConfig||(e=>{const t=Buffer.from(e,"base64").toString("utf8"),[n,r]=t.split("<@>");if(!n||!r)throw new Error("Invalid configuration.");return{serviceUrl:n,environment:r}})(h);await vc();const m={id:f.uuid||String(Date.now()),version:1,author:f.author.id};(e=>{yo=e})(console);const y=aE(_e.WS),v=(e,t)=>{if(t)y?.handleWebsocketMessage({send:w,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg?.json});else{const t=e instanceof Buffer?e.toString():e;y?.handleWebsocketClientCommand(vE,t)}},b=(Tl={instanceServiceId:vE,sendBuf:v,sendCmd:v,triggerOnCommand:(...e)=>Al(...e),triggerOnConnected:()=>Pl(),triggerOnDisconnected:()=>Ml(),triggerOnMessageReceived:(...e)=>Dl(...e)},Tl);const w=(e,t)=>{if(t)b.triggerOnMessageReceived({send:v,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg.json});else{const t=e instanceof Buffer?e.toString():e;b.triggerOnCommand(t)}},S=od(),_=y.getRemoteInvoke();S.disableServiceEncoding(0,!0),_.disableServiceEncoding(vE,!0);const I=Object.values(f.blocks[pe].gates).filter((e=>e.type===Je.hubService&&e.state.service&&!0!==e.state.service?.webOnly)),x=I.map((e=>{const t=e.state.service;return{name:t.name,version:t.version}})),k=Y(a,"services"),E=await n(k).then((()=>!0)).catch((()=>!1));if(x.length>0&&!E)throw new Error("Services directory not found but required services are defined in the recipe. Please make sure there is a `services` directory in the recipe root and add the services you want to use to it.");pE();const C={globalApiKey:d,serviceUrl:p,spawnFn:i?({args:e,options:t,serviceInfo:n})=>{if(!i)throw new Error("Runtime command not provided. Please specify it in the config object, via a command line argument [--runtimeCommand] or as an environment variable [KEMU_EDGE_RUNTIME_COMMAND].");console.log(`Spawning service: "${n.name}" with command: "${i} ${e?.join(" ")}"`);const r=i.split(" ").filter(Boolean),o=Z(r[0],r.slice(1).concat(e||[]),{...t,env:{...process.env,...t?.env}});return(e=>{uE.add(e),e.on("exit",(()=>{uE.delete(e)}))})(o),o}:null,recipeRootPath:a,servicesInstallPath:E?Y(a,"services"):null,defaultServicesAllowList:r?.defaultServicesAllowList??["kemu.io.scriptHttp"],environment:g,ws:{disabled:!0},secrets:{recipeSecrets:{getRecipeDecryptedSecretsFn:async()=>({...l}),getRecipeSecretMappingsFn:$E("getRecipeSecretMappingsFn"),addRecipeSecretFn:$E("addRecipeSecretFn"),deleteRecipeSecretFn:$E("deleteRecipeSecretFn")}},ipc:{appSpace:"kemu-runner.",id:m.id}};await sE(C),mE("Waiting for services to run"),await cE(x),mE("All services are running"),el(yE),il(),Ia.onGlobalProcessingStateChange((e=>{mE("Global processing state changed: ",e)})),f.globalVariables&&(f.globalVariables=await sl(f.globalVariables));const $=await Zc(f,"runner",m.version,m.author,wr.Desktop);return gE=$,pE({onCleanup:async()=>{gE&&await Xc(gE)},onEmergencyCleanup:async()=>{gE&&await Xc(gE)}}),id($),await td({id:f.author.id}),new Promise(((e,t)=>{var n;nd("acknowledged",(async()=>{await yE.getServices();const{failed:n,sendToInputWidget:r,invokeRecipeLoadedWidgets:i}=await Qc($);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)})),mE("Recipe started"),e({sendToInputWidgetAndWaitForOutput:(e,t)=>{const n=wE(t);return r({inputName:e,data:n,waitForOutputChild:!0})},sendToInputWidget:(e,t)=>{const n=wE(t);return r({inputName:e,data:n,waitForOutputChild:!1})},globalVariables:{onChange:_E,setValue:IE,getValue:EE,delete:xE,getAll:kE},status:{onChange:CE},edgeFunctions:{register:Za.registerFunctionHandler,unregister:Za.unregisterFunctionHandler,clearAll:Za.clearAllHandlers}})})),b.triggerOnConnected(),b.triggerOnCommand((n=vE,`${be.SocketAcknowledge}${n}`))}))},terminate:async()=>{gE&&await Xc(gE),fE()}};export{me as DataType,OE as default,SE as isBinaryFile,NE as utils};
|