@kemu-io/edge-runtime 1.10.0 → 1.11.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.js +1 -1
package/package.json
CHANGED
package/runner.js
CHANGED
|
@@ -9,4 +9,4 @@ r.version="2.30.1",function(e){t=e}(jt),r.fn=An,r.min=function(){return Ft("isBe
|
|
|
9
9
|
*/
|
|
10
10
|
var e=x,t=b,n=Sy(),r=j,o=T,s={};vy=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 O,N=new o;return N.auditLog=p,N.end=function(){$.end.apply($,arguments)},d($,N),N.on("close",(function(){O&&O.close()})),N.on("new",(function(n){N.auditLog=f.addLogToAudit(n,N.auditLog,N,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&&N.emit("addWatcher",n)})),N.on("addWatcher",(function(t){O&&O.close(),r.watch_log&&(O=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){N.emit("createLog",t)}(0,t)}}))}catch(e){n&&console.log(new Date,"[FileStreamRotator] Could not add watcher for "+t)}}(t,f.verbose))})),N.on("createLog",(function(t){try{e.lstatSync(t)}catch(n){$&&"function"==$.end&&$.end(),$=e.createWriteStream(t,C),N.emit("new",t),d($,N)}})),N.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),N.emit("new",s),N.emit("rotate",w,s),d($,N)}$.write(t,n),y+=Buffer.byteLength(t,n)}.bind(this),process.nextTick((function(){N.emit("new",S)})),N.emit("new",S),N}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 vy}const Iy=x,xy=E,ky=b,Ey=i,Cy=A,$y=my.exports,Oy=nh.MESSAGE,Ny=O.PassThrough,Ty=$p,Ay={json:!1,colorize:!1,eol:xy.EOL,logstash:null,prettyPrint:!1,label:null,stringify:!1,depth:null,showLevel:!0,timestamp:()=>(new Date).toISOString()},My=function(e){if(e=e||{},Ty.call(this,e),this.options=Object.assign({},Ay,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 Ny,this.logStream.pipe(e.stream);else{if(this.filename=e.filename?ky.basename(e.filename):"winston.log",this.dirname=e.dirname||ky.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=_y().getStream({filename:ky.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:ky.join(this.dirname,"."+$y(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{Iy.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(!Iy.existsSync(e))return}catch(t){return t.message=`Error occurred while checking existence of ${e}: ${t.message}`,void this.emit("error",t)}try{if(Iy.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=Cy.createGzip(),n=Iy.createReadStream(e);n.on("error",(t=>{t.message=`Error occurred while reading ${e}: ${t.message}`,this.emit("error",t)}));const r=Iy.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{Iy.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 Py=My;Ey.inherits(My,Ty),My.prototype.name="dailyRotateFile";const Dy=function(){};My.prototype.log=function(e,t){t=t||Dy,this.logStream.write(e[Oy]+this.options.eol),this.emit("logged",e),t(null,!0)},My.prototype.close=function(){this.logStream&&this.logStream.end((()=>{this.emit("finish")}))},My.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 Iy.readdirSync(this.dirname).filter((t=>ky.basename(t).match(e)))})();0===r.length&&t&&t(null,n);const i=o=>{if(!o)return;const s=ky.join(this.dirname,o);let a,c="";if(o.endsWith(".gz")){a=new Ny;const e=Iy.createReadStream(s);e.on("error",(e=>{e.message=`Error occurred while reading ${s}: ${e.message}`,a.emit("error",e)})),e.pipe(Cy.createGunzip()).pipe(a)}else a=Iy.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 jy=Py;xd.transports.DailyRotateFile=jy;var Ry=sd(jy);const Ly=Date.now();let Fy=Math.ceil(Ly/1e3);var Uy=()=>Fy+=1;const By=w(C(),"kemu-user-services"),Wy=w(C(),"kemu-test-services"),Gy="KMU-CB-v1",Vy=process.env.HUB_PKG_VERSION||'"1.10.1"';var Yy;!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"}(Yy||(Yy={}));const Hy=e=>({...e,type:Array.isArray(e.type)?e.type.map((e=>Du[e])):Du[e.type]}),zy=async e=>{try{return await y(e,"utf-8")}catch(e){return null}},qy=e=>{if(e&&e.startsWith(Gy)){const t=e.slice(9),n=decodeURI(t);return zu(n)}return null},Ky=async(e,t,n)=>{let r=[];e.variants?.length&&(r=e.variants.map((e=>({...e,...e.inputs?{inputs:e.inputs.map(Hy)}:{},...e.outputs?{outputs:e.outputs.map(Hy)}:{}}))));const i={...e,path:t,customWidgets:[],...e.inputs?{inputs:e.inputs.map(Hy)}:{inputs:[]},...e.outputs?{outputs:e.outputs.map(Hy)}:{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 zy(w(e,i));if(!t){n(`Error loading custom widget file ${i}`);continue}const o=t.startsWith(Gy)?t:`${Gy}${t}`,s=qy(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===Yy.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},Jy=async e=>{try{return await f(e,p.F_OK),!0}catch{return!1}};let Zy=null,Xy=null;const Qy=()=>Zy||By,ev=()=>Xy||Wy;let tv=null;const nv={setGlobalUserId:e=>tv?.setGlobalUserId?.(e),captureError:e=>tv?.captureError?.(e),flushMessages:async()=>tv?.flushMessages?.(),isEnabled:()=>!!tv};var rv={...nv,setTracker:e=>{tv=e}};const iv=Id("servicesManager"),ov={};let sv=null,av=null,cv=null,lv=!1;class uv extends Error{code;originalError;constructor(e,t,n){super(e),this.code=t,this.originalError=n,this.name="ServiceError"}}const dv=async e=>{try{return await f(e),!0}catch{return!1}},hv=async e=>{if(!sv)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){iv(`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=gy.createLogger({level:"info",format:gy.format.combine(gy.format.timestamp(),gy.format.errors({stack:!0}),gy.format.json()),defaultMeta:{service:e},transports:[new Ry({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=zu(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;rv.isEnabled()&&rv.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===Ru.Javascript){iv(`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 dv(t)?t:i,s=[`--sessionId=${e.info.sessionId.toString()}`,`--ipcSpace=${sv.appSpace}`,`--ipcId=${sv?.id}`,`--recipePath=${sv.recipePath||""}`];if(e.info.internal&&s.push("--internal=true"),!cv)throw new Error('Get secrets function not set, call "setGetSecretsFunction" first.');const a=await cv({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 uv(`Missing required environment variables: ${c.join(", ")}`,"MISSING_REQUIRED_SECRETS");return new Promise(((t,i)=>{if(!av)throw new Error('Spawn function not set, call "setSpawnNodeFunction" first.');const c=av({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),iv(`[${e.info.name}] - stdout: ${r}`))})),c.stderr.on("data",(t=>{const i=t.toString().trim();i&&(n?.error(i),r(new Error(i)),iv(`[${e.info.name}] - stderr: ${i}`))})),c.on("exit",(t=>{const r=`exited with code ${t}`;n?.info(r,{code:t}),iv(`[${e.info.name}] ${r}`)})),c.on("spawn",(()=>{const r=`spawned with PID ${c.pid}`;n?.info(r,{pid:c.pid}),iv(`[${e.info.name}] ${r}`),t(c)})),c.on("error",(t=>{n?.error(`[${e.info.name}] error`,t),iv(`[${e.info.name}] error: ${t}`),r(t),i(new uv(`Error spawning service ${e.info.name}: ${t}`,"SPAWN_ERROR"))}))}))}throw`Unsupported processor type ${e.info.processor}`}catch(t){if(r(t),t instanceof uv)throw t;throw`Error spawning service ${e.info.name}: ${t}`}},fv=e=>e?.name?e?.version?e?.description?e?.processor?[Ru.Javascript,Ru.Executable,Ru.Python].includes(e?.processor)?null:"Invalid processor":"Missing processor":"Missing description":"Missing version":"Missing name",pv=async(e,t)=>{const n=b.join(e,"manifest.json");if(!await dv(n)){const t=`Missing manifest for service ${e}. Aborting.`;return iv(t),{error:t}}const r=await y(n,"utf-8"),i=zu(r),o=fv(i);if(!i||o){const t=`Invalid service manifest [${e}]: ${o}. Aborting.`;return iv(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 iv(t),{error:t}}})(),(async()=>{if(i.svgIcon){const t=await zy(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 pv(n);r?iv(`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){iv(`Error loading svgIcon for variant ${t.id}: ${e}`)}})()]);const a=Uy(),c=t?.fixedSession||a;iv(`Loaded service ${i.name} with sessionId ${c}`);const l=await Ky(i,e,{widgetUIContents:s});return gv(l),ov[c]={info:{...l,path:e,sessionId:c},status:"loaded",childProcess:null,logsEnabled:t?.logsEnabled},{service:ov[c]}},gv=e=>{e.widgetUIContents?e.uiContentChecksum=(e=>{const t=R("sha256");return t.update(e),t.digest("hex")})(e.widgetUIContents):e.uiContentChecksum=void 0},mv=async e=>{try{return e.childProcess=await hv(e),e.status="started",e.errorMsg=void 0,e.errorCode=void 0,!0}catch(t){return iv(`Service [${e.info.name}] error: ${t}`),e.status="error",t instanceof uv?(e.errorMsg=t.message,e.errorCode=t.code):(e.errorMsg="string"==typeof t?t:JSON.stringify(t),e.errorCode="UNKNOWN_ERROR"),!1}},yv=e=>{const{path:t,...n}=e.info;return{...n}},vv=()=>Object.values(ov).filter((e=>"running"===e.status)).map(yv),bv=e=>{if(!e?.kill)return iv(`Failed to kill service ${e?.pid} because it is not a child process`),!1;let t=e.kill("SIGINT");return t||(iv(`Failed to send SIGINT to service ${e.pid} using SIGINT`),t=e.kill("SIGTERM"),t||(iv(`Failed to send SIGTERM to service ${e.pid} using SIGTERM`),t=e.kill("SIGKILL"),t||iv(`Failed to send SIGKILL to service ${e.pid} using SIGKILL`))),t},wv=async e=>{const{serviceName:t,version:n,force:r,timeout:i=15e3}=e,o=Object.values(ov).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){iv(`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),iv(`Service ${t} process exited with code ${n} and signal ${i}`),e()})),o.childProcess.once("error",(n=>{clearTimeout(r),iv(`Service ${t} process error: ${n.message}`),e()}))}));bv(o.childProcess);try{await r,iv(`Service ${t} process successfully terminated`)}catch(e){iv(`Warning: ${e instanceof Error?e.message:"Unknown error"} while waiting for service ${t} to stop`)}}return o.status="stopped",iv(`Service ${t} stopped`),o},Sv=e=>e.info.internal?e.info.path:b.join(e.info.path,".."),_v=e=>!!e.internal;var Iv={isOfficialKemuService:e=>e.name.startsWith("kemu.io"),loadServices:async(e,t)=>{if(!await Jy(e))return void iv(`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));iv(`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 pv(`${o}${t?.internalServices?"":"/dist"}`,{...t,logsEnabled:Array.isArray(t?.enableLogs)?t?.enableLogs.includes(i):t?.enableLogs});s&&iv(`Failed to load service ${o}. Please check logs`),a&&t?.internalServices&&(a.info.internal=!0)}},launchServices:async e=>{if(iv("Initializing services"),!sv)throw new Error('IPC config not set, call "setHubIpcConfig" first.');for(const t in ov){const n=ov[t];e.noSpawningList&&e.noSpawningList.includes(n.info.name)?iv(`Service ${n.info.name} is in the noSpawningList. Skipping.`):mv(n)}iv("Services initialized")},setServiceStatus:(e,t)=>{const n=ov[e];return n?(n.status=t,!0):(iv(`Service with serviceId ${e} not found`),!1)},getActiveServices:vv,getMatchingService:(e,t)=>{const n=Object.values(ov).filter((e=>"running"===e.status));for(const r of n)if(r.info.name===e){if(r.info.version===t)return r;if(td(r.info.version,t,">="))return r}return null},getServiceBySessionId:e=>ov[e]||null,killAllServices:()=>{for(const e in ov){const t=ov[e];if(t.childProcess)try{iv(`Killing service ${t.info.name} with PID ${t.childProcess.pid}`),bv(t.childProcess)}catch(e){iv(`Error killing service ${t.info.name}: ${e}`)}}},addDevService:async(e,t,n)=>{const r={info:{...await Ky(t,t.path),sessionId:e},status:n,startedAt:new Date,devMode:!0,childProcess:null};ov[e]=r,gv(ov[e].info)},setServiceManifest:(e,t,n)=>{const r=ov[e];if(!r)return iv(`Service with sessionId ${e} not found`),!1;const i=fv(t);if(i)return iv(`Invalid manifest for service ${r.info.name}: ${i}`),!1;gv(t),r.info={...r.info,...t},n&&(r.status=n)},getMatchingDevService:(e,t,n)=>{const r=Object.values(ov).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:()=>vv().filter((e=>e.internal)),getAllServices:()=>Object.values(ov),stopService:wv,uninstallService:async(e,t)=>{iv(`Uninstalling service ${e} v${t}`);const n=await wv({serviceName:e,version:t});if(!n)return!1;iv(`Service ${e} stopped. Removing from disk...`);const r=Sv(n),i=Qy();return r.startsWith(i)?(await m(r,{recursive:!0,force:!0,maxRetries:3}),iv(`Service ${e} successfully removed from disk`),(e=>{ov[e],delete ov[e]})(n.info.sessionId),!0):(iv(`Service ${e} is not installed in the user services directory. Aborting.`),!1)},getAllServiceVersions:e=>Object.values(ov).filter((t=>t.info.name===e)),setHubIpcConfig:e=>{sv={...e}},setEnableServiceLogsConfig:e=>{lv=e},loadAndLaunch:async(e,t,n)=>{const r=_(e,t),{error:i,service:o}=await pv(r,{logsEnabled:lv});if(i||!o)return{errorMsg:i};try{o.info.internal=!!n,o.childProcess=await hv(o),o.status="started"}catch(e){o.status="error",e instanceof uv?(iv(`Service spawning error: ${e.message} (${e.code})`),o.errorMsg=e.message,o.errorCode=e.code):(iv(`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:Sv,setSpawnNodeFunction:e=>{av=e},setGetSecretsFunction:e=>{cv=e},restartService:async(e,t)=>{iv(`Restarting service ${e} v${t}`);const n=await wv({serviceName:e,version:t,force:!0});return!!n&&mv(n)},getFailedServices:()=>Object.values(ov).filter((e=>"error"===e.status)).map((e=>({...yv(e),errorMsg:e.errorMsg||"",errorCode:e.errorCode,status:e.status}))),isInternalKemuService:_v,isNotInternalKemuService:e=>!_v(e),isNotDevService:e=>!e.devMode};class xv{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 kv{constructor(e){e||(e=new xv),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 Ev=sd((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={}})),Cv=sd((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 $v{}class Ov{}const Nv=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 $v,t=Ov){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 $v}}())}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 Tv{constructor(){}on(e,t,n=!1){return Nv.string(e),Nv.function(t),Nv.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(Nv.string(e),e!=this.#e.toString()&&"*"!=e||(e=this.#e),!this.#t[e])return this;if("*"==t)return delete this.#t[e],this;Nv.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){Nv.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)=>{Nv.string(e),Nv.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 Av=new kv;class Mv extends Tv{constructor(e,t){super(),this.config=e,this.log=t,this.publish=super.emit,e.maxRetries&&(this.retriesRemaining=e.maxRetries),Av=new kv(this.config)}Client=Mv;queue=new Cv;socket=!1;connect=jv;emit=Pv;retriesRemaining=0;explicitlyDisconnected=!1}function Pv(e,t){this.log("dispatching event to ",this.id,this.path," : ",e,",",t);let n=new Ev;n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Av.format(n),this.config.sync?this.queue.add(Dv.bind(this,n)):this.socket.write(n)}function Dv(e){this.log("dispatching event to ",this.id,this.path," : ",e),this.socket.write(e)}function jv(){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)!=Av.delimiter||-1==t.indexOf(Av.delimiter))return void e.log("Messages are large, You may want to consider smaller messages.");this.ipcBuffer="";const n=Av.parse(t),r=n.length;for(let t=0;t<r;t++){let r=new Ev;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 Rv=new kv;class Lv extends Tv{constructor(e,t,n,r){super(),this.config=t,this.path=e,this.port=r,this.log=n,this.publish=super.emit,Rv=new kv(this.config),this.on("close",Bv.bind(this))}udp4=!1;udp6=!1;server=!1;sockets=[];emit=Fv;broadcast=Uv;onStart(e){this.publish("start",e)}stop(){this.server.close()}start(){this.path?this.config.unlink?x.unlink(this.path,Yv.bind(this)):Yv.bind(this)():this.log("Socket Server Path not specified, refusing to start")}}function Fv(e,t,n){this.log("dispatching event to socket"," : ",t,n);let r=new Ev;if(r.type=t,r.data=n,this.config.rawBuffer?(this.log(this.config.encoding),r=Buffer.from(t,this.config.encoding)):r=Rv.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 Uv(e,t){this.log("broadcasting event to all known sockets listening to ",this.path," : ",this.port?this.port:"",e,t);let n=new Ev;if(n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Rv.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 Bv(){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 Wv(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)==Rv.delimiter&&-1!=t.indexOf(Rv.delimiter))for(r.ipcBuffer="",t=Rv.parse(t);t.length>0;){let e=new Ev;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 Gv(e){this.publish("close",e)}function Vv(e){this.sockets.push(e),e.setEncoding&&e.setEncoding(this.config.encoding),this.log("## socket connection to server detected ##"),e.on("close",Gv.bind(this)),e.on("error",function(e){this.log("server socket error",e),this.publish("error",e)}.bind(this)),e.on("data",Wv.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 Yv(){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=zv.bind(this),this.server.on("listening",function(){Vv.bind(this)(this.server)}.bind(this))):(this.log("starting TLS server",this.config.tls),this.config.tls?Hv.bind(this)():this.server=L.createServer(Vv.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 Hv(){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,Vv.bind(this))}function zv(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 qv{constructor(){}config=new xv;of={};server=!1;get connectTo(){return eb}get connectToNet(){return tb}get disconnect(){return Jv}get serve(){return Zv}get serveNet(){return Qv}get log(){return Kv}set connectTo(e){return eb}set connectToNet(e){return tb}set disconnect(e){return Jv}set serve(e){return Zv}set serveNet(e){return Qv}set log(e){return Kv}}function Kv(...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 Jv(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 Zv(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=Xv),this.server=new Lv(e,this.config,Kv),this.server.on("start",t)}function Xv(){}function Qv(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=Xv),this.server=new Lv(e,this.config,Kv,t),n&&(this.server[n]=!0,"udp4"===n&&"::1"===e&&(this.server.path="127.0.0.1")),this.server.on("start",r)}function eb(e,t,n){if("function"==typeof t&&(n=t,t=!1),n||(n=Xv),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 Mv(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 tb(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=Xv),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 Mv(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 nb=new class extends qv{constructor(){super()}IPC=qv};const rb=Object.values({protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8}).reduce(((e,t)=>e+t),0),ib=e=>{try{return JSON.parse(e)}catch(e){return null}},ob="undefined"!=typeof window,sb={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},ab={protocolPrefix:4,txtLength:4},cb=Object.values(sb).reduce(((e,t)=>e+t),0),lb=Object.values(ab).reduce(((e,t)=>e+t),0),ub=["width","height","colorSpace"],db=(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)||ub.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},hb=(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},fb=(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&&hb(e,o,l)}return e},pb=e=>_d(e),gb="KMSG",mb="KCMD",yb=pb("klProtocol");var vb={encode:(e,t,n)=>{const r={json:e.json},i=db(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=sb.protocolPrefix+sb.protocolVersion+sb.jsonLength+sb.binaryLength+sb.fromServiceId+sb.toServiceId+sb.sentAt+l+s,d=Buffer.alloc(u),h=Date.now();let f=0;return d.write(gb,f),f+=sb.protocolPrefix,d.writeUInt8(1,f),f+=sb.protocolVersion,d.writeUInt32LE(l,f),f+=sb.jsonLength,d.writeUInt32LE(s,f),f+=sb.binaryLength,d.writeUInt32LE(t,f),f+=sb.fromServiceId,d.writeUInt32LE(n,f),f+=sb.toServiceId,d.writeBigInt64LE(BigInt(h),f),f+=sb.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,sb.protocolPrefix);if(t+=sb.protocolPrefix,n!==gb)return null;if(e.byteLength<cb)return yb(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=sb.protocolVersion;const i=e.readUInt32LE(t);t+=sb.jsonLength;const o=e.readUInt32LE(t);t+=sb.binaryLength;const s=e.readUInt32LE(t);t+=sb.fromServiceId;const a=e.readUInt32LE(t);t+=sb.toServiceId;const c=e.readBigInt64LE(t);t+=sb.sentAt;const l=i+o,u=e.subarray(t,t+l),d=e.subarray(0,cb);let h=null;return e.byteLength-cb-i-o>0&&(h=e.subarray(cb+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=ib(n);if(!i?.json)return yb("Invalid JSON in KL message"),null;i.jsonBinaryMap&&r.byteLength&&fb(i.json,r,i.jsonBinaryMap);const o=Buffer.concat([e.headerPackage,t]);let s=o,a=null;const c=cb+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<cb)return yb("Invalid Header Size"),e;let n=0;return n+=sb.protocolPrefix,n+=sb.protocolVersion,n+=sb.jsonLength,n+=sb.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=sb.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=lb+r,o=Buffer.alloc(i);return o.write(mb,t),t+=ab.protocolPrefix,o.writeUint32LE(r,t),t+=ab.txtLength,n.copy(o,t),o},decodeCommand:e=>{let t=0;if(e.byteLength<lb)return{command:null};const n=e.toString("utf-8",t,ab.protocolPrefix);if(t+=ab.protocolPrefix,n!==mb)return{command:null};const r=e.readUInt32LE(t);t+=ab.txtLength;const i=e.toString("utf-8",t,t+r),o=e.byteLength-lb-r;let s=null;o>0&&(s=e.subarray(lb+r));let a=0;return o<0&&(a=Math.abs(o)),{command:i,remainingData:s,missing:a}}};const bb="KMSG",wb="KCMD",Sb=pb("klProtocol"),_b=new TextEncoder;var Ib={encode:(e,t,n)=>{const r={json:e.json},i=db(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=_b.encode(a),l=c.byteLength,u=new ArrayBuffer(sb.protocolPrefix+sb.protocolVersion+sb.jsonLength+sb.binaryLength+sb.fromServiceId+sb.toServiceId+sb.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++]=bb.charCodeAt(e);return d.setUint8(p,1),p+=sb.protocolVersion,d.setUint32(p,l,!0),p+=sb.jsonLength,d.setUint32(p,s,!0),p+=sb.binaryLength,d.setUint32(p,t,!0),p+=sb.fromServiceId,d.setUint32(p,n,!0),p+=sb.toServiceId,d.setBigInt64(p,BigInt(f),!0),p+=sb.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<sb.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==bb)return null;if(e.byteLength<cb)return Sb.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const i=t.getUint8(n);n+=sb.protocolVersion;const o=t.getUint32(n,!0);n+=sb.jsonLength;const s=t.getUint32(n,!0);n+=sb.binaryLength;const a=t.getUint32(n,!0);n+=sb.fromServiceId;const c=t.getUint32(n,!0);n+=sb.toServiceId;const l=t.getBigInt64(n,!0);n+=sb.sentAt;const u=o+s,d=e.slice(n,n+u),h=new Uint8Array(e,0,cb);let f=null;return e.byteLength-cb-o-s>0&&(f=new Uint8Array(e,cb+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=ib(o);if(!a?.json)return Sb.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&s.byteLength&&fb(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=cb+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<cb)return Sb("Invalid Header Size"),e;let n=0;n+=sb.protocolPrefix,n+=sb.protocolVersion,n+=sb.jsonLength,n+=sb.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=sb.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=_b.encode(e),r=n.byteLength,i=new ArrayBuffer(lb+r),o=new DataView(i),s=new Uint8Array(i);for(let e=0;e<4;++e)s[t++]=wb.charCodeAt(e);return o.setUint32(t,r,!0),t+=ab.txtLength,s.set(n,t),i},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<lb)return{command:null};let r="";for(let e=0;e<ab.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==wb)return{command:null};const i=t.getUint32(n,!0);n+=ab.txtLength;const o=e.byteLength-lb-i,s=new Uint8Array(e,n,Math.min(i,e.byteLength-lb)),a=(new TextDecoder).decode(s);let c=null;o>0&&(c=e.slice(lb+i));let l=0;return o<0&&(l=Math.abs(o)),{command:a,remainingData:c,missing:l}}};const xb=pb("klTransmissionManager"),kb=()=>{const e=(t,n,r,i)=>{let o=n,s=null;const a=t instanceof ArrayBuffer;if(xb(`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=Ib.decodeHeader(c)):(c=o?.partialHeaderData?Buffer.concat([o.partialHeaderData,t]):t,s=vb.decodeHeader(c)),!s){const{command:t,missing:o,remainingData:s}=a?Ib.decodeCommand(c):vb.decodeCommand(c);return t?i({command:t,complete:!0,rawMessage:c}):xb(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?(xb(`${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 xb(`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;xb(`Received ${o.header.totalBytesReceived} of ${o.header.totalBytesExpected} expected in ${t} ms, elapsed since first package: ${n}ms`);const s=a?Ib.decodeFullKlMessage(o.header):vb.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 xb(`${u.byteLength} bytes remaining after processing message with ${c} bytes of data. Re-analyzing...`),e(u,null,r,i)}};return e};nb.config={...nb.config,id:"widgets",retry:1500,silent:!0,rawBuffer:!0,appspace:"kemu.",encoding:"hex"};const Eb={info:Id("ipcServer:info"),data:Id("ipcServer:data")};let Cb,$b,Ob,Nb,Tb={};const Ab=kb(),Mb=e=>{Tb[e]&&(Eb.info(`Client disconnected [${e}]`),delete Tb[e],$b&&$b(e))};var Pb=(e,t)=>{const n=Tb[e];if(!n)return Eb.info(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=rb)return Eb.info("Message is too long to be a command. Use sendMessage instead."),!1;const r=vb.encodeCommand(t);return n.socket.write(r),!0},Db=(e,t)=>{const n=Tb[e];return!!n&&(Eb.info(`Renaming socket id [${e}] to [${t}]`),delete Tb[e],n.socket.id=t,Tb[t]=n,n.socket.removeListener("close",n.disconnectHandler),n.disconnectHandler=()=>Mb(t),n.socket.on("close",n.disconnectHandler),!0)};let jb=vb;ob&&(jb=Ib);var Rb,Lb=jb;!function(e){e.FunctionNotFound="FNC_NOT_FOUND",e.FunctionNotAllowed="FNC_NOT_ALLOWED",e.ParentEventCallbackError="PARENT_EVENT_CALLBACK_ERROR"}(Rb||(Rb={}));let Fb=Math.ceil(Date.now()/1e3);var Ub={exports:{}};const Bb=["nodebuffer","arraybuffer","fragments"],Wb="undefined"!=typeof Blob;Wb&&Bb.push("blob");var Gb={BINARY_TYPES:Bb,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Wb,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:Vb}=Gb,Yb=Buffer[Symbol.species];function Hb(e,t,n,r,i){for(let o=0;o<i;o++)n[r+o]=e[o]^t[3&o]}function zb(e,t){for(let n=0;n<e.length;n++)e[n]^=t[3&n]}if(Ub.exports={concat:function(e,t){if(0===e.length)return Vb;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 Yb(n.buffer,n.byteOffset,r):n},mask:Hb,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 Yb(t):ArrayBuffer.isView(t)?n=new Yb(t.buffer,t.byteOffset,t.byteLength):(n=Buffer.from(t),e.readOnly=!1),n},unmask:zb},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");Ub.exports.mask=function(t,n,r,i,o){o<48?Hb(t,n,r,i,o):e.mask(t,n,r,i,o)},Ub.exports.unmask=function(t,n){t.length<32?zb(t,n):e.unmask(t,n)}}catch(b){}var qb=Ub.exports;const Kb=Symbol("kDone"),Jb=Symbol("kRun"),Zb=A,Xb=qb,Qb=class{constructor(e){this[Kb]=()=>{this.pending--,this[Jb]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Jb]()}[Jb](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[Kb])}}},{kStatusCode:ew}=Gb,tw=Buffer[Symbol.species],nw=Buffer.from([0,0,255,255]),rw=Symbol("permessage-deflate"),iw=Symbol("total-length"),ow=Symbol("callback"),sw=Symbol("buffers"),aw=Symbol("error");let cw;var lw=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,!cw){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;cw=new Qb(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[ow];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){cw.add((r=>{this._decompress(e,t,((e,t)=>{r(),n(e,t)}))}))}compress(e,t,n){cw.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]?Zb.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=Zb.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[rw]=this,this._inflate[iw]=0,this._inflate[sw]=[],this._inflate.on("error",hw),this._inflate.on("data",dw)}this._inflate[ow]=n,this._inflate.write(e),t&&this._inflate.write(nw),this._inflate.flush((()=>{const e=this._inflate[aw];if(e)return this._inflate.close(),this._inflate=null,void n(e);const i=Xb.concat(this._inflate[sw],this._inflate[iw]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[iw]=0,this._inflate[sw]=[],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]?Zb.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=Zb.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[iw]=0,this._deflate[sw]=[],this._deflate.on("data",uw)}this._deflate[ow]=n,this._deflate.write(e),this._deflate.flush(Zb.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=Xb.concat(this._deflate[sw],this._deflate[iw]);t&&(e=new tw(e.buffer,e.byteOffset,e.length-4)),this._deflate[ow]=null,this._deflate[iw]=0,this._deflate[sw]=[],t&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),n(null,e)}))}};function uw(e){this[sw].push(e),this[iw]+=e.length}function dw(e){this[iw]+=e.length,this[rw]._maxPayload<1||this[iw]<=this[rw]._maxPayload?this[sw].push(e):(this[aw]=new RangeError("Max payload size exceeded"),this[aw].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[aw][ew]=1009,this.removeListener("data",dw),this.reset())}function hw(e){this[rw]._inflate=null,e[ew]=1007,this[ow](e)}var fw={exports:{}};const{isUtf8:pw}=N,{hasBlob:gw}=Gb;function mw(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(fw.exports={isBlob:function(e){return gw&&"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:mw,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]},pw)fw.exports.isValidUTF8=function(e){return e.length<24?mw(e):pw(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");fw.exports.isValidUTF8=function(t){return t.length<32?mw(t):e(t)}}catch(b){}var yw=fw.exports;const{Writable:vw}=O,bw=lw,{BINARY_TYPES:ww,EMPTY_BUFFER:Sw,kStatusCode:_w,kWebSocket:Iw}=Gb,{concat:xw,toArrayBuffer:kw,unmask:Ew}=qb,{isValidStatusCode:Cw,isValidUTF8:$w}=yw,Ow=Buffer[Symbol.species];const{randomFillSync:Nw}=j,Tw=lw,{EMPTY_BUFFER:Aw,kWebSocket:Mw,NOOP:Pw}=Gb,{isBlob:Dw,isValidStatusCode:jw}=yw,{mask:Rw,toBuffer:Lw}=qb,Fw=Symbol("kByteLength"),Uw=Buffer.alloc(4),Bw=8192;let Ww,Gw=Bw;function Vw(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 Yw(e,t,n){Vw(e,t,n),e.onerror(t)}const{kForOnEventAttribute:Hw,kListener:zw}=Gb,qw=Symbol("kCode"),Kw=Symbol("kData"),Jw=Symbol("kError"),Zw=Symbol("kMessage"),Xw=Symbol("kReason"),Qw=Symbol("kTarget"),eS=Symbol("kType"),tS=Symbol("kWasClean");class nS{constructor(e){this[Qw]=null,this[eS]=e}get target(){return this[Qw]}get type(){return this[eS]}}Object.defineProperty(nS.prototype,"target",{enumerable:!0}),Object.defineProperty(nS.prototype,"type",{enumerable:!0});class rS extends nS{constructor(e,t={}){super(e),this[qw]=void 0===t.code?0:t.code,this[Xw]=void 0===t.reason?"":t.reason,this[tS]=void 0!==t.wasClean&&t.wasClean}get code(){return this[qw]}get reason(){return this[Xw]}get wasClean(){return this[tS]}}Object.defineProperty(rS.prototype,"code",{enumerable:!0}),Object.defineProperty(rS.prototype,"reason",{enumerable:!0}),Object.defineProperty(rS.prototype,"wasClean",{enumerable:!0});class iS extends nS{constructor(e,t={}){super(e),this[Jw]=void 0===t.error?null:t.error,this[Zw]=void 0===t.message?"":t.message}get error(){return this[Jw]}get message(){return this[Zw]}}Object.defineProperty(iS.prototype,"error",{enumerable:!0}),Object.defineProperty(iS.prototype,"message",{enumerable:!0});class oS extends nS{constructor(e,t={}){super(e),this[Kw]=void 0===t.data?null:t.data}get data(){return this[Kw]}}Object.defineProperty(oS.prototype,"data",{enumerable:!0});const sS={addEventListener(e,t,n={}){for(const r of this.listeners(e))if(!n[Hw]&&r[zw]===t&&!r[Hw])return;let r;if("message"===e)r=function(e,n){const r=new oS("message",{data:n?e:e.toString()});r[Qw]=this,cS(t,this,r)};else if("close"===e)r=function(e,n){const r=new rS("close",{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[Qw]=this,cS(t,this,r)};else if("error"===e)r=function(e){const n=new iS("error",{error:e,message:e.message});n[Qw]=this,cS(t,this,n)};else{if("open"!==e)return;r=function(){const e=new nS("open");e[Qw]=this,cS(t,this,e)}}r[Hw]=!!n[Hw],r[zw]=t,n.once?this.once(e,r):this.on(e,r)},removeEventListener(e,t){for(const n of this.listeners(e))if(n[zw]===t&&!n[Hw]){this.removeListener(e,n);break}}};var aS={CloseEvent:rS,ErrorEvent:iS,Event:nS,EventTarget:sS,MessageEvent:oS};function cS(e,t,n){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}const{tokenChars:lS}=yw;function uS(e,t,n){void 0===e[t]?e[t]=[n]:e[t].push(n)}var dS={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===lS[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?(uS(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===lS[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),uS(i,e.slice(c,u),!0),44===l&&(uS(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!==lS[l])throw new SyntaxError(`Unexpected character at index ${d}`);-1===c?c=d:o||(o=!0),s=!1}else if(a)if(1===lS[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===lS[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),uS(i,r,s),44===l&&(uS(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?uS(t,h,i):(void 0===r?uS(i,h,!0):uS(i,r,o?h.replace(/\\/g,""):h),uS(t,n,i)),t}};const hS=T,fS=D,pS=P,gS=L,mS=F,{randomBytes:yS,createHash:vS}=j,{URL:bS}=B,wS=lw,SS=class extends vw{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||ww[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Iw]=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 Ow(t.buffer,t.byteOffset+e,t.length-e),new Ow(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 Ow(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[bw.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=Sw;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]&&Ew(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[bw.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?xw(n,t):"arraybuffer"===this._binaryType?kw(xw(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=xw(n,t);if(!this._skipUTF8Validation&&!$w(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,Sw),this.end();else{const n=e.readUInt16BE(0);if(!Cw(n)){const e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const r=new Ow(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!$w(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[_w]=r,o}},_S=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=Pw,this[Mw]=void 0}static frame(e,t){let n,r,i=!1,o=2,s=!1;t.mask&&(n=t.maskBuffer||Uw,t.generateMask?t.generateMask(n):(Gw===Bw&&(void 0===Ww&&(Ww=Buffer.alloc(Bw)),Nw(Ww,0,Bw),Gw=0),n[0]=Ww[Gw++],n[1]=Ww[Gw++],n[2]=Ww[Gw++],n[3]=Ww[Gw++]),s=!(n[0]|n[1]|n[2]|n[3]),o=6),"string"==typeof e?r=t.mask&&!s||void 0===t[Fw]?(e=Buffer.from(e)).length:t[Fw]:(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?(Rw(e,n,c,o,r),[c]):(Rw(e,n,e,0,r),[c,e])):[c,e]}close(t,n,r,i){let o;if(void 0===t)o=Aw;else{if("number"!=typeof t||!jw(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={[Fw]: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):Dw(t)?(i=t.size,o=!1):(i=(t=Lw(t)).length,o=Lw.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const s={[Fw]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};Dw(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):Dw(t)?(i=t.size,o=!1):(i=(t=Lw(t)).length,o=Lw.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const s={[Fw]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};Dw(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[Tw.extensionName];let i,o,s=t.binary?2:1,a=t.compress;"string"==typeof e?(i=Buffer.byteLength(e),o=!1):Dw(e)?(i=e.size,o=!1):(i=(e=Lw(e)).length,o=Lw.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={[Fw]:i,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:o,rsv1:a};Dw(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[Fw],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(Vw,this,e,i)}this._bufferedBytes-=r[Fw];const o=Lw(t);n?this.dispatch(o,n,r,i):(this._state=0,this.sendFrame(e.frame(o,r),i),this.dequeue())})).catch((e=>{process.nextTick(Yw,this,e,i)}))}dispatch(t,n,r,i){if(!n)return void this.sendFrame(e.frame(t,r),i);const o=this._extensions[Tw.extensionName];this._bufferedBytes+=r[Fw],this._state=1,o.compress(t,r.fin,((t,n)=>{this._socket.destroyed?Vw(this,new Error("The socket was closed while data was being compressed"),i):(this._bufferedBytes-=r[Fw],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][Fw],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Fw],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:IS}=yw,{BINARY_TYPES:xS,EMPTY_BUFFER:kS,GUID:ES,kForOnEventAttribute:CS,kListener:$S,kStatusCode:OS,kWebSocket:NS,NOOP:TS}=Gb,{EventTarget:{addEventListener:AS,removeEventListener:MS}}=aS,{format:PS,parse:DS}=dS,{toBuffer:jS}=qb,RS=3e4,LS=Symbol("kAborted"),FS=[8,13],US=["CONNECTING","OPEN","CLOSING","CLOSED"],BS=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;let WS=class e extends hS{constructor(t,n,r){super(),this._binaryType=xS[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=kS,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]),VS(this,t,n,r)):(this._autoPong=r.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){xS.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 SS({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),o=new _S(t,this._extensions,r.generateMask);this._receiver=i,this._sender=o,this._socket=t,i[NS]=this,o[NS]=this,t[NS]=this,i.on("conclude",JS),i.on("drain",ZS),i.on("error",XS),i.on("message",e_),i.on("ping",t_),i.on("pong",n_),o.onerror=i_,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on("close",s_),t.on("data",a_),t.on("end",c_),t.on("error",l_),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[wS.extensionName]&&this._extensions[wS.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())})),o_(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";qS(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||kS,n,r)):KS(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||kS,n,r)):KS(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 KS(this,t,r);const i={binary:"string"!=typeof t,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[wS.extensionName]||(i.compress=!1),this._sender.send(t||kS,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";qS(this,this._req,e)}}};Object.defineProperty(WS,"CONNECTING",{enumerable:!0,value:US.indexOf("CONNECTING")}),Object.defineProperty(WS.prototype,"CONNECTING",{enumerable:!0,value:US.indexOf("CONNECTING")}),Object.defineProperty(WS,"OPEN",{enumerable:!0,value:US.indexOf("OPEN")}),Object.defineProperty(WS.prototype,"OPEN",{enumerable:!0,value:US.indexOf("OPEN")}),Object.defineProperty(WS,"CLOSING",{enumerable:!0,value:US.indexOf("CLOSING")}),Object.defineProperty(WS.prototype,"CLOSING",{enumerable:!0,value:US.indexOf("CLOSING")}),Object.defineProperty(WS,"CLOSED",{enumerable:!0,value:US.indexOf("CLOSED")}),Object.defineProperty(WS.prototype,"CLOSED",{enumerable:!0,value:US.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(WS.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(WS.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[CS])return t[$S];return null},set(t){for(const t of this.listeners(e))if(t[CS]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[CS]:!0})}})})),WS.prototype.addEventListener=AS,WS.prototype.removeEventListener=MS;var GS=WS;function VS(e,t,n,r){const i={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:FS[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,!FS.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${FS.join(", ")})`);let o;if(t instanceof bS)o=t;else try{o=new bS(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 YS(e,t)}const l=s?443:80,u=yS(16).toString("base64"),d=s?fS.request:pS.request,h=new Set;let f,p;if(i.createConnection=i.createConnection||(s?zS:HS),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 wS(!0!==i.perMessageDeflate?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=PS({[wS.extensionName]:f.offer()})),n.length){for(const e of n){if("string"!=typeof e||!BS.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",(()=>{qS(e,p,"Opening handshake has timed out")})),p.on("error",(t=>{null===p||p[LS]||(p=e._req=null,YS(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 qS(e,p,"Maximum redirects exceeded");let o;p.abort();try{o=new bS(s,t)}catch(t){const n=new SyntaxError(`Invalid URL: ${s}`);return void YS(e,n)}VS(e,o,n,r)}else e.emit("unexpected-response",p,o)||qS(e,p,`Unexpected server response: ${o.statusCode}`)})),p.on("upgrade",((t,n,r)=>{if(e.emit("upgrade",t),e.readyState!==WS.CONNECTING)return;p=e._req=null;const o=t.headers.upgrade;if(void 0===o||"websocket"!==o.toLowerCase())return void qS(e,n,"Invalid Upgrade header");const s=vS("sha1").update(u+ES).digest("base64");if(t.headers["sec-websocket-accept"]!==s)return void qS(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 qS(e,n,c);a&&(e._protocol=a);const l=t.headers["sec-websocket-extensions"];if(void 0!==l){if(!f)return void qS(e,n,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");let r;try{r=DS(l)}catch(t){return void qS(e,n,"Invalid Sec-WebSocket-Extensions header")}const i=Object.keys(r);if(1!==i.length||i[0]!==wS.extensionName)return void qS(e,n,"Server indicated an extension that was not requested");try{f.accept(r[wS.extensionName])}catch(t){return void qS(e,n,"Invalid Sec-WebSocket-Extensions header")}e._extensions[wS.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 YS(e,t){e._readyState=WS.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function HS(e){return e.path=e.socketPath,gS.connect(e)}function zS(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=gS.isIP(e.host)?"":e.host),mS.connect(e)}function qS(e,t,n){e._readyState=WS.CLOSING;const r=new Error(n);Error.captureStackTrace(r,qS),t.setHeader?(t[LS]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(YS,e,r)):(t.destroy(r),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function KS(e,t,n){if(t){const n=IS(t)?t.size:jS(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${US[e.readyState]})`);process.nextTick(n,t)}}function JS(e,t){const n=this[NS];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,void 0!==n._socket[NS]&&(n._socket.removeListener("data",a_),process.nextTick(r_,n._socket),1005===e?n.close():n.close(e,t))}function ZS(){const e=this[NS];e.isPaused||e._socket.resume()}function XS(e){const t=this[NS];void 0!==t._socket[NS]&&(t._socket.removeListener("data",a_),process.nextTick(r_,t._socket),t.close(e[OS])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function QS(){this[NS].emitClose()}function e_(e,t){this[NS].emit("message",e,t)}function t_(e){const t=this[NS];t._autoPong&&t.pong(e,!this._isServer,TS),t.emit("ping",e)}function n_(e){this[NS].emit("pong",e)}function r_(e){e.resume()}function i_(e){const t=this[NS];t.readyState!==WS.CLOSED&&(t.readyState===WS.OPEN&&(t._readyState=WS.CLOSING,o_(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function o_(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),RS)}function s_(){const e=this[NS];let t;this.removeListener("close",s_),this.removeListener("data",a_),this.removeListener("end",c_),e._readyState=WS.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[NS]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",QS),e._receiver.on("finish",QS))}function a_(e){this[NS]._receiver.write(e)||this.pause()}function c_(){const e=this[NS];e._readyState=WS.CLOSING,e._receiver.end(),this.end()}function l_(){const e=this[NS];this.removeListener("error",l_),this.on("error",TS),e&&(e._readyState=WS.CLOSING,this.destroy())}const{tokenChars:u_}=yw;var d_={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===u_[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 h_=T,f_=P,{createHash:p_}=j,g_=dS,m_=lw,y_=d_,v_=GS,{GUID:b_,kWebSocket:w_}=Gb,S_=/^[+/0-9A-Za-z]{22}==$/;function __(e){e._state=2,e.emit("close")}function I_(){this.destroy()}function x_(e,t,n,r){n=n||f_.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} ${f_.STATUS_CODES[t]}\r\n`+Object.keys(r).map((e=>`${e}: ${r[e]}`)).join("\r\n")+"\r\n\r\n"+n)}function k_(e,t,n,r,i){if(e.listenerCount("wsClientError")){const r=new Error(i);Error.captureStackTrace(r,k_),e.emit("wsClientError",r,n,t)}else x_(n,r,i)}var E_=sd(class extends h_{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:v_,...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=f_.createServer(((e,t)=>{const n=f_.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(__,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(__,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{__(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",I_);const i=e.headers["sec-websocket-key"],o=e.headers.upgrade,s=+e.headers["sec-websocket-version"];if("GET"!==e.method)return void k_(this,e,t,405,"Invalid HTTP method");if(void 0===o||"websocket"!==o.toLowerCase())return void k_(this,e,t,400,"Invalid Upgrade header");if(void 0===i||!S_.test(i))return void k_(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");if(8!==s&&13!==s)return void k_(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header");if(!this.shouldHandle(e))return void x_(t,400);const a=e.headers["sec-websocket-protocol"];let c=new Set;if(void 0!==a)try{c=y_.parse(a)}catch(n){return void k_(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 m_(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=g_.parse(l);e[m_.extensionName]&&(r.accept(e[m_.extensionName]),u[m_.extensionName]=r)}catch(n){return void k_(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 x_(t,s||401,a,l);this.completeUpgrade(u,i,c,e,t,n,r)}));if(!this.options.verifyClient(o))return x_(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[w_])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return x_(i,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${p_("sha1").update(t+b_).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[m_.extensionName]){const t=e[m_.extensionName].params,n=g_.format({[m_.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",I_),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(__,this)}))),s(c,r)}});const C_=Id("websocketServer"),$_={},O_=kb();let N_,T_,A_,M_,P_;const D_=["https://app.kemu.io","https://dev.kemu.io","https://stage.kemu.io","https://local.kemu.io:3003"],j_=e=>{const t=$_[e];t&&t.socket.close()};var R_=e=>{P_=new E_({port:e,maxPayload:1048576e3,verifyClient:(e,t)=>{const n=e.req.headers.origin;n&&D_.includes(n)?t(!0):t(!1,401,"Origin not allowed")}}),P_.on("connection",(e=>{const t=Uy();C_(`New client connected. Registered as "${t}"`),e.id=t,$_[t]={socket:e,activeMessage:null},N_&&N_(t),e.on("message",(t=>{if(t instanceof Buffer){const n=$_[e.id];O_(t,n.activeMessage,(e=>n.activeMessage=e),(t=>{if(!t.complete)return;const r=t=>{e.send(t),C_(`Writing ${t.byteLength} bytes to socket [${n.socket.id}]: ${t.toString()}`)},i=()=>{j_(n.socket.id)};if(t.command)return C_(`Received command from client [${n.socket.id}]: ${t.command}`),void(A_&&A_(n.socket.id,t.command,r,i));t.klMessage&&M_&&M_({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",(()=>{C_(`Client disconnected: ${e.id}`),T_&&T_(e.id),delete $_[e.id]})),e.on("error",(()=>{C_(`Error on client connection: ${e.id}`)}))})),console.log(`WebSocket server is running on port ${e}`)},L_=e=>{N_=e},F_=e=>{T_=e},U_=e=>{A_=e},B_=(e,t)=>{const n=$_[e];if(!n)return C_(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=rb)return C_("Message is too long to be a command. Use sendMessage instead."),!1;const r=vb.encodeCommand(t);return n.socket.send(r),!0},W_=e=>M_=e,G_=j_;const V_=Id("stopService"),Y_=async e=>{const t=e.args[0];if(!t)return e.reply({error:"No service name provided"});const n=Iv.getAllServiceVersions(t);V_(`Stopping ${n.length} services with name: ${t}`);for(const e of n)await Iv.stopService({serviceName:e.info.name,version:e.info.version});const r=n.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[r]})},H_=Id("removeService"),z_=async e=>{const t=e.args[0],n=e.args[1];if(!t)return e.reply({error:"No service name provided"});let r=Iv.getAllServiceVersions(t);n&&(r=r.filter((e=>e.info.version===n))),H_(`Removing ${r.length} service(s) with name: ${t}`);for(const e of r)await Iv.uninstallService(e.info.name,e.info.version);const i=r.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[i]})},q_=Id("launchService"),K_=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=Qy();q_(`Loading service ${t}@${n} from ${i}`);const{errorMsg:o,service:s,errorCode:a}=await Iv.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?(q_(`Service ${t}@${n} loaded and started`),e.reply({success:[]})):(q_(`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"}):(q_("Retrying in 1 second..."),void setTimeout(u,1e3)))};u()}catch(r){return q_(`Error loading service ${t}@${n}: ${r?.message||r}`),e.reply({error:r?.message||"There was an error loading the service"})}},J_=Id("getMatchingServices"),Z_=async e=>{const t=e.args[0],n=[],r=[];J_(`Checking for matching services: ${t.map((e=>e.name)).join(", ")}`);for(const{name:e,version:i}of t){const t=Iv.getMatchingService(e,i);t?n.push({name:e,version:i,installationPath:Iv.getServiceRootDirectory(t)}):r.push({name:e,version:i})}J_(`Found ${n.length} available services and ${r.length} missing services.`),e.reply({success:[{available:n,missing:r}]})},X_=Id("getSecretsValues");let Q_;var eI=async e=>{const t=e.args[0].services;if(!Q_)throw new Error("getSecretValuesFn is not set. Please call setGetSecretValuesFunction before using this function.");X_(`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 Q_({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})},tI=e=>{Q_=e};const nI=Id("getMappedSecrets");let rI;var iI=async e=>{const t=e.args[0].services;nI(`Getting mapped secrets for services: ${t.map((e=>`${e.name}@${e.version}`)).join(", ")}`);const n=await rI(t),r=[{services:t.map((e=>({name:e.name,version:e.version,secrets:n[e.name]||[]})))}];e.reply({success:r})};const oI=Id("getServiceContents"),sI=({reply:e,args:t})=>{const[n]=t;oI(`Received GetServiceContents request for service ${n.serviceName} v${n.version}`);const r=Iv.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}]});oI(`Service ${n.serviceName} v${n.version} not found`),e({error:`Service ${n.serviceName} v${n.version} not found`})};let aI={globalApiKey:void 0,environment:"production"};const cI=()=>({...aI}),lI=Id("apis"),uI=()=>{const e=cI();if(!e.serviceUrl)throw new Error("Unknown server URL. Please call `edgeConfig.setEdgeConfig` before using the APIs.");return e.serviceUrl},dI=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}}},hI={},fI=async e=>{const t=(e=>{const t=hI[e],n=Date.now()-(t?.lastCheckedAt.getTime()??0);return t&&n<3e5?t.features:null})(e);if(t)return{valid:!0,features:t,error:null};const{valid:n,features:r,error:i}=await(async e=>{const{data:t,error:n}=await dI(`${uI()}/v1/organization/validate/apiKey`,{apiKey:e},{"Content-Type":"application/json"});return n?(lI(`Error validating Kemu API key: ${n}`),{valid:!1,features:{},error:n}):t?.features?{valid:!0,features:t.features,error:null}:{valid:!1,features:{},error:"No features returned from the server"}})(e);return n&&(hI[e]={features:r,lastCheckedAt:new Date}),{valid:n,features:r,error:i}};function pI(e){return"number"==typeof e||!!/^0x[0-9a-f]+$/i.test(e)||/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(e)}function gI(e,t){return"constructor"===t&&"function"==typeof e[t]||"__proto__"===t}var mI=sd((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(gI(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];gI(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]&&pI(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._||!pI(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}));pb("ipcClient"),pb("kemuWidgetService"),mI(process.argv.slice(2));const yI=Id("activeClients");let vI,bI={},wI={};const SI=(e,t)=>`${e}_${t}`,_I=e=>bI[e]||null,II=(e,t)=>{const n=SI(e,t);return wI[n]||[]},xI=()=>{for(const e in bI){const t=bI[e];if(t?.transport===Bu.WS){const e=vb.encodeCommand(Lu.ServicesListChanged);t.send(e)}}},kI=async e=>{const t=[],{serviceSessionId:n,transport:r,send:i,terminateFn:o,extraInfo:s,isDevClient:a}=e,c=e=>{console.warn(e),o&&o()};if(r===Bu.WS){if(!s.user?.wsApiKey)return void c(`Attempted to register a WebSocket client without an API key. SessionId: ${n}`);const{valid:e,error:t}=await fI(s.user?.wsApiKey);if(!e&&!t)return void c(`Attempted to register a WebSocket client with an invalid API key. SessionId: ${n}`);t&&(s.user?.wsApiKey&&rv.captureError({error:new Error(t),message:`Error validating api key "${s.user?.wsApiKey}"`,data:s}),yI(`Unable to validate API Key, usage will be limited. SessionId: ${n}`))}bI[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=SI(e.serviceName,e.version);return wI[r]=wI[r]||[],wI[r].some((e=>e.serviceId===n))||wI[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=SI(e.serviceName,e.version),o=wI[i]?.findIndex((e=>e.serviceId===n));if(-1!==o&&(wI[i]?.splice(o,1),!wI[i]?.length)){const t=Iv.getMatchingService(e.serviceName,e.version);if(t?.info.eventEmitter&&"running"===t.status){const e=_I(t.info.sessionId);e?.extraInfo.ipcSocketId&&Pb(e?.extraInfo.ipcSocketId,Lu.BroadcastEnd)}}}},removeAllSubscriptions:()=>{for(const e of t){const t=SI(e.targetService.serviceName,e.targetService.version),r=wI[t]?.findIndex((e=>e.serviceId===n));-1!==r&&wI[t]?.splice(r,1)}t.length=0}},r===Bu.IPC&&(xI(),EI(n))},EI=e=>{const t=Iv.getServiceBySessionId(e);if(t?.info.eventEmitter&&II(t.info.name,t.info.version).length){const t=_I(e);t?.extraInfo.ipcSocketId&&Pb(t?.extraInfo.ipcSocketId,Lu.BroadcastStart)}},CI=e=>{const t=bI[e];var n;t?.transport===Bu.IPC?xI():(t?.removeAllSubscriptions(),(()=>{const e=Object.values(bI);for(const t of e)if(t.transport===Bu.IPC){const e=t.extraInfo.ipcSocketId,n=Iv.getServiceBySessionId(t.serviceSessionId);n?.info.eventEmitter&&(II(n.info.name,n.info.version).length||e&&Pb(e,Lu.BroadcastEnd))}})(),t?.extraInfo.user?.wsApiKey&&(n=t.extraInfo.user.wsApiKey,delete hI[n]),(e=>{const t=bI[e];if(t?.transport===Bu.WS&&t.extraInfo.recipe){const n=[{recipe:t.extraInfo.recipe}];yI(`Notifying IPC clients that a Kemu Compose client [${t.extraInfo.recipe.name} (${t.extraInfo.recipe.poolId})] has disconnected. ServiceSessionId: ${e}`);for(const e in bI){const t=bI[e];t?.transport===Bu.IPC&&vI.execute(Fu.KemuComposerDisconnected,n,t.send,0,t.serviceSessionId,{async:!0}).catch((t=>{yI(`Error notifying IPC client [${e}] that a Kemu Compose client has disconnected: ${t?.message||t}`)}))}}})(e)),delete bI[e]},$I=Id("ipc:handleIpcClientCommand"),OI=(e,t,n)=>{const r=((e,t)=>{if(e.startsWith(Lu.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 $I(`Ignoring ACK response from IPC service ${e} with no service id`);$I(`Received ACK from IPC service ${e}. Marking as running.`);let r=e;t&&e&&e!==t&&(Db(e,t),r=t);let i=!1;t&&(i=Iv.setServiceStatus(t,"running")),i?kI({serviceSessionId:t||e,transport:Bu.IPC,send:n,extraInfo:{ipcSocketId:t}}):Pb(r,Lu.SendManifest)}));!r&&$I(`Received unknown command [${t}] from service ${e}`)};let NI={};G.platform();const TI=async e=>{const t=e.args[0];if(NI.chooseDirectory)try{const n=await NI.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"})},AI=async e=>{const t=e.args[0];if(NI.chooseFile)try{const n=await NI.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 MI={},PI={},DI={};function jI(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function RI(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function LI(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function FI(e,...t){if(!LI(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 UI(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");jI(e.outputLen),jI(e.blockLen)}function BI(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 WI(e,t){FI(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}Object.defineProperty(DI,"__esModule",{value:!0}),DI.output=DI.exists=DI.hash=DI.bytes=DI.bool=DI.number=DI.isBytes=void 0,DI.number=jI,DI.bool=RI,DI.isBytes=LI,DI.bytes=FI,DI.hash=UI,DI.exists=BI,DI.output=WI;const GI={number:jI,bool:RI,bytes:FI,hash:UI,exists:BI,output:WI};DI.default=GI;var VI={};Object.defineProperty(VI,"__esModule",{value:!0}),VI.add5L=VI.add5H=VI.add4H=VI.add4L=VI.add3H=VI.add3L=VI.add=VI.rotlBL=VI.rotlBH=VI.rotlSL=VI.rotlSH=VI.rotr32L=VI.rotr32H=VI.rotrBL=VI.rotrBH=VI.rotrSL=VI.rotrSH=VI.shrSL=VI.shrSH=VI.toBig=VI.split=VI.fromBig=void 0;const YI=BigInt(2**32-1),HI=BigInt(32);function zI(e,t=!1){return t?{h:Number(e&YI),l:Number(e>>HI&YI)}:{h:0|Number(e>>HI&YI),l:0|Number(e&YI)}}function qI(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}=zI(e[i],t);[n[i],r[i]]=[o,s]}return[n,r]}VI.fromBig=zI,VI.split=qI;const KI=(e,t)=>BigInt(e>>>0)<<HI|BigInt(t>>>0);VI.toBig=KI;const JI=(e,t,n)=>e>>>n;VI.shrSH=JI;const ZI=(e,t,n)=>e<<32-n|t>>>n;VI.shrSL=ZI;const XI=(e,t,n)=>e>>>n|t<<32-n;VI.rotrSH=XI;const QI=(e,t,n)=>e<<32-n|t>>>n;VI.rotrSL=QI;const ex=(e,t,n)=>e<<64-n|t>>>n-32;VI.rotrBH=ex;const tx=(e,t,n)=>e>>>n-32|t<<64-n;VI.rotrBL=tx;const nx=(e,t)=>t;VI.rotr32H=nx;const rx=e=>e;VI.rotr32L=rx;const ix=(e,t,n)=>e<<n|t>>>32-n;VI.rotlSH=ix;const ox=(e,t,n)=>t<<n|e>>>32-n;VI.rotlSL=ox;const sx=(e,t,n)=>t<<n-32|e>>>64-n;VI.rotlBH=sx;const ax=(e,t,n)=>e<<n-32|t>>>64-n;function cx(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:0|i}}VI.rotlBL=ax,VI.add=cx;const lx=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0);VI.add3L=lx;const ux=(e,t,n,r)=>t+n+r+(e/2**32|0)|0;VI.add3H=ux;const dx=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0);VI.add4L=dx;const hx=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0;VI.add4H=hx;const fx=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0);VI.add5L=fx;const px=(e,t,n,r,i,o)=>t+n+r+i+o+(e/2**32|0)|0;VI.add5H=px;const gx={fromBig:zI,split:qI,toBig:KI,shrSH:JI,shrSL:ZI,rotrSH:XI,rotrSL:QI,rotrBH:ex,rotrBL:tx,rotr32H:nx,rotr32L:rx,rotlSH:ix,rotlSL:ox,rotlBH:sx,rotlBL:ax,add:cx,add3L:lx,add3H:ux,add4L:dx,add4H:hx,add5H:px,add5L:fx};VI.default=gx;var mx={},yx={};Object.defineProperty(yx,"__esModule",{value:!0}),yx.crypto=void 0,yx.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=yx,n=DI;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")}}(mx),Object.defineProperty(PI,"__esModule",{value:!0}),PI.shake256=PI.shake128=PI.keccak_512=PI.keccak_384=PI.keccak_256=PI.keccak_224=PI.sha3_512=PI.sha3_384=PI.sha3_256=PI.sha3_224=PI.Keccak=PI.keccakP=void 0;const vx=DI,bx=VI,wx=mx,Sx=[],_x=[],Ix=[],xx=BigInt(0),kx=BigInt(1),Ex=BigInt(2),Cx=BigInt(7),$x=BigInt(256),Ox=BigInt(113);for(let e=0,t=kx,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],Sx.push(2*(5*r+n)),_x.push((e+1)*(e+2)/2%64);let i=xx;for(let e=0;e<7;e++)t=(t<<kx^(t>>Cx)*Ox)%$x,t&Ex&&(i^=kx<<(kx<<BigInt(e))-kx);Ix.push(i)}const[Nx,Tx]=(0,bx.split)(Ix,!0),Ax=(e,t,n)=>n>32?(0,bx.rotlBH)(e,t,n):(0,bx.rotlSH)(e,t,n),Mx=(e,t,n)=>n>32?(0,bx.rotlBL)(e,t,n):(0,bx.rotlSL)(e,t,n);function Px(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=Ax(o,s,1)^n[r],c=Mx(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=_x[n],o=Ax(t,i,r),s=Mx(t,i,r),a=Sx[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]^=Nx[r],e[1]^=Tx[r]}n.fill(0)}PI.keccakP=Px;class Dx extends wx.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,vx.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,wx.u32)(this.state)}keccak(){wx.isLE||(0,wx.byteSwap32)(this.state32),Px(this.state32,this.rounds),wx.isLE||(0,wx.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,vx.exists)(this);const{blockLen:t,state:n}=this,r=(e=(0,wx.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,vx.exists)(this,!1),(0,vx.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,vx.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,vx.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 Dx(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}}PI.Keccak=Dx;const jx=(e,t,n)=>(0,wx.wrapConstructor)((()=>new Dx(t,e,n)));PI.sha3_224=jx(6,144,28),PI.sha3_256=jx(6,136,32),PI.sha3_384=jx(6,104,48),PI.sha3_512=jx(6,72,64),PI.keccak_224=jx(1,144,28),PI.keccak_256=jx(1,136,32),PI.keccak_384=jx(1,104,48),PI.keccak_512=jx(1,72,64);const Rx=(e,t,n)=>(0,wx.wrapXOFConstructorWithOpts)(((r={})=>new Dx(t,e,void 0===r.dkLen?n:r.dkLen,!0)));PI.shake128=Rx(31,168,16),PI.shake256=Rx(31,136,32);const{sha3_512:Lx}=PI,Fx=(e=4,t=Math.random)=>{let n="";for(;n.length<e;)n+=Math.floor(36*t()).toString(36);return n};function Ux(e){let t=0n;for(const n of e.values())t=(t<<8n)+BigInt(n);return t}const Bx=(e="")=>Ux(Lx(e)).toString(36).slice(1),Wx=Array.from({length:26},((e,t)=>String.fromCharCode(t+97))),Gx=({globalObj:e=(void 0!==od?od:"undefined"!=typeof window?window:{}),random:t=Math.random}={})=>{const n=Object.keys(e).toString(),r=n.length?n+Fx(32,t):Fx(32,t);return Bx(r).substring(0,32)},Vx=e=>()=>e++,Yx=({random:e=Math.random,counter:t=Vx(Math.floor(476782367*e())),length:n=24,fingerprint:r=Gx({random:e})}={})=>function(){const i=(e=>Wx[Math.floor(e()*Wx.length)])(e),o=Date.now().toString(36),s=t().toString(36),a=Fx(n,e);return`${i+Bx(`${o+a+s+r}`).substring(1,n)}`},Hx=Yx();MI.getConstants=()=>({defaultLength:24,bigLength:32}),MI.init=Yx,MI.createId=Hx,MI.bufToBigInt=Ux,MI.createCounter=Vx,MI.createFingerprint=Gx,MI.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:zx,init:qx,getConstants:Kx,isCuid:Jx}=MI;var Zx=zx;const Xx=Id("getUniqueId"),Qx=({reply:e,sourceServiceId:t})=>(Xx(`Generating unique id for service "${t}"`),e({success:[Zx()]})),ek=Id("getActiveServices"),tk=async({transport:e,sourceServiceId:t,reply:n})=>{if(ek(`Received GetServices request from ${e} [${t}]`),e===Bu.WS){let e=Iv.getActiveServices();const r=_I(t);if(!r)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});let i=[];if(r.transport===Bu.WS){if(!r?.extraInfo.user?.wsApiKey)return n({error:"Client does not have an API key",errCode:"CLIENT_NO_API_KEY"});const t=e.filter(Iv.isInternalKemuService),o=e.filter((e=>e.devMode&&Iv.isNotInternalKemuService(e))),s=e.filter((e=>Iv.isOfficialKemuService(e)&&Iv.isNotInternalKemuService(e)&&Iv.isNotDevService(e))).sort(((e,t)=>e.name.localeCompare(t.name))),a=e.filter((e=>Iv.isNotDevService(e)&&Iv.isNotInternalKemuService(e)&&!Iv.isOfficialKemuService(e))),c=await(async e=>{const{features:t}=await fI(e);return t})(r.extraInfo.user?.wsApiKey),l=c?.hub_services??0,u=s.slice(0,-1!==l?l:s.length);-1!==l&&(i=s.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,...o,...u,...a]}const o=Iv.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:Iv.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 nk="runtime",rk=null;const ik=()=>nk,ok=Id("getSystemInfo"),sk=async({reply:e})=>{ok("Received GetSystemInfo request"),e({success:[await(async()=>({platformArch:qu(),isDesktopHub:"desktop"===ik(),isRuntimeHub:"runtime"===ik(),hubVersion:Vy,...rk?{updateAvailable:rk}:{}}))()]})},ak=Id("removeService"),ck=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=Iv.getAllServiceVersions(i),a=s.find((e=>e.info.version===o));if(!a)return n({error:"Service not found"});ak(`Removing ${s.length} service(s) with name: ${i}`);const c=a.info.publicationId;let l;if(await Iv.uninstallService(a.info.name,a.info.version),c){const e=_I(t);if(!e)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});const r=e.extraInfo.user?.wsApiKey;if(!r)return n({error:"Client does not have an API key",errCode:"CLIENT_NO_API_KEY"});ak(`Updating license details for "${c}"`);const i=await(async e=>{const{data:t,error:n}=await dI(`${uI()}/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=>(ak(`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}}]})},lk=Id("getDecryptedEdgeApiKey"),uk=({reply:e})=>(lk("Getting decrypted edge API key"),e({success:[cI().globalApiKey]})),dk=({reply:e})=>{lk("Getting hub config");const t=cI();return e({success:[{kemuApiKey:t.globalApiKey,environment:t.environment}]})};let hk,fk,pk,gk,mk;const yk=e=>e.transport===Bu.IPC&&(e.reply({error:"Transport is not allowed to call this function"}),!0);var vk=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(!hk)return e.reply({error:"Get recipe secrets function not set"});const i=await hk({...t[0]}),o={};for(const e of r)o[e]=e in i?i[e]:null;const s=[{secrets:o}];e.reply({success:s})},bk=async e=>{const t=e.args,n=t[0].recipeUuid,r=t[0].secretsMap;if(yk(e))return;if(!fk)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 fk({recipeUuid:n,secretsMap:r})}];e.reply({success:i})},wk=async e=>{const t=e.args,n=t[0].recipeUuid,r=t[0].secretName;if(yk(e))return;if(!pk)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 pk({recipeUuid:n,secretName:r})}];e.reply({success:i})},Sk=async e=>{const t=e.args[0].recipeUuid;if(!gk)return e.reply({error:"Get recipe secret mappings function not set"});if(!t)return e.reply({error:"Invalid request parameters"});const n=[{secrets:await gk({recipeUuid:t})}];e.reply({success:n})},_k=async e=>{const t=e.args,n=t[0].hubServiceName,r=t[0].secrets;return mk?n&&r?Array.isArray(r)?(await mk({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 Ik,xk,kk;const Ek=e=>e.transport===Bu.IPC&&(e.reply({error:"You are not allowed to manage secrets using this transport"}),!0);var Ck=async e=>{if(e.args,Ek(e))return;if(!kk)return e.reply({error:"Get hub secrets function not set"});const t=[{contexts:await kk()}];e.reply({success:t})},$k=async e=>{const t=e.args;if(Ek(e))return;if(!Ik)return e.reply({error:"Add hub secret function not set"});const n=[{contexts:await Ik(t[0])}];e.reply({success:n})},Ok=async e=>{const t=e.args;if(Ek(e))return;if(!xk)return e.reply({error:"Delete hub secret function not set"});const n=[{contexts:await xk(t[0])}];e.reply({success:n})};const Nk=S(W(import.meta.url));let Tk=null;const Ak=Id("hub"),Mk=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=ob?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=Lb.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}Fb+=1;const u=`${i}-${Fb}-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=ob?new ArrayBuffer(0):Buffer.alloc(0);const f={json:{functionName:t,args:r,messageId:u,type:"execute"}};s(c)&&(h=Lb.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)=>{Fb+=1;const a=`${i}-${Fb}-multicast-${e.substring(0,10)}`;let c=ob?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=Lb.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=Lb.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");vI=Mk,Mk.setLogger(Ak);const Pk={[Fu.RebootToInstallUpdate]:null,[Fu.GetFileContentFromCacheId]:null,[Fu.SaveRecipeToFile]:null},Dk=(e,t)=>{const{transmission:n}=t;if(0!==n.targetServiceId){const r=_I(n.targetServiceId);if(!r)return Ak(`Service [${e}] ${n.sourceServiceId} is sending data to an unknown service ["${n.targetServiceId}"]`),!0;r.transport,Bu.IPC;const i=t.json?.messageId;return Ak(`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},jk=({sourceServiceId:e,args:t})=>{const n=Iv.getServiceBySessionId(e);if(n){const r=II(n.info.name,n.info.version),i=II(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}};Mk.broadcast(Fu.BroadcastEvent,[s],o,0)}},Rk=async({args:e,reply:t})=>{const n=e[0];if(!n)return Ak("Invalid config for SendToRecipe"),t({error:"Invalid config for SendToRecipe"});const r=(i=n.recipePoolId,Object.values(bI).find((e=>e.extraInfo.recipe?.poolId===i))||null);var i;if(!r)return Ak(`No client found for recipe pool id ${n.recipePoolId}`),t({error:`No client found for recipe pool id "${n.recipePoolId}"`});try{const e=Mk.execute(Fu.SendToRecipe,[n],r.send,0,r.serviceSessionId,{async:!n.waitForResponse,timeout:n.timeout});n.waitForResponse?t({success:await e}):t({success:[]})}catch(e){return Ak(`Error sending to recipe ${n.recipePoolId}: ${e?.message||e}`),t({error:e?.message||"There was an error sending to the recipe"})}},Lk=e=>{const{send:t,transmission:n,json:r}=e;Ak(`Raw message Id received from WS: ${r?.messageId}`),Dk(Bu.WS,e)||Mk.processMessage(Bu.WS,t,n,r)},Fk=e=>{const t=(n=e,`${Lu.SocketAcknowledge}${n}`);var n;B_(e,t)},Uk=(e,t)=>{Ak(`Received unknown command [${t}] from service ${e}`)},Bk=async e=>{const{args:t,sourceServiceId:n,send:r,reply:i}=e,o=n,s=t[0],a=s?.user?.apiKey||cI().globalApiKey;if(!a)return Ak(`Received ACK from WS service ${n} but no API key was provided`),i({error:"No API key was provided",errCode:"MISSING_API_KEY"});s.user?.id&&rv.setGlobalUserId(s.user?.id),await kI({serviceSessionId:n,transport:Bu.WS,send:r,terminateFn:()=>{G_(n)},extraInfo:{websocketId:o,recipe:s.recipe,user:{wsApiKey:a,userEmail:s.user?.email,userId:s.user?.id}}}),i({success:[]})},Wk=e=>{Ak(`WS Client ${e} disconnected`),CI(e)},Gk=e=>1===e.sourceServiceId?e.functionName===Fu.GetFileContentFromCacheId:e.functionName===Fu.SocketAckResponse||e.functionName===Fu.ServiceManifest||e.functionName===Fu.SubscribeToService||(!!_I(e.sourceServiceId)||(e.reply({error:`Session id "${e.sourceServiceId}" not found. Please acknowledge the session first.`}),!1)),Vk=async({sourceServiceId:e,args:t,transport:n,send:r})=>{if(n!==Bu.IPC){var i;Ak(`Received manifest from non IPC service ${e}.`)}else{const n=t[0];if(n.devMode){const t=Iv.getMatchingDevService(n.name,n.version,"stopped");if(t){Ak(`Found matching previous service ${t.info.name} (${t.info.version}). Reactivating previous client with session id ${t.info.sessionId}`);const o=_I(t.info.sessionId);if(!o)return void Ak(`Could not find previous client instance for ${t.info.name} (${t.info.version}). Aborting manifest injection`);o.send=r,bI[i=e]?delete bI[i]:yI(`Could not find source client with session id ${i}`),Db(e,t.info.sessionId);const s=await Ky(n,n.path);t.info={...t.info,...s},Ak(`Updating manifest for dev service ${t.info.sessionId}`),Iv.setServiceManifest(t.info.sessionId,s,"running"),Ak(`Asking service ${e} to assume previous session id ${t.info.sessionId}`),Pb(t.info.sessionId,(e=>`${Lu.AssumeSession}${e}`)(t.info.sessionId)),(e=>{const t=bI[e];t?t.isDevClient?(t.disconnected=!1,t.transport===Bu.IPC&&(xI(),EI(e))):yI(`Client with session id ${e} is not a dev client`):yI(`Could not find source client with session id ${e}`)})(t.info.sessionId)}else{Iv.addDevService(e,n,"running");const t=_I(e);t?t.isDevClient=!0:kI({serviceSessionId:e,transport:Bu.IPC,send:r,extraInfo:{ipcSocketId:e},isDevClient:!0})}return}Ak(`Received manifest from non dev service ${e} [${n.name}@(${n.version})]. Ignoring...`)}};var Yk=async e=>{var t;Ak("Starting Kemu Hub..."),t=e.desktopMode?"desktop":"runtime",nk=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&&rv.setTracker(e.errorTracker),(e=>{aI={...aI,...e}})({serviceUrl:e.serviceUrl,globalApiKey:e.globalApiKey,environment:e.environment}),Mk.registerFunctionsMiddleware(Gk),e.secrets?.serviceSecrets&&(e=>{mk=e})(e.secrets.serviceSecrets.addServiceSecretFn),e.secrets?.recipeSecrets&&((e=>{hk=e})(e.secrets.recipeSecrets.getRecipeDecryptedSecretsFn),(e=>{fk=e})(e.secrets.recipeSecrets.addRecipeSecretFn),(e=>{pk=e})(e.secrets.recipeSecrets.deleteRecipeSecretFn),(e=>{gk=e})(e.secrets.recipeSecrets.getRecipeSecretMappingsFn)),e.secrets?.hubSecrets&&((e=>{kk=e})(e.secrets.hubSecrets.getHubSecretsFn),(e=>{Ik=e})(e.secrets.hubSecrets.addHubSecretsFn),(e=>{xk=e})(e.secrets.hubSecrets.deleteHubSecretFn)),Mk.registerFunction(Fu.GetServiceContents,sI),Mk.registerFunction(Fu.GetServices,tk),Mk.registerFunction(Fu.GetSystemInfo,sk),Mk.registerFunction(Fu.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"})})),Mk.registerFunction(Fu.UnsubscribeFromService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===Bu.WS){const[e]=n,i=_I(r);if(!i)return t({error:`Session id "${r}" not found`});Ak(`Service ${r} unsubscribing from "${e.targetService.serviceName} (${e.targetService.version})"`),t({success:[]}),i?.removeSubscription({serviceName:e.targetService.serviceName,version:e.targetService.version})}})),Mk.registerFunction(Fu.SubscribeToService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===Bu.WS){const[e]=n,i=_I(r),o=e.targetService;if(!i)return t({error:`Session id "${r}" not found`});if(Ak(`Service ${r} subscribing to "${o.serviceName} (${o.version})"`),"hub"===o.serviceName)return i.addSubscription(o),void t({success:[]});if(!i.addSubscription(o))return Ak(`Service ${r} already subscribed to "${o.serviceName} (${o.version})", ignoring request.`),t({success:[]});const s=Iv.getMatchingService(o.serviceName,o.version);if(!s)return Ak(`Service ${o.serviceName} ${o.version} not active yet`),t({success:[]});if(!s.info.eventEmitter)return Ak(`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=_I(s.info.sessionId);return a?.extraInfo.ipcSocketId&&(Ak(`Sending Broadcast START command to service ${s.info.sessionId}`),Pb(a?.extraInfo.ipcSocketId,Lu.BroadcastStart)),t({success:[]})}})),Mk.registerFunction("stopService",Y_),Mk.registerFunction("removeService",z_),Mk.registerFunction("launchService",K_),Mk.registerFunction("getMatchingServices",Z_),Mk.registerFunction("getSecretsValues",eI),Mk.registerFunction(Fu.GetMappedSecrets,iI),Mk.registerFunction(Fu.BroadcastEvent,jk),Mk.registerFunction(Fu.ServiceManifest,Vk),Mk.registerFunction(Fu.ChooseDirectoryDialog,TI),Mk.registerFunction(Fu.ChooseFileDialog,AI),Mk.registerFunction(Fu.GetUniqueId,Qx),Mk.registerFunction(Fu.SendToRecipe,Rk),Mk.registerFunction(Fu.GetDecryptedEdgeApiKey,uk),Mk.registerFunction(Fu.GetHubConfig,dk),Mk.registerFunction(Fu.SocketAckResponse,Bk),Mk.registerFunction(Fu.UninstallService,ck),Mk.registerFunction(Fu.GetRecipeDecryptedSecretsValues,vk),Mk.registerFunction(Fu.GetRecipeSecretMappings,Sk),Mk.registerFunction(Fu.AddRecipeSecretMapping,bk),Mk.registerFunction(Fu.DeleteRecipeSecretMapping,wk),Mk.registerFunction(Fu.GetHubSecrets,Ck),Mk.registerFunction(Fu.AddHubSecrets,$k),Mk.registerFunction(Fu.DeleteHubSecret,Ok),Mk.registerFunction(Fu.AddServiceSecret,_k),Object.entries(Pk).forEach((([e,t])=>{t?Mk.registerFunction(e,t):(Ak(`Skipping registration of "${e}" because it's not implemented`),Mk.registerFunction(e,(({reply:t})=>{t({error:`This hub does not support "${e}"`,errCode:"FUNCTION_NOT_SUPPORTED"})})))})),(e=>{Nb=e})((e=>{const{send:t,transmission:n,json:r}=e;Ak(`Raw message Id received from IPC: ${r?.messageId}`),Dk(Bu.IPC,e)||Mk.processMessage(Bu.IPC,t,n,r)})),W_(Lk),L_(Fk),U_(Uk),F_(Wk),(e=>{Ob=e})(OI),(e=>{Cb=e})((e=>{const t=(e=>`${Lu.IpcAcknowledge}${e}`)(e);Pb(e,t)})),(e=>{$b=e})((e=>{Ak(`IPC socket [${e}] disconnected`);const t=_I(e);if(t){Ak(`Found matching service for disconnected socket. SessionId: ${t.serviceSessionId}`);const e=Iv.getServiceBySessionId(t.serviceSessionId);Iv.setServiceStatus(t.serviceSessionId,"stopped"),e?.devMode?(t.disconnected=!0,xI()):CI(t.serviceSessionId)}})),await(e=>(e?.ipcId&&(nb.config.id=e.ipcId),e?.ipcAppSpace&&(nb.config.appspace=e.ipcAppSpace),new Promise((e=>{nb.serve((()=>{Eb.info("IPC Server Initiated"),nb.server.on("data",((e,t)=>{const n=Tb[t.id];n?(Eb.data(`IPC Socket [${t.id}] data ${e.byteLength} bytes`),Ab(e,n.activeMessage,(e=>n.activeMessage=e),(e=>{if(!e.complete)return;const n=e=>{t.write(e)};if(e.command)return Eb.data(`Received command from client [${t.id}]: ${e.command}`),void(Ob&&Ob(t.id,e.command,n));e.klMessage&&Nb&&Nb({send:n,transmission:{sourceServiceId:e.sourceServiceId??-1,targetServiceId:e.targetServiceId??-1,rawMessage:e.rawMessage},json:e.klMessage.json})}))):Eb.data(`Received data from unknown client [${t.id}]. Ignoring.`)})),nb.server.on("connect",(e=>{const t=Uy();Eb.info(`New client connected. Registered as "${t}"`),e.id=t,Tb[t]={socket:e,activeMessage:null,disconnectHandler:()=>Mb(t)},e.on("close",Tb[t].disconnectHandler),Cb&&Cb(t)})),nb.server.on("disconnect",(e=>{Mb(e.id)})),nb.server.on("error",(e=>{console.log(`IPC Server Error: ${e}`)})),e()})),nb.server.start()}))))({ipcAppSpace:n,ipcId:r}),e?.ws?.disabled||await R_(e?.ws?.port||5368);const i=e?.defaultServicesPath||b.resolve(Nk,"defaultServices");Tk=i;const o=process.env.DEV_SESSION_ID;Iv.setHubIpcConfig({recipePath:e?.recipeRootPath,appSpace:n,id:r}),Iv.setEnableServiceLogsConfig(!!e?.enableServiceLogs),e?.servicesInstallPath&&(e=>{Zy=e})(e.servicesInstallPath),e?.testServicesInstallPath&&(e=>{Xy=e})(e.testServicesInstallPath);const s=Qy(),a=ev(),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=cI().serviceUrl,t.__KEMU_ENVIRONMENT=cI().environment,t};e?.getServiceSecretsFn?(Iv.setGetSecretsFunction(e.getServiceSecretsFn),tI(e.getServiceSecretsFn)):(Iv.setGetSecretsFunction(c),tI(c)),(e=>{rI=e})(e?.getMappedSecretsFn?e.getMappedSecretsFn:async e=>e.reduce(((e,t)=>({...e,[t.name]:[]})),{})),Iv.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 Iv.loadServices(i,{fixedSession:o?parseInt(o):void 0,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,internalServices:!0,enableLogs:!0}),null!==e?.servicesInstallPath&&(await Jy(s)||await h(s,{recursive:!0}),await Iv.loadServices(s,{internalServices:!1,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,enableLogs:!!e?.enableServiceLogs}));const l=process.env.DEV_NO_SPAWN_LIST?.split(",");await Iv.launchServices({noSpawningList:l||[]}),Ak("Kemu Hub started"),(e?.onChooseDirectory||e?.onChooseFile)&&(e=>{NI=e})({chooseDirectory:e.onChooseDirectory,chooseFile:e.onChooseFile})},Hk=e=>{if(e===Bu.WS)return{handleWebsocketConnectionEvent:Fk,handleWebsocketClientDisconnectionEvent:Wk,handleWebsocketMessage:Lk,handleWebsocketClientCommand:Uk,getRemoteInvoke:()=>Mk}},zk=(e=[])=>{let t;const n=new Promise((n=>{const r=()=>{if(Iv.getAllServices().every((e=>"running"===e.status))&&e.every((e=>"running"===Iv.getMatchingService(e.name,e.version)?.status)))return n();t=setTimeout(r,100)};r()}));return n.abort=()=>{t&&clearTimeout(t)},n};let qk;const Kk=Ml("run"),Jk=Vu(),Zk=1e3,Xk=v(process.argv.slice(2)),Qk=e=>"number"==typeof e?{type:ge.Number,value:e}:"string"==typeof e?{type:ge.String,value:e}:"boolean"==typeof e?{type:ge.Boolean,value:e}:Array.isArray(e)?{type:ge.Array,value:e}:e;global.ImageData=q;const eE=e=>e&&"string"==typeof e.format&&e.data&&e.data instanceof ArrayBuffer;xe({createCanvas:(e,t)=>J(e,t),loadImage:async e=>{let t=e;if(eE(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 tE=(e,t)=>"*"===e?co.onAnyGlobalVariableChange(t):co.onGlobalVariableChange(e,t),nE=(e,t,n)=>co.setGlobalVariable({name:e,value:t,disableChangeNotifications:n?.disableChangeNotifications||!1,disableDefineNotifications:n?.disableDefineNotifications||!1,doNotOverrideExisting:n?.doNotOverrideExisting||!1}),rE=e=>{co.deleteGlobalVariable({name:e})},iE=()=>co.getAllVariables(),oE=e=>co.getGlobalVariable(e),sE=e=>Gi(e),aE=e=>async()=>{throw new Error(`${e} not implemented`)},cE={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:ge.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 lE={start:async r=>{r=r||{};const i=r?.runtimeCommand?.trim()||process.env.KEMU_EDGE_RUNTIME_COMMAND?.trim(),o=r?.recipePath||Xk.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=Y(o),{parsed:a,error:c}=await e({path:H(z(s),".env")});c&&console.warn(`Failed to load .env file: ${c.message}. This is not an error, it just means that the .env file is not present or is not readable.`);const l=r.apiKey||process.env.KEMU_API_KEY,u=process.env.KEMU_CONFIG;if(!l)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(!u)throw new Error("Missing server URL or environment in config.envConfig");const d=o.endsWith(".json")||o.endsWith(".kemu"),h=d?Y(o):o,f=d?o:H(h,"recipe.kemu"),p=(e=>{try{return JSON.parse(e||"")}catch(e){return null}})(await t(z(f),"utf-8"));if(!p)throw new Error("Failed to parse recipe file");if(!p.author?.id)throw new Error("Missing required author ID in recipe file.");const{serviceUrl:g,environment:m}=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}})(u);await sc();const y={id:p.uuid||String(Date.now()),version:1,author:p.author.id};(e=>{po=e})(console);const v=Hk(Se.WS),b=(e,t)=>{if(t)v?.handleWebsocketMessage({send:S,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg?.json});else{const t=e instanceof Buffer?e.toString():e;v?.handleWebsocketClientCommand(Zk,t)}},w=(bl={instanceServiceId:Zk,sendBuf:b,sendCmd:b,triggerOnCommand:(...e)=>wl(...e),triggerOnConnected:()=>Sl(),triggerOnDisconnected:()=>_l(),triggerOnMessageReceived:(...e)=>Il(...e)},bl);const S=(e,t)=>{if(t)w.triggerOnMessageReceived({send:b,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg.json});else{const t=e instanceof Buffer?e.toString():e;w.triggerOnCommand(t)}},_=Hu(),I=v.getRemoteInvoke();_.disableServiceEncoding(0,!0),I.disableServiceEncoding(Zk,!0);const x=Object.values(p.blocks[fe].gates).filter((e=>e.type===qe.hubService&&e.state.service&&!0!==e.state.service?.webOnly)),k=x.map((e=>{const t=e.state.service;return{name:t.name,version:t.version}})),E=H(h,"services"),C=await n(E).then((()=>!0)).catch((()=>!1));if(k.length>0&&!C)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.");await Yk({globalApiKey:l,serviceUrl:g,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);return Z(r[0],r.slice(1).concat(e||[]),t)}:null,recipeRootPath:h,servicesInstallPath:C?H(h,"services"):null,noDefaultServices:!0,environment:m,ws:{disabled:!0},secrets:{recipeSecrets:{getRecipeDecryptedSecretsFn:async()=>({...a}),getRecipeSecretMappingsFn:aE("getRecipeSecretMappingsFn"),addRecipeSecretFn:aE("addRecipeSecretFn"),deleteRecipeSecretFn:aE("deleteRecipeSecretFn")}},ipc:{appSpace:"kemu-runner.",id:y.id}}),Kk("Waiting for services to run"),await zk(k),Kk("All services are running"),Wc(Jk),Hc(),ca((e=>{Kk("Global processing state changed: ",e)})),p.globalVariables&&(p.globalVariables=await qc(p.globalVariables));const $=await Fc(p,"runner",y.version,y.author,yr.Desktop);return qk=$,Yu($),await Wu({id:p.author.id}),new Promise(((e,t)=>{var n;Gu("acknowledged",(async()=>{await Jk.getServices();const{failed:n,sendToInputWidget:r,invokeRecipeLoadedWidgets:i}=await Bc($);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)})),Kk("Recipe started"),e({sendToInputWidgetAndWaitForOutput:(e,t)=>{const n=Qk(t);return r({inputName:e,data:n,waitForOutputChild:!0})},sendToInputWidget:(e,t)=>{const n=Qk(t);return r({inputName:e,data:n,waitForOutputChild:!1})},globalVariables:{onChange:tE,setValue:nE,getValue:oE,delete:rE,getAll:iE},status:{onChange:sE},edgeFunctions:{register:Va.registerFunctionHandler,unregister:Va.unregisterFunctionHandler,clearAll:Va.clearAllHandlers}})})),w.triggerOnConnected(),w.triggerOnCommand((n=Zk,`${ve.SocketAcknowledge}${n}`))}))},terminate:async()=>{qk&&await Uc(qk)}};export{ge as DataType,lE as default,eE as isBinaryFile,cE 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=yx,n=DI;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")}}(mx),Object.defineProperty(PI,"__esModule",{value:!0}),PI.shake256=PI.shake128=PI.keccak_512=PI.keccak_384=PI.keccak_256=PI.keccak_224=PI.sha3_512=PI.sha3_384=PI.sha3_256=PI.sha3_224=PI.Keccak=PI.keccakP=void 0;const vx=DI,bx=VI,wx=mx,Sx=[],_x=[],Ix=[],xx=BigInt(0),kx=BigInt(1),Ex=BigInt(2),Cx=BigInt(7),$x=BigInt(256),Ox=BigInt(113);for(let e=0,t=kx,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],Sx.push(2*(5*r+n)),_x.push((e+1)*(e+2)/2%64);let i=xx;for(let e=0;e<7;e++)t=(t<<kx^(t>>Cx)*Ox)%$x,t&Ex&&(i^=kx<<(kx<<BigInt(e))-kx);Ix.push(i)}const[Nx,Tx]=(0,bx.split)(Ix,!0),Ax=(e,t,n)=>n>32?(0,bx.rotlBH)(e,t,n):(0,bx.rotlSH)(e,t,n),Mx=(e,t,n)=>n>32?(0,bx.rotlBL)(e,t,n):(0,bx.rotlSL)(e,t,n);function Px(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=Ax(o,s,1)^n[r],c=Mx(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=_x[n],o=Ax(t,i,r),s=Mx(t,i,r),a=Sx[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]^=Nx[r],e[1]^=Tx[r]}n.fill(0)}PI.keccakP=Px;class Dx extends wx.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,vx.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,wx.u32)(this.state)}keccak(){wx.isLE||(0,wx.byteSwap32)(this.state32),Px(this.state32,this.rounds),wx.isLE||(0,wx.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,vx.exists)(this);const{blockLen:t,state:n}=this,r=(e=(0,wx.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,vx.exists)(this,!1),(0,vx.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,vx.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,vx.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 Dx(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}}PI.Keccak=Dx;const jx=(e,t,n)=>(0,wx.wrapConstructor)((()=>new Dx(t,e,n)));PI.sha3_224=jx(6,144,28),PI.sha3_256=jx(6,136,32),PI.sha3_384=jx(6,104,48),PI.sha3_512=jx(6,72,64),PI.keccak_224=jx(1,144,28),PI.keccak_256=jx(1,136,32),PI.keccak_384=jx(1,104,48),PI.keccak_512=jx(1,72,64);const Rx=(e,t,n)=>(0,wx.wrapXOFConstructorWithOpts)(((r={})=>new Dx(t,e,void 0===r.dkLen?n:r.dkLen,!0)));PI.shake128=Rx(31,168,16),PI.shake256=Rx(31,136,32);const{sha3_512:Lx}=PI,Fx=(e=4,t=Math.random)=>{let n="";for(;n.length<e;)n+=Math.floor(36*t()).toString(36);return n};function Ux(e){let t=0n;for(const n of e.values())t=(t<<8n)+BigInt(n);return t}const Bx=(e="")=>Ux(Lx(e)).toString(36).slice(1),Wx=Array.from({length:26},((e,t)=>String.fromCharCode(t+97))),Gx=({globalObj:e=(void 0!==od?od:"undefined"!=typeof window?window:{}),random:t=Math.random}={})=>{const n=Object.keys(e).toString(),r=n.length?n+Fx(32,t):Fx(32,t);return Bx(r).substring(0,32)},Vx=e=>()=>e++,Yx=({random:e=Math.random,counter:t=Vx(Math.floor(476782367*e())),length:n=24,fingerprint:r=Gx({random:e})}={})=>function(){const i=(e=>Wx[Math.floor(e()*Wx.length)])(e),o=Date.now().toString(36),s=t().toString(36),a=Fx(n,e);return`${i+Bx(`${o+a+s+r}`).substring(1,n)}`},Hx=Yx();MI.getConstants=()=>({defaultLength:24,bigLength:32}),MI.init=Yx,MI.createId=Hx,MI.bufToBigInt=Ux,MI.createCounter=Vx,MI.createFingerprint=Gx,MI.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:zx,init:qx,getConstants:Kx,isCuid:Jx}=MI;var Zx=zx;const Xx=Id("getUniqueId"),Qx=({reply:e,sourceServiceId:t})=>(Xx(`Generating unique id for service "${t}"`),e({success:[Zx()]})),ek=Id("getActiveServices"),tk=async({transport:e,sourceServiceId:t,reply:n})=>{if(ek(`Received GetServices request from ${e} [${t}]`),e===Bu.WS){let e=Iv.getActiveServices();const r=_I(t);if(!r)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});let i=[];if(r.transport===Bu.WS){if(!r?.extraInfo.user?.wsApiKey)return n({error:"Client does not have an API key",errCode:"CLIENT_NO_API_KEY"});const t=e.filter(Iv.isInternalKemuService),o=e.filter((e=>e.devMode&&Iv.isNotInternalKemuService(e))),s=e.filter((e=>Iv.isOfficialKemuService(e)&&Iv.isNotInternalKemuService(e)&&Iv.isNotDevService(e))).sort(((e,t)=>e.name.localeCompare(t.name))),a=e.filter((e=>Iv.isNotDevService(e)&&Iv.isNotInternalKemuService(e)&&!Iv.isOfficialKemuService(e))),c=await(async e=>{const{features:t}=await fI(e);return t})(r.extraInfo.user?.wsApiKey),l=c?.hub_services??0,u=s.slice(0,-1!==l?l:s.length);-1!==l&&(i=s.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,...o,...u,...a]}const o=Iv.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:Iv.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 nk="runtime",rk=null;const ik=()=>nk,ok=Id("getSystemInfo"),sk=async({reply:e})=>{ok("Received GetSystemInfo request"),e({success:[await(async()=>({platformArch:qu(),isDesktopHub:"desktop"===ik(),isRuntimeHub:"runtime"===ik(),hubVersion:Vy,...rk?{updateAvailable:rk}:{}}))()]})},ak=Id("removeService"),ck=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=Iv.getAllServiceVersions(i),a=s.find((e=>e.info.version===o));if(!a)return n({error:"Service not found"});ak(`Removing ${s.length} service(s) with name: ${i}`);const c=a.info.publicationId;let l;if(await Iv.uninstallService(a.info.name,a.info.version),c){const e=_I(t);if(!e)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});const r=e.extraInfo.user?.wsApiKey;if(!r)return n({error:"Client does not have an API key",errCode:"CLIENT_NO_API_KEY"});ak(`Updating license details for "${c}"`);const i=await(async e=>{const{data:t,error:n}=await dI(`${uI()}/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=>(ak(`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}}]})},lk=Id("getDecryptedEdgeApiKey"),uk=({reply:e})=>(lk("Getting decrypted edge API key"),e({success:[cI().globalApiKey]})),dk=({reply:e})=>{lk("Getting hub config");const t=cI();return e({success:[{kemuApiKey:t.globalApiKey,environment:t.environment}]})};let hk,fk,pk,gk,mk;const yk=e=>e.transport===Bu.IPC&&(e.reply({error:"Transport is not allowed to call this function"}),!0);var vk=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(!hk)return e.reply({error:"Get recipe secrets function not set"});const i=await hk({...t[0]}),o={};for(const e of r)o[e]=e in i?i[e]:null;const s=[{secrets:o}];e.reply({success:s})},bk=async e=>{const t=e.args,n=t[0].recipeUuid,r=t[0].secretsMap;if(yk(e))return;if(!fk)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 fk({recipeUuid:n,secretsMap:r})}];e.reply({success:i})},wk=async e=>{const t=e.args,n=t[0].recipeUuid,r=t[0].secretName;if(yk(e))return;if(!pk)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 pk({recipeUuid:n,secretName:r})}];e.reply({success:i})},Sk=async e=>{const t=e.args[0].recipeUuid;if(!gk)return e.reply({error:"Get recipe secret mappings function not set"});if(!t)return e.reply({error:"Invalid request parameters"});const n=[{secrets:await gk({recipeUuid:t})}];e.reply({success:n})},_k=async e=>{const t=e.args,n=t[0].hubServiceName,r=t[0].secrets;return mk?n&&r?Array.isArray(r)?(await mk({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 Ik,xk,kk;const Ek=e=>e.transport===Bu.IPC&&(e.reply({error:"You are not allowed to manage secrets using this transport"}),!0);var Ck=async e=>{if(e.args,Ek(e))return;if(!kk)return e.reply({error:"Get hub secrets function not set"});const t=[{contexts:await kk()}];e.reply({success:t})},$k=async e=>{const t=e.args;if(Ek(e))return;if(!Ik)return e.reply({error:"Add hub secret function not set"});const n=[{contexts:await Ik(t[0])}];e.reply({success:n})},Ok=async e=>{const t=e.args;if(Ek(e))return;if(!xk)return e.reply({error:"Delete hub secret function not set"});const n=[{contexts:await xk(t[0])}];e.reply({success:n})};const Nk=S(W(import.meta.url));let Tk=null;const Ak=Id("hub"),Mk=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=ob?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=Lb.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}Fb+=1;const u=`${i}-${Fb}-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=ob?new ArrayBuffer(0):Buffer.alloc(0);const f={json:{functionName:t,args:r,messageId:u,type:"execute"}};s(c)&&(h=Lb.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)=>{Fb+=1;const a=`${i}-${Fb}-multicast-${e.substring(0,10)}`;let c=ob?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=Lb.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=Lb.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");vI=Mk,Mk.setLogger(Ak);const Pk={[Fu.RebootToInstallUpdate]:null,[Fu.GetFileContentFromCacheId]:null,[Fu.SaveRecipeToFile]:null},Dk=(e,t)=>{const{transmission:n}=t;if(0!==n.targetServiceId){const r=_I(n.targetServiceId);if(!r)return Ak(`Service [${e}] ${n.sourceServiceId} is sending data to an unknown service ["${n.targetServiceId}"]`),!0;r.transport,Bu.IPC;const i=t.json?.messageId;return Ak(`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},jk=({sourceServiceId:e,args:t})=>{const n=Iv.getServiceBySessionId(e);if(n){const r=II(n.info.name,n.info.version),i=II(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}};Mk.broadcast(Fu.BroadcastEvent,[s],o,0)}},Rk=async({args:e,reply:t})=>{const n=e[0];if(!n)return Ak("Invalid config for SendToRecipe"),t({error:"Invalid config for SendToRecipe"});const r=(i=n.recipePoolId,Object.values(bI).find((e=>e.extraInfo.recipe?.poolId===i))||null);var i;if(!r)return Ak(`No client found for recipe pool id ${n.recipePoolId}`),t({error:`No client found for recipe pool id "${n.recipePoolId}"`});try{const e=Mk.execute(Fu.SendToRecipe,[n],r.send,0,r.serviceSessionId,{async:!n.waitForResponse,timeout:n.timeout});n.waitForResponse?t({success:await e}):t({success:[]})}catch(e){return Ak(`Error sending to recipe ${n.recipePoolId}: ${e?.message||e}`),t({error:e?.message||"There was an error sending to the recipe"})}},Lk=e=>{const{send:t,transmission:n,json:r}=e;Ak(`Raw message Id received from WS: ${r?.messageId}`),Dk(Bu.WS,e)||Mk.processMessage(Bu.WS,t,n,r)},Fk=e=>{const t=(n=e,`${Lu.SocketAcknowledge}${n}`);var n;B_(e,t)},Uk=(e,t)=>{Ak(`Received unknown command [${t}] from service ${e}`)},Bk=async e=>{const{args:t,sourceServiceId:n,send:r,reply:i}=e,o=n,s=t[0],a=s?.user?.apiKey||cI().globalApiKey;if(!a)return Ak(`Received ACK from WS service ${n} but no API key was provided`),i({error:"No API key was provided",errCode:"MISSING_API_KEY"});s.user?.id&&rv.setGlobalUserId(s.user?.id),await kI({serviceSessionId:n,transport:Bu.WS,send:r,terminateFn:()=>{G_(n)},extraInfo:{websocketId:o,recipe:s.recipe,user:{wsApiKey:a,userEmail:s.user?.email,userId:s.user?.id}}}),i({success:[]})},Wk=e=>{Ak(`WS Client ${e} disconnected`),CI(e)},Gk=e=>1===e.sourceServiceId?e.functionName===Fu.GetFileContentFromCacheId:e.functionName===Fu.SocketAckResponse||e.functionName===Fu.ServiceManifest||e.functionName===Fu.SubscribeToService||(!!_I(e.sourceServiceId)||(e.reply({error:`Session id "${e.sourceServiceId}" not found. Please acknowledge the session first.`}),!1)),Vk=async({sourceServiceId:e,args:t,transport:n,send:r})=>{if(n!==Bu.IPC){var i;Ak(`Received manifest from non IPC service ${e}.`)}else{const n=t[0];if(n.devMode){const t=Iv.getMatchingDevService(n.name,n.version,"stopped");if(t){Ak(`Found matching previous service ${t.info.name} (${t.info.version}). Reactivating previous client with session id ${t.info.sessionId}`);const o=_I(t.info.sessionId);if(!o)return void Ak(`Could not find previous client instance for ${t.info.name} (${t.info.version}). Aborting manifest injection`);o.send=r,bI[i=e]?delete bI[i]:yI(`Could not find source client with session id ${i}`),Db(e,t.info.sessionId);const s=await Ky(n,n.path);t.info={...t.info,...s},Ak(`Updating manifest for dev service ${t.info.sessionId}`),Iv.setServiceManifest(t.info.sessionId,s,"running"),Ak(`Asking service ${e} to assume previous session id ${t.info.sessionId}`),Pb(t.info.sessionId,(e=>`${Lu.AssumeSession}${e}`)(t.info.sessionId)),(e=>{const t=bI[e];t?t.isDevClient?(t.disconnected=!1,t.transport===Bu.IPC&&(xI(),EI(e))):yI(`Client with session id ${e} is not a dev client`):yI(`Could not find source client with session id ${e}`)})(t.info.sessionId)}else{Iv.addDevService(e,n,"running");const t=_I(e);t?t.isDevClient=!0:kI({serviceSessionId:e,transport:Bu.IPC,send:r,extraInfo:{ipcSocketId:e},isDevClient:!0})}return}Ak(`Received manifest from non dev service ${e} [${n.name}@(${n.version})]. Ignoring...`)}};var Yk=async e=>{var t;Ak("Starting Kemu Hub..."),t=e.desktopMode?"desktop":"runtime",nk=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&&rv.setTracker(e.errorTracker),(e=>{aI={...aI,...e}})({serviceUrl:e.serviceUrl,globalApiKey:e.globalApiKey,environment:e.environment}),Mk.registerFunctionsMiddleware(Gk),e.secrets?.serviceSecrets&&(e=>{mk=e})(e.secrets.serviceSecrets.addServiceSecretFn),e.secrets?.recipeSecrets&&((e=>{hk=e})(e.secrets.recipeSecrets.getRecipeDecryptedSecretsFn),(e=>{fk=e})(e.secrets.recipeSecrets.addRecipeSecretFn),(e=>{pk=e})(e.secrets.recipeSecrets.deleteRecipeSecretFn),(e=>{gk=e})(e.secrets.recipeSecrets.getRecipeSecretMappingsFn)),e.secrets?.hubSecrets&&((e=>{kk=e})(e.secrets.hubSecrets.getHubSecretsFn),(e=>{Ik=e})(e.secrets.hubSecrets.addHubSecretsFn),(e=>{xk=e})(e.secrets.hubSecrets.deleteHubSecretFn)),Mk.registerFunction(Fu.GetServiceContents,sI),Mk.registerFunction(Fu.GetServices,tk),Mk.registerFunction(Fu.GetSystemInfo,sk),Mk.registerFunction(Fu.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"})})),Mk.registerFunction(Fu.UnsubscribeFromService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===Bu.WS){const[e]=n,i=_I(r);if(!i)return t({error:`Session id "${r}" not found`});Ak(`Service ${r} unsubscribing from "${e.targetService.serviceName} (${e.targetService.version})"`),t({success:[]}),i?.removeSubscription({serviceName:e.targetService.serviceName,version:e.targetService.version})}})),Mk.registerFunction(Fu.SubscribeToService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===Bu.WS){const[e]=n,i=_I(r),o=e.targetService;if(!i)return t({error:`Session id "${r}" not found`});if(Ak(`Service ${r} subscribing to "${o.serviceName} (${o.version})"`),"hub"===o.serviceName)return i.addSubscription(o),void t({success:[]});if(!i.addSubscription(o))return Ak(`Service ${r} already subscribed to "${o.serviceName} (${o.version})", ignoring request.`),t({success:[]});const s=Iv.getMatchingService(o.serviceName,o.version);if(!s)return Ak(`Service ${o.serviceName} ${o.version} not active yet`),t({success:[]});if(!s.info.eventEmitter)return Ak(`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=_I(s.info.sessionId);return a?.extraInfo.ipcSocketId&&(Ak(`Sending Broadcast START command to service ${s.info.sessionId}`),Pb(a?.extraInfo.ipcSocketId,Lu.BroadcastStart)),t({success:[]})}})),Mk.registerFunction("stopService",Y_),Mk.registerFunction("removeService",z_),Mk.registerFunction("launchService",K_),Mk.registerFunction("getMatchingServices",Z_),Mk.registerFunction("getSecretsValues",eI),Mk.registerFunction(Fu.GetMappedSecrets,iI),Mk.registerFunction(Fu.BroadcastEvent,jk),Mk.registerFunction(Fu.ServiceManifest,Vk),Mk.registerFunction(Fu.ChooseDirectoryDialog,TI),Mk.registerFunction(Fu.ChooseFileDialog,AI),Mk.registerFunction(Fu.GetUniqueId,Qx),Mk.registerFunction(Fu.SendToRecipe,Rk),Mk.registerFunction(Fu.GetDecryptedEdgeApiKey,uk),Mk.registerFunction(Fu.GetHubConfig,dk),Mk.registerFunction(Fu.SocketAckResponse,Bk),Mk.registerFunction(Fu.UninstallService,ck),Mk.registerFunction(Fu.GetRecipeDecryptedSecretsValues,vk),Mk.registerFunction(Fu.GetRecipeSecretMappings,Sk),Mk.registerFunction(Fu.AddRecipeSecretMapping,bk),Mk.registerFunction(Fu.DeleteRecipeSecretMapping,wk),Mk.registerFunction(Fu.GetHubSecrets,Ck),Mk.registerFunction(Fu.AddHubSecrets,$k),Mk.registerFunction(Fu.DeleteHubSecret,Ok),Mk.registerFunction(Fu.AddServiceSecret,_k),Object.entries(Pk).forEach((([e,t])=>{t?Mk.registerFunction(e,t):(Ak(`Skipping registration of "${e}" because it's not implemented`),Mk.registerFunction(e,(({reply:t})=>{t({error:`This hub does not support "${e}"`,errCode:"FUNCTION_NOT_SUPPORTED"})})))})),(e=>{Nb=e})((e=>{const{send:t,transmission:n,json:r}=e;Ak(`Raw message Id received from IPC: ${r?.messageId}`),Dk(Bu.IPC,e)||Mk.processMessage(Bu.IPC,t,n,r)})),W_(Lk),L_(Fk),U_(Uk),F_(Wk),(e=>{Ob=e})(OI),(e=>{Cb=e})((e=>{const t=(e=>`${Lu.IpcAcknowledge}${e}`)(e);Pb(e,t)})),(e=>{$b=e})((e=>{Ak(`IPC socket [${e}] disconnected`);const t=_I(e);if(t){Ak(`Found matching service for disconnected socket. SessionId: ${t.serviceSessionId}`);const e=Iv.getServiceBySessionId(t.serviceSessionId);Iv.setServiceStatus(t.serviceSessionId,"stopped"),e?.devMode?(t.disconnected=!0,xI()):CI(t.serviceSessionId)}})),await(e=>(e?.ipcId&&(nb.config.id=e.ipcId),e?.ipcAppSpace&&(nb.config.appspace=e.ipcAppSpace),new Promise((e=>{nb.serve((()=>{Eb.info("IPC Server Initiated"),nb.server.on("data",((e,t)=>{const n=Tb[t.id];n?(Eb.data(`IPC Socket [${t.id}] data ${e.byteLength} bytes`),Ab(e,n.activeMessage,(e=>n.activeMessage=e),(e=>{if(!e.complete)return;const n=e=>{t.write(e)};if(e.command)return Eb.data(`Received command from client [${t.id}]: ${e.command}`),void(Ob&&Ob(t.id,e.command,n));e.klMessage&&Nb&&Nb({send:n,transmission:{sourceServiceId:e.sourceServiceId??-1,targetServiceId:e.targetServiceId??-1,rawMessage:e.rawMessage},json:e.klMessage.json})}))):Eb.data(`Received data from unknown client [${t.id}]. Ignoring.`)})),nb.server.on("connect",(e=>{const t=Uy();Eb.info(`New client connected. Registered as "${t}"`),e.id=t,Tb[t]={socket:e,activeMessage:null,disconnectHandler:()=>Mb(t)},e.on("close",Tb[t].disconnectHandler),Cb&&Cb(t)})),nb.server.on("disconnect",(e=>{Mb(e.id)})),nb.server.on("error",(e=>{console.log(`IPC Server Error: ${e}`)})),e()})),nb.server.start()}))))({ipcAppSpace:n,ipcId:r}),e?.ws?.disabled||await R_(e?.ws?.port||5368);const i=e?.defaultServicesPath||b.resolve(Nk,"defaultServices");Tk=i;const o=process.env.DEV_SESSION_ID;Iv.setHubIpcConfig({recipePath:e?.recipeRootPath,appSpace:n,id:r}),Iv.setEnableServiceLogsConfig(!!e?.enableServiceLogs),e?.servicesInstallPath&&(e=>{Zy=e})(e.servicesInstallPath),e?.testServicesInstallPath&&(e=>{Xy=e})(e.testServicesInstallPath);const s=Qy(),a=ev(),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=cI().serviceUrl,t.__KEMU_ENVIRONMENT=cI().environment,t};e?.getServiceSecretsFn?(Iv.setGetSecretsFunction(e.getServiceSecretsFn),tI(e.getServiceSecretsFn)):(Iv.setGetSecretsFunction(c),tI(c)),(e=>{rI=e})(e?.getMappedSecretsFn?e.getMappedSecretsFn:async e=>e.reduce(((e,t)=>({...e,[t.name]:[]})),{})),Iv.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 Iv.loadServices(i,{fixedSession:o?parseInt(o):void 0,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,internalServices:!0,enableLogs:!0}),null!==e?.servicesInstallPath&&(await Jy(s)||await h(s,{recursive:!0}),await Iv.loadServices(s,{internalServices:!1,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,enableLogs:!!e?.enableServiceLogs}));const l=process.env.DEV_NO_SPAWN_LIST?.split(",");await Iv.launchServices({noSpawningList:l||[]}),Ak("Kemu Hub started"),(e?.onChooseDirectory||e?.onChooseFile)&&(e=>{NI=e})({chooseDirectory:e.onChooseDirectory,chooseFile:e.onChooseFile})},Hk=e=>{if(e===Bu.WS)return{handleWebsocketConnectionEvent:Fk,handleWebsocketClientDisconnectionEvent:Wk,handleWebsocketMessage:Lk,handleWebsocketClientCommand:Uk,getRemoteInvoke:()=>Mk}},zk=(e=[])=>{let t;const n=new Promise((n=>{const r=()=>{if(Iv.getAllServices().every((e=>"running"===e.status))&&e.every((e=>"running"===Iv.getMatchingService(e.name,e.version)?.status)))return n();t=setTimeout(r,100)};r()}));return n.abort=()=>{t&&clearTimeout(t)},n};let qk;const Kk=Ml("run"),Jk=Vu(),Zk=1e3,Xk=v(process.argv.slice(2)),Qk=e=>"number"==typeof e?{type:ge.Number,value:e}:"string"==typeof e?{type:ge.String,value:e}:"boolean"==typeof e?{type:ge.Boolean,value:e}:Array.isArray(e)?{type:ge.Array,value:e}:e;global.ImageData=q;const eE=e=>e&&"string"==typeof e.format&&e.data&&e.data instanceof ArrayBuffer;xe({createCanvas:(e,t)=>J(e,t),loadImage:async e=>{let t=e;if(eE(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 tE=(e,t)=>"*"===e?co.onAnyGlobalVariableChange(t):co.onGlobalVariableChange(e,t),nE=(e,t,n)=>co.setGlobalVariable({name:e,value:t,disableChangeNotifications:n?.disableChangeNotifications||!1,disableDefineNotifications:n?.disableDefineNotifications||!1,doNotOverrideExisting:n?.doNotOverrideExisting||!1}),rE=e=>{co.deleteGlobalVariable({name:e})},iE=()=>co.getAllVariables(),oE=e=>co.getGlobalVariable(e),sE=e=>Gi(e),aE=e=>async()=>{throw new Error(`${e} not implemented`)},cE={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:ge.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 lE={start:async r=>{r=r||{};const i=r?.runtimeCommand?.trim()||process.env.KEMU_EDGE_RUNTIME_COMMAND?.trim(),o=r?.recipePath||Xk.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=Y(o),{parsed:a,error:c}=await e({path:H(z(s),".env")});c&&console.warn(`Failed to load .env file: ${c.message}. This is not an error, it just means that the .env file is not present or is not readable.`);const l=r.apiKey||process.env.KEMU_API_KEY,u=process.env.KEMU_CONFIG;if(!l)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(!u)throw new Error("Missing server URL or environment in config.envConfig");const d=o.endsWith(".json")||o.endsWith(".kemu"),h=d?Y(o):o,f=d?o:H(h,"recipe.kemu"),p=(e=>{try{return JSON.parse(e||"")}catch(e){return null}})(await t(z(f),"utf-8"));if(!p)throw new Error("Failed to parse recipe file");if(!p.author?.id)throw new Error("Missing required author ID in recipe file.");const{serviceUrl:g,environment:m}=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}})(u);await sc();const y={id:p.uuid||String(Date.now()),version:1,author:p.author.id};(e=>{po=e})(console);const v=Hk(Se.WS),b=(e,t)=>{if(t)v?.handleWebsocketMessage({send:S,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg?.json});else{const t=e instanceof Buffer?e.toString():e;v?.handleWebsocketClientCommand(Zk,t)}},w=(bl={instanceServiceId:Zk,sendBuf:b,sendCmd:b,triggerOnCommand:(...e)=>wl(...e),triggerOnConnected:()=>Sl(),triggerOnDisconnected:()=>_l(),triggerOnMessageReceived:(...e)=>Il(...e)},bl);const S=(e,t)=>{if(t)w.triggerOnMessageReceived({send:b,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg.json});else{const t=e instanceof Buffer?e.toString():e;w.triggerOnCommand(t)}},_=Hu(),I=v.getRemoteInvoke();_.disableServiceEncoding(0,!0),I.disableServiceEncoding(Zk,!0);const x=Object.values(p.blocks[fe].gates).filter((e=>e.type===qe.hubService&&e.state.service&&!0!==e.state.service?.webOnly)),k=x.map((e=>{const t=e.state.service;return{name:t.name,version:t.version}})),E=H(h,"services"),C=await n(E).then((()=>!0)).catch((()=>!1));if(k.length>0&&!C)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.");await Yk({globalApiKey:l,serviceUrl:g,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);return Z(r[0],r.slice(1).concat(e||[]),{...t,env:{...process.env,...t?.env}})}:null,recipeRootPath:h,servicesInstallPath:C?H(h,"services"):null,noDefaultServices:!0,environment:m,ws:{disabled:!0},secrets:{recipeSecrets:{getRecipeDecryptedSecretsFn:async()=>({...a}),getRecipeSecretMappingsFn:aE("getRecipeSecretMappingsFn"),addRecipeSecretFn:aE("addRecipeSecretFn"),deleteRecipeSecretFn:aE("deleteRecipeSecretFn")}},ipc:{appSpace:"kemu-runner.",id:y.id}}),Kk("Waiting for services to run"),await zk(k),Kk("All services are running"),Wc(Jk),Hc(),ca((e=>{Kk("Global processing state changed: ",e)})),p.globalVariables&&(p.globalVariables=await qc(p.globalVariables));const $=await Fc(p,"runner",y.version,y.author,yr.Desktop);return qk=$,Yu($),await Wu({id:p.author.id}),new Promise(((e,t)=>{var n;Gu("acknowledged",(async()=>{await Jk.getServices();const{failed:n,sendToInputWidget:r,invokeRecipeLoadedWidgets:i}=await Bc($);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)})),Kk("Recipe started"),e({sendToInputWidgetAndWaitForOutput:(e,t)=>{const n=Qk(t);return r({inputName:e,data:n,waitForOutputChild:!0})},sendToInputWidget:(e,t)=>{const n=Qk(t);return r({inputName:e,data:n,waitForOutputChild:!1})},globalVariables:{onChange:tE,setValue:nE,getValue:oE,delete:rE,getAll:iE},status:{onChange:sE},edgeFunctions:{register:Va.registerFunctionHandler,unregister:Va.unregisterFunctionHandler,clearAll:Va.clearAllHandlers}})})),w.triggerOnConnected(),w.triggerOnCommand((n=Zk,`${ve.SocketAcknowledge}${n}`))}))},terminate:async()=>{qk&&await Uc(qk)}};export{ge as DataType,lE as default,eE as isBinaryFile,cE as utils};
|