@overlayed/app 2.9.2 → 2.9.4
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/dist/index.d.mts +15 -10
- package/dist/index.mjs +3 -3
- package/dist/preload.js +1 -1
- package/dist/sand.d.ts +52 -52
- package/package.json +2 -2
package/dist/index.d.mts
CHANGED
|
@@ -378,20 +378,17 @@ declare class OverridesManager extends Manager {
|
|
|
378
378
|
private setKeyInputBlock;
|
|
379
379
|
}
|
|
380
380
|
//#endregion
|
|
381
|
+
//#region src/utilities/modules/windowsModule.d.ts
|
|
382
|
+
type RegisterWindowOptions = {
|
|
383
|
+
muted?: boolean;
|
|
384
|
+
};
|
|
385
|
+
//#endregion
|
|
381
386
|
//#region ../games/universal/dist/index.d.ts
|
|
382
387
|
//#region src/module.d.ts
|
|
383
388
|
declare function module(): {
|
|
384
389
|
readonly key: "universal";
|
|
385
390
|
readonly events: import("arktype").Module<{
|
|
386
391
|
event: {
|
|
387
|
-
game: "sand" | "siege" | "tft";
|
|
388
|
-
type: "module_loaded";
|
|
389
|
-
creationTime: number;
|
|
390
|
-
content: {
|
|
391
|
-
gameVersion: string;
|
|
392
|
-
processHash: string;
|
|
393
|
-
};
|
|
394
|
-
} | {
|
|
395
392
|
game: "sand";
|
|
396
393
|
type: "logged_in";
|
|
397
394
|
creationTime: number;
|
|
@@ -408,6 +405,14 @@ declare function module(): {
|
|
|
408
405
|
content: {
|
|
409
406
|
accountId: string;
|
|
410
407
|
};
|
|
408
|
+
} | {
|
|
409
|
+
game: "sand" | "siege" | "tft";
|
|
410
|
+
type: "module_loaded";
|
|
411
|
+
creationTime: number;
|
|
412
|
+
content: {
|
|
413
|
+
gameVersion: string;
|
|
414
|
+
processHash: string;
|
|
415
|
+
};
|
|
411
416
|
} | {
|
|
412
417
|
game: "sand" | "siege" | "tft";
|
|
413
418
|
type: "module_unloaded";
|
|
@@ -619,14 +624,14 @@ interface OverlayedAppWindowsModule extends Pick<RenderInterface$1, "on" | "off"
|
|
|
619
624
|
* @param options The options for the window.
|
|
620
625
|
* @returns The created window.
|
|
621
626
|
*/
|
|
622
|
-
createWindow(options: BrowserWindowConstructorOptions): BrowserWindow;
|
|
627
|
+
createWindow(options: BrowserWindowConstructorOptions, windowConfig?: RegisterWindowOptions): BrowserWindow;
|
|
623
628
|
/**
|
|
624
629
|
* Creates a new in-game window. All in-game windows must be created with this method.
|
|
625
630
|
*
|
|
626
631
|
* @param options The options for the window.
|
|
627
632
|
* @returns The created window.
|
|
628
633
|
*/
|
|
629
|
-
createInGameWindow(options: RenderWindowConstructorOptions$1): RenderWindow$1;
|
|
634
|
+
createInGameWindow(options: RenderWindowConstructorOptions$1, windowConfig?: RegisterWindowOptions): RenderWindow$1;
|
|
630
635
|
/**
|
|
631
636
|
* Returns information about the currently active game.
|
|
632
637
|
*
|
package/dist/index.mjs
CHANGED
|
@@ -12,8 +12,8 @@ Defaulting to 2020, but this will stop working in the future.`)),t.ecmaVersion=1
|
|
|
12
12
|
`;break;default:e+=String.fromCharCode(n)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},H.readInvalidTemplateToken=function(){for(;this.pos<this.input.length;this.pos++)switch(this.input[this.pos]){case`\\`:++this.pos;break;case`$`:if(this.input[this.pos+1]!==`{`)break;case"`":return this.finishToken(b.invalidTemplate,this.input.slice(this.start,this.pos));case`\r`:this.input[this.pos+1]===`
|
|
13
13
|
`&&++this.pos;case`
|
|
14
14
|
`:case`\u2028`:case`\u2029`:++this.curLine,this.lineStart=this.pos+1}this.raise(this.start,`Unterminated template`)},H.readEscapedChar=function(e){var t=this.input.charCodeAt(++this.pos);switch(++this.pos,t){case 110:return`
|
|
15
|
-
`;case 114:return`\r`;case 120:return String.fromCharCode(this.readHexChar(2));case 117:return O(this.readCodePoint());case 116:return` `;case 98:return`\b`;case 118:return`\v`;case 102:return`\f`;case 13:this.input.charCodeAt(this.pos)===10&&++this.pos;case 10:return this.options.locations&&(this.lineStart=this.pos,++this.curLine),``;case 56:case 57:if(this.strict&&this.invalidStringToken(this.pos-1,`Invalid escape sequence`),e){var n=this.pos-1;this.invalidStringToken(n,`Invalid escape sequence in template string`)}default:if(t>=48&&t<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],i=parseInt(r,8);return i>255&&(r=r.slice(0,-1),i=parseInt(r,8)),this.pos+=r.length-1,t=this.input.charCodeAt(this.pos),r===`0`&&t!==56&&t!==57||!this.strict&&!e||this.invalidStringToken(this.pos-1-r.length,e?`Octal literal in template string`:`Octal literal in strict mode`),String.fromCharCode(i)}return C(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),``):String.fromCharCode(t)}},H.readHexChar=function(e){var t=this.pos,n=this.readInt(16,e);return n===null&&this.invalidStringToken(t,`Bad character escape sequence`),n},H.readWord1=function(){this.containsEsc=!1;for(var e=``,t=!0,n=this.pos,r=this.options.ecmaVersion>=6;this.pos<this.input.length;){var i=this.fullCharCodeAtPos();if(m(i,r))this.pos+=i<=65535?1:2;else{if(i!==92)break;this.containsEsc=!0,e+=this.input.slice(n,this.pos);var a=this.pos;this.input.charCodeAt(++this.pos)!==117&&this.invalidStringToken(this.pos,`Expecting Unicode escape sequence \\uXXXX`),++this.pos;var o=this.readCodePoint();(t?p:m)(o,r)||this.invalidStringToken(a,`Invalid Unicode escape`),e+=O(o),n=this.pos}t=!1}return e+this.input.slice(n,this.pos)},H.readWord=function(){var e=this.readWord1(),t=b.name;return this.keywords.test(e)&&(t=ee[e]),this.finishToken(t,e)},A.acorn={Parser:A,version:`8.16.0`,defaultOptions:de,Position:ce,SourceLocation:le,getLineInfo:ue,Node:Me,TokenType:h,tokTypes:b,keywordTypes:ee,TokContext:F,tokContexts:I,isIdentifierChar:m,isIdentifierStart:p,Token:ot,isNewLine:C,lineBreak:x,lineBreakG:S,nonASCIIwhitespace:te};var lt=r(`node:module`),U=r(`node:fs`);String.fromCharCode;let ut=/\/$|\/\?|\/#/,dt=/^\.?\//;function ft(e=``,t){return t?ut.test(e):e.endsWith(`/`)}function pt(e=``,t){if(!t)return e.endsWith(`/`)?e:e+`/`;if(ft(e,!0))return e||`/`;let n=e,r=``,i=e.indexOf(`#`);if(i!==-1&&(n=e.slice(0,i),r=e.slice(i),!n))return r;let[a,...o]=n.split(`?`);return a+`/`+(o.length>0?`?${o.join(`?`)}`:``)+r}function mt(e){return e&&e!==`/`}function ht(e,...t){let n=e||``;for(let e of t.filter(e=>mt(e)))if(n){let t=e.replace(dt,``);n=pt(n)+t}else n=e;return n}let gt=/^[A-Za-z]:\//;function _t(e=``){return e&&e.replace(/\\/g,`/`).replace(gt,e=>e.toUpperCase())}let vt=/^[/\\]{2}/,yt=/^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/,bt=/^[A-Za-z]:$/,xt=/.(\.[^./]+|\.)$/,St=function(e){if(e.length===0)return`.`;let t=(e=_t(e)).match(vt),n=Dt(e),r=e[e.length-1]===`/`;return(e=Et(e,!n)).length===0?n?`/`:r?`./`:`.`:(r&&(e+=`/`),bt.test(e)&&(e+=`/`),t?n?`//${e}`:`//./${e}`:n&&!Dt(e)?`/${e}`:e)},Ct=function(...e){let t=``;for(let n of e)if(n){if(t.length>0){let e=t[t.length-1]===`/`,r=n[0]===`/`;t+=e&&r?n.slice(1):e||r?n:`/${n}`}else t+=n}return St(t)};function wt(){return typeof process<`u`&&typeof process.cwd==`function`?process.cwd().replace(/\\/g,`/`):`/`}let Tt=function(...e){let t=``,n=!1;for(let r=(e=e.map(e=>_t(e))).length-1;r>=-1&&!n;r--){let i=r>=0?e[r]:wt();i&&i.length!==0&&(t=`${i}/${t}`,n=Dt(i))}return t=Et(t,!n),n&&!Dt(t)?`/${t}`:t.length>0?t:`.`};function Et(e,t){let n=``,r=0,i=-1,a=0,o=null;for(let s=0;s<=e.length;++s){if(s<e.length)o=e[s];else{if(o===`/`)break;o=`/`}if(o===`/`){if(i!==s-1&&a!==1){if(a===2){if(n.length<2||r!==2||n[n.length-1]!==`.`||n[n.length-2]!==`.`){if(n.length>2){let e=n.lastIndexOf(`/`);e===-1?(n=``,r=0):(n=n.slice(0,e),r=n.length-1-n.lastIndexOf(`/`)),i=s,a=0;continue}if(n.length>0){n=``,r=0,i=s,a=0;continue}}t&&(n+=n.length>0?`/..`:`..`,r=2)}else n.length>0?n+=`/${e.slice(i+1,s)}`:n=e.slice(i+1,s),r=s-i-1}i=s,a=0}else o===`.`&&a!==-1?++a:a=-1}return n}let Dt=function(e){return yt.test(e)},Ot=function(e){if(e===`..`)return``;let t=xt.exec(_t(e));return t&&t[1]||``},kt=function(e){let t=_t(e).replace(/\/$/,``).split(`/`).slice(0,-1);return t.length===1&&bt.test(t[0])&&(t[0]+=`/`),t.join(`/`)||(Dt(e)?`/`:`.`)},At=function(e,t){let n=_t(e).split(`/`),r=``;for(let e=n.length-1;e>=0;e--){let t=n[e];if(t){r=t;break}}return t&&r.endsWith(t)?r.slice(0,-t.length):r},W=k(`node:url`),jt=k(`node:assert`),Mt=k(`node:process`);var Nt=r(`node:path`);let Pt=k(`node:v8`),Ft=k(`node:util`),G=new Set(lt.builtinModules);function It(e){return e.replace(/\\/g,`/`)}let Lt={}.hasOwnProperty,Rt=/^([A-Z][a-z\d]*)+$/,zt=/* @__PURE__ */ new Set([`string`,`function`,`number`,`object`,`Function`,`Object`,`boolean`,`bigint`,`symbol`]),K={};function Bt(e,t=`and`){return e.length<3?e.join(` ${t} `):`${e.slice(0,-1).join(`, `)}, ${t} ${e[e.length-1]}`}let Vt=/* @__PURE__ */ new Map,Ht;function Ut(e,t,n){return Vt.set(e,t),function(e,t){return n;function n(...n){let r=Error.stackTraceLimit;Wt()&&(Error.stackTraceLimit=0);let i=new e;Wt()&&(Error.stackTraceLimit=r);let a=function(e,t,n){let r=Vt.get(e);if(jt.ok(r!==void 0,"expected `message` to be found"),typeof r==`function`)return jt.ok(r.length<=t.length,`Code: ${e}; The provided arguments length (${t.length}) does not match the required ones (${r.length}).`),Reflect.apply(r,n,t);let i=/%[dfijoOs]/g,a=0;for(;i.exec(r)!==null;)a++;return jt.ok(a===t.length,`Code: ${e}; The provided arguments length (${t.length}) does not match the required ones (${a}).`),t.length===0?r:(t.unshift(r),Reflect.apply(Ft.format,null,t))}(t,n,i);return Object.defineProperties(i,{message:{value:a,enumerable:!1,writable:!0,configurable:!0},toString:{value(){return`${this.name} [${t}]: ${this.message}`},enumerable:!1,writable:!0,configurable:!0}}),Gt(i),i.code=t,i}}(n,e)}function Wt(){try{if(Pt.startupSnapshot.isBuildingSnapshot())return!1}catch{}let e=Object.getOwnPropertyDescriptor(Error,`stackTraceLimit`);return e===void 0?Object.isExtensible(Error):Lt.call(e,`writable`)&&e.writable!==void 0?e.writable:e.set!==void 0}K.ERR_INVALID_ARG_TYPE=Ut(`ERR_INVALID_ARG_TYPE`,(e,t,n)=>{jt.ok(typeof e==`string`,`'name' must be a string`),Array.isArray(t)||(t=[t]);let r=`The `;if(e.endsWith(` argument`))r+=`${e} `;else{let t=e.includes(`.`)?`property`:`argument`;r+=`"${e}" ${t} `}r+=`must be `;let i=[],a=[],o=[];for(let e of t)jt.ok(typeof e==`string`,`All expected entries have to be of type string`),zt.has(e)?i.push(e.toLowerCase()):Rt.exec(e)===null?(jt.ok(e!==`object`,`The value "object" should be written as "Object"`),o.push(e)):a.push(e);if(a.length>0){let e=i.indexOf(`object`);e!==-1&&(i.slice(e,1),a.push(`Object`))}return i.length>0&&(r+=`${i.length>1?`one of type`:`of type`} ${Bt(i,`or`)}`,(a.length>0||o.length>0)&&(r+=` or `)),a.length>0&&(r+=`an instance of ${Bt(a,`or`)}`,o.length>0&&(r+=` or `)),o.length>0&&(o.length>1?r+=`one of ${Bt(o,`or`)}`:(o[0].toLowerCase()!==o[0]&&(r+=`an `),r+=`${o[0]}`)),r+=`. Received ${function(e){if(e==null)return String(e);if(typeof e==`function`&&e.name)return`function ${e.name}`;if(typeof e==`object`)return e.constructor&&e.constructor.name?`an instance of ${e.constructor.name}`:`${(0,Ft.inspect)(e,{depth:-1})}`;let t=(0,Ft.inspect)(e,{colors:!1});return t.length>28&&(t=`${t.slice(0,25)}...`),`type ${typeof e} (${t})`}(n)}`,r},TypeError),K.ERR_INVALID_MODULE_SPECIFIER=Ut(`ERR_INVALID_MODULE_SPECIFIER`,(e,t,n=void 0)=>`Invalid module "${e}" ${t}${n?` imported from ${n}`:``}`,TypeError),K.ERR_INVALID_PACKAGE_CONFIG=Ut(`ERR_INVALID_PACKAGE_CONFIG`,(e,t,n)=>`Invalid package config ${e}${t?` while importing ${t}`:``}${n?`. ${n}`:``}`,Error),K.ERR_INVALID_PACKAGE_TARGET=Ut(`ERR_INVALID_PACKAGE_TARGET`,(e,t,n,r=!1,i=void 0)=>{let a=typeof n==`string`&&!r&&n.length>0&&!n.startsWith(`./`);return t===`.`?(jt.ok(!1===r),`Invalid "exports" main target ${JSON.stringify(n)} defined in the package config ${e}package.json${i?` imported from ${i}`:``}${a?`; targets must start with "./"`:``}`):`Invalid "${r?`imports`:`exports`}" target ${JSON.stringify(n)} defined for '${t}' in the package config ${e}package.json${i?` imported from ${i}`:``}${a?`; targets must start with "./"`:``}`},Error),K.ERR_MODULE_NOT_FOUND=Ut(`ERR_MODULE_NOT_FOUND`,(e,t,n=!1)=>`Cannot find ${n?`module`:`package`} '${e}' imported from ${t}`,Error),K.ERR_NETWORK_IMPORT_DISALLOWED=Ut(`ERR_NETWORK_IMPORT_DISALLOWED`,`import of '%s' by %s is not supported: %s`,Error),K.ERR_PACKAGE_IMPORT_NOT_DEFINED=Ut(`ERR_PACKAGE_IMPORT_NOT_DEFINED`,(e,t,n)=>`Package import specifier "${e}" is not defined${t?` in package ${t}package.json`:``} imported from ${n}`,TypeError),K.ERR_PACKAGE_PATH_NOT_EXPORTED=Ut(`ERR_PACKAGE_PATH_NOT_EXPORTED`,(e,t,n=void 0)=>t===`.`?`No "exports" main defined in ${e}package.json${n?` imported from ${n}`:``}`:`Package subpath '${t}' is not defined by "exports" in ${e}package.json${n?` imported from ${n}`:``}`,Error),K.ERR_UNSUPPORTED_DIR_IMPORT=Ut(`ERR_UNSUPPORTED_DIR_IMPORT`,`Directory import '%s' is not supported resolving ES modules imported from %s`,Error),K.ERR_UNSUPPORTED_RESOLVE_REQUEST=Ut(`ERR_UNSUPPORTED_RESOLVE_REQUEST`,`Failed to resolve module specifier "%s" from "%s": Invalid relative URL or base scheme is not hierarchical.`,TypeError),K.ERR_UNKNOWN_FILE_EXTENSION=Ut(`ERR_UNKNOWN_FILE_EXTENSION`,(e,t)=>`Unknown file extension "${e}" for ${t}`,TypeError),K.ERR_INVALID_ARG_VALUE=Ut(`ERR_INVALID_ARG_VALUE`,(e,t,n=`is invalid`)=>{let r=(0,Ft.inspect)(t);return r.length>128&&(r=`${r.slice(0,128)}...`),`The ${e.includes(`.`)?`property`:`argument`} '${e}' ${n}. Received ${r}`},TypeError);let Gt=function(e){let t=`__node_internal_`+e.name;return Object.defineProperty(e,"name",{value:t}),e}(function(e){let t=Wt();return t&&(Ht=Error.stackTraceLimit,Error.stackTraceLimit=1/0),Error.captureStackTrace(e),t&&(Error.stackTraceLimit=Ht),e}),Kt={}.hasOwnProperty,{ERR_INVALID_PACKAGE_CONFIG:qt}=K,Jt=/* @__PURE__ */ new Map;function q(e,{base:t,specifier:n}){let r=Jt.get(e);if(r)return r;let i;try{i=U.readFileSync(Nt.toNamespacedPath(e),`utf8`)}catch(e){let t=e;if(t.code!==`ENOENT`)throw t}let a={exists:!1,pjsonPath:e,main:void 0,name:void 0,type:`none`,exports:void 0,imports:void 0};if(i!==void 0){let r;try{r=JSON.parse(i)}catch(r){let i=r,a=new qt(e,(t?`"${n}" from `:``)+(0,W.fileURLToPath)(t||n),i.message);throw a.cause=i,a}a.exists=!0,Kt.call(r,`name`)&&typeof r.name==`string`&&(a.name=r.name),Kt.call(r,`main`)&&typeof r.main==`string`&&(a.main=r.main),Kt.call(r,`exports`)&&(a.exports=r.exports),Kt.call(r,`imports`)&&(a.imports=r.imports),!Kt.call(r,`type`)||r.type!==`commonjs`&&r.type!==`module`||(a.type=r.type)}return Jt.set(e,a),a}function Yt(e){let t=new URL(`package.json`,e);for(;!t.pathname.endsWith(`node_modules/package.json`);){let n=q((0,W.fileURLToPath)(t),{specifier:e});if(n.exists)return n;let r=t;if(t=new URL(`../package.json`,t),t.pathname===r.pathname)break}return{pjsonPath:(0,W.fileURLToPath)(t),exists:!1,type:`none`}}function Xt(e){return Yt(e).type}let{ERR_UNKNOWN_FILE_EXTENSION:Zt}=K,Qt={}.hasOwnProperty,$t={__proto__:null,".cjs":`commonjs`,".js":`module`,".json":`json`,".mjs":`module`},J={__proto__:null,"data:":function(e){let{1:t}=/^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(e.pathname)||[null,null,null];return function(e){return e&&/\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(e)?`module`:e===`application/json`?`json`:null}(t)},"file:":function(e,t,n){let r=function(e){let t=e.pathname,n=t.length;for(;n--;){let e=t.codePointAt(n);if(e===47)return``;if(e===46)return t.codePointAt(n-1)===47?``:t.slice(n)}return``}(e);if(r===`.js`){let t=Xt(e);return t===`none`?`commonjs`:t}if(r===``){let t=Xt(e);return t===`none`||t===`commonjs`?`commonjs`:`module`}let i=$t[r];if(i)return i;if(n)return;let a=(0,W.fileURLToPath)(e);throw new Zt(r,a)},"http:":en,"https:":en,"node:":()=>`builtin`};function en(){}let tn=Object.freeze([`node`,`import`]),nn=new Set(tn);function rn(e){return nn}let an=RegExp.prototype[Symbol.replace],{ERR_INVALID_MODULE_SPECIFIER:on,ERR_INVALID_PACKAGE_CONFIG:sn,ERR_INVALID_PACKAGE_TARGET:cn,ERR_MODULE_NOT_FOUND:ln,ERR_PACKAGE_IMPORT_NOT_DEFINED:un,ERR_PACKAGE_PATH_NOT_EXPORTED:dn,ERR_UNSUPPORTED_DIR_IMPORT:fn,ERR_UNSUPPORTED_RESOLVE_REQUEST:pn}=K,mn={}.hasOwnProperty,hn=/(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i,gn=/(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i,_n=/^\.|%|\\/,vn=/\*/g,yn=/%2f|%5c/i,bn=/* @__PURE__ */ new Set,xn=/[/\\]{2}/;function Sn(e,t,n,r,i,a,o){if(Mt.noDeprecation)return;let s=(0,W.fileURLToPath)(r),c=xn.exec(o?e:t)!==null;Mt.emitWarning(`Use of deprecated ${c?`double slash`:`leading or trailing slash matching`} resolving "${e}" for module request "${t}" ${t===n?``:`matched to "${n}" `}in the "${i?`imports`:`exports`}" field module resolution of the package at ${s}${a?` imported from ${(0,W.fileURLToPath)(a)}`:``}.`,`DeprecationWarning`,`DEP0166`)}function Cn(e,t,n,r){if(Mt.noDeprecation||function(e,t){let n=e.protocol;return Qt.call(J,n)&&J[n](e,t,!0)||null}(e,{parentURL:n.href})!==`module`)return;let i=(0,W.fileURLToPath)(e.href),a=(0,W.fileURLToPath)(new URL(`.`,t)),o=(0,W.fileURLToPath)(n);r?Nt.resolve(a,r)!==i&&Mt.emitWarning(`Package ${a} has a "main" field set to "${r}", excluding the full filename and extension to the resolved file at "${i.slice(a.length)}", imported from ${o}.\n Automatic extension resolution of the "main" field is deprecated for ES modules.`,`DeprecationWarning`,`DEP0151`):Mt.emitWarning(`No "main" or "exports" field defined in the package.json for ${a} resolving the main entry point "${i.slice(a.length)}", imported from ${o}.\nDefault "index" lookups for the main are deprecated for ES modules.`,`DeprecationWarning`,`DEP0151`)}function wn(e){try{return(0,U.statSync)(e)}catch{}}function Tn(e){let t=(0,U.statSync)(e,{throwIfNoEntry:!1}),n=t?t.isFile():void 0;return n!=null&&n}function En(e,t,n){let r;if(t.main!==void 0){if(r=new URL(t.main,e),Tn(r))return r;let i=[`./${t.main}.js`,`./${t.main}.json`,`./${t.main}.node`,`./${t.main}/index.js`,`./${t.main}/index.json`,`./${t.main}/index.node`],a=-1;for(;++a<i.length&&(r=new URL(i[a],e),!Tn(r));)r=void 0;if(r)return Cn(r,e,n,t.main),r}let i=[`./index.js`,`./index.json`,`./index.node`],a=-1;for(;++a<i.length&&(r=new URL(i[a],e),!Tn(r));)r=void 0;if(r)return Cn(r,e,n,t.main),r;throw new ln((0,W.fileURLToPath)(new URL(`.`,e)),(0,W.fileURLToPath)(n))}function Dn(e,t,n){return new dn((0,W.fileURLToPath)(new URL(`.`,t)),e,n&&(0,W.fileURLToPath)(n))}function On(e,t,n,r,i){return t=typeof t==`object`&&t?JSON.stringify(t,null,``):`${t}`,new cn((0,W.fileURLToPath)(new URL(`.`,n)),e,t,r,i&&(0,W.fileURLToPath)(i))}function kn(e,t,n,r,i,a,o,s,c){if(t!==``&&!a&&e[e.length-1]!==`/`)throw On(n,e,r,o,i);if(!e.startsWith(`./`)){if(o&&!e.startsWith(`../`)&&!e.startsWith(`/`)){let n=!1;try{new URL(e),n=!0}catch{}if(!n)return Fn(a?an.call(vn,e,()=>t):e+t,r,c)}throw On(n,e,r,o,i)}if(hn.exec(e.slice(2))!==null){if(gn.exec(e.slice(2))!==null)throw On(n,e,r,o,i);if(!s){let s=a?n.replace(`*`,()=>t):n+t;Sn(a?an.call(vn,e,()=>t):e,s,n,r,o,i,!0)}}let l=new URL(e,r),u=l.pathname,d=new URL(`.`,r).pathname;if(!u.startsWith(d))throw On(n,e,r,o,i);if(t===``)return l;if(hn.exec(t)!==null){let c=a?n.replace(`*`,()=>t):n+t;gn.exec(t)===null?s||Sn(a?an.call(vn,e,()=>t):e,c,n,r,o,i,!1):(function(e,t,n,r,i){let a=`request is not a valid match in pattern "${t}" for the "${r?`imports`:`exports`}" resolution of ${(0,W.fileURLToPath)(n)}`;throw new on(e,a,i&&(0,W.fileURLToPath)(i))})(c,n,r,o,i)}return a?new URL(an.call(vn,l.href,()=>t)):new URL(t,l)}function An(e){let t=Number(e);return`${t}`===e&&t>=0&&t<4294967295}function jn(e,t,n,r,i,a,o,s,c){if(typeof t==`string`)return kn(t,n,r,e,i,a,o,s,c);if(Array.isArray(t)){let l=t;if(l.length===0)return null;let u,d=-1;for(;++d<l.length;){let t=l[d],f;try{f=jn(e,t,n,r,i,a,o,s,c)}catch(e){if(u=e,e.code===`ERR_INVALID_PACKAGE_TARGET`)continue;throw e}if(f!==void 0){if(f!==null)return f;u=null}}if(u==null)return null;throw u}if(typeof t==`object`&&t){let l=Object.getOwnPropertyNames(t),u=-1;for(;++u<l.length;)if(An(l[u]))throw new sn((0,W.fileURLToPath)(e),i,`"exports" cannot contain numeric property keys.`);for(u=-1;++u<l.length;){let d=l[u];if(d==="default"||c&&c.has(d)){let l=jn(e,t[d],n,r,i,a,o,s,c);if(l===void 0)continue;return l}}return null}if(t===null)return null;throw On(r,t,e,o,i)}function Mn(e,t,n){if(Mt.noDeprecation)return;let r=(0,W.fileURLToPath)(t);bn.has(r+`|`+e)||(bn.add(r+`|`+e),Mt.emitWarning(`Use of deprecated trailing slash pattern mapping "${e}" in the "exports" field module resolution of the package at ${r}${n?` imported from ${(0,W.fileURLToPath)(n)}`:``}. Mapping specifiers ending in "/" is no longer supported.`,`DeprecationWarning`,`DEP0155`))}function Nn(e,t,n,r,i){let a=n.exports;if(function(e,t,n){if(typeof e==`string`||Array.isArray(e))return!0;if(typeof e!=`object`||!e)return!1;let r=Object.getOwnPropertyNames(e),i=!1,a=0,o=-1;for(;++o<r.length;){let e=r[o],s=e===``||e[0]!==`.`;if(a++===0)i=s;else if(i!==s)throw new sn((0,W.fileURLToPath)(t),n,`"exports" cannot contain some keys starting with '.' and some not. The exports object must either be an object of package subpath keys or an object of main entry condition name keys only.`)}return i}(a,e,r)&&(a={".":a}),mn.call(a,t)&&!t.includes(`*`)&&!t.endsWith(`/`)){let n=jn(e,a[t],``,t,r,!1,!1,!1,i);if(n==null)throw Dn(t,e,r);return n}let o=``,s=``,c=Object.getOwnPropertyNames(a),l=-1;for(;++l<c.length;){let n=c[l],i=n.indexOf(`*`);if(i!==-1&&t.startsWith(n.slice(0,i))){t.endsWith(`/`)&&Mn(t,e,r);let a=n.slice(i+1);t.length>=n.length&&t.endsWith(a)&&Pn(o,n)===1&&n.lastIndexOf(`*`)===i&&(o=n,s=t.slice(i,t.length-a.length))}}if(o){let n=jn(e,a[o],s,o,r,!0,!1,t.endsWith(`/`),i);if(n==null)throw Dn(t,e,r);return n}throw Dn(t,e,r)}function Pn(e,t){let n=e.indexOf(`*`),r=t.indexOf(`*`),i=n===-1?e.length:n+1,a=r===-1?t.length:r+1;return i>a?-1:a>i||n===-1?1:r===-1||e.length>t.length?-1:+(t.length>e.length)}function Y(e,t,n){if(e===`#`||e.startsWith(`#/`)||e.endsWith(`/`))throw new on(e,`is not a valid internal imports specifier name`,(0,W.fileURLToPath)(t));let r,i=Yt(t);if(i.exists){r=(0,W.pathToFileURL)(i.pjsonPath);let a=i.imports;if(a){if(mn.call(a,e)&&!e.includes(`*`)){let i=jn(r,a[e],``,e,t,!1,!0,!1,n);if(i!=null)return i}else{let i=``,o=``,s=Object.getOwnPropertyNames(a),c=-1;for(;++c<s.length;){let t=s[c],n=t.indexOf(`*`);if(n!==-1&&e.startsWith(t.slice(0,-1))){let r=t.slice(n+1);e.length>=t.length&&e.endsWith(r)&&Pn(i,t)===1&&t.lastIndexOf(`*`)===n&&(i=t,o=e.slice(n,e.length-r.length))}}if(i){let e=jn(r,a[i],o,i,t,!0,!0,!1,n);if(e!=null)return e}}}}throw function(e,t,n){return new un(e,t&&(0,W.fileURLToPath)(new URL(`.`,t)),(0,W.fileURLToPath)(n))}(e,r,t)}function Fn(e,t,n){if(lt.builtinModules.includes(e))return new URL(`node:`+e);let{packageName:r,packageSubpath:i,isScoped:a}=function(e,t){let n=e.indexOf(`/`),r=!0,i=!1;e[0]===`@`&&(i=!0,n===-1||e.length===0?r=!1:n=e.indexOf(`/`,n+1));let a=n===-1?e:e.slice(0,n);if(_n.exec(a)!==null&&(r=!1),!r)throw new on(e,`is not a valid package name`,(0,W.fileURLToPath)(t));return{packageName:a,packageSubpath:`.`+(n===-1?``:e.slice(n)),isScoped:i}}(e,t),o=Yt(t);if(o.exists){let e=(0,W.pathToFileURL)(o.pjsonPath);if(o.name===r&&o.exports!==void 0&&o.exports!==null)return Nn(e,i,o,t,n)}let s,c=new URL(`./node_modules/`+r+`/package.json`,t),l=(0,W.fileURLToPath)(c);do{let o=wn(l.slice(0,-13));if(!o||!o.isDirectory()){s=l,c=new URL((a?`../../../../node_modules/`:`../../../node_modules/`)+r+`/package.json`,c),l=(0,W.fileURLToPath)(c);continue}let u=q(l,{base:t,specifier:e});return u.exports!==void 0&&u.exports!==null?Nn(c,i,u,t,n):i===`.`?En(c,u,t):new URL(i,c)}while(l.length!==s.length)}function In(e,t,n,r){n===void 0&&(n=rn());let i=t.protocol,a=i===`data:`||i===`http:`||i===`https:`,o;if(function(e){return e!==``&&(e[0]===`/`||function(e){return!(e[0]!==`.`||e.length!==1&&e[1]!==`/`&&(e[1]!==`.`||e.length!==2&&e[2]!==`/`))}(e))}(e))try{o=new URL(e,t)}catch(n){let r=new pn(e,t);throw r.cause=n,r}else if(i===`file:`&&e[0]===`#`)o=Y(e,t,n);else try{o=new URL(e)}catch(r){if(a&&!lt.builtinModules.includes(e)){let n=new pn(e,t);throw n.cause=r,n}o=Fn(e,t,n)}return jt.ok(o!==void 0,`expected to be defined`),o.protocol===`file:`?function(e,t){if(yn.exec(e.pathname)!==null)throw new on(e.pathname,`must not include encoded "/" or "\\" characters`,(0,W.fileURLToPath)(t));let n;try{n=(0,W.fileURLToPath)(e)}catch(n){let r=n;throw Object.defineProperty(r,"input",{value:String(e)}),Object.defineProperty(r,"module",{value:String(t)}),r}let r=wn(n.endsWith(`/`)?n.slice(-1):n);if(r&&r.isDirectory()){let r=new fn(n,(0,W.fileURLToPath)(t));throw r.url=String(e),r}if(!r||!r.isFile()){let r=new ln(n||e.pathname,t&&(0,W.fileURLToPath)(t),!0);throw r.url=String(e),r}{let t=(0,U.realpathSync)(n),{search:r,hash:i}=e;(e=(0,W.pathToFileURL)(t+(n.endsWith(Nt.sep)?`/`:``))).search=r,e.hash=i}return e}(o,t):o}function Ln(e){return typeof e!=`string`||e.startsWith(`file://`)?It((0,W.fileURLToPath)(e)):It(e)}function Rn(e){return(0,W.pathToFileURL)(Ln(e)).toString()}let zn=/* @__PURE__ */ new Set([`node`,`import`]),Bn=[`.mjs`,`.cjs`,`.js`,`.json`],Vn=/* @__PURE__ */ new Set([`ERR_MODULE_NOT_FOUND`,`ERR_UNSUPPORTED_DIR_IMPORT`,`MODULE_NOT_FOUND`,`ERR_PACKAGE_PATH_NOT_EXPORTED`]);function Hn(e,t,n){try{return In(e,t,n)}catch(e){if(!Vn.has(e?.code))throw e}}function Un(e,t={}){if(typeof e!=`string`){if(!(e instanceof URL))throw TypeError("input must be a `string` or `URL`");e=Ln(e)}if(/(?:node|data|http|https):/.test(e))return e;if(G.has(e))return`node:`+e;if(e.startsWith(`file://`)&&(e=Ln(e)),Dt(e))try{if((0,U.statSync)(e).isFile())return Rn(e)}catch(e){if(e?.code!==`ENOENT`)throw e}let n=t.conditions?new Set(t.conditions):zn,r=(Array.isArray(t.url)?t.url:[t.url]).filter(Boolean).map(e=>new URL(function(e){return typeof e!=`string`&&(e=e.toString()),/(?:node|data|http|https|file):/.test(e)?e:G.has(e)?`node:`+e:`file://`+encodeURI(It(e))}(e.toString())));r.length===0&&r.push(new URL(Rn(process.cwd())));let i=[...r];for(let e of r)e.protocol===`file:`&&i.push(new URL(`./`,e),new URL(ht(e.pathname,`_index.js`),e),new URL(`node_modules`,e));let a;for(let r of i){if(a=Hn(e,r,n),a)break;for(let i of[``,`/index`]){for(let o of t.extensions||Bn)if(a=Hn(ht(e,i)+o,r,n),a)break;if(a)break}if(a)break}if(!a){let t=/* @__PURE__ */ Error(`Cannot find module ${e} imported from ${i.join(`, `)}`);throw t.code=`ERR_MODULE_NOT_FOUND`,t}return Rn(a)}function Wn(e,t){return Un(e,t)}function Gn(e,t){return Ln(Wn(e,t))}let Kn=/(?:[\s;]|^)(?:import[\s\w*,{}]*from|import\s*["'*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m,qn=/\/\*.+?\*\/|\/\/.*(?=[nr])/g;function Jn(e,t={}){return t.stripComments&&(e=e.replace(qn,``)),Kn.test(e)}function Yn(e){if(typeof e!=`string`)throw TypeError(`Expected a string`);return e.replace(/[|\\{}()[\]^$+*?.]/g,`\\$&`).replace(/-/g,`\\x2d`)}let Xn=/* @__PURE__ */ new Set([`/`,`\\`,void 0]),Zn=Symbol.for(`pathe:normalizedAlias`),Qn=/[/\\]/;function $n(e){if(e[Zn])return e;let t=Object.fromEntries(Object.entries(e).sort(([e],[t])=>function(e,t){return t.split(`/`).length-e.split(`/`).length}(e,t)));for(let e in t)for(let n in t)n===e||e.startsWith(n)||t[e]?.startsWith(n)&&Xn.has(t[e][n.length])&&(t[e]=t[n]+t[e].slice(n.length));return Object.defineProperty(t,Zn,{value:!0,enumerable:!1}),t}function er(e=`/`){let t=e[e.length-1];return t===`/`||t===`\\`}var tr={rE:`2.6.1`};let nr=k(`node:crypto`);var rr=r.n(nr);let X=globalThis.process?.env||Object.create(null),ir=globalThis.process||{env:X},ar=ir!==void 0&&ir.env&&ir.env.NODE_ENV||void 0,or=[[`claude`,[`CLAUDECODE`,`CLAUDE_CODE`]],[`replit`,[`REPL_ID`]],[`gemini`,[`GEMINI_CLI`]],[`codex`,[`CODEX_SANDBOX`,`CODEX_THREAD_ID`]],[`opencode`,[`OPENCODE`]],[`pi`,[sr(`PATH`,/\.pi[\\/]agent/)]],[`auggie`,[`AUGMENT_AGENT`]],[`goose`,[`GOOSE_PROVIDER`]],[`devin`,[sr(`EDITOR`,/devin/)]],[`cursor`,[`CURSOR_AGENT`]],[`kiro`,[sr(`TERM_PROGRAM`,/kiro/)]]];function sr(e,t){return()=>{let n=X[e];return!!n&&t.test(n)}}let cr=function(){let e=X.AI_AGENT;if(e)return{name:e.toLowerCase()};for(let[e,t]of or)for(let n of t)if(typeof n==`string`?X[n]:n())return{name:e};return{}}(),lr=(cr.name,cr.name,[[`APPVEYOR`],[`AWS_AMPLIFY`,`AWS_APP_ID`,{ci:!0}],[`AZURE_PIPELINES`,`SYSTEM_TEAMFOUNDATIONCOLLECTIONURI`],[`AZURE_STATIC`,`INPUT_AZURE_STATIC_WEB_APPS_API_TOKEN`],[`APPCIRCLE`,`AC_APPCIRCLE`],[`BAMBOO`,`bamboo_planKey`],[`BITBUCKET`,`BITBUCKET_COMMIT`],[`BITRISE`,`BITRISE_IO`],[`BUDDY`,`BUDDY_WORKSPACE_ID`],[`BUILDKITE`],[`CIRCLE`,`CIRCLECI`],[`CIRRUS`,`CIRRUS_CI`],[`CLOUDFLARE_PAGES`,`CF_PAGES`,{ci:!0}],[`CLOUDFLARE_WORKERS`,`WORKERS_CI`,{ci:!0}],[`GOOGLE_CLOUDRUN`,`K_SERVICE`],[`GOOGLE_CLOUDRUN_JOB`,`CLOUD_RUN_JOB`],[`CODEBUILD`,`CODEBUILD_BUILD_ARN`],[`CODEFRESH`,`CF_BUILD_ID`],[`DRONE`],[`DRONE`,`DRONE_BUILD_EVENT`],[`DSARI`],[`GITHUB_ACTIONS`],[`GITLAB`,`GITLAB_CI`],[`GITLAB`,`CI_MERGE_REQUEST_ID`],[`GOCD`,`GO_PIPELINE_LABEL`],[`LAYERCI`],[`JENKINS`,`JENKINS_URL`],[`HUDSON`,`HUDSON_URL`],[`MAGNUM`],[`NETLIFY`],[`NETLIFY`,`NETLIFY_LOCAL`,{ci:!1}],[`NEVERCODE`],[`RENDER`],[`SAIL`,`SAILCI`],[`SEMAPHORE`],[`SCREWDRIVER`],[`SHIPPABLE`],[`SOLANO`,`TDDIUM`],[`STRIDER`],[`TEAMCITY`,`TEAMCITY_VERSION`],[`TRAVIS`],[`VERCEL`,`NOW_BUILDER`],[`VERCEL`,`VERCEL`,{ci:!1}],[`VERCEL`,`VERCEL_ENV`,{ci:!1}],[`APPCENTER`,`APPCENTER_BUILD_ID`],[`CODESANDBOX`,`CODESANDBOX_SSE`,{ci:!1}],[`CODESANDBOX`,`CODESANDBOX_HOST`,{ci:!1}],[`STACKBLITZ`],[`STORMKIT`],[`CLEAVR`],[`ZEABUR`],[`CODESPHERE`,`CODESPHERE_APP_ID`,{ci:!0}],[`RAILWAY`,`RAILWAY_PROJECT_ID`],[`RAILWAY`,`RAILWAY_SERVICE_ID`],[`DENO-DEPLOY`,`DENO_DEPLOY`],[`DENO-DEPLOY`,`DENO_DEPLOYMENT_ID`],[`FIREBASE_APP_HOSTING`,`FIREBASE_APP_HOSTING`,{ci:!0}],[`EDGEONE_PAGES`,`EO_PAGES_CI`,{ci:!0}]]),ur=function(){for(let e of lr)if(X[e[1]||e[0]])return{name:e[0].toLowerCase(),...e[2]};return X.SHELL===`/bin/jsh`&&ir.versions?.webcontainer?{name:`stackblitz`,ci:!1}:{name:``,ci:!1}}(),dr=(ur.name,ir.platform||``);X.CI||ur.ci;let fr=!!ir.stdout?.isTTY;X.DEBUG,ar===`test`||X.TEST;let pr=(ar===`production`||X.MODE,ar===`dev`||ar===`development`||X.MODE,X.MINIMAL,/^win/i.test(dr)),mr=(/^linux/i.test(dr),/^darwin/i.test(dr),!X.NO_COLOR&&(X.FORCE_COLOR||(fr||pr)&&X.TERM),(ir.versions?.node||``).replace(/^v/,``)||null),hr=(Number(mr?.split(`.`)[0]),!!ir?.versions?.node),gr=`Bun`in globalThis,_r=`Deno`in globalThis,vr=`fastly`in globalThis,yr=[[`Netlify`in globalThis,`netlify`],[`EdgeRuntime`in globalThis,`edge-light`],[globalThis.navigator?.userAgent===`Cloudflare-Workers`,`workerd`],[vr,`fastly`],[_r,`deno`],[gr,`bun`],[hr,`node`]];(function(){let e=yr.find(e=>e[0]);e&&e[1]})();let br=k(`node:tty`)?.WriteStream?.prototype?.hasColors?.()??!1,Z=(e,t)=>{if(!br)return e=>e;let n=`[${e}m`,r=`[${t}m`;return e=>{let i=e+``,a=i.indexOf(r);if(a===-1)return n+i+r;let o=n,s=0,c=(t===22?r:``)+n;for(;a!==-1;)o+=i.slice(s,a)+c,s=a+r.length,a=i.indexOf(r,s);return o+=i.slice(s)+r,o}},xr=(Z(0,0),Z(1,22),Z(2,22),Z(3,23),Z(4,24),Z(53,55),Z(7,27),Z(8,28),Z(9,29),Z(30,39),Z(31,39)),Sr=Z(32,39),Cr=Z(33,39),Q=Z(34,39),wr=(Z(35,39),Z(36,39)),Tr=(Z(37,39),Z(90,39));Z(40,49),Z(41,49),Z(42,49),Z(43,49),Z(44,49),Z(45,49),Z(46,49),Z(47,49),Z(100,49),Z(91,39),Z(92,39),Z(93,39),Z(94,39),Z(95,39),Z(96,39),Z(97,39),Z(101,49),Z(102,49),Z(103,49),Z(104,49),Z(105,49),Z(106,49),Z(107,49);function Er(e){if(typeof e!=`string`||e.startsWith(`file://`))return!1;try{return(0,U.lstatSync)(e).isDirectory()}catch{return!1}}function Dr(e,t=8){return(function(){if(Ar!==void 0)return Ar;try{return Ar=!!rr().getFips?.(),Ar}catch{return Ar=!1,Ar}}()?rr().createHash(`sha256`):rr().createHash(`md5`)).update(e).digest(`hex`).slice(0,t)}let Or={true:Sr(`true`),false:Cr(`false`),"[rebuild]":Cr(`[rebuild]`),"[esm]":Q(`[esm]`),"[cjs]":Sr(`[cjs]`),"[import]":Q(`[import]`),"[require]":Sr(`[require]`),"[native]":wr(`[native]`),"[transpile]":Cr(`[transpile]`),"[fallback]":xr(`[fallback]`),"[unknown]":xr(`[unknown]`),"[hit]":Sr(`[hit]`),"[miss]":Cr(`[miss]`),"[json]":Sr(`[json]`),"[data]":Sr(`[data]`)};function $(e,...t){if(!e.opts.debug)return;let n=process.cwd();console.log(Tr([`[jiti]`,...t.map(e=>e in Or?Or[e]:typeof e==`string`?e.replace(n,`.`):JSON.stringify(e))].join(` `)))}function kr(e,t){return e.opts.interopDefault?function(e){let t=typeof e;if(e===null||t!==`object`&&t!==`function`)return e;let n=e.default,r=typeof n,i=n==null,a=r===`object`||r===`function`;if(i&&e instanceof Promise)return e;let o=r===`function`&&t!==`function`,s=a&&!(n instanceof Promise),c=/* @__PURE__ */ new Map;return new Proxy(e,{get(t,r){if(c.has(r))return c.get(r);let a;return r==="__esModule"?a=!0:r==="default"?a=i?e:typeof n?.default==`function`&&e.__esModule?n.default:n:r in t?a=t[r]:s&&(a=n[r],typeof a==`function`&&(a=a.bind(n))),c.set(r,a),a},apply:o?(e,t,r)=>Reflect.apply(n,t,r):void 0})}(t):t}let Ar;function jr(e,t){return!!Mr(e,t)}function Mr(e,t,n){let r=process.env[e];if(!(e in process.env))return t;try{return JSON.parse(r)}catch{return n?r:t}}let Nr=/\.(c|m)?j(sx?)$/,Pr=/\.(c|m)?t(sx?)$/;function Fr(e,t,n){let r,i;if(e.isNativeRe.test(t))return t;if(e.resolveTsConfigPaths&&!n.skipTsConfigPaths){let r=e.resolveTsConfigPaths(t);for(let t of r){let r=Fr(e,t,{...n,try:!0,skipTsConfigPaths:!0});if(r)return r}}e.alias&&(t=function(e,t){let n=_t(e);t=$n(t);for(let[e,r]of Object.entries(t))if(n.startsWith(e)&&er(n[(er(e)?e.slice(0,-1):e).length]))return Ct(r,n.slice(e.length));return n}(t,e.alias));let a=n?.parentURL||e.url;Er(a)&&(a=Ct(a,`_index.js`));let o=(n?.async?[n?.conditions,[`node`,`import`],[`node`,`require`]]:[n?.conditions,[`node`,`require`],[`node`,`import`]]).filter(Boolean);for(let n of o){try{r=Gn(t,{url:a,conditions:n,extensions:e.opts.extensions})}catch(e){i=e}if(r)return r}try{return e.nativeRequire.resolve(t,{paths:n.paths})}catch(e){i=e}for(let i of e.additionalExts)if(r=Ir(e,t+i,a,n)||Ir(e,t+`/index`+i,a,n),r||(Pr.test(e.filename)||Pr.test(e.parentModule?.filename||``)||Nr.test(t))&&(r=Ir(e,t.replace(Nr,`.$1t$2`),a,n),r))return r;if(!n?.try)throw i}function Ir(e,t,n,r){try{return e.nativeRequire.resolve(t,{...r,paths:[kt(Ln(n)),...r?.paths||[]]})}catch{}}let Lr=k(`node:fs/promises`),Rr=k(`node:perf_hooks`),zr=k(`node:vm`);var Br=r.n(zr);function Vr(e,t,n){let r=e.parentCache||{};if(t.startsWith(`node:`))return Hr(e,t,n.async);if(t.startsWith(`file:`))t=(0,W.fileURLToPath)(t);else if(t.startsWith(`data:`)){if(!n.async)throw Error("`data:` URLs are only supported in ESM context. Use `import` or `jiti.import` instead.");return $(e,`[native]`,`[data]`,`[import]`,t),Hr(e,t,!0)}if(lt.builtinModules.includes(t)||t===`.pnp.js`)return Hr(e,t,n.async);if(e.opts.virtualModules&&t in e.opts.virtualModules){$(e,`[virtual]`,t);let r=e.opts.virtualModules[t];return n.async?Promise.resolve(kr(e,r)):kr(e,r)}if(e.opts.tryNative&&!e.opts.transformOptions)try{if(!(t=Fr(e,t,n))&&n.try)return;if($(e,`[try-native]`,n.async&&e.nativeImport?`[import]`:`[require]`,t),n.async&&e.nativeImport)return e.nativeImport(t).then(n=>(!1===e.opts.moduleCache&&delete e.nativeRequire.cache[t],kr(e,n))).catch(r=>($(e,`[try-native] Using fallback for ${t} because of an error:`,r),Vr({...e,opts:{...e.opts,tryNative:!1}},t,n)));{let n=e.nativeRequire(t);return!1===e.opts.moduleCache&&delete e.nativeRequire.cache[t],kr(e,n)}}catch(n){$(e,`[try-native] Using fallback for ${t} because of an error:`,n)}let i=Fr(e,t,n);if(!i&&n.try)return;let a=Ot(i);if(a===`.json`){$(e,`[json]`,i);let t=e.nativeRequire(i);return t&&!(`default`in t)&&Object.defineProperty(t,"default",{value:t,enumerable:!1}),t}if(a&&!e.opts.extensions.includes(a))return $(e,`[native]`,`[unknown]`,n.async?`[import]`:`[require]`,i),Hr(e,i,n.async);if(e.isNativeRe.test(i))return $(e,`[native]`,n.async?`[import]`:`[require]`,i),Hr(e,i,n.async);if(r[i])return kr(e,r[i]?.exports);if(e.opts.moduleCache){let t=e.nativeRequire.cache[i];if(t?.loaded)return kr(e,t.exports)}return Kr(e,(0,U.readFileSync)(i,`utf8`),{id:t,filename:i,ext:a,cache:r,async:n.async})}function Hr(e,t,n){return n&&e.nativeImport?e.nativeImport(function(e){return pr&&Dt(e)?Rn(e):e}(t)).then(t=>kr(e,t)):kr(e,e.nativeRequire(t))}function Ur(e,t,n){if(!e.opts.fsCache||!t.filename)return n();let r=` /* v9-${Dr(t.source,16)} */\n`,i=`${At(kt(t.filename))}-${function(e){let t=e.split(Qn).pop();if(!t)return;let n=t.lastIndexOf(`.`);return n<=0?t:t.slice(0,n)}(t.filename)}`+(e.opts.sourceMaps?`+map`:``)+(t.interopDefault?`.i`:``)+`.${Dr(t.filename)}`+(t.async?`.mjs`:`.cjs`);t.jsx&&t.filename.endsWith(`x`)&&(i+=`x`);let a=e.opts.fsCache,o=Ct(a,i);if(!e.opts.rebuildFsCache&&(0,U.existsSync)(o)){let n=(0,U.readFileSync)(o,`utf8`);if(n.endsWith(r))return $(e,`[cache]`,`[hit]`,t.filename,`~>`,o),n}$(e,`[cache]`,`[miss]`,t.filename);let s=n();return s.includes(`__JITI_ERROR__`)||((0,U.writeFileSync)(o,s+r,`utf8`),$(e,`[cache]`,`[store]`,t.filename,`~>`,o)),s}function Wr(t){if(!0===t.opts.fsCache&&(t.opts.fsCache=function(t){let n=t.filename&&Tt(t.filename,`../node_modules`);if(n&&(0,U.existsSync)(n))return Ct(n,`.cache/jiti`);let r=(0,e.tmpdir)();if(process.env.TMPDIR&&r===process.cwd()&&!process.env.JITI_RESPECT_TMPDIR_ENV){let t=process.env.TMPDIR;delete process.env.TMPDIR,r=(0,e.tmpdir)(),process.env.TMPDIR=t}return Ct(r,`jiti`)}(t)),t.opts.fsCache)try{if((0,U.mkdirSync)(t.opts.fsCache,{recursive:!0}),!function(e){try{return(0,U.accessSync)(e,U.constants.W_OK),!0}catch{return!1}}(t.opts.fsCache))throw Error(`directory is not writable!`)}catch(e){$(t,`Error creating cache directory at `,t.opts.fsCache,e),t.opts.fsCache=!1}}function Gr(e,t){let n=Ur(e,t,()=>{let n=e.opts.transform({...e.opts.transformOptions,babel:{...e.opts.sourceMaps?{sourceFileName:t.filename,sourceMaps:`inline`}:{},...e.opts.transformOptions?.babel},interopDefault:e.opts.interopDefault,...t});return n.error&&e.opts.debug&&$(e,n.error),n.code});return n.startsWith(`#!`)&&(n=`// `+n),n}function Kr(t,n,r={}){let i=r.id||(r.filename?At(r.filename):`_jitiEval.${r.ext||(r.async?`mjs`:`js`)}`),a=r.filename||Fr(t,i,{async:r.async}),o=r.ext||Ot(a),s=r.cache||t.parentCache||{},c=/\.[cm]?tsx?$/.test(o),l=o===`.mjs`||o===`.js`&&function(e){for(;e&&e!==`.`&&e!==`/`;){e=Ct(e,`..`);try{let t=(0,U.readFileSync)(Ct(e,`package.json`),`utf8`);try{return JSON.parse(t)}catch{}break}catch{}}}(a)?.type===`module`,u=o===`.cjs`,d=r.forceTranspile??(!u&&!(l&&r.async)&&(c||l||t.isTransformRe.test(a)||Jn(n))),f=Rr.performance.now();if(d){n=Gr(t,{filename:a,source:n,ts:c,async:r.async??!1,jsx:t.opts.jsx});let e=Math.round(1e3*(Rr.performance.now()-f))/1e3;$(t,`[transpile]`,r.async?`[esm]`:`[cjs]`,a,`(${e}ms)`)}else{if($(t,`[native]`,r.async?`[import]`:`[require]`,a),r.async)return Promise.resolve(Hr(t,a,r.async)).catch(e=>($(t,`Native import error:`,e),$(t,`[fallback]`,a),Kr(t,n,{...r,forceTranspile:!0})));try{return Hr(t,a,r.async)}catch(e){$(t,`Native require error:`,e),$(t,`[fallback]`,a),n=Gr(t,{filename:a,source:n,ts:c,async:r.async??!1,jsx:t.opts.jsx})}}let p=new lt.Module(a);p.filename=a,t.parentModule&&(p.parent=t.parentModule,Array.isArray(t.parentModule.children)&&!t.parentModule.children.includes(p)&&t.parentModule.children.push(p));let m=Jr(a,t.opts,{parentModule:p,parentCache:s,nativeImport:t.nativeImport,onError:t.onError,createRequire:t.createRequire},!0),h;p.require=m,p.path=kt(a),p.paths=lt.Module._nodeModulePaths(p.path),s[a]=p,t.opts.moduleCache&&(t.nativeRequire.cache[a]=p);let g=function(e,t){return`(${t?.async?`async `:``}function (exports, require, module, __filename, __dirname, jitiImport, jitiESMResolve) { ${e}\n});`}(n,{async:r.async});try{h=Br().runInThisContext(g,{filename:a,lineOffset:0,displayErrors:!1})}catch(n){n.name===`SyntaxError`&&r.async&&t.nativeImport?($(t,`[esm]`,`[import]`,`[fallback]`,a),h=function(t,n,r,i,a){let o=`export default ${n}`,s=a?void 0:`data:text/javascript;base64,${Buffer.from(o).toString(`base64`)}`;return(...n)=>{let a,c=()=>(a=function(t,n){let r=Ct((0,e.tmpdir)(),`jiti-esm`);try{(0,U.mkdirSync)(r,{recursive:!0})}catch{}let i=Ct(r,`${At(n,Ot(n))}-${Date.now()}-${Math.random().toString(36).slice(2)}.mjs`);return(0,U.writeFileSync)(i,t),i}(o,r),$(t,`[esm]`,`[tempfile]`,a),i(Rn(a)));return(s?i(s).catch(e=>{if(e?.code!==`ENAMETOOLONG`)throw e;return c()}):c()).then(e=>e.default(...n)).finally(()=>{a&&(0,Lr.unlink)(a).catch(()=>{})})}}(t,g,a,t.nativeImport,t.opts.esmEvalTempFile)):(t.opts.moduleCache&&delete t.nativeRequire.cache[a],t.onError(n))}let _;try{_=h(p.exports,p.require,p,p.filename,kt(p.filename),m.import,m.esmResolve)}catch(e){t.opts.moduleCache&&delete t.nativeRequire.cache[a],t.onError(e)}function v(){if(p.exports&&p.exports.__JITI_ERROR__){let{filename:e,line:n,column:r,code:i,message:a}=p.exports.__JITI_ERROR__,o=/* @__PURE__ */ Error(`${i}: ${a} \n ${`${e}:${n}:${r}`}`);Error.captureStackTrace(o,Vr),t.onError(o)}return p.loaded=!0,kr(t,p.exports)}return r.async?Promise.resolve(_).then(v):v()}let qr=(0,e.platform)()===`win32`;function Jr(e,t={},n,i=!1){let a=i?t:function(e){let t={fsCache:jr(`JITI_FS_CACHE`,jr(`JITI_CACHE`,!0)),rebuildFsCache:jr(`JITI_REBUILD_FS_CACHE`,!1),moduleCache:jr(`JITI_MODULE_CACHE`,jr(`JITI_REQUIRE_CACHE`,!0)),debug:jr(`JITI_DEBUG`,!1),sourceMaps:jr(`JITI_SOURCE_MAPS`,!1),interopDefault:jr(`JITI_INTEROP_DEFAULT`,!0),extensions:Mr(`JITI_EXTENSIONS`,[`.js`,`.mjs`,`.cjs`,`.ts`,`.tsx`,`.mts`,`.cts`,`.mtsx`,`.ctsx`]),alias:Mr(`JITI_ALIAS`,{}),nativeModules:Mr(`JITI_NATIVE_MODULES`,[]),transformModules:Mr(`JITI_TRANSFORM_MODULES`,[]),tryNative:Mr(`JITI_TRY_NATIVE`,`Bun`in globalThis),esmEvalTempFile:jr(`JITI_ESM_EVAL_TEMP_FILE`,!1),jsx:jr(`JITI_JSX`,!1),tsconfigPaths:Mr(`JITI_TSCONFIG_PATHS`,!1,!0)};t.jsx&&t.extensions.push(`.jsx`,`.tsx`);let n={};return e.cache!==void 0&&(n.fsCache=e.cache),e.requireCache!==void 0&&(n.moduleCache=e.requireCache),{...t,...n,...e}}(t);typeof e==`string`&&e.startsWith(`file://`)&&(e=Ln(e));let o=a.alias&&Object.keys(a.alias).length>0?$n(a.alias||{}):void 0,s;if(a.tsconfigPaths){let{getTsconfig:t,createPathsMatcher:n}=r(`./node_modules/.pnpm/get-tsconfig@4.14.0/node_modules/get-tsconfig/dist/index.cjs`),i=t(typeof a.tsconfigPaths==`string`?a.tsconfigPaths:kt(e));i&&(s=n(i))}let c=[`typescript`,`jiti`,...a.nativeModules||[]],l=RegExp(`node_modules/(${c.map(e=>Yn(e)).join(`|`)})/`),u=[...a.transformModules||[]],d=RegExp(`node_modules/(${u.map(e=>Yn(e)).join(`|`)})/`);e||=process.cwd(),!i&&Er(e)&&(e=Ct(e,`_index.js`));let f=Rn(e),p=[...a.extensions].filter(e=>e!==`.js`),m=n.createRequire(qr?e.replace(/\//g,`\\`):e),h={filename:e,url:f,opts:a,alias:o,resolveTsConfigPaths:s,nativeModules:c,transformModules:u,isNativeRe:l,isTransformRe:d,additionalExts:p,nativeRequire:m,onError:n.onError,parentModule:n.parentModule,parentCache:n.parentCache,nativeImport:n.nativeImport,createRequire:n.createRequire};return i||$(h,`[init]`,...[[`version:`,tr.rE],[`module-cache:`,a.moduleCache],[`fs-cache:`,a.fsCache],[`rebuild-fs-cache:`,a.rebuildFsCache],[`interop-defaults:`,a.interopDefault]].flat()),i||Wr(h),Object.assign(function(e){return Vr(h,e,{async:!1})},{cache:a.moduleCache?m.cache:Object.create(null),extensions:m.extensions,main:m.main,options:a,resolve:Object.assign(function(e,t){return Fr(h,e,{...t,async:!1})},{paths:m.resolve.paths}),transform:e=>Gr(h,e),evalModule:(e,t)=>Kr(h,e,t),async import(e,t){let n=await Vr(h,e,{...t,async:!0});return t?.default?n?.default??n:n},esmResolve(e,t){typeof t==`string`&&(t={parentURL:t});let n=Fr(h,e,{parentURL:f,...t,async:!0});return!n||typeof n!=`string`||n.startsWith(`file://`)?n:Rn(n)}})}})(),t.exports=i.default})()})))();var A=class{emitter;constructor(){this.emitter=r()}on(e,t){me(e).forEach(e=>{this.emitter.on(e,t)})}off(e,t){me(e).forEach(e=>{this.emitter.off(e,t)})}emit(e,t){me(e).forEach(e=>{this.emitter.emit(e,t)})}removeAllListeners(){this.emitter.all.clear()}},j=class{listeners;constructor(){this.listeners=/* @__PURE__ */ new Map}on(e,t){me(e).forEach(e=>{let n=this.listeners.get(e)||/* @__PURE__ */ new Set;n.add(t),this.listeners.set(e,n)})}off(e,t){me(e).forEach(e=>{let n=this.listeners.get(e);n&&n.delete(t)})}async emit(e,...t){let n=me(e).flatMap(e=>{let t=this.listeners.get(e)||/* @__PURE__ */ new Set,n=this.listeners.get(`*`)||/* @__PURE__ */ new Set;return[...Array.from(t),...Array.from(n)]});return n.length===0?[]:await Promise.all(n.map(async n=>{try{let e=n(...t);return e instanceof Promise?await e:e}catch(t){console.error(`Error in event listener for ${String(e)}:`,t);return}}))}removeAllListeners(){this.listeners.clear()}};function M(e,...t){return class extends e{static _instance;static getInstance(){return this._instance||=new e(...t),this._instance}static clearInstance(){this._instance=void 0}}}const _e=M(class extends A{destroy(){this.removeAllListeners()}fatal(e,t,n){this.emit(`fatal`,{code:t,message:e,data:n,timestamp:Date.now()})}error(e,t,n){this.emit(`error`,{code:t,message:e,data:n,timestamp:Date.now()})}warn(e,t,n){this.emit(`warning`,{code:t,message:e,data:n,timestamp:Date.now()})}});var ve=class{data;_schema;_defaultValue;_path;constructor(e){let{schema:t,default:n,path:r}=e;this._schema=t,this._defaultValue=n,this._path=r}set(e){let t=this._schema[`~standard`].validate(e);if(t instanceof Promise)throw Error(`StructuredConfigFile does not support async validation`);if(t.issues)throw this.reportInvalidConfigFile(t.issues),Error(`Invalid config data for ${this._path}: ${t.issues.map(e=>e.message).join(`; `)}`);this.data=this.onBeforeSave(e),this.save(e)}get(e={}){return this.data?this.data:this.load(e)}getKey(e,t={}){return this.get(t)[e]}save(e){let t=this.onBeforeSave(e);try{d(this.getFilePath()),i.writeFileSync(this.getFilePath(),JSON.stringify(t,void 0,2))}catch{return}return this.data=t}load(e={}){let{createIfMissing:t=!0}=e;if(!this.fileExists(this.getFilePath())||!this.canReadWriteFile(this.getFilePath())){t&&this.save(this._defaultValue);let e=this.onAfterLoad(this._defaultValue);return t&&(this.data=e),e}try{let e=i.readFileSync(this.getFilePath(),`utf8`),t=this.onAfterLoad(this.parseStoredData(e));return this.data=t,t}catch{return this.data=this._defaultValue}}onBeforeSave(e){return e}onAfterLoad(e){return e}getFilePath(){return this._path}parseStoredData(e){try{let t=n(`string.json.parse`).to(`object`)(e);if(t instanceof n.errors)return this._defaultValue;let r=this._schema[`~standard`].validate(t);if(r instanceof Promise)throw Error(`StructuredConfigFile does not support async validation`);return r.issues?this.migrate(t,this._defaultValue):this.migrate(r.value,this._defaultValue)}catch{return this._defaultValue}}canReadWriteFile(e){try{return i.accessSync(e,i.constants.R_OK|i.constants.W_OK),!0}catch{return!1}}fileExists(e){try{return i.accessSync(e,i.constants.F_OK),!0}catch{return!1}}migrate(e,t){let n={...e};for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&(r in e?e[r]!==null&&t[r]!==null&&typeof e[r]==`object`&&typeof t[r]==`object`&&!Array.isArray(e[r])&&!Array.isArray(t[r])?n[r]=this.migrate(e[r],t[r]):Array.isArray(t[r])&&(n[r]=e[r]):n[r]=t[r]);return n}reportInvalidConfigFile(e){_e.getInstance().error(`Invalid config file`,`INVALID_CONFIG_FILE`,{issues:e.map(e=>e.message),filePath:this._path,data:this.data})}};function N(e,t,n){return typeof e!=`object`||!e?String(e):e instanceof Error?JSON.stringify(e,(e,t)=>{if(t instanceof Error){let e={};for(let n of Object.getOwnPropertyNames(t))e[n]=t[n];return e}return t},n):e instanceof Map?JSON.stringify(Object.fromEntries(e.entries()),t,n):e instanceof Set?JSON.stringify(Array.from(e),t,n):JSON.stringify(e,t,n)}const ye=/\x1b\[[0-9;]*m/g;function be(e){return e.replace(ye,``)}var xe=class e extends A{stream;logPath;baseFileName;currentDate;rotationCheckInterval;isRotating=!1;constructor(e,t){super(),this.logPath=e,this.baseFileName=t.replace(`.log`,``),this.currentDate=this.getDateString(/* @__PURE__ */ new Date),this.ensureLogDirectory(),this.ensureLogFile(),this.stream=this.createStream(),this.rotationCheckInterval=this.startRotationCheck(),this.cleanupOldLogs()}static scope(t,n){return new e(t,n)}log(...e){this.write(`info`,...e)}error(...e){this.write(`error`,...e)}warn(...e){this.write(`warn`,...e)}info(...e){this.write(`info`,...e)}debug(...e){this.write(`debug`,...e)}async close(){clearInterval(this.rotationCheckInterval),await new Promise(e=>{this.stream.end(()=>e())})}getCurrentFileName(){return this.getFileName(this.currentDate)}static getMessageElements(e,...t){let n=/* @__PURE__ */ new Date;return{timestamp:n.toISOString().replace(`T`,` `).replace(/\.\d+Z$/,``)+`.${n.getUTCMilliseconds().toString().padStart(3,`0`)}`,level:e,message:t.map(e=>N(e)).join(` `)}}getFileName(e){return`${this.baseFileName}-${e}.log`}ensureLogDirectory(){try{s(this.logPath,{recursive:!0})}catch(e){throw console.error(`Failed to create log directory ${this.logPath}:`,e),e}}ensureLogFile(){let e=p(this.logPath,this.getFileName(this.currentDate));if(!o(e))try{u(e,``,`utf8`)}catch(t){throw console.error(`Failed to create log file ${e}:`,t),t}}getDateString(e){return`${e.getUTCFullYear()}-${(e.getUTCMonth()+1).toString().padStart(2,`0`)}-${e.getUTCDate().toString().padStart(2,`0`)}`}createStream(){s(this.logPath,{recursive:!0});let e=p(this.logPath,this.getFileName(this.currentDate)),t=a(e,{flags:`a`,encoding:`utf8`});return t.on(`error`,e=>this.emit(`error`,e)),t}async rotateLogs(){if(this.isRotating)return;this.isRotating=!0;let e=this.getDateString(/* @__PURE__ */ new Date);e!==this.currentDate&&await new Promise(t=>{this.stream.end(()=>{this.currentDate=e;try{this.stream=this.createStream()}catch(e){this.emit(`error`,e instanceof Error?e:Error(String(e)))}this.cleanupOldLogs(),t()})}),this.isRotating=!1}startRotationCheck(){return setInterval(()=>this.rotateLogs(),6e4)}cleanupOldLogs(){let e;try{e=c(this.logPath)}catch(e){console.error(`Failed to read log directory ${this.logPath}:`,e);return}let t=/* @__PURE__ */ new Date,n=new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()-7));e.filter(e=>e.startsWith(this.baseFileName)&&e.endsWith(`.log`)).filter(e=>{let[t,r,i]=e.replace(`${this.baseFileName}-`,``).replace(`.log`,``).split(`-`).map(Number);return new Date(Date.UTC(t,r-1,i))<=n}).forEach(e=>{try{l(p(this.logPath,e))}catch(t){console.error(`Failed to delete old log file ${e}:`,t)}})}ensureStreamValid(){if(!this.stream.writable||this.stream.destroyed)try{this.stream=this.createStream()}catch(e){this.emit(`error`,e instanceof Error?e:Error(String(e)))}}write(t,...n){let{timestamp:r,message:i}=e.getMessageElements(t,...n),a=`[${r}] [${t}] ${be(i)}\n`;this.ensureStreamValid(),this.stream.write(a,e=>{if(e){if(e.code===`ERR_STREAM_WRITE_AFTER_END`||!this.stream.writable)try{this.stream=this.createStream(),this.stream.write(a,e=>{e?this.emit(`error`,e):this.emit(`write`,a)})}catch(e){this.emit(`error`,e instanceof Error?e:Error(String(e)))}else this.emit(`error`,e)}else this.emit(`write`,a)})}};const Se=()=>h.join(process.env.APPDATA??``,`overlayed`),Ce=()=>h.join(Se(),`logs`),we=e=>h.join(Se(),`apps`,e),Te=e=>h.join(we(e),`logs`),P=()=>h.join(Se(),`meta.json`),F=()=>h.join(Se(),`crash-dumps`);var I=class{fileLogger;path;appId;messageQueue=new ge;fileName;_debug=!1;silent=!1;forceSilent=!1;constructor(e){this.fileName=e}init(e,t=!1,n=!1,r=!1){this.appId=e,this._debug=t,this.silent=n,this.forceSilent=r,this.path=Te(e),this.fileLogger=new xe(this.path,this.fileName),this.messageQueue.flush().forEach(e=>{this.fileLogger?.[e.type](...e.args)})}scope(e){if(!this.appId||!this.path)throw Error(`Logger not initialized`);let t=v.cyan(`[${e}]`);return{scope:e=>this.scope(e),error:(...e)=>this.error(t,...e),warn:(...e)=>this.warn(t,...e),info:(...e)=>this.info(t,...e),log:(...e)=>this.log(t,...e),debug:(...e)=>this.debug(t,...e)}}error(...e){this.handle(`error`,...e)}warn(...e){this.handle(`warn`,...e)}info(...e){this.handle(`log`,...e)}debug(...e){this._debug&&this.handle(`debug`,...e)}log(...e){this.handle(`log`,...e)}handle(e,...t){this.logToConsole(e,...t),this.fileLogger?this.fileLogger[e](...t):this.messageQueue.add({type:e,args:t})}logToConsole(e,...t){let n={error:v.red,warn:v.yellow,debug:v.blue,log:v.white};if(this.forceSilent||this.silent&&!this._debug)return;let{timestamp:r,message:i}=xe.getMessageElements(e,...t),a=console[e],o=n[e];a(`${v.gray(r)} ${o(i)}`)}};const L=M(I,`overlayed.log`);var R=class extends ee{blob;chunkSizeMb;maxConcurrent;shouldStop=!1;constructor(e,t){super(),this.blob=e,this.chunkSizeMb=t.chunkSizeMb,this.maxConcurrent=t.maxConcurrent??3}get totalChunks(){return Math.ceil(this.blob.size/(this.chunkSizeMb*1024*1024))}async chunk(e){let t=this.chunkSizeMb*1024*1024,n=this.totalChunks;if(n===0)return;let r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Set,o=[];for(let e=0;e<n;e++)o.push(e);let s=async n=>{let s=n*t,c=Math.min(s+t,this.blob.size),l=this.blob.slice(s,c);try{await e(l,n),a.add(n),this.emit(`chunkComplete`,n),i.delete(n)}catch(e){let t=r.get(n)||0;t<5?(r.set(n,t+1),await new Promise(e=>setTimeout(e,(t+1)*1e3)),o.push(n)):(a.add(n),this.emit(`error`,e),this.shouldStop=!0,i.delete(n))}},c=[],l=async()=>{for(;(o.length>0||i.size>0)&&!this.shouldStop;){if(o.length===0){await new Promise(e=>setTimeout(e,10));continue}let e=o.shift();a.has(e)||i.has(e)||(i.add(e),await s(e))}};for(let e=0;e<this.maxConcurrent;e++)c.push(l());await Promise.all(c)}};function Ee(e,t){let{recursive:n}=De(t);return S(e)?n?Oe(e).map(t=>[e,t]):w(e).map(t=>[e,t]):[]}function De(e){return{recursive:e?.recursive??!0}}function Oe(e){return w(e,{withFileTypes:!0}).flatMap(t=>{let n=h.join(e,t.name);return t.isDirectory()?Oe(n):[n]})}function ke(e){return Ae(e),e}function Ae(e){if(!he(e.applicationId))throw Error(`Invalid applicationId, must be a valid ULID.`)}function je(e,t){let n=t?.cwd??process.cwd(),r=m.join(n,`.overlayed`);y.existsSync(r)||y.mkdirSync(r,{recursive:!0});let i={application:{id:e.id,name:e.name,slug:e.slug,siteUrl:e.siteUrl},release:{id:null,channel:`local`,version:`0.0.0`}},a=m.join(r,`meta.json`);return y.writeFileSync(a,JSON.stringify(i,null,2)),i}const{PipeEventServer:Me,PipeEventClient:Ne,PipeEventBase:Pe,GameMonitor:Fe,GameInstance:Ie,HardwareInterface:Le}=e(import.meta.url)(`@overlayed/app/dist/native-interface/build/overlayed_native_interface_x64.node`),Re=M(class extends A{server=null;_hasConnection=!1;pipeId;get hasConnection(){return this._hasConnection}constructor(e){super(),this.pipeId=e,this.init()}destroy(){this.server&&=(this._hasConnection=!1,this.server.removeAllListeners(),this.server.close(),null)}init(){this.server=new Me(this.pipeId,{clientCount:1,access:1}),this.server.on(`event`,e=>{try{let t=JSON.parse(e);this.emit(`data`,[t])}catch(e){this.emit(`error`,e)}}),this.server.on(`connected`,()=>{this._hasConnection=!0,this.emit(`connected`,void 0)}),this.server.on(`disconnected`,()=>{this._hasConnection=!1,this.emit(`disconnected`,void 0)})}},`overlayed-event-server`),{RenderInterface:ze,renderHookPath:Be}=e(import.meta.url)(`@overlayed/app/dist/render-interface/build/overlayed_render_interface_x64.node`);let Ve=/* @__PURE__ */ function(e){return e[e.LeftButton=1]=`LeftButton`,e[e.RightButton=2]=`RightButton`,e[e.Cancel=3]=`Cancel`,e[e.MiddleButton=4]=`MiddleButton`,e[e.ExtraButton1=5]=`ExtraButton1`,e[e.ExtraButton2=6]=`ExtraButton2`,e[e.Back=8]=`Back`,e[e.Tab=9]=`Tab`,e[e.Clear=12]=`Clear`,e[e.Return=13]=`Return`,e[e.Shift=16]=`Shift`,e[e.Control=17]=`Control`,e[e.Menu=18]=`Menu`,e[e.Pause=19]=`Pause`,e[e.CapsLock=20]=`CapsLock`,e[e.Kana=21]=`Kana`,e[e.Hangeul=21]=`Hangeul`,e[e.Hangul=21]=`Hangul`,e[e.Junja=23]=`Junja`,e[e.Final=24]=`Final`,e[e.Hanja=25]=`Hanja`,e[e.Kanji=25]=`Kanji`,e[e.Escape=27]=`Escape`,e[e.Convert=28]=`Convert`,e[e.NonConvert=29]=`NonConvert`,e[e.Accept=30]=`Accept`,e[e.ModeChange=31]=`ModeChange`,e[e.Space=32]=`Space`,e[e.Prior=33]=`Prior`,e[e.Next=34]=`Next`,e[e.End=35]=`End`,e[e.Home=36]=`Home`,e[e.Left=37]=`Left`,e[e.Up=38]=`Up`,e[e.Right=39]=`Right`,e[e.Down=40]=`Down`,e[e.Select=41]=`Select`,e[e.Print=42]=`Print`,e[e.Execute=43]=`Execute`,e[e.Snapshot=44]=`Snapshot`,e[e.Insert=45]=`Insert`,e[e.Delete=46]=`Delete`,e[e.Help=47]=`Help`,e[e.N0=48]=`N0`,e[e.N1=49]=`N1`,e[e.N2=50]=`N2`,e[e.N3=51]=`N3`,e[e.N4=52]=`N4`,e[e.N5=53]=`N5`,e[e.N6=54]=`N6`,e[e.N7=55]=`N7`,e[e.N8=56]=`N8`,e[e.N9=57]=`N9`,e[e.A=65]=`A`,e[e.B=66]=`B`,e[e.C=67]=`C`,e[e.D=68]=`D`,e[e.E=69]=`E`,e[e.F=70]=`F`,e[e.G=71]=`G`,e[e.H=72]=`H`,e[e.I=73]=`I`,e[e.J=74]=`J`,e[e.K=75]=`K`,e[e.L=76]=`L`,e[e.M=77]=`M`,e[e.N=78]=`N`,e[e.O=79]=`O`,e[e.P=80]=`P`,e[e.Q=81]=`Q`,e[e.R=82]=`R`,e[e.S=83]=`S`,e[e.T=84]=`T`,e[e.U=85]=`U`,e[e.V=86]=`V`,e[e.W=87]=`W`,e[e.X=88]=`X`,e[e.Y=89]=`Y`,e[e.Z=90]=`Z`,e[e.LeftWindows=91]=`LeftWindows`,e[e.RightWindows=92]=`RightWindows`,e[e.Application=93]=`Application`,e[e.Sleep=95]=`Sleep`,e[e.Numpad0=96]=`Numpad0`,e[e.Numpad1=97]=`Numpad1`,e[e.Numpad2=98]=`Numpad2`,e[e.Numpad3=99]=`Numpad3`,e[e.Numpad4=100]=`Numpad4`,e[e.Numpad5=101]=`Numpad5`,e[e.Numpad6=102]=`Numpad6`,e[e.Numpad7=103]=`Numpad7`,e[e.Numpad8=104]=`Numpad8`,e[e.Numpad9=105]=`Numpad9`,e[e.Multiply=106]=`Multiply`,e[e.Add=107]=`Add`,e[e.Separator=108]=`Separator`,e[e.Subtract=109]=`Subtract`,e[e.Decimal=110]=`Decimal`,e[e.Divide=111]=`Divide`,e[e.F1=112]=`F1`,e[e.F2=113]=`F2`,e[e.F3=114]=`F3`,e[e.F4=115]=`F4`,e[e.F5=116]=`F5`,e[e.F6=117]=`F6`,e[e.F7=118]=`F7`,e[e.F8=119]=`F8`,e[e.F9=120]=`F9`,e[e.F10=121]=`F10`,e[e.F11=122]=`F11`,e[e.F12=123]=`F12`,e[e.F13=124]=`F13`,e[e.F14=125]=`F14`,e[e.F15=126]=`F15`,e[e.F16=127]=`F16`,e[e.F17=128]=`F17`,e[e.F18=129]=`F18`,e[e.F19=130]=`F19`,e[e.F20=131]=`F20`,e[e.F21=132]=`F21`,e[e.F22=133]=`F22`,e[e.F23=134]=`F23`,e[e.F24=135]=`F24`,e[e.NumLock=144]=`NumLock`,e[e.ScrollLock=145]=`ScrollLock`,e[e.NEC_Equal=146]=`NEC_Equal`,e[e.Fujitsu_Jisho=146]=`Fujitsu_Jisho`,e[e.Fujitsu_Masshou=147]=`Fujitsu_Masshou`,e[e.Fujitsu_Touroku=148]=`Fujitsu_Touroku`,e[e.Fujitsu_Loya=149]=`Fujitsu_Loya`,e[e.Fujitsu_Roya=150]=`Fujitsu_Roya`,e[e.LeftShift=160]=`LeftShift`,e[e.RightShift=161]=`RightShift`,e[e.LeftControl=162]=`LeftControl`,e[e.RightControl=163]=`RightControl`,e[e.LeftMenu=164]=`LeftMenu`,e[e.RightMenu=165]=`RightMenu`,e[e.BrowserBack=166]=`BrowserBack`,e[e.BrowserForward=167]=`BrowserForward`,e[e.BrowserRefresh=168]=`BrowserRefresh`,e[e.BrowserStop=169]=`BrowserStop`,e[e.BrowserSearch=170]=`BrowserSearch`,e[e.BrowserFavorites=171]=`BrowserFavorites`,e[e.BrowserHome=172]=`BrowserHome`,e[e.VolumeMute=173]=`VolumeMute`,e[e.VolumeDown=174]=`VolumeDown`,e[e.VolumeUp=175]=`VolumeUp`,e[e.MediaNextTrack=176]=`MediaNextTrack`,e[e.MediaPrevTrack=177]=`MediaPrevTrack`,e[e.MediaStop=178]=`MediaStop`,e[e.MediaPlayPause=179]=`MediaPlayPause`,e[e.LaunchMail=180]=`LaunchMail`,e[e.LaunchMediaSelect=181]=`LaunchMediaSelect`,e[e.LaunchApplication1=182]=`LaunchApplication1`,e[e.LaunchApplication2=183]=`LaunchApplication2`,e[e.OEM1=186]=`OEM1`,e[e.OEMPlus=187]=`OEMPlus`,e[e.OEMComma=188]=`OEMComma`,e[e.OEMMinus=189]=`OEMMinus`,e[e.OEMPeriod=190]=`OEMPeriod`,e[e.OEM2=191]=`OEM2`,e[e.OEM3=192]=`OEM3`,e[e.OEM4=219]=`OEM4`,e[e.OEM5=220]=`OEM5`,e[e.OEM6=221]=`OEM6`,e[e.OEM7=222]=`OEM7`,e[e.OEM8=223]=`OEM8`,e[e.OEMAX=225]=`OEMAX`,e[e.OEM102=226]=`OEM102`,e[e.ICOHelp=227]=`ICOHelp`,e[e.ICO00=228]=`ICO00`,e[e.ProcessKey=229]=`ProcessKey`,e[e.ICOClear=230]=`ICOClear`,e[e.Packet=231]=`Packet`,e[e.OEMReset=233]=`OEMReset`,e[e.OEMJump=234]=`OEMJump`,e[e.OEMPA1=235]=`OEMPA1`,e[e.OEMPA2=236]=`OEMPA2`,e[e.OEMPA3=237]=`OEMPA3`,e[e.OEMWSCtrl=238]=`OEMWSCtrl`,e[e.OEMCUSel=239]=`OEMCUSel`,e[e.OEMATTN=240]=`OEMATTN`,e[e.OEMFinish=241]=`OEMFinish`,e[e.OEMCopy=242]=`OEMCopy`,e[e.OEMAuto=243]=`OEMAuto`,e[e.OEMENLW=244]=`OEMENLW`,e[e.OEMBackTab=245]=`OEMBackTab`,e[e.ATTN=246]=`ATTN`,e[e.CRSel=247]=`CRSel`,e[e.EXSel=248]=`EXSel`,e[e.EREOF=249]=`EREOF`,e[e.Play=250]=`Play`,e[e.Zoom=251]=`Zoom`,e[e.Noname=252]=`Noname`,e[e.PA1=253]=`PA1`,e[e.OEMClear=254]=`OEMClear`,e}({});const He=n({game:`string`,type:`string`,creationTime:`number`}),Ue=He.and({game:`'siege' | 'tft'`,type:`'logged_in'`,content:{accountId:`string`}}),We=He.and({game:`'sand'`,type:`'logged_in'`,content:{accountId:`string`,displayName:`string`,platformId:`string`,playfabId:`string`}}).or(Ue),Ge=He.and({game:`'siege' | 'tft' | 'sand'`}),Ke=Ge.and({type:`'module_loaded'`,content:{gameVersion:`string`,processHash:`string`}}),qe=Ge.and({type:`'module_unloaded'`}),Je=Ge.and({type:`'unsupported_game_version'`,content:{gameVersion:`string`,processHash:`string`}}),Ye=t({"#event1":`logged_in | module_loaded | module_unloaded | unsupported_game_version`,event:`event1`,logged_in:We,module_loaded:Ke,module_unloaded:qe,unsupported_game_version:Je}).export(),Xe=Object.keys(Ye).filter(e=>e!==`event`);function z(){return{key:`universal`,events:Ye}}var Ze=class{options=null;logger;initialized=!1;constructor(e){this.logger=L.getInstance().scope(e)}init(e){this.logger.log(`Initializing`),this.options=e||null,this.initialized=!0}destroy(){this.logger.log(`Destroying`),this.initialized=!1}},B=class extends A{options=null;logger;initialized=!1;constructor(e){super(),this.logger=L.getInstance().scope(e)}init(e){this.logger.log(`Initializing`),this.options=e||null,this.initialized=!0}destroy(){this.logger.log(`Destroying`),this.initialized=!1,this.removeAllListeners()}},Qe=class extends j{options=null;logger;initialized=!1;constructor(e){super(),this.logger=L.getInstance().scope(e)}init(e){this.logger.log(`Initializing`),this.options=e||null,this.initialized=!0}destroy(){this.logger.log(`Destroying`),this.initialized=!1,this.removeAllListeners()}};const $e=`https://api.overlayed.gg`,V=re.create({baseURL:$e,paramsSerializer:e=>ie(e,!0,null,{arrayFormat:`repeat`}),headers:{Accept:`application/json`,"Accept-Encoding":`gzip, deflate, br`}});let et;function tt(e){et=e}let nt;function rt(e){nt=e}function it(e){return`overlayed/app (${Object.entries(e).map(([e,t])=>`${e}=${t}`).join(`, `)})`}V.interceptors.request.use(e=>{let t=et?.();e.headers??={},t&&(e.headers[`X-Api-Key`]=t);let n=nt?.();return n&&(e.headers[`User-Agent`]=it(n)),e});function at(e,t){if(t<=0)throw Error(`Chunk size must be greater than 0`);if(e.length===0)return[];let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function ot(e){return e}function H(e){return e?t=>(e(t),t):ot}const st=H();function ct(e){return V.get(`/v1/public/applications/${e}`)}function lt(e,t){return V.get(`/v1/public/applications/${e}/releases/check`,{params:t})}function U(e,t){return V.post(`/v1/public/applications/${e}/game-crash-reports`,t)}function ut(e,t,n){return V.post(`/v1/public/applications/${e}/game-crash-reports/${t}/confirm`,n)}function dt(e,t){let n=new FormData;return n.append(`file`,new Blob([t.file],{type:`application/zip`}),`logs.zip`),n.append(`data`,JSON.stringify(t.data)),V.post(`/v1/public/applications/${e}/feedbacks`,n)}function ft(e,t){return V.get(`/v1/public/applications/${e}/feature-flags`,{params:t})}function pt(e,t){return V.get(`/v1/public/applications/${e}/notices`,{params:t})}const mt=H();function ht(e,t){return V.get(`/v1/public/modules/${e}/release`,{params:{cortex_user_id:t}})}function gt(e,t,n){return V.post(`/v1/public/modules/${e}/releases/${t}/download`,n)}async function _t(e,t){if(e.method!==`GET`)throw Error(`Unsupported presigned request method: ${e.method}`);let n=await fetch(e.url,{method:e.method,headers:e.headers,signal:t?.signal});if(!n.ok){let e=await yt(n);throw Error(`Presigned download failed (${n.status} ${n.statusText})${e?`: ${e}`:``}`)}let r=await n.arrayBuffer();return new Uint8Array(r)}async function vt(e,t){if(e.method!==`PUT`)throw Error(`Unsupported presigned request method: ${e.method}`);let n=await fetch(e.url,{method:e.method,headers:{...e.headers,"Content-Length":t.byteLength.toString()},body:t});if(!n.ok){let e=await yt(n);throw Error(`Presigned upload failed (${n.status} ${n.statusText})${e?`: ${e}`:``}`)}}async function yt(e){try{let t=(await e.text()).trim();if(t.length===0)return;let n=2048;return t.length>n?`${t.slice(0,n)}…`:t}catch{return}}function bt(){return V.get(`/v1/public/raven/config`)}const xt=H();function St(e,t){return V.get(`/v1/public/raven/games/${e}/builds/${t}`)}function Ct(e,t){return V.post(`/v1/public/raven/games/${e}/builds/upload`,null,{params:t})}function wt(e,t){let{chunk:n,...r}=t,i=new FormData;return i.append(`file`,n),V.patch(`/v1/public/raven/games/${e}/builds/upload`,i,{params:r})}function Tt(e){let t=Date.now(),n=e.messages.filter(e=>t-e.created_at.getTime()<6e5),r=e.messages.length-n.length;r>0&&console.warn(`Dropped ${r} cortex event(s) older than 600s`);let i=at(n.map(e=>Et(t,e)),50),a=Promise.all(i.map(async t=>V.post(`/v1/public/cortex/events`,{...e,messages:t})));return a.catch(e=>{let t=e?.response?.data||e?.message||e;console.error(`Failed to submit cortex events`,t)}),a}function Et(e,t){let n=e-t.created_at.getTime(),r=Math.max(0,Math.floor(n/1e3));return{properties:t.properties,type:t.type,seconds_offset:r}}function Dt(e){return e instanceof Error&&(e.name===`XiorError`||e.name===`XiorTimeoutError`)}function Ot(e){return!!(e&&`kind`in e.data&&`message`in e.data)}const{PipeEventServer:kt,PipeEventClient:At,PipeEventBase:W,GameMonitor:jt,GameInstance:Mt,HardwareInterface:Nt}=e(import.meta.url)(`@overlayed/app/dist/native-interface/build/overlayed_native_interface_x64.node`);function Pt(e=[]){return h.normalize(h.join(we(global.OVERLAYED.APPLICATION_ID),...e))}const Ft=n({game:`string`,type:`string`,creationTime:`number`}),G=new ve({path:P(),schema:n({userId:`string | undefined`,sessionId:`string | undefined`,sessionLastUsed:`number | undefined`,accessToken:`string | undefined`,accessTokenChannel:`string | undefined`,"debug?":{"ri_disabled?":`boolean`,"gm_disabled?":`boolean`}}),default:{userId:void 0,sessionId:void 0,sessionLastUsed:void 0,accessToken:void 0,accessTokenChannel:void 0}});function It(){let{debug:e}=G.get();return e?{ri_disabled:e.ri_disabled??!1,gm_disabled:e.gm_disabled??!1}:{ri_disabled:!1,gm_disabled:!1}}function Lt(){let e=G.get().userId;if(e)return e;let t=Ht();return G.set({...G.get(),userId:t}),t}function Rt(){let e=G.get();if(e.sessionId&&typeof e.sessionLastUsed==`number`&&Date.now()-e.sessionLastUsed<=3e5)return e.sessionId;let t=crypto.randomUUID();return G.set({...e,sessionId:t,sessionLastUsed:Date.now()}),t}function zt(){try{let e=G.get();G.set({...e,sessionLastUsed:Date.now()})}catch(e){L.getInstance().log(`Failed to update sessionLastUsed`,e)}}function K(){return G.get().accessToken}function Bt(){return G.get().accessTokenChannel}function Vt(e,t){try{let n=G.get();G.set({...n,accessToken:e??void 0,accessTokenChannel:e?t:void 0})}catch(e){L.getInstance().log(`Failed to set accessToken`,e)}}function Ht(){try{return Nt.generateUniqueIdentifier()}catch{return crypto.randomUUID()}}function Ut(e,...t){let n=h.join(e,...t);if(!h.resolve(n).startsWith(h.resolve(e)+h.sep))throw Error(`Path escapes ${e}: ${n}`);return n}const Wt=M(class extends B{UPDATE_CHECK_INTERVAL_MS=3e5;targetDir;updateInterval;constructor(){super(`NativeModuleManager`),this.targetDir=h.join(Se(),`resources`),this.logger.log(`Target directory`,this.targetDir)}async initWithDlls(e){super.init(),await D.mkdir(this.targetDir,{recursive:!0}),await this.checkForUpdates(e),clearInterval(this.updateInterval),this.updateInterval=setInterval(()=>this.checkForUpdates(e),this.UPDATE_CHECK_INTERVAL_MS)}destroy(){this.updateInterval&&=(clearInterval(this.updateInterval),void 0),super.destroy()}async getDllFile(e){if(!he(e)){this.logger.error(`Invalid module id`,{moduleId:e});return}let t=await this.getCurrentBuildInfo(e);if(!t){this.logger.error(`No build found for module`,{moduleId:e});return}let n=this.getBuildPath(e,t.buildId);if(!S(n)){this.logger.error(`No build file found for module`,{moduleId:e});return}let r=this.getBuildFilePath(e,t.buildId,t.buildFileName);if(!S(r))this.logger.error(`No DLL file found for module`,{moduleId:e});else return r}async getCurrentBuildInfo(e){try{let t=this.resolvePath(e,`build.json`),n=await D.readFile(t,`utf-8`),r=JSON.parse(n);return!he(r.buildId)||!this.isDllFileName(r.buildFileName)?(this.logger.error(`Ignoring invalid build info for module`,{moduleId:e,buildInfo:r}),null):r}catch{return null}}getModulePath(e){return this.resolvePath(e)}getBuildPath(e,t){return this.resolvePath(e,t)}resolvePath(...e){return Ut(this.targetDir,...e)}getBuildFilePath(e,t,n){return this.resolvePath(e,t,n)}isDllFileName(e){return typeof e==`string`&&!/[\\/:*?"<>|\x00-\x1f]/.test(e)&&e!==`.`&&e!==`..`&&e.toLowerCase().endsWith(`.dll`)}findHashMismatch(e,t){let n=T(`sha256`).update(e).digest(`hex`);return n===t.toLowerCase()?void 0:n}async checkForUpdates(e){this.logger.log(`Checking for updates`);let t=Lt();if(!t)this.logger.error(`Failed to resolve cortex user id`);else{this.logger.log(`Cortex User ID`,t);for(let n of e)if(!he(n))this.logger.error(`Skipping module with invalid id`,{moduleId:n});else try{let{data:e}=await ht(n,t);if(this.logger.log(`Release`,e),!he(e.build_id)||!this.isDllFileName(e.build_file_name)){this.logger.error(`${n} > Release has an invalid build id or file name`,{buildId:e.build_id,buildFileName:e.build_file_name});continue}let r=(await this.getCurrentBuildInfo(n))?.buildId||null;if(this.logger.log(`${n} > Performing update check. current: ${r}, requested: ${e.build_id}`),e.build_id!==r||await this.isDownloadCorrupted(n,e)){if(this.logger.log(`${n} > Update found. current: ${r}, requested: ${e.build_id}`),this.logger.log(`${n} > Downloading and extracting DLLs`),!await this.downloadAndExtractDll(n,e)){this.logger.error(`${n} > Download failed, keeping existing builds`);continue}this.logger.log(`${n} > Cleaning up other builds`),await this.cleanupExistingBuilds(n,e.build_id),this.emit(`dllUpdated`,{moduleId:n,buildId:e.build_id,releaseId:e.release_id})}else this.logger.log(`${n} > No update found`)}catch(e){this.logger.error(`${n} > Error checking/updating`,e)}}}async downloadAndExtractDll(e,t){this.logger.log(`${e} > Requesting download for build ${t.build_id}`);let n=Lt();if(!n)return this.logger.error(`Failed to resolve cortex user id`),!1;let{data:r}=await gt(e,t.release_id,{download_token:t.download_token,cortex_user_id:n});this.logger.log(`${e} > Downloading DLLs for build ${t.build_id}`);let i=await _t(r,{signal:AbortSignal.timeout(3e5)});this.logger.log(`${e} > Downloaded zip file for build ${t.build_id}`);let a=new ae;await a.loadAsync(i);let o=Object.keys(a.files).map(e=>({name:e,file:a.files[e]})).filter(({file:e})=>!e.dir);if(o.length!==1)return this.logger.error(`${e} > Zip must contain exactly 1 file, got ${o.length}`),!1;let s=o[0];if(h.basename(s.name).toLowerCase()!==t.build_file_name.toLowerCase())return this.logger.error(`${e} > Zip entry ${s.name} does not match build file ${t.build_file_name}`),!1;let c=await s.file.async(`nodebuffer`),l=t.build_hash&&this.findHashMismatch(c,t.build_hash);if(l)return this.logger.error(`${e} > Build file hash mismatch: ${l} !== ${t.build_hash}`),!1;let u=this.getBuildFilePath(e,t.build_id,t.build_file_name);await D.mkdir(h.dirname(u),{recursive:!0}),await D.writeFile(u,c),this.logger.log(`${e} > Extracted 1 file to ${u}`);let d={buildId:t.build_id,buildFileName:t.build_file_name},f=this.resolvePath(e,`build.json`);return await D.writeFile(f,JSON.stringify(d),`utf-8`),this.logger.log(`${e} > Saved buildId to file: ${t.build_id}`),!0}async cleanupExistingBuilds(e,t){let n=this.getModulePath(e),r=this.getBuildPath(e,t),i=await D.readdir(n,{withFileTypes:!0});for(let t of i){let n=this.resolvePath(e,t.name);t.isDirectory()&&n!==r&&(await D.rm(n,{recursive:!0,force:!0}),this.logger.log(`${e} > Cleaned up build: ${t.name}`))}}async hasPathAccess(e){try{return await D.access(e,D.constants.F_OK),!0}catch{return!1}}async isDownloadCorrupted(e,t){let n=this.getBuildPath(e,t.build_id);if(!await this.hasPathAccess(n))return this.logger.error(`Download is corrupted. Path does not exist: ${n}`),!0;let r=t.build_file_name,i=this.getBuildFilePath(e,t.build_id,r);if(!S(i))return this.logger.error(`Download is corrupted. Build file not found: ${i}`),!0;if(t.build_hash){let e=this.findHashMismatch(await D.readFile(i),t.build_hash);if(e)return this.logger.error(`Download is corrupted. Build file hash mismatch: ${r} ${e} !== ${t.build_hash}`),!0}return!1}}),Gt=M(class extends B{_gameMonitor;_games=/* @__PURE__ */ new Map;constructor(){super(`GameManager`),this._gameMonitor=new jt}get hasAnyActiveGames(){return this._games.size>0}init(){super.init(),this._gameMonitor.on(`launch`,e=>{this.logger.log(`Game launched`,e.identifier,e.processId),this._games.set(e.processId,e),this.logger.log(`Active Game Count: ${this._games.size}`),this.emit(`launch`,{game:e})}),this._gameMonitor.on(`close`,e=>{this.logger.log(`Game closed`,e.identifier,e.processId),this._games.delete(e.processId),this.logger.log(`Active Game Count: ${this._games.size}`),this.emit(`close`,{game:e})})}destroy(){this._games.clear(),this._gameMonitor.removeAllListeners(),super.destroy()}}),Kt=M(class extends B{REFETCH_INTERVAL=3e5;FAILED_REFETCH_INTERVAL=3e4;_refetchIntervalHandler=null;_failedRefetchTimeoutHandler=null;_ready;_resolveReady;constructor(){super(`RavenManager`),this._ready=new Promise(e=>{this._resolveReady=e})}get ready(){return this._ready}init(e){super.init(e),this.fetchRavenConfig(),this._refetchIntervalHandler=setInterval(()=>{this._failedRefetchTimeoutHandler&&=(clearTimeout(this._failedRefetchTimeoutHandler),null),this.fetchRavenConfig()},this.REFETCH_INTERVAL)}destroy(){this._refetchIntervalHandler&&clearInterval(this._refetchIntervalHandler),this._failedRefetchTimeoutHandler&&clearTimeout(this._failedRefetchTimeoutHandler),Wt.getInstance().destroy(),super.destroy()}async fetchRavenConfig(){try{let e=await bt();if(!this.initialized)return;let t=new Set(this.options?.subscribedGames??[]),n=/* @__PURE__ */ new Set;for(let r of e.data.games)(t.has(`*`)||t.has(r.identifier))&&r.game_module&&n.add(r.game_module);n.size===0&&e.data.games.length>0&&this.logger.warn(`No raven game matched the subscribed games`,{subscribed:Array.from(t),available:e.data.games.map(e=>e.identifier)}),await Wt.getInstance().initWithDlls(Array.from(n)),this.logger.log(`Raven updated, tracking ${n.size} game modules`),this._resolveReady()}catch(e){this.logger.error(`Failed to fetch Raven config`,e),this._failedRefetchTimeoutHandler=setTimeout(()=>this.fetchRavenConfig(),this.FAILED_REFETCH_INTERVAL)}}});var qt=class{_instance;_resolution;boundOnResolutionChanged=this.onResolutionChanged.bind(this);constructor(e){this._instance=e,this._resolution={width:0,height:0},this._instance.on(`resolution`,this.boundOnResolutionChanged)}destroy(){this._instance.off(`resolution`,this.boundOnResolutionChanged)}get instance(){return this._instance}get resolution(){return this._resolution}onResolutionChanged(e,t){this._resolution={width:e,height:t}}};const Jt=M(class{interfaces={};constructor(){}createInterface(e){return this.interfaces[e]||(this.interfaces[e]=new qt(new ze(e,{access:1}))),this.interfaces[e]}getInterface(e){return this.interfaces[e]?this.interfaces[e]:this.createInterface(e)}}),q=M(class{options;eventQueue;meta=null;enabled=!0;constructor(e){this.options=this.resolveOptions(e),this.eventQueue=new ge,this.setupFlushInterval()}track(e,t){this.enabled&&this.eventQueue.add({type:e,properties:t,created_at:/* @__PURE__ */ new Date})}flush(){if(!this.enabled)return[];let e=Array.from(this.eventQueue.flush()).concat({type:`ping`,properties:{},created_at:/* @__PURE__ */ new Date});if(!this.meta)throw Error(`Tried to flush Cortex events before meta was set`);try{Tt({...this.meta,messages:e})}catch{}return e}setupFlushInterval(){this.enabled&&setInterval(()=>{this.flush()},this.options.batchIntervalSeconds*1e3)}resolveOptions(e){return{batchIntervalSeconds:e?.batchIntervalSeconds??15}}}),Yt=e(import.meta.url),Xt=Yt.resolve(`@overlayed/app/dist/render-interface/build/overlayed_render_hook_x64.dll`),Zt=Yt.resolve(`@overlayed/app/dist/render-interface/build/overlayed_render_hook_x86.dll`),Qt=Yt.resolve(`@overlayed/app/dist/native-interface/build/overlayed_injector_x64.exe`),$t=Yt.resolve(`@overlayed/app/dist/native-interface/build/overlayed_injector_x86.exe`),J=M(class extends Qe{boundOnGameLaunch=this.onGameLaunch.bind(this);boundOnGameClose=this.onGameClose.bind(this);subscribedGames=/* @__PURE__ */ new Set;activeGames=/* @__PURE__ */ new Map;pendingLaunches=/* @__PURE__ */ new Map;sessions=/* @__PURE__ */ new Map;get isInGame(){return this.activeGames.size>0}constructor(){super(`GameLaunchManager`)}setSubscribedGames(e){this.subscribedGames=new Set(e)}getActiveGames(){return Array.from(new Set(Array.from(this.activeGames.values()).map(e=>e.game)))}init(){super.init(),Jt.getInstance().createInterface(`OGG_SIEGE`),Gt.getInstance().on(`launch`,this.boundOnGameLaunch),Gt.getInstance().on(`close`,this.boundOnGameClose)}endActiveSessions(){for(let e of this.sessions.values())this.trackSessionEnd(e,`app_quit`);this.sessions.clear()}destroy(){this.endActiveSessions(),Gt.getInstance().off(`launch`,this.boundOnGameLaunch),Gt.getInstance().off(`close`,this.boundOnGameClose),super.destroy()}on(e,t){super.on(e,t);let n=me(e);if(!(n.includes(`gameReady`)||n.includes(`*`))||this.activeGames.size===0)return;let r=t;for(let e of this.activeGames.values())this.logger.log(`Late calling gameReady callback for game`,e.game),r(e)}async onGameLaunch({game:e}){this.logger.log(`On game launch`,e.identifier,e.executableName,e.processId);let t=xt(e.identifier);q.getInstance().track(`game_launch`,{game:t});let n={id:crypto.randomUUID(),game:t,startedAt:performance.now(),subscribed:!1,ready:!1,renderSupported:!1};if(this.sessions.set(e.processId,n),this.subscribedGames.size===0){this.logger.warn(`No subscribed games, skipping`);return}if(!this.subscribedGames.has(t)&&!this.subscribedGames.has(`*`))return;n.subscribed=!0;let r=new AbortController;if(this.pendingLaunches.set(e.processId,r),await this.emit(`gameLaunch`,{game:t,processId:e.processId,reject:()=>r.abort()}),r.signal.aborted)return;if(this.logger.log(`Game Launched`,e.identifier),this.logger.log(`Game is elevated: `,e.isElevated),e.hasElevationMismatch){_e.getInstance().fatal(`Game is elevated but the App is not`,`ELEVATION_MISMATCH`,{appElevated:!1,gameElevated:!0}),this.logger.log(`Game elevated but App is not`);return}if(e.injectionDelayMs>0){if(this.logger.log(`Delaying injection for ${e.injectionDelayMs}ms to allow game to be ready`),await new Promise(t=>{let n=setTimeout(t,e.injectionDelayMs);r.signal.addEventListener(`abort`,()=>{clearTimeout(n),t()},{once:!0})}),r.signal.aborted){this.logger.log(`Game closed during the injection delay, skipping injection`);return}this.logger.log(`Finished delay`)}let{ri_disabled:i,gm_disabled:a}=It(),o=!1;if(!i&&e.hasRenderSupport&&e.allowDllInjections?o=await this.injectRenderInterface(e):this.logger.log(`Skipping render interface injection`,{has_render_support:e.hasRenderSupport,allow_dll_injections:e.allowDllInjections,ri_disabled:i}),!a&&e.allowDllInjections?await this.injectGameModules(e):this.logger.log(`Skipping game module(s) injection`,{allow_dll_injections:e.allowDllInjections,gm_disabled:a}),r.signal.aborted){this.logger.log(`Game closed during injection, skipping ready`);return}this.pendingLaunches.delete(e.processId);let s={game:t,processId:e.processId,inGameRenderingSupported:o};this.activeGames.set(e.processId,s),this.logger.debug(`Active games`,this.getActiveGames().join(`, `)),n.ready=!0,n.renderSupported=o,n.readyAt=performance.now(),this.logger.log(`Game Ready`),this.emit(`gameReadyInternal`,{game:e}),this.emit(`gameReady`,s),q.getInstance().track(`game_ready`,{game:t})}trackSessionEnd(e,t){q.getInstance().track(`game_session_end`,{game:e.game,game_session_id:e.id,duration_ms:Math.round(performance.now()-e.startedAt),subscribed:e.subscribed,ready:e.ready,render_supported:e.renderSupported,...e.readyAt!==void 0&&{time_to_ready_ms:Math.round(e.readyAt-e.startedAt)},end_reason:t})}copyInjectors(){let e=this.copyDll(Qt),t=this.copyDll($t);return!e||!t?(this.logger.error(`Failed to copy injector executables`),!1):h.dirname(e)}copyDll(e){let t=h.basename(e),n=_(e),r=h.join(Se(),`resources`),i=h.join(r,t);this.logger.info(`Copying`,n,`to`,i);try{S(r)||C(r,{recursive:!0}),b(n,i)}catch(e){return e.code===`EBUSY`?i:(this.logger.error(`Failed to copy`,e),this.logger.error(`Failed to copy`,{originalPath:n,targetPath:i}),!1)}return i}async injectRenderInterface(e){this.logger.log(`Injecting render interface`,{is32Bit:e.is32Bit,game:e.identifier});let t=e.is32Bit?Zt:Xt;this.logger.log(`Render hook path`,t);let n=this.copyDll(t);if(!n)return this.logger.error(`Failed to copy render hook DLL`,{renderHookPath:t}),!1;let r=this.copyInjectors();if(!r)return!1;this.logger.log(`Resolved injector path`,r);try{return this.logger.log(`Injecting render interface`,n),await e.injectDll(n,r),this.logger.log(`Render Interface Injection Successful`,n),!0}catch(e){return this.logger.error(`Render Interface Injection Failed`,e),this.logger.error(`Render Interface Injection Failed`,{renderHookPathCopied:n}),!1}}async injectGameModules(e){let t=this.copyInjectors();if(t){this.logger.log(`Resolved injector path`,t),await Kt.getInstance().ready;for(let n of e.modules){let r=await Wt.getInstance().getDllFile(n);if(!r)this.logger.error(`No DLL file found for module`,{moduleId:n});else try{this.logger.log(`Injecting game module`,r),await e.injectDll(r,t),this.logger.log(`Injection Successful`,r)}catch(e){this.logger.error(`Injection Failed`,{dllFile:r},e)}}}}async onGameClose({game:e}){let t=xt(e.identifier);this.pendingLaunches.get(e.processId)?.abort(),this.pendingLaunches.delete(e.processId),this.activeGames.delete(e.processId),this.logger.debug(`Active games`,this.getActiveGames().join(`, `));let n=this.sessions.get(e.processId);n&&(this.sessions.delete(e.processId),this.trackSessionEnd(n,`game_closed`)),this.emit(`gameCloseInternal`,{game:e}),this.emit(`gameClose`,{game:t,processId:e.processId}),q.getInstance().track(`game_close`,{game:t})}}),en=M(class extends Ze{boundOnGameLaunch=this.onGameLaunch.bind(this);boundOnGameClose=this.onGameClose.bind(this);pendingBuilds=/* @__PURE__ */ new Map;constructor(){super(`GameBuildManager`)}init(){super.init(),J.getInstance().on(`gameReadyInternal`,this.boundOnGameLaunch),J.getInstance().on(`gameCloseInternal`,this.boundOnGameClose)}destroy(){J.getInstance().off(`gameReadyInternal`,this.boundOnGameLaunch),J.getInstance().off(`gameCloseInternal`,this.boundOnGameClose),super.destroy()}onGameClose(...e){let[{game:t}]=e;this.pendingBuilds.get(t.processId)?.abort(),this.pendingBuilds.delete(t.processId)}async onGameLaunch(...e){let[{game:t}]=e;if(!t.executablePath||!t.executableName){this.logger.error(`Executable path or name not found, could not check for build hash`,void 0,t.identifier);return}let n=xt(t.identifier),r=new AbortController;this.pendingBuilds.set(t.processId,r);try{await this.checkBuild(t.executablePath,t.executableName,t,n,r.signal)}finally{this.pendingBuilds.delete(t.processId)}}async checkBuild(e,t,n,r,i){let a;try{a=await n.computeBuildHash()}catch(e){this.logger.error(`Error hashing the game build`,e);return}if(i.aborted){this.logger.log(`Game closed while hashing the build, skipping the upload`);return}this.logger.log(`Executable Path`,e),this.logger.log(`Executable Name`,t),this.logger.log(`Build Hash`,a);let o=!1;try{o=(await St(r,a)).data.upload}catch(e){this.logger.error(`Error checking game build hash`,e);return}if(!o){this.logger.log(`Build hash already exists, skipping upload`);return}if(i.aborted){this.logger.log(`Game closed before the build was read, skipping the upload`);return}let s=new ae;s.file(t,await ne(e));let c=await s.generateAsync({type:`blob`});try{this.logger.log(`Uploading build (size: `,c.size,` bytes)`);let e=new R(c,{chunkSizeMb:25,maxConcurrent:1}),t=await Ct(r,{build_hash:a,chunk_count:e.totalChunks,file_size_bytes:c.size});await e.chunk(async(e,n)=>{this.logger.log(`Uploading chunk`,n),await wt(r,{chunk:e,build_hash:a,chunk_index:n,upload_token:t.data.upload_token})}),this.logger.log(`Build uploaded successfully`)}catch(e){Dt(e)?Ot(e.response)?this.logger.error(`Error uploading build hash, api error`,e):this.logger.error(`Error uploading build hash, request error`,e):this.logger.error(`Error uploading build hash, unknown error`,e)}}}),tn=M(class extends Ze{constructor(){super(`CampaignManager`)}async check(e){let t=h.join(we(e),`campaign_code.txt`);try{let e=(await E.readFile(t,`utf-8`)).trim().replace(/ \(\d+\)/g,``);e&&(this.logger.log(`UTM campaign code found`,e),q.getInstance().track(`utm_attribution`,{campaign_code:e}),q.getInstance().flush())}catch{}}}),nn=[`lcp`,`inp`,`fcp`,`ttfb`];function rn({protocol:e,pathname:t,hash:n}){let r=e===`file:`?t.slice(t.lastIndexOf(`/`)):t;if(n.startsWith(`#/`)){let e=n.indexOf(`?`);r+=e===-1?n:n.slice(0,e)}return r.slice(0,512)}const an={reason:128,processType:128,processName:256,game:128,errorName:256,message:512,stack:4096},on=[/[A-Za-z]:[\\/]+Users[\\/]+[^\\/\r\n"'`)]+/gi,/\/(?:Users|home)\/[^/\s"'`)]+/g];function sn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function cn(e,t){let n=e,r=te.homedir();if(r){let e=sn(r).replace(/\\\\|\//g,`[\\\\/]`);n=n.replace(new RegExp(e,`gi`),`~`)}for(let e of on)n=n.replace(e,`~`);return n.slice(0,t)}function ln(e){return e.replace(/:\d+(?::\d+)?(?=\)?$)/,``).replace(/(?:file:\/\/\/?)?[^\s()]*[\\/]/g,``).trim()}function un(e,t,n){let r=(n??``).split(`
|
|
15
|
+
`;case 114:return`\r`;case 120:return String.fromCharCode(this.readHexChar(2));case 117:return O(this.readCodePoint());case 116:return` `;case 98:return`\b`;case 118:return`\v`;case 102:return`\f`;case 13:this.input.charCodeAt(this.pos)===10&&++this.pos;case 10:return this.options.locations&&(this.lineStart=this.pos,++this.curLine),``;case 56:case 57:if(this.strict&&this.invalidStringToken(this.pos-1,`Invalid escape sequence`),e){var n=this.pos-1;this.invalidStringToken(n,`Invalid escape sequence in template string`)}default:if(t>=48&&t<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],i=parseInt(r,8);return i>255&&(r=r.slice(0,-1),i=parseInt(r,8)),this.pos+=r.length-1,t=this.input.charCodeAt(this.pos),r===`0`&&t!==56&&t!==57||!this.strict&&!e||this.invalidStringToken(this.pos-1-r.length,e?`Octal literal in template string`:`Octal literal in strict mode`),String.fromCharCode(i)}return C(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),``):String.fromCharCode(t)}},H.readHexChar=function(e){var t=this.pos,n=this.readInt(16,e);return n===null&&this.invalidStringToken(t,`Bad character escape sequence`),n},H.readWord1=function(){this.containsEsc=!1;for(var e=``,t=!0,n=this.pos,r=this.options.ecmaVersion>=6;this.pos<this.input.length;){var i=this.fullCharCodeAtPos();if(m(i,r))this.pos+=i<=65535?1:2;else{if(i!==92)break;this.containsEsc=!0,e+=this.input.slice(n,this.pos);var a=this.pos;this.input.charCodeAt(++this.pos)!==117&&this.invalidStringToken(this.pos,`Expecting Unicode escape sequence \\uXXXX`),++this.pos;var o=this.readCodePoint();(t?p:m)(o,r)||this.invalidStringToken(a,`Invalid Unicode escape`),e+=O(o),n=this.pos}t=!1}return e+this.input.slice(n,this.pos)},H.readWord=function(){var e=this.readWord1(),t=b.name;return this.keywords.test(e)&&(t=ee[e]),this.finishToken(t,e)},A.acorn={Parser:A,version:`8.16.0`,defaultOptions:de,Position:ce,SourceLocation:le,getLineInfo:ue,Node:Me,TokenType:h,tokTypes:b,keywordTypes:ee,TokContext:F,tokContexts:I,isIdentifierChar:m,isIdentifierStart:p,Token:ot,isNewLine:C,lineBreak:x,lineBreakG:S,nonASCIIwhitespace:te};var lt=r(`node:module`),U=r(`node:fs`);String.fromCharCode;let ut=/\/$|\/\?|\/#/,dt=/^\.?\//;function ft(e=``,t){return t?ut.test(e):e.endsWith(`/`)}function pt(e=``,t){if(!t)return e.endsWith(`/`)?e:e+`/`;if(ft(e,!0))return e||`/`;let n=e,r=``,i=e.indexOf(`#`);if(i!==-1&&(n=e.slice(0,i),r=e.slice(i),!n))return r;let[a,...o]=n.split(`?`);return a+`/`+(o.length>0?`?${o.join(`?`)}`:``)+r}function mt(e){return e&&e!==`/`}function ht(e,...t){let n=e||``;for(let e of t.filter(e=>mt(e)))if(n){let t=e.replace(dt,``);n=pt(n)+t}else n=e;return n}let gt=/^[A-Za-z]:\//;function _t(e=``){return e&&e.replace(/\\/g,`/`).replace(gt,e=>e.toUpperCase())}let vt=/^[/\\]{2}/,yt=/^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/,bt=/^[A-Za-z]:$/,xt=/.(\.[^./]+|\.)$/,St=function(e){if(e.length===0)return`.`;let t=(e=_t(e)).match(vt),n=Dt(e),r=e[e.length-1]===`/`;return(e=Et(e,!n)).length===0?n?`/`:r?`./`:`.`:(r&&(e+=`/`),bt.test(e)&&(e+=`/`),t?n?`//${e}`:`//./${e}`:n&&!Dt(e)?`/${e}`:e)},Ct=function(...e){let t=``;for(let n of e)if(n){if(t.length>0){let e=t[t.length-1]===`/`,r=n[0]===`/`;t+=e&&r?n.slice(1):e||r?n:`/${n}`}else t+=n}return St(t)};function wt(){return typeof process<`u`&&typeof process.cwd==`function`?process.cwd().replace(/\\/g,`/`):`/`}let Tt=function(...e){let t=``,n=!1;for(let r=(e=e.map(e=>_t(e))).length-1;r>=-1&&!n;r--){let i=r>=0?e[r]:wt();i&&i.length!==0&&(t=`${i}/${t}`,n=Dt(i))}return t=Et(t,!n),n&&!Dt(t)?`/${t}`:t.length>0?t:`.`};function Et(e,t){let n=``,r=0,i=-1,a=0,o=null;for(let s=0;s<=e.length;++s){if(s<e.length)o=e[s];else{if(o===`/`)break;o=`/`}if(o===`/`){if(i!==s-1&&a!==1){if(a===2){if(n.length<2||r!==2||n[n.length-1]!==`.`||n[n.length-2]!==`.`){if(n.length>2){let e=n.lastIndexOf(`/`);e===-1?(n=``,r=0):(n=n.slice(0,e),r=n.length-1-n.lastIndexOf(`/`)),i=s,a=0;continue}if(n.length>0){n=``,r=0,i=s,a=0;continue}}t&&(n+=n.length>0?`/..`:`..`,r=2)}else n.length>0?n+=`/${e.slice(i+1,s)}`:n=e.slice(i+1,s),r=s-i-1}i=s,a=0}else o===`.`&&a!==-1?++a:a=-1}return n}let Dt=function(e){return yt.test(e)},Ot=function(e){if(e===`..`)return``;let t=xt.exec(_t(e));return t&&t[1]||``},kt=function(e){let t=_t(e).replace(/\/$/,``).split(`/`).slice(0,-1);return t.length===1&&bt.test(t[0])&&(t[0]+=`/`),t.join(`/`)||(Dt(e)?`/`:`.`)},At=function(e,t){let n=_t(e).split(`/`),r=``;for(let e=n.length-1;e>=0;e--){let t=n[e];if(t){r=t;break}}return t&&r.endsWith(t)?r.slice(0,-t.length):r},W=k(`node:url`),jt=k(`node:assert`),Mt=k(`node:process`);var Nt=r(`node:path`);let Pt=k(`node:v8`),Ft=k(`node:util`),G=new Set(lt.builtinModules);function It(e){return e.replace(/\\/g,`/`)}let Lt={}.hasOwnProperty,Rt=/^([A-Z][a-z\d]*)+$/,zt=/* @__PURE__ */ new Set([`string`,`function`,`number`,`object`,`Function`,`Object`,`boolean`,`bigint`,`symbol`]),K={};function Bt(e,t=`and`){return e.length<3?e.join(` ${t} `):`${e.slice(0,-1).join(`, `)}, ${t} ${e[e.length-1]}`}let Vt=/* @__PURE__ */ new Map,Ht;function Ut(e,t,n){return Vt.set(e,t),function(e,t){return n;function n(...n){let r=Error.stackTraceLimit;Wt()&&(Error.stackTraceLimit=0);let i=new e;Wt()&&(Error.stackTraceLimit=r);let a=function(e,t,n){let r=Vt.get(e);if(jt.ok(r!==void 0,"expected `message` to be found"),typeof r==`function`)return jt.ok(r.length<=t.length,`Code: ${e}; The provided arguments length (${t.length}) does not match the required ones (${r.length}).`),Reflect.apply(r,n,t);let i=/%[dfijoOs]/g,a=0;for(;i.exec(r)!==null;)a++;return jt.ok(a===t.length,`Code: ${e}; The provided arguments length (${t.length}) does not match the required ones (${a}).`),t.length===0?r:(t.unshift(r),Reflect.apply(Ft.format,null,t))}(t,n,i);return Object.defineProperties(i,{message:{value:a,enumerable:!1,writable:!0,configurable:!0},toString:{value(){return`${this.name} [${t}]: ${this.message}`},enumerable:!1,writable:!0,configurable:!0}}),Gt(i),i.code=t,i}}(n,e)}function Wt(){try{if(Pt.startupSnapshot.isBuildingSnapshot())return!1}catch{}let e=Object.getOwnPropertyDescriptor(Error,`stackTraceLimit`);return e===void 0?Object.isExtensible(Error):Lt.call(e,`writable`)&&e.writable!==void 0?e.writable:e.set!==void 0}K.ERR_INVALID_ARG_TYPE=Ut(`ERR_INVALID_ARG_TYPE`,(e,t,n)=>{jt.ok(typeof e==`string`,`'name' must be a string`),Array.isArray(t)||(t=[t]);let r=`The `;if(e.endsWith(` argument`))r+=`${e} `;else{let t=e.includes(`.`)?`property`:`argument`;r+=`"${e}" ${t} `}r+=`must be `;let i=[],a=[],o=[];for(let e of t)jt.ok(typeof e==`string`,`All expected entries have to be of type string`),zt.has(e)?i.push(e.toLowerCase()):Rt.exec(e)===null?(jt.ok(e!==`object`,`The value "object" should be written as "Object"`),o.push(e)):a.push(e);if(a.length>0){let e=i.indexOf(`object`);e!==-1&&(i.slice(e,1),a.push(`Object`))}return i.length>0&&(r+=`${i.length>1?`one of type`:`of type`} ${Bt(i,`or`)}`,(a.length>0||o.length>0)&&(r+=` or `)),a.length>0&&(r+=`an instance of ${Bt(a,`or`)}`,o.length>0&&(r+=` or `)),o.length>0&&(o.length>1?r+=`one of ${Bt(o,`or`)}`:(o[0].toLowerCase()!==o[0]&&(r+=`an `),r+=`${o[0]}`)),r+=`. Received ${function(e){if(e==null)return String(e);if(typeof e==`function`&&e.name)return`function ${e.name}`;if(typeof e==`object`)return e.constructor&&e.constructor.name?`an instance of ${e.constructor.name}`:`${(0,Ft.inspect)(e,{depth:-1})}`;let t=(0,Ft.inspect)(e,{colors:!1});return t.length>28&&(t=`${t.slice(0,25)}...`),`type ${typeof e} (${t})`}(n)}`,r},TypeError),K.ERR_INVALID_MODULE_SPECIFIER=Ut(`ERR_INVALID_MODULE_SPECIFIER`,(e,t,n=void 0)=>`Invalid module "${e}" ${t}${n?` imported from ${n}`:``}`,TypeError),K.ERR_INVALID_PACKAGE_CONFIG=Ut(`ERR_INVALID_PACKAGE_CONFIG`,(e,t,n)=>`Invalid package config ${e}${t?` while importing ${t}`:``}${n?`. ${n}`:``}`,Error),K.ERR_INVALID_PACKAGE_TARGET=Ut(`ERR_INVALID_PACKAGE_TARGET`,(e,t,n,r=!1,i=void 0)=>{let a=typeof n==`string`&&!r&&n.length>0&&!n.startsWith(`./`);return t===`.`?(jt.ok(!1===r),`Invalid "exports" main target ${JSON.stringify(n)} defined in the package config ${e}package.json${i?` imported from ${i}`:``}${a?`; targets must start with "./"`:``}`):`Invalid "${r?`imports`:`exports`}" target ${JSON.stringify(n)} defined for '${t}' in the package config ${e}package.json${i?` imported from ${i}`:``}${a?`; targets must start with "./"`:``}`},Error),K.ERR_MODULE_NOT_FOUND=Ut(`ERR_MODULE_NOT_FOUND`,(e,t,n=!1)=>`Cannot find ${n?`module`:`package`} '${e}' imported from ${t}`,Error),K.ERR_NETWORK_IMPORT_DISALLOWED=Ut(`ERR_NETWORK_IMPORT_DISALLOWED`,`import of '%s' by %s is not supported: %s`,Error),K.ERR_PACKAGE_IMPORT_NOT_DEFINED=Ut(`ERR_PACKAGE_IMPORT_NOT_DEFINED`,(e,t,n)=>`Package import specifier "${e}" is not defined${t?` in package ${t}package.json`:``} imported from ${n}`,TypeError),K.ERR_PACKAGE_PATH_NOT_EXPORTED=Ut(`ERR_PACKAGE_PATH_NOT_EXPORTED`,(e,t,n=void 0)=>t===`.`?`No "exports" main defined in ${e}package.json${n?` imported from ${n}`:``}`:`Package subpath '${t}' is not defined by "exports" in ${e}package.json${n?` imported from ${n}`:``}`,Error),K.ERR_UNSUPPORTED_DIR_IMPORT=Ut(`ERR_UNSUPPORTED_DIR_IMPORT`,`Directory import '%s' is not supported resolving ES modules imported from %s`,Error),K.ERR_UNSUPPORTED_RESOLVE_REQUEST=Ut(`ERR_UNSUPPORTED_RESOLVE_REQUEST`,`Failed to resolve module specifier "%s" from "%s": Invalid relative URL or base scheme is not hierarchical.`,TypeError),K.ERR_UNKNOWN_FILE_EXTENSION=Ut(`ERR_UNKNOWN_FILE_EXTENSION`,(e,t)=>`Unknown file extension "${e}" for ${t}`,TypeError),K.ERR_INVALID_ARG_VALUE=Ut(`ERR_INVALID_ARG_VALUE`,(e,t,n=`is invalid`)=>{let r=(0,Ft.inspect)(t);return r.length>128&&(r=`${r.slice(0,128)}...`),`The ${e.includes(`.`)?`property`:`argument`} '${e}' ${n}. Received ${r}`},TypeError);let Gt=function(e){let t=`__node_internal_`+e.name;return Object.defineProperty(e,"name",{value:t}),e}(function(e){let t=Wt();return t&&(Ht=Error.stackTraceLimit,Error.stackTraceLimit=1/0),Error.captureStackTrace(e),t&&(Error.stackTraceLimit=Ht),e}),Kt={}.hasOwnProperty,{ERR_INVALID_PACKAGE_CONFIG:qt}=K,Jt=/* @__PURE__ */ new Map;function q(e,{base:t,specifier:n}){let r=Jt.get(e);if(r)return r;let i;try{i=U.readFileSync(Nt.toNamespacedPath(e),`utf8`)}catch(e){let t=e;if(t.code!==`ENOENT`)throw t}let a={exists:!1,pjsonPath:e,main:void 0,name:void 0,type:`none`,exports:void 0,imports:void 0};if(i!==void 0){let r;try{r=JSON.parse(i)}catch(r){let i=r,a=new qt(e,(t?`"${n}" from `:``)+(0,W.fileURLToPath)(t||n),i.message);throw a.cause=i,a}a.exists=!0,Kt.call(r,`name`)&&typeof r.name==`string`&&(a.name=r.name),Kt.call(r,`main`)&&typeof r.main==`string`&&(a.main=r.main),Kt.call(r,`exports`)&&(a.exports=r.exports),Kt.call(r,`imports`)&&(a.imports=r.imports),!Kt.call(r,`type`)||r.type!==`commonjs`&&r.type!==`module`||(a.type=r.type)}return Jt.set(e,a),a}function Yt(e){let t=new URL(`package.json`,e);for(;!t.pathname.endsWith(`node_modules/package.json`);){let n=q((0,W.fileURLToPath)(t),{specifier:e});if(n.exists)return n;let r=t;if(t=new URL(`../package.json`,t),t.pathname===r.pathname)break}return{pjsonPath:(0,W.fileURLToPath)(t),exists:!1,type:`none`}}function Xt(e){return Yt(e).type}let{ERR_UNKNOWN_FILE_EXTENSION:Zt}=K,Qt={}.hasOwnProperty,$t={__proto__:null,".cjs":`commonjs`,".js":`module`,".json":`json`,".mjs":`module`},J={__proto__:null,"data:":function(e){let{1:t}=/^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(e.pathname)||[null,null,null];return function(e){return e&&/\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(e)?`module`:e===`application/json`?`json`:null}(t)},"file:":function(e,t,n){let r=function(e){let t=e.pathname,n=t.length;for(;n--;){let e=t.codePointAt(n);if(e===47)return``;if(e===46)return t.codePointAt(n-1)===47?``:t.slice(n)}return``}(e);if(r===`.js`){let t=Xt(e);return t===`none`?`commonjs`:t}if(r===``){let t=Xt(e);return t===`none`||t===`commonjs`?`commonjs`:`module`}let i=$t[r];if(i)return i;if(n)return;let a=(0,W.fileURLToPath)(e);throw new Zt(r,a)},"http:":en,"https:":en,"node:":()=>`builtin`};function en(){}let tn=Object.freeze([`node`,`import`]),nn=new Set(tn);function rn(e){return nn}let an=RegExp.prototype[Symbol.replace],{ERR_INVALID_MODULE_SPECIFIER:on,ERR_INVALID_PACKAGE_CONFIG:sn,ERR_INVALID_PACKAGE_TARGET:cn,ERR_MODULE_NOT_FOUND:ln,ERR_PACKAGE_IMPORT_NOT_DEFINED:un,ERR_PACKAGE_PATH_NOT_EXPORTED:dn,ERR_UNSUPPORTED_DIR_IMPORT:fn,ERR_UNSUPPORTED_RESOLVE_REQUEST:pn}=K,mn={}.hasOwnProperty,hn=/(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i,gn=/(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i,_n=/^\.|%|\\/,vn=/\*/g,yn=/%2f|%5c/i,bn=/* @__PURE__ */ new Set,xn=/[/\\]{2}/;function Sn(e,t,n,r,i,a,o){if(Mt.noDeprecation)return;let s=(0,W.fileURLToPath)(r),c=xn.exec(o?e:t)!==null;Mt.emitWarning(`Use of deprecated ${c?`double slash`:`leading or trailing slash matching`} resolving "${e}" for module request "${t}" ${t===n?``:`matched to "${n}" `}in the "${i?`imports`:`exports`}" field module resolution of the package at ${s}${a?` imported from ${(0,W.fileURLToPath)(a)}`:``}.`,`DeprecationWarning`,`DEP0166`)}function Cn(e,t,n,r){if(Mt.noDeprecation||function(e,t){let n=e.protocol;return Qt.call(J,n)&&J[n](e,t,!0)||null}(e,{parentURL:n.href})!==`module`)return;let i=(0,W.fileURLToPath)(e.href),a=(0,W.fileURLToPath)(new URL(`.`,t)),o=(0,W.fileURLToPath)(n);r?Nt.resolve(a,r)!==i&&Mt.emitWarning(`Package ${a} has a "main" field set to "${r}", excluding the full filename and extension to the resolved file at "${i.slice(a.length)}", imported from ${o}.\n Automatic extension resolution of the "main" field is deprecated for ES modules.`,`DeprecationWarning`,`DEP0151`):Mt.emitWarning(`No "main" or "exports" field defined in the package.json for ${a} resolving the main entry point "${i.slice(a.length)}", imported from ${o}.\nDefault "index" lookups for the main are deprecated for ES modules.`,`DeprecationWarning`,`DEP0151`)}function wn(e){try{return(0,U.statSync)(e)}catch{}}function Tn(e){let t=(0,U.statSync)(e,{throwIfNoEntry:!1}),n=t?t.isFile():void 0;return n!=null&&n}function En(e,t,n){let r;if(t.main!==void 0){if(r=new URL(t.main,e),Tn(r))return r;let i=[`./${t.main}.js`,`./${t.main}.json`,`./${t.main}.node`,`./${t.main}/index.js`,`./${t.main}/index.json`,`./${t.main}/index.node`],a=-1;for(;++a<i.length&&(r=new URL(i[a],e),!Tn(r));)r=void 0;if(r)return Cn(r,e,n,t.main),r}let i=[`./index.js`,`./index.json`,`./index.node`],a=-1;for(;++a<i.length&&(r=new URL(i[a],e),!Tn(r));)r=void 0;if(r)return Cn(r,e,n,t.main),r;throw new ln((0,W.fileURLToPath)(new URL(`.`,e)),(0,W.fileURLToPath)(n))}function Dn(e,t,n){return new dn((0,W.fileURLToPath)(new URL(`.`,t)),e,n&&(0,W.fileURLToPath)(n))}function On(e,t,n,r,i){return t=typeof t==`object`&&t?JSON.stringify(t,null,``):`${t}`,new cn((0,W.fileURLToPath)(new URL(`.`,n)),e,t,r,i&&(0,W.fileURLToPath)(i))}function kn(e,t,n,r,i,a,o,s,c){if(t!==``&&!a&&e[e.length-1]!==`/`)throw On(n,e,r,o,i);if(!e.startsWith(`./`)){if(o&&!e.startsWith(`../`)&&!e.startsWith(`/`)){let n=!1;try{new URL(e),n=!0}catch{}if(!n)return Fn(a?an.call(vn,e,()=>t):e+t,r,c)}throw On(n,e,r,o,i)}if(hn.exec(e.slice(2))!==null){if(gn.exec(e.slice(2))!==null)throw On(n,e,r,o,i);if(!s){let s=a?n.replace(`*`,()=>t):n+t;Sn(a?an.call(vn,e,()=>t):e,s,n,r,o,i,!0)}}let l=new URL(e,r),u=l.pathname,d=new URL(`.`,r).pathname;if(!u.startsWith(d))throw On(n,e,r,o,i);if(t===``)return l;if(hn.exec(t)!==null){let c=a?n.replace(`*`,()=>t):n+t;gn.exec(t)===null?s||Sn(a?an.call(vn,e,()=>t):e,c,n,r,o,i,!1):(function(e,t,n,r,i){let a=`request is not a valid match in pattern "${t}" for the "${r?`imports`:`exports`}" resolution of ${(0,W.fileURLToPath)(n)}`;throw new on(e,a,i&&(0,W.fileURLToPath)(i))})(c,n,r,o,i)}return a?new URL(an.call(vn,l.href,()=>t)):new URL(t,l)}function An(e){let t=Number(e);return`${t}`===e&&t>=0&&t<4294967295}function jn(e,t,n,r,i,a,o,s,c){if(typeof t==`string`)return kn(t,n,r,e,i,a,o,s,c);if(Array.isArray(t)){let l=t;if(l.length===0)return null;let u,d=-1;for(;++d<l.length;){let t=l[d],f;try{f=jn(e,t,n,r,i,a,o,s,c)}catch(e){if(u=e,e.code===`ERR_INVALID_PACKAGE_TARGET`)continue;throw e}if(f!==void 0){if(f!==null)return f;u=null}}if(u==null)return null;throw u}if(typeof t==`object`&&t){let l=Object.getOwnPropertyNames(t),u=-1;for(;++u<l.length;)if(An(l[u]))throw new sn((0,W.fileURLToPath)(e),i,`"exports" cannot contain numeric property keys.`);for(u=-1;++u<l.length;){let d=l[u];if(d==="default"||c&&c.has(d)){let l=jn(e,t[d],n,r,i,a,o,s,c);if(l===void 0)continue;return l}}return null}if(t===null)return null;throw On(r,t,e,o,i)}function Mn(e,t,n){if(Mt.noDeprecation)return;let r=(0,W.fileURLToPath)(t);bn.has(r+`|`+e)||(bn.add(r+`|`+e),Mt.emitWarning(`Use of deprecated trailing slash pattern mapping "${e}" in the "exports" field module resolution of the package at ${r}${n?` imported from ${(0,W.fileURLToPath)(n)}`:``}. Mapping specifiers ending in "/" is no longer supported.`,`DeprecationWarning`,`DEP0155`))}function Nn(e,t,n,r,i){let a=n.exports;if(function(e,t,n){if(typeof e==`string`||Array.isArray(e))return!0;if(typeof e!=`object`||!e)return!1;let r=Object.getOwnPropertyNames(e),i=!1,a=0,o=-1;for(;++o<r.length;){let e=r[o],s=e===``||e[0]!==`.`;if(a++===0)i=s;else if(i!==s)throw new sn((0,W.fileURLToPath)(t),n,`"exports" cannot contain some keys starting with '.' and some not. The exports object must either be an object of package subpath keys or an object of main entry condition name keys only.`)}return i}(a,e,r)&&(a={".":a}),mn.call(a,t)&&!t.includes(`*`)&&!t.endsWith(`/`)){let n=jn(e,a[t],``,t,r,!1,!1,!1,i);if(n==null)throw Dn(t,e,r);return n}let o=``,s=``,c=Object.getOwnPropertyNames(a),l=-1;for(;++l<c.length;){let n=c[l],i=n.indexOf(`*`);if(i!==-1&&t.startsWith(n.slice(0,i))){t.endsWith(`/`)&&Mn(t,e,r);let a=n.slice(i+1);t.length>=n.length&&t.endsWith(a)&&Pn(o,n)===1&&n.lastIndexOf(`*`)===i&&(o=n,s=t.slice(i,t.length-a.length))}}if(o){let n=jn(e,a[o],s,o,r,!0,!1,t.endsWith(`/`),i);if(n==null)throw Dn(t,e,r);return n}throw Dn(t,e,r)}function Pn(e,t){let n=e.indexOf(`*`),r=t.indexOf(`*`),i=n===-1?e.length:n+1,a=r===-1?t.length:r+1;return i>a?-1:a>i||n===-1?1:r===-1||e.length>t.length?-1:+(t.length>e.length)}function Y(e,t,n){if(e===`#`||e.startsWith(`#/`)||e.endsWith(`/`))throw new on(e,`is not a valid internal imports specifier name`,(0,W.fileURLToPath)(t));let r,i=Yt(t);if(i.exists){r=(0,W.pathToFileURL)(i.pjsonPath);let a=i.imports;if(a){if(mn.call(a,e)&&!e.includes(`*`)){let i=jn(r,a[e],``,e,t,!1,!0,!1,n);if(i!=null)return i}else{let i=``,o=``,s=Object.getOwnPropertyNames(a),c=-1;for(;++c<s.length;){let t=s[c],n=t.indexOf(`*`);if(n!==-1&&e.startsWith(t.slice(0,-1))){let r=t.slice(n+1);e.length>=t.length&&e.endsWith(r)&&Pn(i,t)===1&&t.lastIndexOf(`*`)===n&&(i=t,o=e.slice(n,e.length-r.length))}}if(i){let e=jn(r,a[i],o,i,t,!0,!0,!1,n);if(e!=null)return e}}}}throw function(e,t,n){return new un(e,t&&(0,W.fileURLToPath)(new URL(`.`,t)),(0,W.fileURLToPath)(n))}(e,r,t)}function Fn(e,t,n){if(lt.builtinModules.includes(e))return new URL(`node:`+e);let{packageName:r,packageSubpath:i,isScoped:a}=function(e,t){let n=e.indexOf(`/`),r=!0,i=!1;e[0]===`@`&&(i=!0,n===-1||e.length===0?r=!1:n=e.indexOf(`/`,n+1));let a=n===-1?e:e.slice(0,n);if(_n.exec(a)!==null&&(r=!1),!r)throw new on(e,`is not a valid package name`,(0,W.fileURLToPath)(t));return{packageName:a,packageSubpath:`.`+(n===-1?``:e.slice(n)),isScoped:i}}(e,t),o=Yt(t);if(o.exists){let e=(0,W.pathToFileURL)(o.pjsonPath);if(o.name===r&&o.exports!==void 0&&o.exports!==null)return Nn(e,i,o,t,n)}let s,c=new URL(`./node_modules/`+r+`/package.json`,t),l=(0,W.fileURLToPath)(c);do{let o=wn(l.slice(0,-13));if(!o||!o.isDirectory()){s=l,c=new URL((a?`../../../../node_modules/`:`../../../node_modules/`)+r+`/package.json`,c),l=(0,W.fileURLToPath)(c);continue}let u=q(l,{base:t,specifier:e});return u.exports!==void 0&&u.exports!==null?Nn(c,i,u,t,n):i===`.`?En(c,u,t):new URL(i,c)}while(l.length!==s.length)}function In(e,t,n,r){n===void 0&&(n=rn());let i=t.protocol,a=i===`data:`||i===`http:`||i===`https:`,o;if(function(e){return e!==``&&(e[0]===`/`||function(e){return!(e[0]!==`.`||e.length!==1&&e[1]!==`/`&&(e[1]!==`.`||e.length!==2&&e[2]!==`/`))}(e))}(e))try{o=new URL(e,t)}catch(n){let r=new pn(e,t);throw r.cause=n,r}else if(i===`file:`&&e[0]===`#`)o=Y(e,t,n);else try{o=new URL(e)}catch(r){if(a&&!lt.builtinModules.includes(e)){let n=new pn(e,t);throw n.cause=r,n}o=Fn(e,t,n)}return jt.ok(o!==void 0,`expected to be defined`),o.protocol===`file:`?function(e,t){if(yn.exec(e.pathname)!==null)throw new on(e.pathname,`must not include encoded "/" or "\\" characters`,(0,W.fileURLToPath)(t));let n;try{n=(0,W.fileURLToPath)(e)}catch(n){let r=n;throw Object.defineProperty(r,"input",{value:String(e)}),Object.defineProperty(r,"module",{value:String(t)}),r}let r=wn(n.endsWith(`/`)?n.slice(-1):n);if(r&&r.isDirectory()){let r=new fn(n,(0,W.fileURLToPath)(t));throw r.url=String(e),r}if(!r||!r.isFile()){let r=new ln(n||e.pathname,t&&(0,W.fileURLToPath)(t),!0);throw r.url=String(e),r}{let t=(0,U.realpathSync)(n),{search:r,hash:i}=e;(e=(0,W.pathToFileURL)(t+(n.endsWith(Nt.sep)?`/`:``))).search=r,e.hash=i}return e}(o,t):o}function Ln(e){return typeof e!=`string`||e.startsWith(`file://`)?It((0,W.fileURLToPath)(e)):It(e)}function Rn(e){return(0,W.pathToFileURL)(Ln(e)).toString()}let zn=/* @__PURE__ */ new Set([`node`,`import`]),Bn=[`.mjs`,`.cjs`,`.js`,`.json`],Vn=/* @__PURE__ */ new Set([`ERR_MODULE_NOT_FOUND`,`ERR_UNSUPPORTED_DIR_IMPORT`,`MODULE_NOT_FOUND`,`ERR_PACKAGE_PATH_NOT_EXPORTED`]);function Hn(e,t,n){try{return In(e,t,n)}catch(e){if(!Vn.has(e?.code))throw e}}function Un(e,t={}){if(typeof e!=`string`){if(!(e instanceof URL))throw TypeError("input must be a `string` or `URL`");e=Ln(e)}if(/(?:node|data|http|https):/.test(e))return e;if(G.has(e))return`node:`+e;if(e.startsWith(`file://`)&&(e=Ln(e)),Dt(e))try{if((0,U.statSync)(e).isFile())return Rn(e)}catch(e){if(e?.code!==`ENOENT`)throw e}let n=t.conditions?new Set(t.conditions):zn,r=(Array.isArray(t.url)?t.url:[t.url]).filter(Boolean).map(e=>new URL(function(e){return typeof e!=`string`&&(e=e.toString()),/(?:node|data|http|https|file):/.test(e)?e:G.has(e)?`node:`+e:`file://`+encodeURI(It(e))}(e.toString())));r.length===0&&r.push(new URL(Rn(process.cwd())));let i=[...r];for(let e of r)e.protocol===`file:`&&i.push(new URL(`./`,e),new URL(ht(e.pathname,`_index.js`),e),new URL(`node_modules`,e));let a;for(let r of i){if(a=Hn(e,r,n),a)break;for(let i of[``,`/index`]){for(let o of t.extensions||Bn)if(a=Hn(ht(e,i)+o,r,n),a)break;if(a)break}if(a)break}if(!a){let t=/* @__PURE__ */ Error(`Cannot find module ${e} imported from ${i.join(`, `)}`);throw t.code=`ERR_MODULE_NOT_FOUND`,t}return Rn(a)}function Wn(e,t){return Un(e,t)}function Gn(e,t){return Ln(Wn(e,t))}let Kn=/(?:[\s;]|^)(?:import[\s\w*,{}]*from|import\s*["'*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m,qn=/\/\*.+?\*\/|\/\/.*(?=[nr])/g;function Jn(e,t={}){return t.stripComments&&(e=e.replace(qn,``)),Kn.test(e)}function Yn(e){if(typeof e!=`string`)throw TypeError(`Expected a string`);return e.replace(/[|\\{}()[\]^$+*?.]/g,`\\$&`).replace(/-/g,`\\x2d`)}let Xn=/* @__PURE__ */ new Set([`/`,`\\`,void 0]),Zn=Symbol.for(`pathe:normalizedAlias`),Qn=/[/\\]/;function $n(e){if(e[Zn])return e;let t=Object.fromEntries(Object.entries(e).sort(([e],[t])=>function(e,t){return t.split(`/`).length-e.split(`/`).length}(e,t)));for(let e in t)for(let n in t)n===e||e.startsWith(n)||t[e]?.startsWith(n)&&Xn.has(t[e][n.length])&&(t[e]=t[n]+t[e].slice(n.length));return Object.defineProperty(t,Zn,{value:!0,enumerable:!1}),t}function er(e=`/`){let t=e[e.length-1];return t===`/`||t===`\\`}var tr={rE:`2.6.1`};let nr=k(`node:crypto`);var rr=r.n(nr);let X=globalThis.process?.env||Object.create(null),ir=globalThis.process||{env:X},ar=ir!==void 0&&ir.env&&ir.env.NODE_ENV||void 0,or=[[`claude`,[`CLAUDECODE`,`CLAUDE_CODE`]],[`replit`,[`REPL_ID`]],[`gemini`,[`GEMINI_CLI`]],[`codex`,[`CODEX_SANDBOX`,`CODEX_THREAD_ID`]],[`opencode`,[`OPENCODE`]],[`pi`,[sr(`PATH`,/\.pi[\\/]agent/)]],[`auggie`,[`AUGMENT_AGENT`]],[`goose`,[`GOOSE_PROVIDER`]],[`devin`,[sr(`EDITOR`,/devin/)]],[`cursor`,[`CURSOR_AGENT`]],[`kiro`,[sr(`TERM_PROGRAM`,/kiro/)]]];function sr(e,t){return()=>{let n=X[e];return!!n&&t.test(n)}}let cr=function(){let e=X.AI_AGENT;if(e)return{name:e.toLowerCase()};for(let[e,t]of or)for(let n of t)if(typeof n==`string`?X[n]:n())return{name:e};return{}}(),lr=(cr.name,cr.name,[[`APPVEYOR`],[`AWS_AMPLIFY`,`AWS_APP_ID`,{ci:!0}],[`AZURE_PIPELINES`,`SYSTEM_TEAMFOUNDATIONCOLLECTIONURI`],[`AZURE_STATIC`,`INPUT_AZURE_STATIC_WEB_APPS_API_TOKEN`],[`APPCIRCLE`,`AC_APPCIRCLE`],[`BAMBOO`,`bamboo_planKey`],[`BITBUCKET`,`BITBUCKET_COMMIT`],[`BITRISE`,`BITRISE_IO`],[`BUDDY`,`BUDDY_WORKSPACE_ID`],[`BUILDKITE`],[`CIRCLE`,`CIRCLECI`],[`CIRRUS`,`CIRRUS_CI`],[`CLOUDFLARE_PAGES`,`CF_PAGES`,{ci:!0}],[`CLOUDFLARE_WORKERS`,`WORKERS_CI`,{ci:!0}],[`GOOGLE_CLOUDRUN`,`K_SERVICE`],[`GOOGLE_CLOUDRUN_JOB`,`CLOUD_RUN_JOB`],[`CODEBUILD`,`CODEBUILD_BUILD_ARN`],[`CODEFRESH`,`CF_BUILD_ID`],[`DRONE`],[`DRONE`,`DRONE_BUILD_EVENT`],[`DSARI`],[`GITHUB_ACTIONS`],[`GITLAB`,`GITLAB_CI`],[`GITLAB`,`CI_MERGE_REQUEST_ID`],[`GOCD`,`GO_PIPELINE_LABEL`],[`LAYERCI`],[`JENKINS`,`JENKINS_URL`],[`HUDSON`,`HUDSON_URL`],[`MAGNUM`],[`NETLIFY`],[`NETLIFY`,`NETLIFY_LOCAL`,{ci:!1}],[`NEVERCODE`],[`RENDER`],[`SAIL`,`SAILCI`],[`SEMAPHORE`],[`SCREWDRIVER`],[`SHIPPABLE`],[`SOLANO`,`TDDIUM`],[`STRIDER`],[`TEAMCITY`,`TEAMCITY_VERSION`],[`TRAVIS`],[`VERCEL`,`NOW_BUILDER`],[`VERCEL`,`VERCEL`,{ci:!1}],[`VERCEL`,`VERCEL_ENV`,{ci:!1}],[`APPCENTER`,`APPCENTER_BUILD_ID`],[`CODESANDBOX`,`CODESANDBOX_SSE`,{ci:!1}],[`CODESANDBOX`,`CODESANDBOX_HOST`,{ci:!1}],[`STACKBLITZ`],[`STORMKIT`],[`CLEAVR`],[`ZEABUR`],[`CODESPHERE`,`CODESPHERE_APP_ID`,{ci:!0}],[`RAILWAY`,`RAILWAY_PROJECT_ID`],[`RAILWAY`,`RAILWAY_SERVICE_ID`],[`DENO-DEPLOY`,`DENO_DEPLOY`],[`DENO-DEPLOY`,`DENO_DEPLOYMENT_ID`],[`FIREBASE_APP_HOSTING`,`FIREBASE_APP_HOSTING`,{ci:!0}],[`EDGEONE_PAGES`,`EO_PAGES_CI`,{ci:!0}]]),ur=function(){for(let e of lr)if(X[e[1]||e[0]])return{name:e[0].toLowerCase(),...e[2]};return X.SHELL===`/bin/jsh`&&ir.versions?.webcontainer?{name:`stackblitz`,ci:!1}:{name:``,ci:!1}}(),dr=(ur.name,ir.platform||``);X.CI||ur.ci;let fr=!!ir.stdout?.isTTY;X.DEBUG,ar===`test`||X.TEST;let pr=(ar===`production`||X.MODE,ar===`dev`||ar===`development`||X.MODE,X.MINIMAL,/^win/i.test(dr)),mr=(/^linux/i.test(dr),/^darwin/i.test(dr),!X.NO_COLOR&&(X.FORCE_COLOR||(fr||pr)&&X.TERM),(ir.versions?.node||``).replace(/^v/,``)||null),hr=(Number(mr?.split(`.`)[0]),!!ir?.versions?.node),gr=`Bun`in globalThis,_r=`Deno`in globalThis,vr=`fastly`in globalThis,yr=[[`Netlify`in globalThis,`netlify`],[`EdgeRuntime`in globalThis,`edge-light`],[globalThis.navigator?.userAgent===`Cloudflare-Workers`,`workerd`],[vr,`fastly`],[_r,`deno`],[gr,`bun`],[hr,`node`]];(function(){let e=yr.find(e=>e[0]);e&&e[1]})();let br=k(`node:tty`)?.WriteStream?.prototype?.hasColors?.()??!1,Z=(e,t)=>{if(!br)return e=>e;let n=`[${e}m`,r=`[${t}m`;return e=>{let i=e+``,a=i.indexOf(r);if(a===-1)return n+i+r;let o=n,s=0,c=(t===22?r:``)+n;for(;a!==-1;)o+=i.slice(s,a)+c,s=a+r.length,a=i.indexOf(r,s);return o+=i.slice(s)+r,o}},xr=(Z(0,0),Z(1,22),Z(2,22),Z(3,23),Z(4,24),Z(53,55),Z(7,27),Z(8,28),Z(9,29),Z(30,39),Z(31,39)),Sr=Z(32,39),Cr=Z(33,39),wr=Z(34,39),Q=(Z(35,39),Z(36,39)),Tr=(Z(37,39),Z(90,39));Z(40,49),Z(41,49),Z(42,49),Z(43,49),Z(44,49),Z(45,49),Z(46,49),Z(47,49),Z(100,49),Z(91,39),Z(92,39),Z(93,39),Z(94,39),Z(95,39),Z(96,39),Z(97,39),Z(101,49),Z(102,49),Z(103,49),Z(104,49),Z(105,49),Z(106,49),Z(107,49);function Er(e){if(typeof e!=`string`||e.startsWith(`file://`))return!1;try{return(0,U.lstatSync)(e).isDirectory()}catch{return!1}}function Dr(e,t=8){return(function(){if(Ar!==void 0)return Ar;try{return Ar=!!rr().getFips?.(),Ar}catch{return Ar=!1,Ar}}()?rr().createHash(`sha256`):rr().createHash(`md5`)).update(e).digest(`hex`).slice(0,t)}let Or={true:Sr(`true`),false:Cr(`false`),"[rebuild]":Cr(`[rebuild]`),"[esm]":wr(`[esm]`),"[cjs]":Sr(`[cjs]`),"[import]":wr(`[import]`),"[require]":Sr(`[require]`),"[native]":Q(`[native]`),"[transpile]":Cr(`[transpile]`),"[fallback]":xr(`[fallback]`),"[unknown]":xr(`[unknown]`),"[hit]":Sr(`[hit]`),"[miss]":Cr(`[miss]`),"[json]":Sr(`[json]`),"[data]":Sr(`[data]`)};function $(e,...t){if(!e.opts.debug)return;let n=process.cwd();console.log(Tr([`[jiti]`,...t.map(e=>e in Or?Or[e]:typeof e==`string`?e.replace(n,`.`):JSON.stringify(e))].join(` `)))}function kr(e,t){return e.opts.interopDefault?function(e){let t=typeof e;if(e===null||t!==`object`&&t!==`function`)return e;let n=e.default,r=typeof n,i=n==null,a=r===`object`||r===`function`;if(i&&e instanceof Promise)return e;let o=r===`function`&&t!==`function`,s=a&&!(n instanceof Promise),c=/* @__PURE__ */ new Map;return new Proxy(e,{get(t,r){if(c.has(r))return c.get(r);let a;return r==="__esModule"?a=!0:r==="default"?a=i?e:typeof n?.default==`function`&&e.__esModule?n.default:n:r in t?a=t[r]:s&&(a=n[r],typeof a==`function`&&(a=a.bind(n))),c.set(r,a),a},apply:o?(e,t,r)=>Reflect.apply(n,t,r):void 0})}(t):t}let Ar;function jr(e,t){return!!Mr(e,t)}function Mr(e,t,n){let r=process.env[e];if(!(e in process.env))return t;try{return JSON.parse(r)}catch{return n?r:t}}let Nr=/\.(c|m)?j(sx?)$/,Pr=/\.(c|m)?t(sx?)$/;function Fr(e,t,n){let r,i;if(e.isNativeRe.test(t))return t;if(e.resolveTsConfigPaths&&!n.skipTsConfigPaths){let r=e.resolveTsConfigPaths(t);for(let t of r){let r=Fr(e,t,{...n,try:!0,skipTsConfigPaths:!0});if(r)return r}}e.alias&&(t=function(e,t){let n=_t(e);t=$n(t);for(let[e,r]of Object.entries(t))if(n.startsWith(e)&&er(n[(er(e)?e.slice(0,-1):e).length]))return Ct(r,n.slice(e.length));return n}(t,e.alias));let a=n?.parentURL||e.url;Er(a)&&(a=Ct(a,`_index.js`));let o=(n?.async?[n?.conditions,[`node`,`import`],[`node`,`require`]]:[n?.conditions,[`node`,`require`],[`node`,`import`]]).filter(Boolean);for(let n of o){try{r=Gn(t,{url:a,conditions:n,extensions:e.opts.extensions})}catch(e){i=e}if(r)return r}try{return e.nativeRequire.resolve(t,{paths:n.paths})}catch(e){i=e}for(let i of e.additionalExts)if(r=Ir(e,t+i,a,n)||Ir(e,t+`/index`+i,a,n),r||(Pr.test(e.filename)||Pr.test(e.parentModule?.filename||``)||Nr.test(t))&&(r=Ir(e,t.replace(Nr,`.$1t$2`),a,n),r))return r;if(!n?.try)throw i}function Ir(e,t,n,r){try{return e.nativeRequire.resolve(t,{...r,paths:[kt(Ln(n)),...r?.paths||[]]})}catch{}}let Lr=k(`node:fs/promises`),Rr=k(`node:perf_hooks`),zr=k(`node:vm`);var Br=r.n(zr);function Vr(e,t,n){let r=e.parentCache||{};if(t.startsWith(`node:`))return Hr(e,t,n.async);if(t.startsWith(`file:`))t=(0,W.fileURLToPath)(t);else if(t.startsWith(`data:`)){if(!n.async)throw Error("`data:` URLs are only supported in ESM context. Use `import` or `jiti.import` instead.");return $(e,`[native]`,`[data]`,`[import]`,t),Hr(e,t,!0)}if(lt.builtinModules.includes(t)||t===`.pnp.js`)return Hr(e,t,n.async);if(e.opts.virtualModules&&t in e.opts.virtualModules){$(e,`[virtual]`,t);let r=e.opts.virtualModules[t];return n.async?Promise.resolve(kr(e,r)):kr(e,r)}if(e.opts.tryNative&&!e.opts.transformOptions)try{if(!(t=Fr(e,t,n))&&n.try)return;if($(e,`[try-native]`,n.async&&e.nativeImport?`[import]`:`[require]`,t),n.async&&e.nativeImport)return e.nativeImport(t).then(n=>(!1===e.opts.moduleCache&&delete e.nativeRequire.cache[t],kr(e,n))).catch(r=>($(e,`[try-native] Using fallback for ${t} because of an error:`,r),Vr({...e,opts:{...e.opts,tryNative:!1}},t,n)));{let n=e.nativeRequire(t);return!1===e.opts.moduleCache&&delete e.nativeRequire.cache[t],kr(e,n)}}catch(n){$(e,`[try-native] Using fallback for ${t} because of an error:`,n)}let i=Fr(e,t,n);if(!i&&n.try)return;let a=Ot(i);if(a===`.json`){$(e,`[json]`,i);let t=e.nativeRequire(i);return t&&!(`default`in t)&&Object.defineProperty(t,"default",{value:t,enumerable:!1}),t}if(a&&!e.opts.extensions.includes(a))return $(e,`[native]`,`[unknown]`,n.async?`[import]`:`[require]`,i),Hr(e,i,n.async);if(e.isNativeRe.test(i))return $(e,`[native]`,n.async?`[import]`:`[require]`,i),Hr(e,i,n.async);if(r[i])return kr(e,r[i]?.exports);if(e.opts.moduleCache){let t=e.nativeRequire.cache[i];if(t?.loaded)return kr(e,t.exports)}return Kr(e,(0,U.readFileSync)(i,`utf8`),{id:t,filename:i,ext:a,cache:r,async:n.async})}function Hr(e,t,n){return n&&e.nativeImport?e.nativeImport(function(e){return pr&&Dt(e)?Rn(e):e}(t)).then(t=>kr(e,t)):kr(e,e.nativeRequire(t))}function Ur(e,t,n){if(!e.opts.fsCache||!t.filename)return n();let r=` /* v9-${Dr(t.source,16)} */\n`,i=`${At(kt(t.filename))}-${function(e){let t=e.split(Qn).pop();if(!t)return;let n=t.lastIndexOf(`.`);return n<=0?t:t.slice(0,n)}(t.filename)}`+(e.opts.sourceMaps?`+map`:``)+(t.interopDefault?`.i`:``)+`.${Dr(t.filename)}`+(t.async?`.mjs`:`.cjs`);t.jsx&&t.filename.endsWith(`x`)&&(i+=`x`);let a=e.opts.fsCache,o=Ct(a,i);if(!e.opts.rebuildFsCache&&(0,U.existsSync)(o)){let n=(0,U.readFileSync)(o,`utf8`);if(n.endsWith(r))return $(e,`[cache]`,`[hit]`,t.filename,`~>`,o),n}$(e,`[cache]`,`[miss]`,t.filename);let s=n();return s.includes(`__JITI_ERROR__`)||((0,U.writeFileSync)(o,s+r,`utf8`),$(e,`[cache]`,`[store]`,t.filename,`~>`,o)),s}function Wr(t){if(!0===t.opts.fsCache&&(t.opts.fsCache=function(t){let n=t.filename&&Tt(t.filename,`../node_modules`);if(n&&(0,U.existsSync)(n))return Ct(n,`.cache/jiti`);let r=(0,e.tmpdir)();if(process.env.TMPDIR&&r===process.cwd()&&!process.env.JITI_RESPECT_TMPDIR_ENV){let t=process.env.TMPDIR;delete process.env.TMPDIR,r=(0,e.tmpdir)(),process.env.TMPDIR=t}return Ct(r,`jiti`)}(t)),t.opts.fsCache)try{if((0,U.mkdirSync)(t.opts.fsCache,{recursive:!0}),!function(e){try{return(0,U.accessSync)(e,U.constants.W_OK),!0}catch{return!1}}(t.opts.fsCache))throw Error(`directory is not writable!`)}catch(e){$(t,`Error creating cache directory at `,t.opts.fsCache,e),t.opts.fsCache=!1}}function Gr(e,t){let n=Ur(e,t,()=>{let n=e.opts.transform({...e.opts.transformOptions,babel:{...e.opts.sourceMaps?{sourceFileName:t.filename,sourceMaps:`inline`}:{},...e.opts.transformOptions?.babel},interopDefault:e.opts.interopDefault,...t});return n.error&&e.opts.debug&&$(e,n.error),n.code});return n.startsWith(`#!`)&&(n=`// `+n),n}function Kr(t,n,r={}){let i=r.id||(r.filename?At(r.filename):`_jitiEval.${r.ext||(r.async?`mjs`:`js`)}`),a=r.filename||Fr(t,i,{async:r.async}),o=r.ext||Ot(a),s=r.cache||t.parentCache||{},c=/\.[cm]?tsx?$/.test(o),l=o===`.mjs`||o===`.js`&&function(e){for(;e&&e!==`.`&&e!==`/`;){e=Ct(e,`..`);try{let t=(0,U.readFileSync)(Ct(e,`package.json`),`utf8`);try{return JSON.parse(t)}catch{}break}catch{}}}(a)?.type===`module`,u=o===`.cjs`,d=r.forceTranspile??(!u&&!(l&&r.async)&&(c||l||t.isTransformRe.test(a)||Jn(n))),f=Rr.performance.now();if(d){n=Gr(t,{filename:a,source:n,ts:c,async:r.async??!1,jsx:t.opts.jsx});let e=Math.round(1e3*(Rr.performance.now()-f))/1e3;$(t,`[transpile]`,r.async?`[esm]`:`[cjs]`,a,`(${e}ms)`)}else{if($(t,`[native]`,r.async?`[import]`:`[require]`,a),r.async)return Promise.resolve(Hr(t,a,r.async)).catch(e=>($(t,`Native import error:`,e),$(t,`[fallback]`,a),Kr(t,n,{...r,forceTranspile:!0})));try{return Hr(t,a,r.async)}catch(e){$(t,`Native require error:`,e),$(t,`[fallback]`,a),n=Gr(t,{filename:a,source:n,ts:c,async:r.async??!1,jsx:t.opts.jsx})}}let p=new lt.Module(a);p.filename=a,t.parentModule&&(p.parent=t.parentModule,Array.isArray(t.parentModule.children)&&!t.parentModule.children.includes(p)&&t.parentModule.children.push(p));let m=Jr(a,t.opts,{parentModule:p,parentCache:s,nativeImport:t.nativeImport,onError:t.onError,createRequire:t.createRequire},!0),h;p.require=m,p.path=kt(a),p.paths=lt.Module._nodeModulePaths(p.path),s[a]=p,t.opts.moduleCache&&(t.nativeRequire.cache[a]=p);let g=function(e,t){return`(${t?.async?`async `:``}function (exports, require, module, __filename, __dirname, jitiImport, jitiESMResolve) { ${e}\n});`}(n,{async:r.async});try{h=Br().runInThisContext(g,{filename:a,lineOffset:0,displayErrors:!1})}catch(n){n.name===`SyntaxError`&&r.async&&t.nativeImport?($(t,`[esm]`,`[import]`,`[fallback]`,a),h=function(t,n,r,i,a){let o=`export default ${n}`,s=a?void 0:`data:text/javascript;base64,${Buffer.from(o).toString(`base64`)}`;return(...n)=>{let a,c=()=>(a=function(t,n){let r=Ct((0,e.tmpdir)(),`jiti-esm`);try{(0,U.mkdirSync)(r,{recursive:!0})}catch{}let i=Ct(r,`${At(n,Ot(n))}-${Date.now()}-${Math.random().toString(36).slice(2)}.mjs`);return(0,U.writeFileSync)(i,t),i}(o,r),$(t,`[esm]`,`[tempfile]`,a),i(Rn(a)));return(s?i(s).catch(e=>{if(e?.code!==`ENAMETOOLONG`)throw e;return c()}):c()).then(e=>e.default(...n)).finally(()=>{a&&(0,Lr.unlink)(a).catch(()=>{})})}}(t,g,a,t.nativeImport,t.opts.esmEvalTempFile)):(t.opts.moduleCache&&delete t.nativeRequire.cache[a],t.onError(n))}let _;try{_=h(p.exports,p.require,p,p.filename,kt(p.filename),m.import,m.esmResolve)}catch(e){t.opts.moduleCache&&delete t.nativeRequire.cache[a],t.onError(e)}function v(){if(p.exports&&p.exports.__JITI_ERROR__){let{filename:e,line:n,column:r,code:i,message:a}=p.exports.__JITI_ERROR__,o=/* @__PURE__ */ Error(`${i}: ${a} \n ${`${e}:${n}:${r}`}`);Error.captureStackTrace(o,Vr),t.onError(o)}return p.loaded=!0,kr(t,p.exports)}return r.async?Promise.resolve(_).then(v):v()}let qr=(0,e.platform)()===`win32`;function Jr(e,t={},n,i=!1){let a=i?t:function(e){let t={fsCache:jr(`JITI_FS_CACHE`,jr(`JITI_CACHE`,!0)),rebuildFsCache:jr(`JITI_REBUILD_FS_CACHE`,!1),moduleCache:jr(`JITI_MODULE_CACHE`,jr(`JITI_REQUIRE_CACHE`,!0)),debug:jr(`JITI_DEBUG`,!1),sourceMaps:jr(`JITI_SOURCE_MAPS`,!1),interopDefault:jr(`JITI_INTEROP_DEFAULT`,!0),extensions:Mr(`JITI_EXTENSIONS`,[`.js`,`.mjs`,`.cjs`,`.ts`,`.tsx`,`.mts`,`.cts`,`.mtsx`,`.ctsx`]),alias:Mr(`JITI_ALIAS`,{}),nativeModules:Mr(`JITI_NATIVE_MODULES`,[]),transformModules:Mr(`JITI_TRANSFORM_MODULES`,[]),tryNative:Mr(`JITI_TRY_NATIVE`,`Bun`in globalThis),esmEvalTempFile:jr(`JITI_ESM_EVAL_TEMP_FILE`,!1),jsx:jr(`JITI_JSX`,!1),tsconfigPaths:Mr(`JITI_TSCONFIG_PATHS`,!1,!0)};t.jsx&&t.extensions.push(`.jsx`,`.tsx`);let n={};return e.cache!==void 0&&(n.fsCache=e.cache),e.requireCache!==void 0&&(n.moduleCache=e.requireCache),{...t,...n,...e}}(t);typeof e==`string`&&e.startsWith(`file://`)&&(e=Ln(e));let o=a.alias&&Object.keys(a.alias).length>0?$n(a.alias||{}):void 0,s;if(a.tsconfigPaths){let{getTsconfig:t,createPathsMatcher:n}=r(`./node_modules/.pnpm/get-tsconfig@4.14.0/node_modules/get-tsconfig/dist/index.cjs`),i=t(typeof a.tsconfigPaths==`string`?a.tsconfigPaths:kt(e));i&&(s=n(i))}let c=[`typescript`,`jiti`,...a.nativeModules||[]],l=RegExp(`node_modules/(${c.map(e=>Yn(e)).join(`|`)})/`),u=[...a.transformModules||[]],d=RegExp(`node_modules/(${u.map(e=>Yn(e)).join(`|`)})/`);e||=process.cwd(),!i&&Er(e)&&(e=Ct(e,`_index.js`));let f=Rn(e),p=[...a.extensions].filter(e=>e!==`.js`),m=n.createRequire(qr?e.replace(/\//g,`\\`):e),h={filename:e,url:f,opts:a,alias:o,resolveTsConfigPaths:s,nativeModules:c,transformModules:u,isNativeRe:l,isTransformRe:d,additionalExts:p,nativeRequire:m,onError:n.onError,parentModule:n.parentModule,parentCache:n.parentCache,nativeImport:n.nativeImport,createRequire:n.createRequire};return i||$(h,`[init]`,...[[`version:`,tr.rE],[`module-cache:`,a.moduleCache],[`fs-cache:`,a.fsCache],[`rebuild-fs-cache:`,a.rebuildFsCache],[`interop-defaults:`,a.interopDefault]].flat()),i||Wr(h),Object.assign(function(e){return Vr(h,e,{async:!1})},{cache:a.moduleCache?m.cache:Object.create(null),extensions:m.extensions,main:m.main,options:a,resolve:Object.assign(function(e,t){return Fr(h,e,{...t,async:!1})},{paths:m.resolve.paths}),transform:e=>Gr(h,e),evalModule:(e,t)=>Kr(h,e,t),async import(e,t){let n=await Vr(h,e,{...t,async:!0});return t?.default?n?.default??n:n},esmResolve(e,t){typeof t==`string`&&(t={parentURL:t});let n=Fr(h,e,{parentURL:f,...t,async:!0});return!n||typeof n!=`string`||n.startsWith(`file://`)?n:Rn(n)}})}})(),t.exports=i.default})()})))();var A=class{emitter;constructor(){this.emitter=r()}on(e,t){me(e).forEach(e=>{this.emitter.on(e,t)})}off(e,t){me(e).forEach(e=>{this.emitter.off(e,t)})}emit(e,t){me(e).forEach(e=>{this.emitter.emit(e,t)})}removeAllListeners(){this.emitter.all.clear()}},j=class{listeners;constructor(){this.listeners=/* @__PURE__ */ new Map}on(e,t){me(e).forEach(e=>{let n=this.listeners.get(e)||/* @__PURE__ */ new Set;n.add(t),this.listeners.set(e,n)})}off(e,t){me(e).forEach(e=>{let n=this.listeners.get(e);n&&n.delete(t)})}async emit(e,...t){let n=me(e).flatMap(e=>{let t=this.listeners.get(e)||/* @__PURE__ */ new Set,n=this.listeners.get(`*`)||/* @__PURE__ */ new Set;return[...Array.from(t),...Array.from(n)]});return n.length===0?[]:await Promise.all(n.map(async n=>{try{let e=n(...t);return e instanceof Promise?await e:e}catch(t){console.error(`Error in event listener for ${String(e)}:`,t);return}}))}removeAllListeners(){this.listeners.clear()}};function M(e,...t){return class extends e{static _instance;static getInstance(){return this._instance||=new e(...t),this._instance}static clearInstance(){this._instance=void 0}}}const _e=M(class extends A{destroy(){this.removeAllListeners()}fatal(e,t,n){this.emit(`fatal`,{code:t,message:e,data:n,timestamp:Date.now()})}error(e,t,n){this.emit(`error`,{code:t,message:e,data:n,timestamp:Date.now()})}warn(e,t,n){this.emit(`warning`,{code:t,message:e,data:n,timestamp:Date.now()})}});var ve=class{data;_schema;_defaultValue;_path;constructor(e){let{schema:t,default:n,path:r}=e;this._schema=t,this._defaultValue=n,this._path=r}set(e){let t=this._schema[`~standard`].validate(e);if(t instanceof Promise)throw Error(`StructuredConfigFile does not support async validation`);if(t.issues)throw this.reportInvalidConfigFile(t.issues),Error(`Invalid config data for ${this._path}: ${t.issues.map(e=>e.message).join(`; `)}`);this.data=this.onBeforeSave(e),this.save(e)}get(e={}){return this.data?this.data:this.load(e)}getKey(e,t={}){return this.get(t)[e]}save(e){let t=this.onBeforeSave(e);try{d(this.getFilePath()),i.writeFileSync(this.getFilePath(),JSON.stringify(t,void 0,2))}catch{return}return this.data=t}load(e={}){let{createIfMissing:t=!0}=e;if(!this.fileExists(this.getFilePath())||!this.canReadWriteFile(this.getFilePath())){t&&this.save(this._defaultValue);let e=this.onAfterLoad(this._defaultValue);return t&&(this.data=e),e}try{let e=i.readFileSync(this.getFilePath(),`utf8`),t=this.onAfterLoad(this.parseStoredData(e));return this.data=t,t}catch{return this.data=this._defaultValue}}onBeforeSave(e){return e}onAfterLoad(e){return e}getFilePath(){return this._path}parseStoredData(e){try{let t=n(`string.json.parse`).to(`object`)(e);if(t instanceof n.errors)return this._defaultValue;let r=this._schema[`~standard`].validate(t);if(r instanceof Promise)throw Error(`StructuredConfigFile does not support async validation`);return r.issues?this.migrate(t,this._defaultValue):this.migrate(r.value,this._defaultValue)}catch{return this._defaultValue}}canReadWriteFile(e){try{return i.accessSync(e,i.constants.R_OK|i.constants.W_OK),!0}catch{return!1}}fileExists(e){try{return i.accessSync(e,i.constants.F_OK),!0}catch{return!1}}migrate(e,t){let n={...e};for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&(r in e?e[r]!==null&&t[r]!==null&&typeof e[r]==`object`&&typeof t[r]==`object`&&!Array.isArray(e[r])&&!Array.isArray(t[r])?n[r]=this.migrate(e[r],t[r]):Array.isArray(t[r])&&(n[r]=e[r]):n[r]=t[r]);return n}reportInvalidConfigFile(e){_e.getInstance().error(`Invalid config file`,`INVALID_CONFIG_FILE`,{issues:e.map(e=>e.message),filePath:this._path,data:this.data})}};function N(e,t,n){return typeof e!=`object`||!e?String(e):e instanceof Error?JSON.stringify(e,(e,t)=>{if(t instanceof Error){let e={};for(let n of Object.getOwnPropertyNames(t))e[n]=t[n];return e}return t},n):e instanceof Map?JSON.stringify(Object.fromEntries(e.entries()),t,n):e instanceof Set?JSON.stringify(Array.from(e),t,n):JSON.stringify(e,t,n)}const ye=/\x1b\[[0-9;]*m/g;function be(e){return e.replace(ye,``)}var xe=class e extends A{stream;logPath;baseFileName;currentDate;rotationCheckInterval;isRotating=!1;constructor(e,t){super(),this.logPath=e,this.baseFileName=t.replace(`.log`,``),this.currentDate=this.getDateString(/* @__PURE__ */ new Date),this.ensureLogDirectory(),this.ensureLogFile(),this.stream=this.createStream(),this.rotationCheckInterval=this.startRotationCheck(),this.cleanupOldLogs()}static scope(t,n){return new e(t,n)}log(...e){this.write(`info`,...e)}error(...e){this.write(`error`,...e)}warn(...e){this.write(`warn`,...e)}info(...e){this.write(`info`,...e)}debug(...e){this.write(`debug`,...e)}async close(){clearInterval(this.rotationCheckInterval),await new Promise(e=>{this.stream.end(()=>e())})}getCurrentFileName(){return this.getFileName(this.currentDate)}static getMessageElements(e,...t){let n=/* @__PURE__ */ new Date;return{timestamp:n.toISOString().replace(`T`,` `).replace(/\.\d+Z$/,``)+`.${n.getUTCMilliseconds().toString().padStart(3,`0`)}`,level:e,message:t.map(e=>N(e)).join(` `)}}getFileName(e){return`${this.baseFileName}-${e}.log`}ensureLogDirectory(){try{s(this.logPath,{recursive:!0})}catch(e){throw console.error(`Failed to create log directory ${this.logPath}:`,e),e}}ensureLogFile(){let e=p(this.logPath,this.getFileName(this.currentDate));if(!o(e))try{u(e,``,`utf8`)}catch(t){throw console.error(`Failed to create log file ${e}:`,t),t}}getDateString(e){return`${e.getUTCFullYear()}-${(e.getUTCMonth()+1).toString().padStart(2,`0`)}-${e.getUTCDate().toString().padStart(2,`0`)}`}createStream(){s(this.logPath,{recursive:!0});let e=p(this.logPath,this.getFileName(this.currentDate)),t=a(e,{flags:`a`,encoding:`utf8`});return t.on(`error`,e=>this.emit(`error`,e)),t}async rotateLogs(){if(this.isRotating)return;this.isRotating=!0;let e=this.getDateString(/* @__PURE__ */ new Date);e!==this.currentDate&&await new Promise(t=>{this.stream.end(()=>{this.currentDate=e;try{this.stream=this.createStream()}catch(e){this.emit(`error`,e instanceof Error?e:Error(String(e)))}this.cleanupOldLogs(),t()})}),this.isRotating=!1}startRotationCheck(){return setInterval(()=>this.rotateLogs(),6e4)}cleanupOldLogs(){let e;try{e=c(this.logPath)}catch(e){console.error(`Failed to read log directory ${this.logPath}:`,e);return}let t=/* @__PURE__ */ new Date,n=new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()-7));e.filter(e=>e.startsWith(this.baseFileName)&&e.endsWith(`.log`)).filter(e=>{let[t,r,i]=e.replace(`${this.baseFileName}-`,``).replace(`.log`,``).split(`-`).map(Number);return new Date(Date.UTC(t,r-1,i))<=n}).forEach(e=>{try{l(p(this.logPath,e))}catch(t){console.error(`Failed to delete old log file ${e}:`,t)}})}ensureStreamValid(){if(!this.stream.writable||this.stream.destroyed)try{this.stream=this.createStream()}catch(e){this.emit(`error`,e instanceof Error?e:Error(String(e)))}}write(t,...n){let{timestamp:r,message:i}=e.getMessageElements(t,...n),a=`[${r}] [${t}] ${be(i)}\n`;this.ensureStreamValid(),this.stream.write(a,e=>{if(e){if(e.code===`ERR_STREAM_WRITE_AFTER_END`||!this.stream.writable)try{this.stream=this.createStream(),this.stream.write(a,e=>{e?this.emit(`error`,e):this.emit(`write`,a)})}catch(e){this.emit(`error`,e instanceof Error?e:Error(String(e)))}else this.emit(`error`,e)}else this.emit(`write`,a)})}};const Se=()=>h.join(process.env.APPDATA??``,`overlayed`),Ce=()=>h.join(Se(),`logs`),we=e=>h.join(Se(),`apps`,e),Te=e=>h.join(we(e),`logs`),P=()=>h.join(Se(),`meta.json`),F=()=>h.join(Se(),`crash-dumps`);var I=class{fileLogger;path;appId;messageQueue=new ge;fileName;_debug=!1;silent=!1;forceSilent=!1;constructor(e){this.fileName=e}init(e,t=!1,n=!1,r=!1){this.appId=e,this._debug=t,this.silent=n,this.forceSilent=r,this.path=Te(e),this.fileLogger=new xe(this.path,this.fileName),this.messageQueue.flush().forEach(e=>{this.fileLogger?.[e.type](...e.args)})}scope(e){if(!this.appId||!this.path)throw Error(`Logger not initialized`);let t=v.cyan(`[${e}]`);return{scope:e=>this.scope(e),error:(...e)=>this.error(t,...e),warn:(...e)=>this.warn(t,...e),info:(...e)=>this.info(t,...e),log:(...e)=>this.log(t,...e),debug:(...e)=>this.debug(t,...e)}}error(...e){this.handle(`error`,...e)}warn(...e){this.handle(`warn`,...e)}info(...e){this.handle(`log`,...e)}debug(...e){this._debug&&this.handle(`debug`,...e)}log(...e){this.handle(`log`,...e)}handle(e,...t){this.logToConsole(e,...t),this.fileLogger?this.fileLogger[e](...t):this.messageQueue.add({type:e,args:t})}logToConsole(e,...t){let n={error:v.red,warn:v.yellow,debug:v.blue,log:v.white};if(this.forceSilent||this.silent&&!this._debug)return;let{timestamp:r,message:i}=xe.getMessageElements(e,...t),a=console[e],o=n[e];a(`${v.gray(r)} ${o(i)}`)}};const L=M(I,`overlayed.log`);var R=class extends ee{blob;chunkSizeMb;maxConcurrent;shouldStop=!1;constructor(e,t){super(),this.blob=e,this.chunkSizeMb=t.chunkSizeMb,this.maxConcurrent=t.maxConcurrent??3}get totalChunks(){return Math.ceil(this.blob.size/(this.chunkSizeMb*1024*1024))}async chunk(e){let t=this.chunkSizeMb*1024*1024,n=this.totalChunks;if(n===0)return;let r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Set,o=[];for(let e=0;e<n;e++)o.push(e);let s=async n=>{let s=n*t,c=Math.min(s+t,this.blob.size),l=this.blob.slice(s,c);try{await e(l,n),a.add(n),this.emit(`chunkComplete`,n),i.delete(n)}catch(e){let t=r.get(n)||0;t<5?(r.set(n,t+1),await new Promise(e=>setTimeout(e,(t+1)*1e3)),o.push(n)):(a.add(n),this.emit(`error`,e),this.shouldStop=!0,i.delete(n))}},c=[],l=async()=>{for(;(o.length>0||i.size>0)&&!this.shouldStop;){if(o.length===0){await new Promise(e=>setTimeout(e,10));continue}let e=o.shift();a.has(e)||i.has(e)||(i.add(e),await s(e))}};for(let e=0;e<this.maxConcurrent;e++)c.push(l());await Promise.all(c)}};function Ee(e,t){let{recursive:n}=De(t);return S(e)?n?Oe(e).map(t=>[e,t]):w(e).map(t=>[e,t]):[]}function De(e){return{recursive:e?.recursive??!0}}function Oe(e){return w(e,{withFileTypes:!0}).flatMap(t=>{let n=h.join(e,t.name);return t.isDirectory()?Oe(n):[n]})}function ke(e){return Ae(e),e}function Ae(e){if(!he(e.applicationId))throw Error(`Invalid applicationId, must be a valid ULID.`)}function je(e,t){let n=t?.cwd??process.cwd(),r=m.join(n,`.overlayed`);y.existsSync(r)||y.mkdirSync(r,{recursive:!0});let i={application:{id:e.id,name:e.name,slug:e.slug,siteUrl:e.siteUrl},release:{id:null,channel:`local`,version:`0.0.0`}},a=m.join(r,`meta.json`);return y.writeFileSync(a,JSON.stringify(i,null,2)),i}const{PipeEventServer:Me,PipeEventClient:Ne,PipeEventBase:Pe,GameMonitor:Fe,GameInstance:Ie,HardwareInterface:Le}=e(import.meta.url)(`@overlayed/app/dist/native-interface/build/overlayed_native_interface_x64.node`),Re=M(class extends A{server=null;_hasConnection=!1;pipeId;get hasConnection(){return this._hasConnection}constructor(e){super(),this.pipeId=e,this.init()}destroy(){this.server&&=(this._hasConnection=!1,this.server.removeAllListeners(),this.server.close(),null)}init(){this.server=new Me(this.pipeId,{clientCount:1,access:1}),this.server.on(`event`,e=>{try{let t=JSON.parse(e);this.emit(`data`,[t])}catch(e){this.emit(`error`,e)}}),this.server.on(`connected`,()=>{this._hasConnection=!0,this.emit(`connected`,void 0)}),this.server.on(`disconnected`,()=>{this._hasConnection=!1,this.emit(`disconnected`,void 0)})}},`overlayed-event-server`),{RenderInterface:ze,renderHookPath:Be}=e(import.meta.url)(`@overlayed/app/dist/render-interface/build/overlayed_render_interface_x64.node`);let Ve=/* @__PURE__ */ function(e){return e[e.LeftButton=1]=`LeftButton`,e[e.RightButton=2]=`RightButton`,e[e.Cancel=3]=`Cancel`,e[e.MiddleButton=4]=`MiddleButton`,e[e.ExtraButton1=5]=`ExtraButton1`,e[e.ExtraButton2=6]=`ExtraButton2`,e[e.Back=8]=`Back`,e[e.Tab=9]=`Tab`,e[e.Clear=12]=`Clear`,e[e.Return=13]=`Return`,e[e.Shift=16]=`Shift`,e[e.Control=17]=`Control`,e[e.Menu=18]=`Menu`,e[e.Pause=19]=`Pause`,e[e.CapsLock=20]=`CapsLock`,e[e.Kana=21]=`Kana`,e[e.Hangeul=21]=`Hangeul`,e[e.Hangul=21]=`Hangul`,e[e.Junja=23]=`Junja`,e[e.Final=24]=`Final`,e[e.Hanja=25]=`Hanja`,e[e.Kanji=25]=`Kanji`,e[e.Escape=27]=`Escape`,e[e.Convert=28]=`Convert`,e[e.NonConvert=29]=`NonConvert`,e[e.Accept=30]=`Accept`,e[e.ModeChange=31]=`ModeChange`,e[e.Space=32]=`Space`,e[e.Prior=33]=`Prior`,e[e.Next=34]=`Next`,e[e.End=35]=`End`,e[e.Home=36]=`Home`,e[e.Left=37]=`Left`,e[e.Up=38]=`Up`,e[e.Right=39]=`Right`,e[e.Down=40]=`Down`,e[e.Select=41]=`Select`,e[e.Print=42]=`Print`,e[e.Execute=43]=`Execute`,e[e.Snapshot=44]=`Snapshot`,e[e.Insert=45]=`Insert`,e[e.Delete=46]=`Delete`,e[e.Help=47]=`Help`,e[e.N0=48]=`N0`,e[e.N1=49]=`N1`,e[e.N2=50]=`N2`,e[e.N3=51]=`N3`,e[e.N4=52]=`N4`,e[e.N5=53]=`N5`,e[e.N6=54]=`N6`,e[e.N7=55]=`N7`,e[e.N8=56]=`N8`,e[e.N9=57]=`N9`,e[e.A=65]=`A`,e[e.B=66]=`B`,e[e.C=67]=`C`,e[e.D=68]=`D`,e[e.E=69]=`E`,e[e.F=70]=`F`,e[e.G=71]=`G`,e[e.H=72]=`H`,e[e.I=73]=`I`,e[e.J=74]=`J`,e[e.K=75]=`K`,e[e.L=76]=`L`,e[e.M=77]=`M`,e[e.N=78]=`N`,e[e.O=79]=`O`,e[e.P=80]=`P`,e[e.Q=81]=`Q`,e[e.R=82]=`R`,e[e.S=83]=`S`,e[e.T=84]=`T`,e[e.U=85]=`U`,e[e.V=86]=`V`,e[e.W=87]=`W`,e[e.X=88]=`X`,e[e.Y=89]=`Y`,e[e.Z=90]=`Z`,e[e.LeftWindows=91]=`LeftWindows`,e[e.RightWindows=92]=`RightWindows`,e[e.Application=93]=`Application`,e[e.Sleep=95]=`Sleep`,e[e.Numpad0=96]=`Numpad0`,e[e.Numpad1=97]=`Numpad1`,e[e.Numpad2=98]=`Numpad2`,e[e.Numpad3=99]=`Numpad3`,e[e.Numpad4=100]=`Numpad4`,e[e.Numpad5=101]=`Numpad5`,e[e.Numpad6=102]=`Numpad6`,e[e.Numpad7=103]=`Numpad7`,e[e.Numpad8=104]=`Numpad8`,e[e.Numpad9=105]=`Numpad9`,e[e.Multiply=106]=`Multiply`,e[e.Add=107]=`Add`,e[e.Separator=108]=`Separator`,e[e.Subtract=109]=`Subtract`,e[e.Decimal=110]=`Decimal`,e[e.Divide=111]=`Divide`,e[e.F1=112]=`F1`,e[e.F2=113]=`F2`,e[e.F3=114]=`F3`,e[e.F4=115]=`F4`,e[e.F5=116]=`F5`,e[e.F6=117]=`F6`,e[e.F7=118]=`F7`,e[e.F8=119]=`F8`,e[e.F9=120]=`F9`,e[e.F10=121]=`F10`,e[e.F11=122]=`F11`,e[e.F12=123]=`F12`,e[e.F13=124]=`F13`,e[e.F14=125]=`F14`,e[e.F15=126]=`F15`,e[e.F16=127]=`F16`,e[e.F17=128]=`F17`,e[e.F18=129]=`F18`,e[e.F19=130]=`F19`,e[e.F20=131]=`F20`,e[e.F21=132]=`F21`,e[e.F22=133]=`F22`,e[e.F23=134]=`F23`,e[e.F24=135]=`F24`,e[e.NumLock=144]=`NumLock`,e[e.ScrollLock=145]=`ScrollLock`,e[e.NEC_Equal=146]=`NEC_Equal`,e[e.Fujitsu_Jisho=146]=`Fujitsu_Jisho`,e[e.Fujitsu_Masshou=147]=`Fujitsu_Masshou`,e[e.Fujitsu_Touroku=148]=`Fujitsu_Touroku`,e[e.Fujitsu_Loya=149]=`Fujitsu_Loya`,e[e.Fujitsu_Roya=150]=`Fujitsu_Roya`,e[e.LeftShift=160]=`LeftShift`,e[e.RightShift=161]=`RightShift`,e[e.LeftControl=162]=`LeftControl`,e[e.RightControl=163]=`RightControl`,e[e.LeftMenu=164]=`LeftMenu`,e[e.RightMenu=165]=`RightMenu`,e[e.BrowserBack=166]=`BrowserBack`,e[e.BrowserForward=167]=`BrowserForward`,e[e.BrowserRefresh=168]=`BrowserRefresh`,e[e.BrowserStop=169]=`BrowserStop`,e[e.BrowserSearch=170]=`BrowserSearch`,e[e.BrowserFavorites=171]=`BrowserFavorites`,e[e.BrowserHome=172]=`BrowserHome`,e[e.VolumeMute=173]=`VolumeMute`,e[e.VolumeDown=174]=`VolumeDown`,e[e.VolumeUp=175]=`VolumeUp`,e[e.MediaNextTrack=176]=`MediaNextTrack`,e[e.MediaPrevTrack=177]=`MediaPrevTrack`,e[e.MediaStop=178]=`MediaStop`,e[e.MediaPlayPause=179]=`MediaPlayPause`,e[e.LaunchMail=180]=`LaunchMail`,e[e.LaunchMediaSelect=181]=`LaunchMediaSelect`,e[e.LaunchApplication1=182]=`LaunchApplication1`,e[e.LaunchApplication2=183]=`LaunchApplication2`,e[e.OEM1=186]=`OEM1`,e[e.OEMPlus=187]=`OEMPlus`,e[e.OEMComma=188]=`OEMComma`,e[e.OEMMinus=189]=`OEMMinus`,e[e.OEMPeriod=190]=`OEMPeriod`,e[e.OEM2=191]=`OEM2`,e[e.OEM3=192]=`OEM3`,e[e.OEM4=219]=`OEM4`,e[e.OEM5=220]=`OEM5`,e[e.OEM6=221]=`OEM6`,e[e.OEM7=222]=`OEM7`,e[e.OEM8=223]=`OEM8`,e[e.OEMAX=225]=`OEMAX`,e[e.OEM102=226]=`OEM102`,e[e.ICOHelp=227]=`ICOHelp`,e[e.ICO00=228]=`ICO00`,e[e.ProcessKey=229]=`ProcessKey`,e[e.ICOClear=230]=`ICOClear`,e[e.Packet=231]=`Packet`,e[e.OEMReset=233]=`OEMReset`,e[e.OEMJump=234]=`OEMJump`,e[e.OEMPA1=235]=`OEMPA1`,e[e.OEMPA2=236]=`OEMPA2`,e[e.OEMPA3=237]=`OEMPA3`,e[e.OEMWSCtrl=238]=`OEMWSCtrl`,e[e.OEMCUSel=239]=`OEMCUSel`,e[e.OEMATTN=240]=`OEMATTN`,e[e.OEMFinish=241]=`OEMFinish`,e[e.OEMCopy=242]=`OEMCopy`,e[e.OEMAuto=243]=`OEMAuto`,e[e.OEMENLW=244]=`OEMENLW`,e[e.OEMBackTab=245]=`OEMBackTab`,e[e.ATTN=246]=`ATTN`,e[e.CRSel=247]=`CRSel`,e[e.EXSel=248]=`EXSel`,e[e.EREOF=249]=`EREOF`,e[e.Play=250]=`Play`,e[e.Zoom=251]=`Zoom`,e[e.Noname=252]=`Noname`,e[e.PA1=253]=`PA1`,e[e.OEMClear=254]=`OEMClear`,e}({});const He=n({game:`string`,type:`string`,creationTime:`number`}),Ue=He.and({game:`'siege' | 'tft'`,type:`'logged_in'`,content:{accountId:`string`}}),We=He.and({game:`'sand'`,type:`'logged_in'`,content:{accountId:`string`,displayName:`string`,platformId:`string`,playfabId:`string`}}).or(Ue),Ge=He.and({game:`'siege' | 'tft' | 'sand'`}),Ke=Ge.and({type:`'module_loaded'`,content:{gameVersion:`string`,processHash:`string`}}),qe=Ge.and({type:`'module_unloaded'`}),Je=Ge.and({type:`'unsupported_game_version'`,content:{gameVersion:`string`,processHash:`string`}}),Ye=t({"#event1":`logged_in | module_loaded | module_unloaded | unsupported_game_version`,event:`event1`,logged_in:We,module_loaded:Ke,module_unloaded:qe,unsupported_game_version:Je}).export(),Xe=Object.keys(Ye).filter(e=>e!==`event`);function z(){return{key:`universal`,events:Ye}}var Ze=class{options=null;logger;initialized=!1;constructor(e){this.logger=L.getInstance().scope(e)}init(e){this.logger.log(`Initializing`),this.options=e||null,this.initialized=!0}destroy(){this.logger.log(`Destroying`),this.initialized=!1}},B=class extends A{options=null;logger;initialized=!1;constructor(e){super(),this.logger=L.getInstance().scope(e)}init(e){this.logger.log(`Initializing`),this.options=e||null,this.initialized=!0}destroy(){this.logger.log(`Destroying`),this.initialized=!1,this.removeAllListeners()}},Qe=class extends j{options=null;logger;initialized=!1;constructor(e){super(),this.logger=L.getInstance().scope(e)}init(e){this.logger.log(`Initializing`),this.options=e||null,this.initialized=!0}destroy(){this.logger.log(`Destroying`),this.initialized=!1,this.removeAllListeners()}};const $e=`https://api.overlayed.gg`,V=re.create({baseURL:$e,paramsSerializer:e=>ie(e,!0,null,{arrayFormat:`repeat`}),headers:{Accept:`application/json`,"Accept-Encoding":`gzip, deflate, br`}});let et;function tt(e){et=e}let nt;function rt(e){nt=e}function it(e){return`overlayed/app (${Object.entries(e).map(([e,t])=>`${e}=${t}`).join(`, `)})`}V.interceptors.request.use(e=>{let t=et?.();e.headers??={},t&&(e.headers[`X-Api-Key`]=t);let n=nt?.();return n&&(e.headers[`User-Agent`]=it(n)),e});function at(e,t){if(t<=0)throw Error(`Chunk size must be greater than 0`);if(e.length===0)return[];let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function ot(e){return e}function H(e){return e?t=>(e(t),t):ot}const st=H();function ct(e){return V.get(`/v1/public/applications/${e}`)}function lt(e,t){return V.get(`/v1/public/applications/${e}/releases/check`,{params:t})}function U(e,t){return V.post(`/v1/public/applications/${e}/game-crash-reports`,t)}function ut(e,t,n){return V.post(`/v1/public/applications/${e}/game-crash-reports/${t}/confirm`,n)}function dt(e,t){let n=new FormData;return n.append(`file`,new Blob([t.file],{type:`application/zip`}),`logs.zip`),n.append(`data`,JSON.stringify(t.data)),V.post(`/v1/public/applications/${e}/feedbacks`,n)}function ft(e,t){return V.get(`/v1/public/applications/${e}/feature-flags`,{params:t})}function pt(e,t){return V.get(`/v1/public/applications/${e}/notices`,{params:t})}const mt=H();function ht(e,t){return V.get(`/v1/public/modules/${e}/release`,{params:{cortex_user_id:t}})}function gt(e,t,n){return V.post(`/v1/public/modules/${e}/releases/${t}/download`,n)}async function _t(e,t){if(e.method!==`GET`)throw Error(`Unsupported presigned request method: ${e.method}`);let n=await fetch(e.url,{method:e.method,headers:e.headers,signal:t?.signal});if(!n.ok){let e=await yt(n);throw Error(`Presigned download failed (${n.status} ${n.statusText})${e?`: ${e}`:``}`)}let r=await n.arrayBuffer();return new Uint8Array(r)}async function vt(e,t){if(e.method!==`PUT`)throw Error(`Unsupported presigned request method: ${e.method}`);let n=await fetch(e.url,{method:e.method,headers:{...e.headers,"Content-Length":t.byteLength.toString()},body:t});if(!n.ok){let e=await yt(n);throw Error(`Presigned upload failed (${n.status} ${n.statusText})${e?`: ${e}`:``}`)}}async function yt(e){try{let t=(await e.text()).trim();if(t.length===0)return;let n=2048;return t.length>n?`${t.slice(0,n)}…`:t}catch{return}}function bt(){return V.get(`/v1/public/raven/config`)}const xt=H();function St(e,t){return V.get(`/v1/public/raven/games/${e}/builds/${t}`)}function Ct(e,t){return V.post(`/v1/public/raven/games/${e}/builds/upload`,null,{params:t})}function wt(e,t){let{chunk:n,...r}=t,i=new FormData;return i.append(`file`,n),V.patch(`/v1/public/raven/games/${e}/builds/upload`,i,{params:r})}function Tt(e){let t=Date.now(),n=e.messages.filter(e=>t-e.created_at.getTime()<6e5),r=e.messages.length-n.length;r>0&&console.warn(`Dropped ${r} cortex event(s) older than 600s`);let i=at(n.map(e=>Et(t,e)),50),a=Promise.all(i.map(async t=>V.post(`/v1/public/cortex/events`,{...e,messages:t})));return a.catch(e=>{let t=e?.response?.data||e?.message||e;console.error(`Failed to submit cortex events`,t)}),a}function Et(e,t){let n=e-t.created_at.getTime(),r=Math.max(0,Math.floor(n/1e3));return{properties:t.properties,type:t.type,seconds_offset:r}}function Dt(e){return e instanceof Error&&(e.name===`XiorError`||e.name===`XiorTimeoutError`)}function Ot(e){return!!(e&&`kind`in e.data&&`message`in e.data)}const{PipeEventServer:kt,PipeEventClient:At,PipeEventBase:W,GameMonitor:jt,GameInstance:Mt,HardwareInterface:Nt}=e(import.meta.url)(`@overlayed/app/dist/native-interface/build/overlayed_native_interface_x64.node`);function Pt(e=[]){return h.normalize(h.join(we(global.OVERLAYED.APPLICATION_ID),...e))}const Ft=n({game:`string`,type:`string`,creationTime:`number`}),G=new ve({path:P(),schema:n({userId:`string | undefined`,sessionId:`string | undefined`,sessionLastUsed:`number | undefined`,accessToken:`string | undefined`,accessTokenChannel:`string | undefined`,"debug?":{"ri_disabled?":`boolean`,"gm_disabled?":`boolean`}}),default:{userId:void 0,sessionId:void 0,sessionLastUsed:void 0,accessToken:void 0,accessTokenChannel:void 0}});function It(){let{debug:e}=G.get();return e?{ri_disabled:e.ri_disabled??!1,gm_disabled:e.gm_disabled??!1}:{ri_disabled:!1,gm_disabled:!1}}function Lt(){let e=G.get().userId;if(e)return e;let t=Ht();return G.set({...G.get(),userId:t}),t}function Rt(){let e=G.get();if(e.sessionId&&typeof e.sessionLastUsed==`number`&&Date.now()-e.sessionLastUsed<=3e5)return e.sessionId;let t=crypto.randomUUID();return G.set({...e,sessionId:t,sessionLastUsed:Date.now()}),t}function zt(){try{let e=G.get();G.set({...e,sessionLastUsed:Date.now()})}catch(e){L.getInstance().log(`Failed to update sessionLastUsed`,e)}}function K(){return G.get().accessToken}function Bt(){return G.get().accessTokenChannel}function Vt(e,t){try{let n=G.get();G.set({...n,accessToken:e??void 0,accessTokenChannel:e?t:void 0})}catch(e){L.getInstance().log(`Failed to set accessToken`,e)}}function Ht(){try{return Nt.generateUniqueIdentifier()}catch{return crypto.randomUUID()}}function Ut(e,...t){let n=h.join(e,...t);if(!h.resolve(n).startsWith(h.resolve(e)+h.sep))throw Error(`Path escapes ${e}: ${n}`);return n}const Wt=M(class extends B{UPDATE_CHECK_INTERVAL_MS=3e5;targetDir;updateInterval;constructor(){super(`NativeModuleManager`),this.targetDir=h.join(Se(),`resources`),this.logger.log(`Target directory`,this.targetDir)}async initWithDlls(e){super.init(),await D.mkdir(this.targetDir,{recursive:!0}),await this.checkForUpdates(e),clearInterval(this.updateInterval),this.updateInterval=setInterval(()=>this.checkForUpdates(e),this.UPDATE_CHECK_INTERVAL_MS)}destroy(){this.updateInterval&&=(clearInterval(this.updateInterval),void 0),super.destroy()}async getDllFile(e){if(!he(e)){this.logger.error(`Invalid module id`,{moduleId:e});return}let t=await this.getCurrentBuildInfo(e);if(!t){this.logger.error(`No build found for module`,{moduleId:e});return}let n=this.getBuildPath(e,t.buildId);if(!S(n)){this.logger.error(`No build file found for module`,{moduleId:e});return}let r=this.getBuildFilePath(e,t.buildId,t.buildFileName);if(!S(r))this.logger.error(`No DLL file found for module`,{moduleId:e});else return r}async getCurrentBuildInfo(e){try{let t=this.resolvePath(e,`build.json`),n=await D.readFile(t,`utf-8`),r=JSON.parse(n);return!he(r.buildId)||!this.isDllFileName(r.buildFileName)?(this.logger.error(`Ignoring invalid build info for module`,{moduleId:e,buildInfo:r}),null):r}catch{return null}}getModulePath(e){return this.resolvePath(e)}getBuildPath(e,t){return this.resolvePath(e,t)}resolvePath(...e){return Ut(this.targetDir,...e)}getBuildFilePath(e,t,n){return this.resolvePath(e,t,n)}isDllFileName(e){return typeof e==`string`&&!/[\\/:*?"<>|\x00-\x1f]/.test(e)&&e!==`.`&&e!==`..`&&e.toLowerCase().endsWith(`.dll`)}findHashMismatch(e,t){let n=T(`sha256`).update(e).digest(`hex`);return n===t.toLowerCase()?void 0:n}async checkForUpdates(e){this.logger.log(`Checking for updates`);let t=Lt();if(!t)this.logger.error(`Failed to resolve cortex user id`);else{this.logger.log(`Cortex User ID`,t);for(let n of e)if(!he(n))this.logger.error(`Skipping module with invalid id`,{moduleId:n});else try{let{data:e}=await ht(n,t);if(this.logger.log(`Release`,e),!he(e.build_id)||!this.isDllFileName(e.build_file_name)){this.logger.error(`${n} > Release has an invalid build id or file name`,{buildId:e.build_id,buildFileName:e.build_file_name});continue}let r=(await this.getCurrentBuildInfo(n))?.buildId||null;if(this.logger.log(`${n} > Performing update check. current: ${r}, requested: ${e.build_id}`),e.build_id!==r||await this.isDownloadCorrupted(n,e)){if(this.logger.log(`${n} > Update found. current: ${r}, requested: ${e.build_id}`),this.logger.log(`${n} > Downloading and extracting DLLs`),!await this.downloadAndExtractDll(n,e)){this.logger.error(`${n} > Download failed, keeping existing builds`);continue}this.logger.log(`${n} > Cleaning up other builds`),await this.cleanupExistingBuilds(n,e.build_id),this.emit(`dllUpdated`,{moduleId:n,buildId:e.build_id,releaseId:e.release_id})}else this.logger.log(`${n} > No update found`)}catch(e){this.logger.error(`${n} > Error checking/updating`,e)}}}async downloadAndExtractDll(e,t){this.logger.log(`${e} > Requesting download for build ${t.build_id}`);let n=Lt();if(!n)return this.logger.error(`Failed to resolve cortex user id`),!1;let{data:r}=await gt(e,t.release_id,{download_token:t.download_token,cortex_user_id:n});this.logger.log(`${e} > Downloading DLLs for build ${t.build_id}`);let i=await _t(r,{signal:AbortSignal.timeout(3e5)});this.logger.log(`${e} > Downloaded zip file for build ${t.build_id}`);let a=new ae;await a.loadAsync(i);let o=Object.keys(a.files).map(e=>({name:e,file:a.files[e]})).filter(({file:e})=>!e.dir);if(o.length!==1)return this.logger.error(`${e} > Zip must contain exactly 1 file, got ${o.length}`),!1;let s=o[0];if(h.basename(s.name).toLowerCase()!==t.build_file_name.toLowerCase())return this.logger.error(`${e} > Zip entry ${s.name} does not match build file ${t.build_file_name}`),!1;let c=await s.file.async(`nodebuffer`),l=t.build_hash&&this.findHashMismatch(c,t.build_hash);if(l)return this.logger.error(`${e} > Build file hash mismatch: ${l} !== ${t.build_hash}`),!1;let u=this.getBuildFilePath(e,t.build_id,t.build_file_name);await D.mkdir(h.dirname(u),{recursive:!0}),await D.writeFile(u,c),this.logger.log(`${e} > Extracted 1 file to ${u}`);let d={buildId:t.build_id,buildFileName:t.build_file_name},f=this.resolvePath(e,`build.json`);return await D.writeFile(f,JSON.stringify(d),`utf-8`),this.logger.log(`${e} > Saved buildId to file: ${t.build_id}`),!0}async cleanupExistingBuilds(e,t){let n=this.getModulePath(e),r=this.getBuildPath(e,t),i=await D.readdir(n,{withFileTypes:!0});for(let t of i){let n=this.resolvePath(e,t.name);t.isDirectory()&&n!==r&&(await D.rm(n,{recursive:!0,force:!0}),this.logger.log(`${e} > Cleaned up build: ${t.name}`))}}async hasPathAccess(e){try{return await D.access(e,D.constants.F_OK),!0}catch{return!1}}async isDownloadCorrupted(e,t){let n=this.getBuildPath(e,t.build_id);if(!await this.hasPathAccess(n))return this.logger.error(`Download is corrupted. Path does not exist: ${n}`),!0;let r=t.build_file_name,i=this.getBuildFilePath(e,t.build_id,r);if(!S(i))return this.logger.error(`Download is corrupted. Build file not found: ${i}`),!0;if(t.build_hash){let e=this.findHashMismatch(await D.readFile(i),t.build_hash);if(e)return this.logger.error(`Download is corrupted. Build file hash mismatch: ${r} ${e} !== ${t.build_hash}`),!0}return!1}}),Gt=M(class extends B{_gameMonitor;_games=/* @__PURE__ */ new Map;constructor(){super(`GameManager`),this._gameMonitor=new jt}get hasAnyActiveGames(){return this._games.size>0}init(){super.init(),this._gameMonitor.on(`launch`,e=>{this.logger.log(`Game launched`,e.identifier,e.processId),this._games.set(e.processId,e),this.logger.log(`Active Game Count: ${this._games.size}`),this.emit(`launch`,{game:e})}),this._gameMonitor.on(`close`,e=>{this.logger.log(`Game closed`,e.identifier,e.processId),this._games.delete(e.processId),this.logger.log(`Active Game Count: ${this._games.size}`),this.emit(`close`,{game:e})})}destroy(){this._games.clear(),this._gameMonitor.removeAllListeners(),super.destroy()}}),Kt=M(class extends B{REFETCH_INTERVAL=3e5;FAILED_REFETCH_INTERVAL=3e4;_refetchIntervalHandler=null;_failedRefetchTimeoutHandler=null;_ready;_resolveReady;constructor(){super(`RavenManager`),this._ready=new Promise(e=>{this._resolveReady=e})}get ready(){return this._ready}init(e){super.init(e),this.fetchRavenConfig(),this._refetchIntervalHandler=setInterval(()=>{this._failedRefetchTimeoutHandler&&=(clearTimeout(this._failedRefetchTimeoutHandler),null),this.fetchRavenConfig()},this.REFETCH_INTERVAL)}destroy(){this._refetchIntervalHandler&&clearInterval(this._refetchIntervalHandler),this._failedRefetchTimeoutHandler&&clearTimeout(this._failedRefetchTimeoutHandler),Wt.getInstance().destroy(),super.destroy()}async fetchRavenConfig(){try{let e=await bt();if(!this.initialized)return;let t=new Set(this.options?.subscribedGames??[]),n=/* @__PURE__ */ new Set;for(let r of e.data.games)(t.has(`*`)||t.has(r.identifier))&&r.game_module&&n.add(r.game_module);n.size===0&&e.data.games.length>0&&this.logger.warn(`No raven game matched the subscribed games`,{subscribed:Array.from(t),available:e.data.games.map(e=>e.identifier)}),await Wt.getInstance().initWithDlls(Array.from(n)),this.logger.log(`Raven updated, tracking ${n.size} game modules`),this._resolveReady()}catch(e){this.logger.error(`Failed to fetch Raven config`,e),this._failedRefetchTimeoutHandler=setTimeout(()=>this.fetchRavenConfig(),this.FAILED_REFETCH_INTERVAL)}}});var qt=class{_instance;_resolution;boundOnResolutionChanged=this.onResolutionChanged.bind(this);constructor(e){this._instance=e,this._resolution={width:0,height:0},this._instance.on(`resolution`,this.boundOnResolutionChanged)}destroy(){this._instance.off(`resolution`,this.boundOnResolutionChanged)}get instance(){return this._instance}get resolution(){return this._resolution}onResolutionChanged(e,t){this._resolution={width:e,height:t}}};const Jt=M(class{interfaces={};constructor(){}createInterface(e){return this.interfaces[e]||(this.interfaces[e]=new qt(new ze(e,{access:1}))),this.interfaces[e]}getInterface(e){return this.interfaces[e]?this.interfaces[e]:this.createInterface(e)}}),q=M(class{options;eventQueue;meta=null;enabled=!0;constructor(e){this.options=this.resolveOptions(e),this.eventQueue=new ge,this.setupFlushInterval()}track(e,t){this.enabled&&this.eventQueue.add({type:e,properties:t,created_at:/* @__PURE__ */ new Date})}flush(){if(!this.enabled)return[];let e=Array.from(this.eventQueue.flush()).concat({type:`ping`,properties:{},created_at:/* @__PURE__ */ new Date});if(!this.meta)throw Error(`Tried to flush Cortex events before meta was set`);try{Tt({...this.meta,messages:e})}catch{}return e}setupFlushInterval(){this.enabled&&setInterval(()=>{this.flush()},this.options.batchIntervalSeconds*1e3)}resolveOptions(e){return{batchIntervalSeconds:e?.batchIntervalSeconds??15}}}),Yt=e(import.meta.url),Xt=Yt.resolve(`@overlayed/app/dist/render-interface/build/overlayed_render_hook_x64.dll`),Zt=Yt.resolve(`@overlayed/app/dist/render-interface/build/overlayed_render_hook_x86.dll`),Qt=Yt.resolve(`@overlayed/app/dist/native-interface/build/overlayed_injector_x64.exe`),$t=Yt.resolve(`@overlayed/app/dist/native-interface/build/overlayed_injector_x86.exe`),J=M(class extends Qe{boundOnGameLaunch=this.onGameLaunch.bind(this);boundOnGameClose=this.onGameClose.bind(this);subscribedGames=/* @__PURE__ */ new Set;activeGames=/* @__PURE__ */ new Map;pendingLaunches=/* @__PURE__ */ new Map;sessions=/* @__PURE__ */ new Map;get isInGame(){return this.activeGames.size>0}constructor(){super(`GameLaunchManager`)}setSubscribedGames(e){this.subscribedGames=new Set(e)}getActiveGames(){return Array.from(new Set(Array.from(this.activeGames.values()).map(e=>e.game)))}init(){super.init(),Jt.getInstance().createInterface(`OGG_SIEGE`),Gt.getInstance().on(`launch`,this.boundOnGameLaunch),Gt.getInstance().on(`close`,this.boundOnGameClose)}endActiveSessions(){for(let e of this.sessions.values())this.trackSessionEnd(e,`app_quit`);this.sessions.clear()}destroy(){this.endActiveSessions(),Gt.getInstance().off(`launch`,this.boundOnGameLaunch),Gt.getInstance().off(`close`,this.boundOnGameClose),super.destroy()}on(e,t){super.on(e,t);let n=me(e);if(!(n.includes(`gameReady`)||n.includes(`*`))||this.activeGames.size===0)return;let r=t;for(let e of this.activeGames.values())this.logger.log(`Late calling gameReady callback for game`,e.game),r(e)}async onGameLaunch({game:e}){this.logger.log(`On game launch`,e.identifier,e.executableName,e.processId);let t=xt(e.identifier);q.getInstance().track(`game_launch`,{game:t});let n={id:crypto.randomUUID(),game:t,startedAt:performance.now(),subscribed:!1,ready:!1,renderSupported:!1};if(this.sessions.set(e.processId,n),this.subscribedGames.size===0){this.logger.warn(`No subscribed games, skipping`);return}if(!this.subscribedGames.has(t)&&!this.subscribedGames.has(`*`))return;n.subscribed=!0;let r=new AbortController;if(this.pendingLaunches.set(e.processId,r),await this.emit(`gameLaunch`,{game:t,processId:e.processId,reject:()=>r.abort()}),r.signal.aborted)return;if(this.logger.log(`Game Launched`,e.identifier),this.logger.log(`Game is elevated: `,e.isElevated),e.hasElevationMismatch){_e.getInstance().fatal(`Game is elevated but the App is not`,`ELEVATION_MISMATCH`,{appElevated:!1,gameElevated:!0}),this.logger.log(`Game elevated but App is not`);return}if(e.injectionDelayMs>0){if(this.logger.log(`Delaying injection for ${e.injectionDelayMs}ms to allow game to be ready`),await new Promise(t=>{let n=setTimeout(t,e.injectionDelayMs);r.signal.addEventListener(`abort`,()=>{clearTimeout(n),t()},{once:!0})}),r.signal.aborted){this.logger.log(`Game closed during the injection delay, skipping injection`);return}this.logger.log(`Finished delay`)}let{ri_disabled:i,gm_disabled:a}=It(),o=!1;if(!i&&e.hasRenderSupport&&e.allowDllInjections?o=await this.injectRenderInterface(e):this.logger.log(`Skipping render interface injection`,{has_render_support:e.hasRenderSupport,allow_dll_injections:e.allowDllInjections,ri_disabled:i}),!a&&e.allowDllInjections?await this.injectGameModules(e):this.logger.log(`Skipping game module(s) injection`,{allow_dll_injections:e.allowDllInjections,gm_disabled:a}),r.signal.aborted){this.logger.log(`Game closed during injection, skipping ready`);return}this.pendingLaunches.delete(e.processId);let s={game:t,processId:e.processId,inGameRenderingSupported:o};this.activeGames.set(e.processId,s),this.logger.debug(`Active games`,this.getActiveGames().join(`, `)),n.ready=!0,n.renderSupported=o,n.readyAt=performance.now(),this.logger.log(`Game Ready`),this.emit(`gameReadyInternal`,{game:e}),this.emit(`gameReady`,s),q.getInstance().track(`game_ready`,{game:t})}trackSessionEnd(e,t){q.getInstance().track(`game_session_end`,{game:e.game,game_session_id:e.id,duration_ms:Math.round(performance.now()-e.startedAt),subscribed:e.subscribed,ready:e.ready,render_supported:e.renderSupported,...e.readyAt!==void 0&&{time_to_ready_ms:Math.round(e.readyAt-e.startedAt)},end_reason:t})}copyInjectors(){let e=this.copyDll(Qt),t=this.copyDll($t);return!e||!t?(this.logger.error(`Failed to copy injector executables`),!1):h.dirname(e)}copyDll(e){let t=h.basename(e),n=_(e),r=h.join(Se(),`resources`),i=h.join(r,t);this.logger.info(`Copying`,n,`to`,i);try{S(r)||C(r,{recursive:!0}),b(n,i)}catch(e){return e.code===`EBUSY`?i:(this.logger.error(`Failed to copy`,e),this.logger.error(`Failed to copy`,{originalPath:n,targetPath:i}),!1)}return i}async injectRenderInterface(e){this.logger.log(`Injecting render interface`,{is32Bit:e.is32Bit,game:e.identifier});let t=e.is32Bit?Zt:Xt;this.logger.log(`Render hook path`,t);let n=this.copyDll(t);if(!n)return this.logger.error(`Failed to copy render hook DLL`,{renderHookPath:t}),!1;let r=this.copyInjectors();if(!r)return!1;this.logger.log(`Resolved injector path`,r);try{return this.logger.log(`Injecting render interface`,n),await e.injectDll(n,r),this.logger.log(`Render Interface Injection Successful`,n),!0}catch(e){return this.logger.error(`Render Interface Injection Failed`,e),this.logger.error(`Render Interface Injection Failed`,{renderHookPathCopied:n}),!1}}async injectGameModules(e){let t=this.copyInjectors();if(t){this.logger.log(`Resolved injector path`,t),await Kt.getInstance().ready;for(let n of e.modules){let r=await Wt.getInstance().getDllFile(n);if(!r)this.logger.error(`No DLL file found for module`,{moduleId:n});else try{this.logger.log(`Injecting game module`,r),await e.injectDll(r,t),this.logger.log(`Injection Successful`,r)}catch(e){this.logger.error(`Injection Failed`,{dllFile:r},e)}}}}async onGameClose({game:e}){let t=xt(e.identifier);this.pendingLaunches.get(e.processId)?.abort(),this.pendingLaunches.delete(e.processId),this.activeGames.delete(e.processId),this.logger.debug(`Active games`,this.getActiveGames().join(`, `));let n=this.sessions.get(e.processId);n&&(this.sessions.delete(e.processId),this.trackSessionEnd(n,`game_closed`)),this.emit(`gameCloseInternal`,{game:e}),this.emit(`gameClose`,{game:t,processId:e.processId}),q.getInstance().track(`game_close`,{game:t})}}),en=M(class extends Ze{boundOnGameLaunch=this.onGameLaunch.bind(this);boundOnGameClose=this.onGameClose.bind(this);pendingBuilds=/* @__PURE__ */ new Map;constructor(){super(`GameBuildManager`)}init(){super.init(),J.getInstance().on(`gameReadyInternal`,this.boundOnGameLaunch),J.getInstance().on(`gameCloseInternal`,this.boundOnGameClose)}destroy(){J.getInstance().off(`gameReadyInternal`,this.boundOnGameLaunch),J.getInstance().off(`gameCloseInternal`,this.boundOnGameClose),super.destroy()}onGameClose(...e){let[{game:t}]=e;this.pendingBuilds.get(t.processId)?.abort(),this.pendingBuilds.delete(t.processId)}async onGameLaunch(...e){let[{game:t}]=e;if(!t.executablePath||!t.executableName){this.logger.error(`Executable path or name not found, could not check for build hash`,void 0,t.identifier);return}let n=xt(t.identifier),r=new AbortController;this.pendingBuilds.set(t.processId,r);try{await this.checkBuild(t.executablePath,t.executableName,t,n,r.signal)}finally{this.pendingBuilds.delete(t.processId)}}async checkBuild(e,t,n,r,i){let a;try{a=await n.computeBuildHash()}catch(e){this.logger.error(`Error hashing the game build`,e);return}if(i.aborted){this.logger.log(`Game closed while hashing the build, skipping the upload`);return}this.logger.log(`Executable Path`,e),this.logger.log(`Executable Name`,t),this.logger.log(`Build Hash`,a);let o=!1;try{o=(await St(r,a)).data.upload}catch(e){this.logger.error(`Error checking game build hash`,e);return}if(!o){this.logger.log(`Build hash already exists, skipping upload`);return}if(i.aborted){this.logger.log(`Game closed before the build was read, skipping the upload`);return}let s=new ae;s.file(t,await ne(e));let c=await s.generateAsync({type:`blob`});try{this.logger.log(`Uploading build (size: `,c.size,` bytes)`);let e=new R(c,{chunkSizeMb:25,maxConcurrent:1}),t=await Ct(r,{build_hash:a,chunk_count:e.totalChunks,file_size_bytes:c.size});await e.chunk(async(e,n)=>{this.logger.log(`Uploading chunk`,n),await wt(r,{chunk:e,build_hash:a,chunk_index:n,upload_token:t.data.upload_token})}),this.logger.log(`Build uploaded successfully`)}catch(e){Dt(e)?Ot(e.response)?this.logger.error(`Error uploading build hash, api error`,e):this.logger.error(`Error uploading build hash, request error`,e):this.logger.error(`Error uploading build hash, unknown error`,e)}}}),tn=M(class extends Ze{constructor(){super(`CampaignManager`)}async check(e){let t=h.join(we(e),`campaign_code.txt`);try{let e=(await E.readFile(t,`utf-8`)).trim().replace(/ \(\d+\)/g,``);e&&(this.logger.log(`UTM campaign code found`,e),q.getInstance().track(`utm_attribution`,{campaign_code:e}),q.getInstance().flush())}catch{}}}),nn=[`lcp`,`inp`,`fcp`,`ttfb`];function rn({protocol:e,pathname:t,hash:n}){let r=e===`file:`?t.slice(t.lastIndexOf(`/`)):t;if(n.startsWith(`#/`)){let e=n.indexOf(`?`);r+=e===-1?n:n.slice(0,e)}return r.slice(0,512)}const an={reason:128,processType:128,processName:256,game:128,errorName:256,message:512,stack:4096},on=[/[A-Za-z]:[\\/]+Users[\\/]+[^\\/\r\n"'`)]+/gi,/\/(?:Users|home)\/[^/\s"'`)]+/g];function sn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function cn(e,t){let n=e,r=te.homedir();if(r){let e=sn(r).replace(/\\\\|\//g,`[\\\\/]`);n=n.replace(new RegExp(e,`gi`),`~`)}for(let e of on)n=n.replace(e,`~`);return n.slice(0,t)}function ln(e){return e.replace(/:\d+(?::\d+)?(?=\)?$)/,``).replace(/(?:file:\/\/\/?)?[^\s()]*[\\/]/g,``).trim()}function un(e,t,n){let r=(n??``).split(`
|
|
16
16
|
`).map(e=>e.trim()).filter(e=>e.startsWith(`at `)).slice(0,5).map(ln),i=r.length>0?[e,...r]:[e,t];return T(`sha256`).update(i.join(`
|
|
17
|
-
`)).digest(`hex`).slice(0,32)}function dn(e){try{let t=e();return typeof t==`string`?t:``}catch{return``}}function fn(e){try{return e instanceof Error}catch{return!1}}function pn(e){let t,n,r;fn(e)?(t=dn(()=>e.name)||`Error`,n=dn(()=>e.message),r=dn(()=>e.stack)||void 0):(t=e===null?`null`:typeof e,n=typeof e==`string`?e:dn(()=>JSON.stringify(e))||dn(()=>String(e))||`[unserializable]`);let i={name:cn(t,an.errorName),message:cn(n,an.message),fingerprint:``};return r&&(i.stack=cn(r,an.stack)),i.fingerprint=un(i.name,i.message,i.stack),i}function mn(e){return URL.canParse(e)?rn(new URL(e)):``}const hn=n({kind:`'uncaught_exception' | 'unhandled_rejection'`,name:`string`,message:`string`,"stack?":`string`,fingerprint:`string`,crashedAt:`number`}),gn=n({pid:`number`,sessionId:`string`,releaseId:`string`,appVersion:`string`,startedAt:`number`,lastHeartbeatAt:`number`,inGame:`boolean`,"game?":`string`,"exception?":hn,"shutdown?":`boolean`,"quit?":`boolean`}),_n=/* @__PURE__ */ new Set([`clean-exit`]),vn=/* @__PURE__ */ new WeakMap;function yn(e,t){vn.set(e,{inGame:t,createdAt:Date.now()})}function bn(e,t){return{type:e,properties:t,created_at:/* @__PURE__ */ new Date}}const xn=M(class extends Ze{state=null;statePath=null;heartbeatInterval;survivalTimeout;exceptionCount=0;exceptionCountByFingerprint=/* @__PURE__ */ new Map;boundOnRenderProcessGone=this.onRenderProcessGone.bind(this);boundOnChildProcessGone=this.onChildProcessGone.bind(this);boundOnUncaughtException=this.onUncaughtException.bind(this);boundOnGameStateChange=this.onGameStateChange.bind(this);boundOnBrowserWindowCreated=this.onBrowserWindowCreated.bind(this);boundOnShutdown=this.onShutdown.bind(this);boundOnExit=this.onExit.bind(this);boundOnQuit=this.onQuit.bind(this);constructor(){super(`AppCrashManager`)}init(e){super.init(e),O.on(`render-process-gone`,this.boundOnRenderProcessGone),O.on(`child-process-gone`,this.boundOnChildProcessGone),process.on(`uncaughtExceptionMonitor`,this.boundOnUncaughtException),this.reportPreviousSessions(e.stateDir),this.startSession(e.stateDir)}destroy(){O.off(`render-process-gone`,this.boundOnRenderProcessGone),O.off(`child-process-gone`,this.boundOnChildProcessGone),O.off(`browser-window-created`,this.boundOnBrowserWindowCreated),O.off(`quit`,this.boundOnQuit),process.off(`uncaughtExceptionMonitor`,this.boundOnUncaughtException),process.off(`exit`,this.boundOnExit),J.getInstance().off([`gameReady`,`gameClose`],this.boundOnGameStateChange),O.isReady()&&se.off(`shutdown`,this.boundOnShutdown),clearInterval(this.heartbeatInterval),clearTimeout(this.survivalTimeout),this.heartbeatInterval=void 0,this.survivalTimeout=void 0,this.state=null,this.statePath=null,this.exceptionCount=0,this.exceptionCountByFingerprint.clear(),super.destroy()}startSession(e){let t=Date.now();this.statePath=m.join(e,`${process.pid}-${t}.json`),this.state={pid:process.pid,sessionId:global.OVERLAYED.sessionId,releaseId:global.OVERLAYED_META.release.id??``,appVersion:global.OVERLAYED.APP_VERSION,startedAt:t,lastHeartbeatAt:t,inGame:!1},this.updateGameState(),this.writeState(),this.heartbeatInterval=setInterval(()=>{this.state&&(this.state.lastHeartbeatAt=Date.now(),this.writeState())},3e4),this.heartbeatInterval.unref(),J.getInstance().on([`gameReady`,`gameClose`],this.boundOnGameStateChange),O.on(`quit`,this.boundOnQuit),process.on(`exit`,this.boundOnExit),O.on(`browser-window-created`,this.boundOnBrowserWindowCreated);for(let e of oe.getAllWindows())e.once(`session-end`,this.boundOnShutdown);O.whenReady().then(()=>{this.state&&se.on(`shutdown`,this.boundOnShutdown)})}async reportPreviousSessions(e){let t;try{t=y.readdirSync(e)}catch{return}let n=[];for(let r of t){let t=/^(.+\.json)\.claimed-(\d+)$/.exec(r);if(!r.endsWith(`.json`)&&(!t||this.isProcessAlive(Number(t[2]))))continue;let i=m.join(e,t?t[1]:r),a=m.join(e,r),o=this.readState(a);if(o===void 0||o!==null&&!t&&this.isLiveInstance(o))continue;if(o===null||(o.shutdown||o.quit)&&!o.exception){this.removeFile(a);continue}let s=`${i}.claimed-${process.pid}`;try{y.renameSync(a,s)}catch{continue}n.push({originalPath:i,claimedPath:s,state:o})}let r=q.getInstance().meta;for(let{originalPath:e,claimedPath:t,state:i}of n)try{if(!r)throw Error(`Cortex meta is not set`);await Tt({...r,messages:this.getPreviousSessionMessages(i)}),this.removeFile(t)}catch(n){this.logger.warn(`Failed to report previous session, retrying on next launch`,n);try{y.renameSync(t,e)}catch{}}}getPreviousSessionMessages(e){let t=[],n=e.exception?.crashedAt,r={crashed_session_id:e.sessionId,crashed_release_id:e.releaseId,crashed_app_version:e.appVersion};if(e.exception){let{kind:n,name:i,message:a,stack:o,fingerprint:s}=e.exception;t.push(bn(`main_exception`,{kind:n,name:i,message:a,...o===void 0?{}:{stack:o},fingerprint:s,fatal:!0,...r,crashed_at:e.exception.crashedAt,was_in_game:e.inGame}))}let i={...r,started_at:e.startedAt,last_heartbeat_at:e.lastHeartbeatAt,uptime_ms:Math.max(0,(n??e.lastHeartbeatAt)-e.startedAt),was_in_game:e.inGame,has_minidump:!1};return e.game&&(i.game=e.game),n!==void 0&&(i.crashed_at=n),this.logger.warn(`Previous session did not exit cleanly`,i),t.push(bn(`unclean_exit`,i)),t}onRenderProcessGone(e,t,n){if(_n.has(n.reason))return;let r=vn.get(t),i=``;try{i=t.getURL()}catch{}this.logger.warn(`Render process gone`,{reason:n.reason,exitCode:n.exitCode,url:i}),q.getInstance().track(`renderer_crash`,{reason:n.reason.slice(0,an.reason),exit_code:n.exitCode,page:mn(i),window_type:r?.inGame?`in_game`:`desktop`,...r?{window_age_ms:Date.now()-r.createdAt}:{}})}onChildProcessGone(e,t){_n.has(t.reason)||(this.logger.warn(`Child process gone`,t),q.getInstance().track(`child_process_crash`,{process_type:t.type.slice(0,an.processType),reason:t.reason.slice(0,an.reason),exit_code:t.exitCode,...t.serviceName?{service_name:t.serviceName.slice(0,an.processName)}:{},...t.name?{name:t.name.slice(0,an.processName)}:{}}))}onUncaughtException(e,t){try{let n={kind:t===`unhandledRejection`?`unhandled_rejection`:`uncaught_exception`,...pn(e),crashedAt:Date.now()};if(!this.state){this.trackNonFatalException(n);return}this.state.exception&&(this.trackNonFatalException(this.state.exception),clearTimeout(this.survivalTimeout)),this.state.exception=n,this.writeState(),this.survivalTimeout=setTimeout(()=>{if(this.survivalTimeout=void 0,!this.state?.exception)return;let e=this.state.exception;delete this.state.exception,this.writeState(),this.trackNonFatalException(e)},5e3),this.survivalTimeout.unref()}catch{}}trackNonFatalException({kind:e,name:t,message:n,stack:r,fingerprint:i}){let a=this.exceptionCountByFingerprint.get(i)??0;this.exceptionCount>=50||a>=5||(this.exceptionCount++,this.exceptionCountByFingerprint.set(i,a+1),q.getInstance().track(`main_exception`,{kind:e,name:t,message:n,...r===void 0?{}:{stack:r},fingerprint:i,fatal:!1}))}onGameStateChange(){this.updateGameState(),this.writeState()}updateGameState(){if(!this.state)return;let e=J.getInstance(),[t]=e.getActiveGames();this.state.inGame=e.isInGame,t?this.state.game=String(t).slice(0,an.game):delete this.state.game}onBrowserWindowCreated(e,t){t.once(`session-end`,this.boundOnShutdown)}onShutdown(){this.state&&!this.state.shutdown&&(this.state.shutdown=!0,this.writeState())}onExit(e){this.state&&!this.state.exception&&e===0&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0,this.statePath&&this.removeFile(this.statePath))}onQuit(e,t){this.state&&t===0&&(this.state.quit=!0,this.writeState())}isProcessAlive(e){if(e===process.pid)return!1;try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}isLiveInstance(e){return Date.now()-e.lastHeartbeatAt<=9e4&&this.isProcessAlive(e.pid)}readState(e){let t;try{t=y.readFileSync(e,`utf8`)}catch{return}try{let e=gn(JSON.parse(t));return e instanceof n.errors?(this.logger.warn(`Ignoring invalid session state file`,e.summary),null):e}catch(e){return this.logger.warn(`Ignoring unreadable session state file`,e),null}}writeState(){if(this.state&&this.statePath)try{let e=`${this.statePath}.tmp`;y.mkdirSync(m.dirname(this.statePath),{recursive:!0}),y.writeFileSync(e,JSON.stringify(this.state)),y.renameSync(e,this.statePath)}catch(e){this.logger.warn(`Failed to write session state file`,e)}}removeFile(e){try{y.rmSync(e,{force:!0})}catch(e){this.logger.warn(`Failed to remove session state file`,e)}}}),Sn=new ve({path:f.normalize(`${process.env.APPDATA||process.env.HOME||`.`}/.overlayed/config.json`),default:void 0,schema:t({Account:n({email:`string`,apiKey:`string`,"applicationId?":`string`,"applicationIds?":`string[]`,"baseUrl?":`string`})}).type({currentAccount:`Account | undefined`,accounts:`Account[]`}).or(`undefined`)});function Cn(e){return wn(e).map(e=>String(e).toUpperCase())}function wn(e){let{applicationId:t,applicationIds:n}=e;return Array.isArray(n)&&n.length>0?n:t===void 0?n===void 0||Array.isArray(n)?[]:[n]:[t]}function Tn(e,t,n){let r=Cn(e),i=t===void 0||r.length===0||r.includes(t),a=(e.baseUrl??`https://api.overlayed.gg`)===n;return i&&a}function En(e){let{currentAccount:t,accounts:n,expected:r}=e,i=r.applicationId===void 0?void 0:String(r.applicationId).toUpperCase(),a=e=>Tn(e,i,r.baseUrl);if(t&&a(t))return{account:t,source:`current`};let o=n.find(a);if(o)return{account:o,source:`other`}}function Dn(e,t){return`${e}:${t}`}function On(e,t,n){return e.reduce((e,r)=>{let i=r.key;return e[i]={on(e,n){let r=Dn(i,e),a=t.get(r)??/* @__PURE__ */ new Set;a.add(n),t.set(r,a)},onAny(e){let n=Dn(i,`*`),r=t.get(n)??/* @__PURE__ */ new Set;r.add(e),t.set(n,r)},off(e,n){let r=Dn(i,e),a=t.get(r);a&&(a.delete(n),a.size===0&&t.delete(r))},offAny(e){let n=Dn(i,`*`),r=t.get(n);r&&(r.delete(e),r.size===0&&t.delete(n))},readyForGameEvents:()=>{n.emit(`flushEvents`,i)}},e},{})}function kn(){let e=_e.getInstance(),t=J.getInstance();return{on:(n,r)=>{switch(n){case`fatal`:e.on(`fatal`,r);break;case`error`:e.on(`error`,r);break;case`warning`:e.on(`warning`,r);break;case`gameLaunch`:t.on(`gameLaunch`,r);break;case`gameClose`:t.on(`gameClose`,r);break;case`gameReady`:t.on(`gameReady`,r);break;default:throw Error(`Event type not implemented ${n}`,{cause:[n,r]})}},off:(n,r)=>{switch(n){case`fatal`:e.off(`fatal`,r);break;case`error`:e.off(`error`,r);break;case`warning`:e.off(`warning`,r);break;case`gameLaunch`:t.off(`gameLaunch`,r);break;case`gameClose`:t.off(`gameClose`,r);break;case`gameReady`:t.off(`gameReady`,r);break;default:throw Error(`Event type not implemented ${n}`,{cause:[n,r]})}}}}const An=/* @__PURE__ */ new Map([[1,`LeftButton`],[2,`RightButton`],[3,`Cancel`],[4,`MiddleButton`],[5,`ExtraButton1`],[6,`ExtraButton2`],[8,`Backspace`],[9,`Tab`],[12,`Clear`],[13,`Enter`],[16,`ShiftLeft`],[17,`ControlLeft`],[18,`AltLeft`],[19,`Pause`],[20,`CapsLock`],[21,`KanaMode`],[23,`JunjaMode`],[24,`Finalize`],[25,`HanjaMode`],[27,`Escape`],[28,`Convert`],[29,`NonConvert`],[30,`Accept`],[31,`ModeChange`],[32,`Space`],[33,`PageUp`],[34,`PageDown`],[35,`End`],[36,`Home`],[37,`ArrowLeft`],[38,`ArrowUp`],[39,`ArrowRight`],[40,`ArrowDown`],[41,`Select`],[42,`PrintScreen`],[43,`Execute`],[44,`Snapshot`],[45,`Insert`],[46,`Delete`],[47,`Help`],[48,`Digit0`],[49,`Digit1`],[50,`Digit2`],[51,`Digit3`],[52,`Digit4`],[53,`Digit5`],[54,`Digit6`],[55,`Digit7`],[56,`Digit8`],[57,`Digit9`],[65,`KeyA`],[66,`KeyB`],[67,`KeyC`],[68,`KeyD`],[69,`KeyE`],[70,`KeyF`],[71,`KeyG`],[72,`KeyH`],[73,`KeyI`],[74,`KeyJ`],[75,`KeyK`],[76,`KeyL`],[77,`KeyM`],[78,`KeyN`],[79,`KeyO`],[80,`KeyP`],[81,`KeyQ`],[82,`KeyR`],[83,`KeyS`],[84,`KeyT`],[85,`KeyU`],[86,`KeyV`],[87,`KeyW`],[88,`KeyX`],[89,`KeyY`],[90,`KeyZ`],[91,`MetaLeft`],[92,`MetaRight`],[93,`ContextMenu`],[95,`Sleep`],[96,`Numpad0`],[97,`Numpad1`],[98,`Numpad2`],[99,`Numpad3`],[100,`Numpad4`],[101,`Numpad5`],[102,`Numpad6`],[103,`Numpad7`],[104,`Numpad8`],[105,`Numpad9`],[106,`NumpadMultiply`],[107,`NumpadAdd`],[108,`NumpadSeparator`],[109,`NumpadSubtract`],[110,`NumpadDecimal`],[111,`NumpadDivide`],[112,`F1`],[113,`F2`],[114,`F3`],[115,`F4`],[116,`F5`],[117,`F6`],[118,`F7`],[119,`F8`],[120,`F9`],[121,`F10`],[122,`F11`],[123,`F12`],[124,`F13`],[125,`F14`],[126,`F15`],[127,`F16`],[128,`F17`],[129,`F18`],[130,`F19`],[131,`F20`],[132,`F21`],[133,`F22`],[134,`F23`],[135,`F24`],[144,`NumLock`],[145,`ScrollLock`],[146,`NEC_Equal`],[147,`Fujitsu_Masshou`],[148,`Fujitsu_Touroku`],[149,`Fujitsu_Loya`],[150,`Fujitsu_Roya`],[160,`ShiftLeft`],[161,`ShiftRight`],[162,`ControlLeft`],[163,`ControlRight`],[164,`AltLeft`],[165,`AltRight`],[166,`BrowserBack`],[167,`BrowserForward`],[168,`BrowserRefresh`],[169,`BrowserStop`],[170,`BrowserSearch`],[171,`BrowserFavorites`],[172,`BrowserHome`],[173,`VolumeMute`],[174,`VolumeDown`],[175,`VolumeUp`],[176,`MediaTrackNext`],[177,`MediaTrackPrevious`],[178,`MediaStop`],[179,`MediaPlayPause`],[180,`LaunchMail`],[181,`LaunchMediaSelect`],[182,`LaunchApplication1`],[183,`LaunchApplication2`],[186,`OEM_1`],[187,`Equal`],[188,`Comma`],[189,`Minus`],[190,`Period`],[191,`Slash`],[192,`Backquote`],[219,`BracketLeft`],[220,`Backslash`],[221,`BracketRight`],[222,`Quote`],[223,`IntlRo`],[225,`OEM_AX`],[226,`IntlBackslash`],[227,`ICO_HELP`],[228,`ICO_00`],[229,`Process`],[230,`ICO_CLEAR`],[231,`Packet`],[233,`OEM_Reset`],[234,`OEM_Jump`],[235,`OEM_PA1`],[236,`OEM_PA2`],[237,`OEM_PA3`],[238,`OEM_WS_Ctrl`],[239,`OEM_CU_Sel`],[240,`OEM_ATTN`],[241,`OEM_Finish`],[242,`OEM_Copy`],[243,`OEM_Auto`],[244,`OEM_ENLW`],[245,`BackTab`],[246,`ATTN`],[247,`CRSel`],[248,`EXSel`],[249,`EREOF`],[250,`MediaPlay`],[251,`Zoom`],[252,`Noname`],[253,`PA1`],[254,`OEM_Clear`]]),jn=new Map(An.entries().map(([e,t])=>[t,e])),Mn=n({"[string]":{keys:`string[]`,mode:n(`'toggle' | 'hold'`).pipe(e=>e??`toggle`)}});var Nn=class extends B{preferencesKeybindToCallbacks=/* @__PURE__ */ new Map;pressedKeys=/* @__PURE__ */ new Set;activeKeybinds=/* @__PURE__ */ new Set;triggeredToggleKeybinds=/* @__PURE__ */ new Set;boundHandleKeyboardFocus=this.handleKeyboardFocus.bind(this);boundHandleKeyDown=this.handleKeyDown.bind(this);boundHandleKeyUp=this.handleKeyUp.bind(this);keybindsFile;keybindListeningPaused=!1;constructor(e){super(`KeybindManager`),this.keybindsFile=new ve({path:Pt([`keybinds.json`]),schema:Mn,default:e})}init(){super.init();let e=Jt.getInstance().getInterface(`OGG_SIEGE`);e.instance.on(`keyboardFocus`,this.boundHandleKeyboardFocus),e.instance.on(`keyDown`,this.boundHandleKeyDown),e.instance.on(`keyUp`,this.boundHandleKeyUp)}async onKeybindToggled(e,t){let n=this.preferencesKeybindToCallbacks.get(e)??{toggle:[],down:[],up:[]};n.toggle.push(t),this.preferencesKeybindToCallbacks.set(e,n)}async onKeybindDown(e,t){let n=this.preferencesKeybindToCallbacks.get(e)??{toggle:[],down:[],up:[]};n.down.push(t),this.preferencesKeybindToCallbacks.set(e,n)}async onKeybindUp(e,t){let n=this.preferencesKeybindToCallbacks.get(e)??{toggle:[],down:[],up:[]};n.up.push(t),this.preferencesKeybindToCallbacks.set(e,n)}async updateKeybind(e,t){this.keybindsFile.set({[e]:t})}async updateKeybinds(e){let t=Object.fromEntries(Object.entries(e).filter(([e,t])=>t!==void 0));this.keybindsFile.set({...this.keybindsFile.get(),...t})}getConfig(){return this.keybindsFile.get()}destroy(){let e=Jt.getInstance().getInterface(`OGG_SIEGE`);e.instance.off(`keyboardFocus`,this.boundHandleKeyboardFocus),e.instance.off(`keyDown`,this.boundHandleKeyDown),e.instance.off(`keyUp`,this.boundHandleKeyUp),super.destroy()}handleKeyDown(e){if(this.keybindListeningPaused)return;let t=An.get(e.key);t?(this.pressedKeys.add(t),this.checkKeybindings()):this.logger.error(`Unknown key down`,e)}handleKeyboardFocus(){this.pressedKeys.clear(),this.activeKeybinds.clear(),this.triggeredToggleKeybinds.clear()}async handleKeyUp(e){if(this.keybindListeningPaused)return;let t=An.get(e.key);if(!t)return;this.pressedKeys.delete(t);let n=this.keybindsFile.get();for(let[e]of this.preferencesKeybindToCallbacks.entries())n[e].keys.includes(t)&&this.triggeredToggleKeybinds.delete(e);this.checkKeybindUps()}async checkKeybindUps(){let e=this.keybindsFile.get();for(let[t,n]of this.preferencesKeybindToCallbacks.entries()){if(!n.up||n.up.length===0)continue;let r=e[t];if(this.activeKeybinds.has(t)&&r.keys.some(e=>!this.pressedKeys.has(e))){this.activeKeybinds.delete(t);for(let e of n.up)e();this.logger.log(`Keybind up triggered`,this.getKeybindToString(r))}}}async checkKeybindings(){let e=this.keybindsFile.get();for(let[t,n]of this.preferencesKeybindToCallbacks.entries()){let r=e[t];if(r.keys.length===this.pressedKeys.size&&r.keys.every(e=>jn.has(e)?this.pressedKeys.has(e):!1)){this.triggerKeybind(r,n,t);return}}for(let[t,n]of this.preferencesKeybindToCallbacks.entries()){let r=e[t];r.keys.every(e=>jn.has(e)?this.pressedKeys.has(e):(this.logger.error(`Unknown key`,e,r),!1))&&this.triggerKeybind(r,n,t)}}triggerKeybind(e,t,n){let r=e.mode;if(r===`toggle`&&t.toggle&&t.toggle.length>0&&!this.triggeredToggleKeybinds.has(n)){let r;for(let e of t.toggle){let t=e();typeof t==`string`&&r===void 0&&(r=t)}this.triggeredToggleKeybinds.add(n),this.logger.log(r?`Keybind pressed rejected: ${r}`:`Keybind pressed accepted`,this.getKeybindToString(e))}if(r===`hold`&&t.down&&t.down.length>0&&!this.activeKeybinds.has(n)){let r;for(let e of t.down){let t=e();if(typeof t==`string`){r=t;break}}r?this.logger.log(`Keybind down rejected: ${r}`,this.getKeybindToString(e)):(this.activeKeybinds.add(n),this.logger.log(`Keybind down accepted`,this.getKeybindToString(e)))}}getKeybindToString(e){return`(${e.keys.join(`+`)}${e.mode?` ${e.mode}`:``})`}};function Pn(e){let t=new Nn(e),n={};for(let r in e)n[r]={on:(e,n)=>{switch(e){case`down`:t.onKeybindDown(r,n);break;case`up`:t.onKeybindUp(r,n);break;case`toggle`:t.onKeybindToggled(r,n);break;default:throw Error(`Event type not implemented ${e}`,{cause:[e,n]})}}};let r={...n,getConfig:()=>t.getConfig(),pauseKeybindListening:()=>{t.keybindListeningPaused=!0},resumeKeybindListening:()=>{t.keybindListeningPaused=!1},updateKeybind:(e,n)=>{t.updateKeybind(e,n)},updateKeybinds:e=>{t.updateKeybinds(e)}};return t.init(),O.on(`quit`,()=>{t.destroy()}),r}function Y(){return Jt.getInstance().getInterface(`OGG_SIEGE`)}function Fn(){let e=J.getInstance(),t=_e.getInstance(),n=q.getInstance();if(!O.isPackaged)L.getInstance().info(`Cortex is disabled in development`),n.enabled=!1;else{try{n.meta=In()}catch(e){L.getInstance().error(`Failed to setup cortex`,e);return}e.on([`gameReady`,`gameClose`],()=>{n.meta||=In(),n.meta.in_game=e.isInGame}),t.on(`fatal`,e=>{n.track(`fatal`,{message:e.message,code:e.code,data:JSON.stringify(e.data)})}),t.on(`error`,e=>{n.track(`error`,{code:e.code,message:e.message,data:JSON.stringify(e.data)})}),t.on(`warning`,e=>{n.track(`warning`,{message:e.message,code:e.code,data:JSON.stringify(e.data)})})}}function In(){if(!global.OVERLAYED_META.release.id)throw Error(`Release ID is required`);return{app_id:global.OVERLAYED.APPLICATION_ID,user_id:Lt(),release_id:global.OVERLAYED_META.release.id,app_channel:global.OVERLAYED.APP_BUILD_CHANNEL,app_version:global.OVERLAYED.APP_VERSION,package_version:global.OVERLAYED.PACKAGE_VERSION,frontend_version:global.OVERLAYED.FRONTEND_VERSION,frontend_release_id:global.OVERLAYED.FRONTEND_RELEASE_ID,session_id:global.OVERLAYED.sessionId,in_game:!1}}const Ln=/* @__PURE__ */ new Set([`http:`,`https:`]);function Rn(){let e=global.OVERLAYED_META?.application?.siteUrl;if(e&&URL.canParse(e))return new URL(e).origin}function zn(e){return URL.canParse(e)?new URL(e):void 0}function Bn(e){return e===`mouseDown`}function Vn(e){let t,n=()=>{t=Date.now()};return e.on(`before-input-event`,(e,t)=>{t.type===`keyDown`&&!t.isAutoRepeat&&n()}),e.on(`input-event`,(e,t)=>{Bn(t.type)&&n()}),e.on(`before-mouse-event`,(e,t)=>{Bn(t.type)&&n()}),{isActive:(e=-1/0)=>t!==void 0&&t>=e&&Date.now()-t<=5e3,consume:()=>{t=void 0}}}function Hn(e,t){return Un(e.webContents,t),e}function Un(e,t,n){let{allowedHosts:r=[],windowOpenHandler:i,logger:a}=t,{shell:o}=global.OVERLAYED.electron,s=Rn(),c=n===void 0?void 0:zn(n),l=c&&Ln.has(c.protocol)?c.origin:void 0,u=Vn(e),d=t=>{let n=zn(e.getURL());return n?.protocol===`file:`&&t.protocol===`file:`?!0:Ln.has(t.protocol)?s&&t.origin===s||l&&t.origin===l||r.includes(t.host)?!0:n!==void 0&&Ln.has(n.protocol)&&t.origin===n.origin:!1},f=(e,t,n)=>{e.preventDefault(),a.warn(`[navigation-guard] Blocked main-frame navigation to ${t} (${n})`),q.getInstance().track(`navigation_blocked`,{url:t,reason:n})},p=n!==void 0,m=n!==void 0;e.on(`will-navigate`,e=>{let t=zn(e.url);t&&d(t)?p=!0:f(e,e.url,t?`cross_origin`:`unparseable`)}),e.on(`will-redirect`,e=>{if(!e.isMainFrame||!p)return;let t=zn(e.url);t&&d(t)||f(e,e.url,t?`cross_origin_redirect`:`unparseable`)}),e.on(`did-start-navigation`,e=>{e.isMainFrame&&!e.isSameDocument&&(p=m,m=!1)});let h,g=()=>{let e=Date.now();if(!u.isActive())return h=e,{action:`deny`,reason:`no_user_activation`};let t=(h??-1/0)+1e4;return u.isActive(t)?{action:`external`}:{action:`deny`,reason:`popup_cooldown`}},_=e=>{let t=i?.({url:e});if(t===`allow`)return{action:`allow`};if(t===`deny`)return{action:`deny`,reason:`application`};let n=zn(e);return n?t===`external`?Ln.has(n.protocol)?{action:`external`}:{action:`deny`,reason:`unsupported_scheme`}:d(n)?{action:`allow`}:Ln.has(n.protocol)?g():{action:`deny`,reason:`unsupported_scheme`}:{action:`deny`,reason:`unparseable`}},v=(e,n)=>{let{url:r}=e,i=_(r);if(i.action===`deny`)return a.warn(`[navigation-guard] Denied window.open to ${r} (${i.reason})`),q.getInstance().track(`window_open_denied`,{url:r,reason:i.reason}),{action:`deny`};let s=n?.(e);if(s?.action===`deny`)return s;if(i.action===`allow`){a.info(`[navigation-guard] Allowing in-app window for ${r}`);let e=s?.createWindow;return!s||!e?s??{action:`allow`}:{...s,createWindow:n=>{let i=e(n);return Un(i,t,r),i}}}return u.consume(),a.info(`[navigation-guard] Opening external url in system browser: ${r}`),q.getInstance().track(`window_open_external`,{url:r}),o.openExternal(r).catch(e=>{a.warn(`[navigation-guard] Failed to open external url ${r}: ${String(e)}`)}),{action:`deny`}},ee=e.setWindowOpenHandler.bind(e);e.setWindowOpenHandler=e=>{ee(t=>v(t,e))},ee(e=>v(e)),e.on(`did-create-window`,(e,n)=>{Un(e.webContents,t,n.url)})}const Wn=n({page:`0 < string <= 512`,"lcp?":`number`,"inp?":`number`,"fcp?":`number`,"ttfb?":`number`,"cls?":`number`}),Gn=/* @__PURE__ */ new WeakMap;let Kn=!1;function qn(e,t){return e!==void 0&&Number.isFinite(e)&&e>=0&&e<=t}function Jn(e,t){let r=Gn.get(e.sender);if(r===void 0)return;let i=Wn(t);if(i instanceof n.errors)return;let a={page:i.page,window_type:r?`in_game`:`desktop`},o=!1;for(let e of nn){let t=i[e];qn(t,6e4)&&(a[e]=Math.round(t),o=!0)}qn(i.cls,10)&&(a.cls=Math.round(i.cls*1e4)/1e4,o=!0),o&&q.getInstance().track(`web_vitals`,a)}function Yn(e,t){Gn.set(e,t),Kn||(Kn=!0,global.OVERLAYED.electron.ipcMain.on(`overlayed:web-vitals`,Jn))}const Xn=M(class extends B{CHECK_INTERVAL=9e5;RETRY_INTERVAL=15e3;_updateCheckInterval=null;_latestCheckResponse=null;_activeCheckResponse=null;initialReleaseId=null;get manualUpdatesEnabled(){return this.options?.manualUpdates??!1}get activeReleaseId(){return this._activeCheckResponse?.release_id??this.initialReleaseId}constructor(){super(`SiteManager`)}init(e){super.init(e),e?.manualUpdates&&this.enableManualUpdates()}destroy(){super.destroy(),this._updateCheckInterval&&=(clearInterval(this._updateCheckInterval),null)}allowSiteUpdateOnNextLoad(){this.options?.manualUpdates?this._latestCheckResponse?this._activeCheckResponse?.release_id===this._latestCheckResponse.release_id?this.logger.warn(`allowSiteUpdateOnNextLoad called but theres no update available`):(this._activeCheckResponse=this._latestCheckResponse,q.getInstance().track(`site_update_applied`,{version:this._latestCheckResponse.version,release_id:this._latestCheckResponse.release_id}),this.setFrontendCortexMeta(this._latestCheckResponse.release_id,this._latestCheckResponse.version)):this.logger.warn(`allowSiteUpdateOnNextLoad called but no update has been checked yet`):this.logger.warn(`allowSiteUpdateOnNextLoad called but manual updates are disabled`)}setFrontendCortexMeta(e,t){let n=q.getInstance();n.meta||=In(),e&&(global.OVERLAYED.FRONTEND_RELEASE_ID=e,n.meta.frontend_release_id=e),t&&(global.OVERLAYED.FRONTEND_VERSION=t,n.meta.frontend_version=t),e&&t&&n.track(`frontend_version_changed`,{version:t,release_id:e})}enableManualUpdates(){this.logger.log(`Enabling manual site updates`),this.checkForUpdates(),this._updateCheckInterval=setInterval(()=>{this.checkForUpdates(!0)},this.CHECK_INTERVAL)}async checkForUpdates(e=!1){let t=global.OVERLAYED_META?.application?.siteUrl;if(!t)this.logger.log(`No siteUrl configured, skipping check`);else{q.getInstance().track(`site_check_for_update`,{});try{let n=new URL(`/check`,t).toString();this.logger.log(`Checking site URL`,n);let r={"Overlayed-User-Agent":it({package_version:global.OVERLAYED.PACKAGE_VERSION,application_id:global.OVERLAYED.APPLICATION_ID,application_version:global.OVERLAYED.APP_VERSION}),"Overlayed-Cortex-User-Id":global.OVERLAYED_RUNTIME.userId},i=K();i&&(r[`Overlayed-Access-Token`]=i);let a=global.OVERLAYED_META.release.channelId;a&&(r[`Overlayed-Channel-Id`]=a);let o=await fetch(n,{headers:r});if(!o.ok){this.logger.warn(`Site check failed with status`,o.status),q.getInstance().track(`site_check_error`,{status:o.status}),e&&this.scheduleRetry();return}let s=await o.json();if(this.logger.log(`Site check response`,s),!s.release_id){this.logger.error(`Site check response missing release_id`);return}if(!this._latestCheckResponse){this._latestCheckResponse=s;return}return this._latestCheckResponse.release_id===s.release_id?void 0:(this.logger.log(`New site version detected`,s),this._latestCheckResponse=s,q.getInstance().track(`site_update_ready`,{version:s.version,release_id:s.release_id}),this.emit(`siteUpdateReady`,{releaseId:s.release_id,version:s.version}),s)}catch(e){let t=e instanceof Error?e.message:String(e);q.getInstance().track(`site_check_error`,{message:t}),this.logger.error(`Site check failed`,{error:e,message:t}),this.scheduleRetry()}}}scheduleRetry(){setTimeout(()=>{this.checkForUpdates()},this.RETRY_INTERVAL)}}),Zn=M(I,`browser-windows.log`);let Qn;function $n(){return Qn||(Qn=class e extends global.OVERLAYED.electron.BrowserWindow{static session=void 0;constructor(t){let n=e.resolveCustomOptions(t);super(n)}static resolveCustomOptions(t){let n=global.OVERLAYED_META,r=global.OVERLAYED_RUNTIME;return{...t,webPreferences:{...t.webPreferences,session:e.getSession(),additionalArguments:[...(t.webPreferences?.additionalArguments||[]).filter(e=>!e.startsWith(`--overlayed-meta=`)&&!e.startsWith(`--overlayed-runtime=`)),...global.OVERLAYED.electron.app.isPackaged?[]:[`--overlayed-meta=${JSON.stringify(n)}`],`--overlayed-runtime=${JSON.stringify(r)}`]}}}static getSession(){if(!global.OVERLAYED_META?.application?.siteUrl)return;if(e.session)return e.session;e.session=global.OVERLAYED.electron.session.fromPartition(`persist:overlayed-${global.OVERLAYED.APPLICATION_ID}`);let t=Xn.getInstance(),n=it({package_version:global.OVERLAYED.PACKAGE_VERSION,application_id:global.OVERLAYED.APPLICATION_ID,application_version:global.OVERLAYED.APP_VERSION}),r={urls:[global.OVERLAYED_META.application.siteUrl+`/*`]},i=global.OVERLAYED_RUNTIME.userId;return e.session.webRequest.onBeforeSendHeaders(r,(e,r)=>{let a=K();a&&(e.requestHeaders[`Overlayed-Access-Token`]=a);let o=global.OVERLAYED_META.release.channelId;o&&(e.requestHeaders[`Overlayed-Channel-Id`]=o),t.manualUpdatesEnabled&&t.activeReleaseId&&(e.requestHeaders[`Overlayed-Release-Id`]=t.activeReleaseId),e.requestHeaders[`Overlayed-Cortex-User-Id`]=i,e.requestHeaders[`Overlayed-User-Agent`]=n,r({requestHeaders:e.requestHeaders})}),t.manualUpdatesEnabled&&e.session.webRequest.onHeadersReceived(r,(e,n)=>{if(t.initialReleaseId){n(e);return}let r=e.responseHeaders?.[`Overlayed-Release-Id`]?.[0];r&&(t.initialReleaseId=mt(r));let i=e.responseHeaders?.[`Overlayed-Release-Version`]?.[0];t.setFrontendCortexMeta(r,i),n(e)}),e.session}},Qn)}function er(e){function t(t,n){let r=Zn.getInstance();return Hn(t,{...e,logger:r}),global.OVERLAYED_RUNTIME.webVitals!==!1&&Yn(t.webContents,n),yn(t.webContents,n),t.once(`closed`,()=>{t.isDestroyed()||q.getInstance().track(`window_closed`,{url:t.webContents.getURL(),in_game:n})}),t.on(`unresponsive`,()=>{t.isDestroyed()||q.getInstance().track(`window_unresponsive`,{url:t.webContents.getURL(),in_game:n})}),t.webContents.on(`console-message`,(e,n,i,a,o)=>{let s=t.isDestroyed()?`destroyed`:t.webContents.getURL();r[n===3?`error`:n===2?`warn`:`log`](`[${s}] [${o}:${a}] ${i}`)}),q.getInstance().track(`window_created`,{url:t.webContents.getURL(),in_game:n}),t}return{getProductionSiteUrl:()=>{let e=global.OVERLAYED_META.application.siteUrl;return URL.canParse(e)?new URL(e):new URL(`https://default.overlayedapps.com`)},createWindow:e=>t(new($n())(e),!1),createInGameWindow:e=>{let n=$n();return t(Y().instance.newWindowInternal(n,e),!0)},on:(e,t)=>Y().instance.on(e,t),off:(e,t)=>Y().instance.off(e,t),once:(e,t)=>Y().instance.once(e,t),addListener:(e,t)=>Y().instance.addListener(e,t),removeListener:(e,t)=>Y().instance.removeListener(e,t),removeAllListeners:()=>Y().instance.removeAllListeners(),prependListener:(e,t)=>Y().instance.prependListener(e,t),prependOnceListener:(e,t)=>Y().instance.prependOnceListener(e,t),getActiveGameInfo:()=>{let e=Y(),t=Re.getInstance();return{resolution:e.resolution,isConnected:t.hasConnection}}}}const tr=M(class extends Ze{renderInterface;globalCursorOverrideCount=/* @__PURE__ */ new Set;globalMouseBlockCount=/* @__PURE__ */ new Set;globalKeyboardBlockCount=/* @__PURE__ */ new Set;keyInputBlocks={};constructor(e){super(`OverridesManager`),this.renderInterface=Jt.getInstance().getInterface(e)}scope(e){return{setGlobalCursorOverride:t=>this.setGlobalCursorOverride(e,t),setGlobalMouseBlock:t=>this.setGlobalMouseBlock(e,t),setGlobalKeyboardBlock:t=>this.setGlobalKeyboardBlock(e,t),setKeyInputBlock:(t,n)=>this.setKeyInputBlock(e,t,n)}}setGlobalCursorOverride(e,t){t?this.globalCursorOverrideCount.add(e):this.globalCursorOverrideCount.delete(e),t&&this.globalCursorOverrideCount.size===1?this.renderInterface.instance.setGlobalCursorOverride(!0):!t&&this.globalCursorOverrideCount.size===0&&this.renderInterface.instance.setGlobalCursorOverride(!1)}setGlobalMouseBlock(e,t){t?this.globalMouseBlockCount.add(e):this.globalMouseBlockCount.delete(e),t&&this.globalMouseBlockCount.size===1?this.renderInterface.instance.setGlobalMouseBlock(!0):!t&&this.globalMouseBlockCount.size===0&&this.renderInterface.instance.setGlobalMouseBlock(!1)}setGlobalKeyboardBlock(e,t){t?this.globalKeyboardBlockCount.add(e):this.globalKeyboardBlockCount.delete(e),t&&this.globalKeyboardBlockCount.size===1?this.renderInterface.instance.setGlobalKeyboardBlock(!0):!t&&this.globalKeyboardBlockCount.size===0&&this.renderInterface.instance.setGlobalKeyboardBlock(!1)}setKeyInputBlock(e,t,n){this.keyInputBlocks[t]||(this.keyInputBlocks[t]=/* @__PURE__ */ new Set),n?this.keyInputBlocks[t].add(e):this.keyInputBlocks[t].delete(e),n&&this.keyInputBlocks[t].size===1?this.renderInterface.instance.setKeyInputBlock(t,!0):!n&&this.keyInputBlocks[t].size===0&&this.renderInterface.instance.setKeyInputBlock(t,!1)}},`OGG_SIEGE`);function nr(){return{scope:e=>tr.getInstance().scope(e),raw:{setGlobalMouseBlock:e=>Y().instance.setGlobalMouseBlock(e),setGlobalKeyboardBlock:e=>Y().instance.setGlobalKeyboardBlock(e),setGlobalCursorOverride:e=>Y().instance.setGlobalCursorOverride(e),setKeyInputBlock:(e,t)=>Y().instance.setKeyInputBlock(e,t),getGlobalMouseBlock:()=>Y().instance.getGlobalMouseBlock(),getGlobalKeyboardBlock:()=>Y().instance.getGlobalKeyboardBlock(),getGlobalCursorOverride:()=>Y().instance.getGlobalCursorOverride(),getKeyInputBlock:e=>Y().instance.getKeyInputBlock(e)}}}function rr(){return{track:(e,t)=>{q.getInstance().track(`custom__${String(e)}`,t)}}}function X(){return{registerWindow:()=>{}}}const ir=/(\d{4})-(\d{2})-(\d{2})\.log$/;function ar(e){let t=e.match(ir);if(!t)return!1;let[,n,r,i]=t,a=Number(n),o=Number(r),s=Number(i);if(o<1||o>12||s<1||s>31)return!1;let c=new Date(a,o-1,s);if(isNaN(c.getTime())||c.getFullYear()!==a||c.getMonth()!==o-1||c.getDate()!==s)return!1;let l=/* @__PURE__ */ new Date;return l.setDate(l.getDate()-7),l.setHours(0,0,0,0),c>=l}function or(e){let{silent:t=!1,additionalFiles:n}=e??{},r=Te(global.OVERLAYED.APPLICATION_ID),i=Ee(r,{recursive:!0}),a=Ce(),o=Ee(a,{recursive:!0});t||(L.getInstance().info(`Logs path: `,r),L.getInstance().info(`Overlayed logs path: `,a));let s=new ae;return i.forEach(([e,n])=>{t||L.getInstance().info(`Zipping: `,n);let r=x(n);s.file(g(n),r,{compression:`DEFLATE`})}),o.forEach(([e,n])=>{if(!ar(g(n))){t||L.getInstance().info(`Skipping old/unrecognized log: `,n);return}t||L.getInstance().info(`Zipping: `,n);let r=x(n);s.file(g(n),r,{compression:`DEFLATE`})}),n&&Object.entries(n).forEach(([e,n])=>{t||L.getInstance().info(`Zipping extra file: `,e),s.file(e,n,{compression:`DEFLATE`})}),s}async function sr(e,t,n){let r=global.OVERLAYED_META.release.id?mt(global.OVERLAYED_META.release.id):void 0,i=Lt();return dt(global.OVERLAYED.APPLICATION_ID,{file:Buffer.from(n,`base64`),data:{release_id:r,type:e,cortex_user_id:i,...t}}).then(e=>(L.getInstance().info(`Feedback submitted`,e),e.data.id)).catch(e=>{console.error(JSON.stringify(e,null,2)),L.getInstance().error(`Failed to submit feedback`,e)})}function cr(e){let t=new I(`app.log`);return t.init(global.OVERLAYED.APPLICATION_ID,e.debug),{scope:e=>t.scope(e),info:e=>t.info(e),warn:e=>t.warn(e),error:e=>t.error(e),debug:e=>t.debug(e),submitFeedback:async(e,t,n)=>{let r=global.OVERLAYED_META.release.id?mt(global.OVERLAYED_META.release.id):void 0;return r&&O.isPackaged&&q.getInstance().track(e===`bug_report`?`bug_report_submitted`:`suggestion_submitted`,{release_id:r}),await sr(e,t,await or(n).generateAsync({type:`base64`}))},getLogsZip:e=>or(e)}}const lr=1e3;function ur(e,t,r,i,a){let o=Re.getInstance(),s=L.getInstance().scope(`SetupPipeServer`);s.log(`Initializing`);function c(e,t){let n=r.get(t);if(!n)r.set(t,[e]);else{if(n.length>=lr){_e.getInstance().warn(`Event buffer full, removing oldest event`,`EVENT_BUFFER_FULL`,{summary:`Event buffer overflow for module ${t}. Buffer size: ${n.length}, max: ${lr}`});return}n.push(e)}}function l(e,r,i){let o=i.events.event,l=o(e);if(l instanceof n.errors){if(`type`in l.byPath)return;s.warn(`Invalid event`,{summary:l.summary}),q.getInstance().track(`invalid_game_event`,{game:r.game,type:r.type,summary:l.summary}),_e.getInstance().warn(`Invalid event`,`INVALID_EVENT`,{summary:l.summary});return}if(!a[i.key]){c(e,i.key);return}if(l.type===`unsupported_game_version`){let{content:e}=l;q.getInstance().track(`unsupported_game_version`,{game:l.game,hash:e.processHash,version:e.gameVersion})}let u=Dn(i.key,l.type),d=Dn(i.key,`*`),f=t.get(u),p=t.get(d),m=[...Array.from(f??[]),...Array.from(p??[])];m.length===0?s.info(`No handlers found for event`,{event:l}):m.forEach(e=>{e(l)})}function u(t){s.info(t);let r=Ft(t);if(r instanceof n.errors){q.getInstance().track(`invalid_game_event`,{}),_e.getInstance().warn(`Invalid event`,`INVALID_EVENT`,{summary:r.summary});return}let i=Xe.includes(r.type),a=e.modules.find(e=>e.key===`universal`),o=e.modules.find(e=>e.key===r.game),c=[];i&&a&&c.push(a),o&&o!==a&&(!i||r.type in o.events)&&c.push(o),c.length===0?s.warn(`Invalid module`,{module:i?`universal`:r.game}):c.forEach(e=>l(t,r,e))}return i.on(`flushEvents`,t=>{if(a[t])return;a[t]=!0;let i=r.get(t);if(!i)return;L.getInstance().info(`Flushing ${i.length} events for module ${t}`);let o=e.modules.find(e=>e.key===t);o&&i.forEach(e=>{let t=Ft(e);t instanceof n.errors||l(e,t,o)}),r.delete(t)}),o.on(`data`,e=>e.forEach(u)),o.on(`error`,e=>{s.error(`Pipe server error`,e),_e.getInstance().error(`Pipe server error`,`PIPE_SERVER_ERROR`,{error:e})}),o.on(`connected`,()=>{s.log(`Pipe server connected`)}),o.on(`disconnected`,()=>{s.log(`Pipe server disconnected`)}),o}const dr=M(class extends B{FETCH_INTERVAL=6e5;_fetchInterval=null;_flags=/* @__PURE__ */ new Map;_overrides=/* @__PURE__ */ new Map;_defaults=/* @__PURE__ */ new Map;_boundOnGameReady=this.onGameEvent.bind(this);_boundOnGameClose=this.onGameEvent.bind(this);_readyResolve;ready;constructor(){super(`FeatureFlagManager`),this.ready=new Promise(e=>{this._readyResolve=e}),this.fetchFlags(),this.setupInterval(),J.getInstance().on(`gameReady`,this._boundOnGameReady),J.getInstance().on(`gameClose`,this._boundOnGameClose)}destroy(){this._fetchInterval&&=(clearInterval(this._fetchInterval),null),J.getInstance().off(`gameReady`,this._boundOnGameReady),J.getInstance().off(`gameClose`,this._boundOnGameClose),super.destroy()}setDefaults(e){this._defaults=new Map(Object.entries(e))}async refresh(){await this.fetchFlags()}override(e,t){let n=this.get(e);this._overrides.set(e,t),n!==t&&(this.emit(e,t),this.emit(`updated`,!0))}clearOverride(e){if(!this._overrides.has(e))return;let t=this.get(e);this._overrides.delete(e);let n=this.get(e);t!==n&&(this.emit(e,n),this.emit(`updated`,!0))}clearOverrides(){if(this._overrides.size===0)return;let e=/* @__PURE__ */ new Map;for(let t of this._overrides.keys())e.set(t,this.get(t));this._overrides.clear();let t=!1;for(let[n,r]of e){let e=this.get(n);r!==e&&(this.emit(n,e),t=!0)}t&&this.emit(`updated`,!0)}isOverridden(e){return this._overrides.has(e)}getAllOverrides(){return Object.fromEntries(this._overrides)}inspect(e){let t=this._overrides.get(e),n=this._flags.get(e),r=this._defaults.get(e);return{effective:t??n??r??!1,override:t,actual:n,default:r}}get(e){let t=this._overrides.get(e),n=this._flags.get(e),r=this._defaults.get(e);return t??n??r??!1}getAll(){let e=Object.fromEntries(this._defaults);for(let[t,n]of this._flags)e[t]=n;for(let[t,n]of this._overrides)e[t]=n;return e}onGameEvent(){this.fetchFlags()}setupInterval(){this._fetchInterval=setInterval(()=>{this.fetchFlags()},this.FETCH_INTERVAL)}async fetchFlags(){try{let e=J.getInstance().getActiveGames(),{data:t}=await ft(global.OVERLAYED.APPLICATION_ID,{cortex_user_id:global.OVERLAYED_RUNTIME.userId,release_id:global.OVERLAYED_META.release.id??void 0,channel_id:global.OVERLAYED_META.release.channelId??void 0,active_games:e.map(e=>e.toString())??void 0}),n=/* @__PURE__ */ new Map;for(let e of t)n.set(e.name,e.enabled);for(let[e,t]of n){if(this._overrides.has(e))continue;let n=this._flags.get(e);n!==void 0&&n!==t&&this.emit(e,t)}for(let[e]of this._flags)this._overrides.has(e)||n.has(e)||this.emit(e,this._defaults.get(e)??!1);this._flags=n;for(let e of this._defaults.keys())this._flags.has(e)||this.logger.warn(`Registered feature flag "${e}" was not found in the API response`);this.emit(`updated`,!0)}catch(e){this.logger.error(`Failed to fetch feature flags`,e)}finally{this._readyResolve()}}});function fr(e){let t=dr.getInstance();return e&&t.setDefaults(e),{on:(e,n)=>t.on(e,n),off:(e,n)=>t.off(e,n),ready:t.ready,get:e=>t.get(e),getAll:()=>t.getAll(),refresh:()=>t.refresh(),override:(e,n)=>t.override(e,n),clearOverride:e=>t.clearOverride(e),clearOverrides:()=>t.clearOverrides(),isOverridden:e=>t.isOverridden(e),getAllOverrides:()=>t.getAllOverrides(),inspect:e=>t.inspect(e)}}function pr(){let e=Xn.getInstance();return{on:(t,n)=>{e.on(t,n)},off:(t,n)=>{e.off(t,n)},allowSiteUpdateOnNextLoad:()=>{e.allowSiteUpdateOnNextLoad()}}}const mr=n({dismissedNotices:pe(n.string).array()}),hr=M(class extends B{NOTICE_FETCH_INTERVAL=6e5;MAX_DISMISSED_NOTICES=100;_noticeFetchInterval=null;_notices=[];_noticesFile;_boundOnGameReady=this.onGameReady.bind(this);get notices(){let e=this._noticesFile.get().dismissedNotices;return this._notices.filter(t=>!e.includes(t.id))}constructor(){super(`NoticeManager`),this._noticesFile=this.getNoticesFile(),this._noticesFile.load(),this.fetchNotices(),this.setupNoticeInterval(),J.getInstance().on(`gameReady`,this._boundOnGameReady)}destroy(){this._noticeFetchInterval&&=(clearInterval(this._noticeFetchInterval),null),J.getInstance().off(`gameReady`,this._boundOnGameReady),super.destroy()}dismissNotice(e){let t=this._notices.find(t=>t.id===e);if(!t||!t.dismissible)return;let n=this._noticesFile.get().dismissedNotices;n.unshift(e),this._noticesFile.set({dismissedNotices:n.slice(0,this.MAX_DISMISSED_NOTICES)}),this.emitNoticesUpdated()}onGameReady(){this.fetchNotices()}setupNoticeInterval(){this._noticeFetchInterval=setInterval(()=>{this.fetchNotices()},this.NOTICE_FETCH_INTERVAL)}getNoticesFile(){return new ve({path:Pt([`notices.json`]),schema:mr,default:{dismissedNotices:[]}})}async fetchNotices(){let e=J.getInstance().getActiveGames();try{let{data:t}=await pt(global.OVERLAYED.APPLICATION_ID,{release_id:global.OVERLAYED_META.release.id?mt(global.OVERLAYED_META.release.id):void 0,games:e});this._notices=t,this.emitNoticesUpdated()}catch(e){this.logger.error(`Failed to fetch notices`,e)}}emitNoticesUpdated(){this.emit(`noticesUpdated`,{notices:this.notices})}});function gr(){let e=hr.getInstance();return{on:(t,n)=>{e.on(t,n)},off:(t,n)=>{e.off(t,n)},dismissNotice:t=>{e.dismissNotice(t)},getNotices:()=>e.notices}}const{Provider:_r}=ue;var vr=class extends _r{options;updater;logger=L.getInstance().scope(`OverlayedProvider`);constructor(e,t,n){super(n),this.options=e,this.updater=t}async getLatestVersion(){let e=await this.checkWithAccess();if(`error`in e){let t=e.error,n=t instanceof Error?t.stack||t.message:String(t);throw q.getInstance().track(`update_release_check_error`,{message:n}),Error(`Unable to find the latest version (${this.options.release_id}), please ensure release exists. ${n}`)}let t=e.response;this.logger.log(`checkApplicationRelease response`,t.data),q.getInstance().track(`update_release_check_success`,{version:t.data.release.version,channel:t.data.release.channel,fallback:!!t.data.fallback}),t.data.fallback&&this.logger.warn(`Update fallback detected, switching to default channel`);let n=Z(t.data.release.version,this.options.release_version),r=!!this.options.requested_channel||t.data.rollback===!0||n===!1;this.updater.allowDowngrade=r;let i={path:``,sha512:t.data.download_hash??``,version:`${t.data.release.version}-${t.data.release.channel}`,releaseName:t.data.release.id,releaseDate:t.data.release.created_at,files:[{url:t.data.download_url,sha512:t.data.download_hash??``}]};return!r&&n&&yr.add(i),i}resolveFiles(e){return[{info:e.files[0],url:new URL(e.files[0].url)}]}async checkWithAccess(){let{access:e}=this.options,t=await this.checkRelease(this.options.access_token);if(!e)return t;let n=xr(t);if(!n)return`response`in t&&e.onAccessGranted(),t;this.logger.log(`Release check needs an access token`,n);let r=await e.fetchAccessToken(),i=r&&r!==this.options.access_token?await this.checkRelease(r):t,a=xr(i);return r&&`response`in i&&!a?e.onAccessGranted(r):Sr(n)&&Sr(a)&&e.onAccessDenied(),i}async checkRelease(e){try{return{response:await lt(this.options.application_id,{release_id:this.options.release_id,cortex_user_id:this.options.cortex_user_id,access_token:e,requested_channel:this.options.requested_channel})}}catch(e){return{error:e}}}};const yr=/* @__PURE__ */ new WeakSet;function br(e){return yr.has(e)}function Z(e,t){return!de.valid(e)||!de.valid(t)?e!==t&&void 0:de.lt(e,t)}function xr(e){if(`response`in e)return e.response.data.fallback?`fallback`:void 0;let{error:t}=e;if(!Dt(t)||t.response?.status!==403&&t.response?.status!==404||typeof t.response.data!=`object`||!t.response.data||!Ot(t.response))return;let{kind:n}=t.response.data;if(t.response.status===403&&n===`public_releases_disabled`||t.response.status===404&&n===`no_releases_available`)return n}function Sr(e){return e===`fallback`||e===`public_releases_disabled`}function Cr(e){return{provider:`custom`,updateProvider:vr,...e}}function Q(){return ue.autoUpdater}const wr=M(class extends B{TOKEN_REFRESH_INTERVAL=9e5;TOKEN_EXPIRY_BUFFER=3e5;accessTokenFetcher=void 0;_tokenRefreshInterval=null;_downloadStarted=!1;_isUpdateSupported=null;_accessDeniedChannels=/* @__PURE__ */ new Set;constructor(){super(`UpdateManager`)}init(){super.init(),this.registerListenerForwarders(),this.migrateAccessTokenChannel(),this.setupTokenRefreshInterval(),Q().disableDifferentialDownload=!0;let e=Q().isUpdateSupported;this._isUpdateSupported=e,Q().isUpdateSupported=t=>!br(t)&&e(t)}destroy(){Q().removeAllListeners(),this._isUpdateSupported&&=(Q().isUpdateSupported=this._isUpdateSupported,null),this._tokenRefreshInterval&&=(clearInterval(this._tokenRefreshInterval),null),super.destroy()}setupTokenRefreshInterval(){this._tokenRefreshInterval=setInterval(()=>{this.checkAndRefreshToken()},this.TOKEN_REFRESH_INTERVAL)}async checkAndRefreshToken(){let e=K(),t=Bt();if(!e||!t||!this.accessTokenFetcher||!this.isAccessTokenExpiring(e))return;this.logger.log(`Refreshing access token for channel`,t);let n=await this.fetchAccessToken(t);n!==void 0&&K()===e&&Vt(n,t)}async checkForUpdates(e){this.logger.log(`Starting checkForUpdates`);let t=e??global.OVERLAYED_META.release.channel;return q.getInstance().track(`check_for_update`,{channel:t}),this._downloadStarted=!1,e?(Q().allowDowngrade=!0,Q().channel=e):(Q().channel=global.OVERLAYED_META.release.channel,Q().allowDowngrade=!1),this.setFeedUrl({channel:t,requestedChannel:e}),this.logger.log(`Checking for updates`),Q().checkForUpdates()}async switchChannel(e){return this.logger.log(`Switching channel`,e),q.getInstance().track(`update_channel_switch`,{from_channel:global.OVERLAYED_META.release.channel,to_channel:e}),this._downloadStarted=!1,Q().allowDowngrade=!0,Q().channel=e,this.setFeedUrl({channel:e,requestedChannel:e}),Q().checkForUpdates()}quitAndInstall(e,t){this.logger.log(`quitAndInstall`,{isSilent:e,isForceRunAfter:t});let[n,r]=this.canUpdate();if(!n)throw this.logger.warn(`Cannot update`,{denialReason:r}),q.getInstance().track(`update_install_blocked`,{reason:r}),Error(r);return this.logger.log(`Quitting and installing`),q.getInstance().track(`update_install`,{}),Q().quitAndInstall(e,t)}canUpdate(){return J.getInstance().isInGame?[!1,`User is in game`]:[!0,null]}downloadUpdate(e){return Q().downloadUpdate(e)}setAccessTokenFetcher(e){this.accessTokenFetcher=e}setFeedUrl(e){if(this.accessTokenFetcher||(this.logger.warn(`accessTokenFetcher is not set, private channels will not work.`),Vt(null)),!global.OVERLAYED_META.release.id){this.logger.warn(`Tried to set feed URL in development mode`);return}let t=this.getHeldAccessToken(e.channel);Q().setFeedURL(Cr({application_id:global.OVERLAYED.APPLICATION_ID,release_id:global.OVERLAYED_META.release.id,release_version:global.OVERLAYED_META.release.version,cortex_user_id:global.OVERLAYED_RUNTIME.userId,access_token:t,requested_channel:e.requestedChannel,access:this.createReleaseCheckAccess(e.channel)}))}getHeldAccessToken(e){let t=K();if(t&&Bt()===e&&!this.isAccessTokenExpiring(t))return t}createReleaseCheckAccess(e){if(this.accessTokenFetcher)return{fetchAccessToken:async()=>await this.fetchAccessToken(e)??null,onAccessGranted:t=>{this._accessDeniedChannels.delete(e),t&&Vt(t,e)},onAccessDenied:()=>{K()&&Bt()===e&&Vt(null),!this._accessDeniedChannels.has(e)&&(this._accessDeniedChannels.add(e),q.getInstance().track(`update_token_invalid`,{channel:e}),this.emit(`authTokenInvalid`,{}))}}}async fetchAccessToken(e){if(!this.accessTokenFetcher)return null;try{let t=await this.accessTokenFetcher(e)??null;return this.logger.log(`New token fetched`,t?.slice(0,5)+`...`),t}catch(e){let t=e instanceof Error?e.message:String(e);q.getInstance().track(`update_token_fetch_error`,{message:t}),this.logger.error(`Error fetching new token`,{error:e,message:t});return}}migrateAccessTokenChannel(){let e=K(),t=Bt(),n=global.OVERLAYED_META.release.channel;e&&!t?Vt(e,n):e&&t!==n&&Vt(null)}isAccessTokenExpiring(e){let t=this.getAccessTokenExpirationDate(e);return!t||t.getTime()<Date.now()+this.TOKEN_EXPIRY_BUFFER}registerListenerForwarders(){Q().on(`checking-for-update`,()=>{this.logger.info(`Checking for updates`),this.emit(`checkingForUpdates`,{})}),Q().on(`download-progress`,e=>{this._downloadStarted||(this._downloadStarted=!0,q.getInstance().track(`update_download_started`,{version:Q().currentVersion?.version??``})),this.emit(`downloadProgress`,{info:e});let t=`Download speed: ${e.bytesPerSecond} - Downloaded ${e.percent}%`;t+=` (${e.transferred}/${e.total})`,this.logger.log(t)}),Q().on(`error`,(e,t)=>{this.logger.error(`Error`,e,t),q.getInstance().track(`update_download_error`,{message:t??e.message}),this.emit(`error`,{error:e,message:t})}),Q().on(`update-not-available`,e=>{this.logger.info(`Update not available`,e),q.getInstance().track(`update_not_available`,{version:e.version}),this.emit(`updateNotAvailable`,{info:e})}),Q().on(`update-available`,e=>{this.logger.info(`Update available`,e),q.getInstance().track(`update_available`,{version:e.version,channel:Q().channel??``}),this.emit(`updateAvailable`,{info:e})}),Q().on(`update-downloaded`,e=>{this.logger.info(`Update downloaded`,e),q.getInstance().track(`update_download_complete`,{version:e.version}),this.emit(`updateDownloaded`,{event:e})}),Q().on(`update-cancelled`,e=>{this.logger.info(`Update cancelled`,e),q.getInstance().track(`update_cancelled`,{version:e.version}),this.emit(`updateCancelled`,{info:e})})}getAccessTokenExpirationDate(e){try{let t=e.split(`.`)[1];if(!t)return null;let n=atob(t.replace(/-/g,`+`).replace(/_/g,`/`)),r=JSON.parse(n);return r.exp?/* @__PURE__ */ new Date(r.exp*1e3):null}catch{return null}}});function Tr(){let e=wr.getInstance();return{site:pr(),on:(t,n)=>{e.on(t,n)},off:(t,n)=>{e.off(t,n)},setAccessTokenFetcher:t=>e.setAccessTokenFetcher(t),checkForUpdates:()=>e.checkForUpdates(),switchChannel:t=>e.checkForUpdates(t),quitAndInstall:(t,n)=>e.quitAndInstall(t,n),canUpdate:()=>e.canUpdate(),downloadUpdate:t=>e.downloadUpdate(t)}}function Er(){return{getChannel:()=>global.OVERLAYED_META.release.channel,getVersion:()=>global.OVERLAYED_META.release.version,getReleaseId:()=>global.OVERLAYED_META.release.id}}const Dr=M(class extends B{_knownModificationTimes=/* @__PURE__ */ new Map;_confirmedDumps=/* @__PURE__ */ new Set;_pendingReports=/* @__PURE__ */ new Map;_snapshotTimestamp=0;boundOnGameReady=this.onGameReady.bind(this);boundOnGameClose=this.onGameClose.bind(this);constructor(){super(`CrashDumpManager`)}init(){super.init(),this.logger.debug(`init() registering game event listeners`),J.getInstance().on(`gameReadyInternal`,this.boundOnGameReady),J.getInstance().on(`gameCloseInternal`,this.boundOnGameClose),this.logger.debug(`init() complete`)}destroy(){this.logger.debug(`destroy() called`,{pendingReports:this._pendingReports.size,confirmedDumps:this._confirmedDumps.size,knownModificationTimes:this._knownModificationTimes.size}),J.getInstance().off(`gameReadyInternal`,this.boundOnGameReady),J.getInstance().off(`gameCloseInternal`,this.boundOnGameClose),this._knownModificationTimes.clear(),this._confirmedDumps.clear(),this._pendingReports.clear(),this._snapshotTimestamp=0,this.logger.debug(`destroy() cleanup complete`),super.destroy()}async submit(e){this.logger.debug(`submit() called`,{id:e,pendingCount:this._pendingReports.size});let t=this._pendingReports.get(e);if(!t){this.logger.warn(`submit called with unknown id`,e);return}let{response:n,dumpPath:r}=t;this.logger.debug(`Resolved pending report for submission`,{id:e,dumpPath:r});let i=global.OVERLAYED.APPLICATION_ID,a=Lt();if(this.logger.debug(`Resolved identifiers for submission`,{applicationId:i,cortexUserId:a}),n.crash_dump_upload_request)try{this.logger.debug(`Reading crash dump file`,{dumpPath:r});let t=await E.readFile(r);this.logger.debug(`Uploading crash dump`,{dumpPath:r,size:t.byteLength}),await vt(n.crash_dump_upload_request,new Uint8Array(t)),this.logger.debug(`Crash dump uploaded, confirming`,{id:e}),await ut(i,e,{cortex_user_id:a,file_type:`crash_dump`}),this.logger.debug(`Crash dump confirmed`,{id:e})}catch(e){this.logger.error(`Failed to upload crash dump`,{dumpPath:r,error:e})}else this.logger.warn(`No crash dump upload request in response`,{id:e});this._pendingReports.delete(e),this._confirmedDumps.add(r),this.logger.debug(`Report state updated, attempting dump file cleanup`,{id:e,dumpPath:r});try{await E.unlink(r),this.logger.debug(`Dump file cleaned up successfully`,{dumpPath:r})}catch(e){this.logger.warn(`Failed to clean up dump file after submission`,{dumpPath:r,error:e})}this.logger.log(`Crash report submitted successfully`,r)}async onGameReady({game:e}){this.logger.debug(`onGameReady() fired`,{game:e.identifier}),await this.snapshotModificationTimes(),this.logger.debug(`onGameReady() snapshot complete`,{game:e.identifier})}async onGameClose({game:e}){this.logger.debug(`onGameClose() fired`,{game:e.identifier}),await this.scanForNewDumps(xt(e.identifier)),this.logger.debug(`onGameClose() scan complete`,{game:e.identifier})}async snapshotModificationTimes(){let e=F();this._snapshotTimestamp=Date.now(),this.logger.debug(`snapshotModificationTimes() called`,{crashDumpsPath:e,snapshotTimestamp:this._snapshotTimestamp});try{await E.access(e)}catch{this.logger.debug(`Crash dumps directory does not exist, skipping snapshot`,{crashDumpsPath:e});return}let t=await this.findAllDumps(e);this.logger.debug(`Found dumps for snapshot`,{count:t.length});for(let e of t)try{let t=await E.stat(e);if(t.mtimeMs>=this._snapshotTimestamp-3e4){this.logger.debug(`Skipping recent dump from snapshot`,{dumpPath:e,mtimeMs:t.mtimeMs,snapshotTimestamp:this._snapshotTimestamp});continue}this._knownModificationTimes.set(e,t.mtimeMs),this.logger.debug(`Recorded modification time`,{dumpPath:e,mtimeMs:t.mtimeMs})}catch(t){this.logger.warn(`Failed to stat dump file during snapshot`,{dumpPath:e,error:t})}this.logger.debug(`Snapshot complete`,{totalTracked:this._knownModificationTimes.size})}async scanForNewDumps(e){let t=F();this.logger.debug(`scanForNewDumps() called`,{game:e,crashDumpsPath:t});try{await E.access(t)}catch{this.logger.debug(`Crash dumps directory does not exist, skipping scan`,{crashDumpsPath:t});return}let n=new Set([...this._pendingReports.values()].map(e=>e.dumpPath)),r=await this.findAllDumps(t);this.logger.debug(`Scan found dumps`,{total:r.length,pendingCount:n.size,confirmedCount:this._confirmedDumps.size});for(let t of r){if(this._confirmedDumps.has(t)){this.logger.debug(`Skipping already confirmed dump`,{dumpPath:t});continue}if(n.has(t)){this.logger.debug(`Skipping already pending dump`,{dumpPath:t});continue}let r;try{r=await E.stat(t)}catch(e){this.logger.warn(`Failed to stat dump file during scan`,{dumpPath:t,error:e});continue}let i=r.mtimeMs,a=this._knownModificationTimes.get(t);if(this.logger.debug(`Comparing modification times`,{dumpPath:t,modificationTime:i,knownModificationTime:a}),a===void 0||i>a){this.logger.debug(`Dump is new or modified`,{dumpPath:t,isNew:a===void 0});try{let n=r.size,i=m.basename(m.dirname(t)),a=m.basename(t,m.extname(t));this.logger.debug(`Preparing crash report`,{dumpPath:t,crashDumpSize:n,crashSource:i});let o=(await or().generateAsync({type:`uint8array`})).byteLength,s=global.OVERLAYED.APPLICATION_ID,c=Lt(),l=global.OVERLAYED_META.release.id;if(!l)throw Error(`Missing release id, the API rejects crash reports without one`);this.logger.debug(`Creating game crash report via API`,{applicationId:s,cortexUserId:c,game:e,crashSource:i,crashDumpSize:n,logsSize:o});let{data:u}=await U(s,{cortex_user_id:c,game:e,crash_source:i,crash_identifier:a,release_id:l,logs_size:o,crash_dump_size:n});this._pendingReports.set(u.id,{response:u,dumpPath:t}),this.logger.debug(`Crash report created, emitting 'new' event`,{id:u.id,game:e}),this.logger.log(`New crash dump detected`,{dumpPath:t,game:e,id:u.id}),this.emit(`new`,{id:u.id,game:e})}catch(e){this.logger.error(`Failed to create game crash report`,{dumpPath:t,error:e})}}else this.logger.debug(`Dump unchanged, skipping`,{dumpPath:t});this._knownModificationTimes.set(t,i)}this.logger.debug(`scanForNewDumps() complete`,{game:e,pendingReports:this._pendingReports.size})}async findAllDumps(e){this.logger.debug(`findAllDumps() called`,{basePath:e});let t=[],n;try{n=await E.readdir(e,{withFileTypes:!0})}catch(n){return this.logger.warn(`Failed to read crash dumps directory`,{basePath:e,error:n}),t}this.logger.debug(`Top-level entries in crash dumps directory`,{count:n.length,directories:n.filter(e=>e.isDirectory()).map(e=>e.name)});for(let r of n)if(r.isDirectory()){let n=m.join(e,r.name),i;try{i=await E.readdir(n,{withFileTypes:!0})}catch(e){this.logger.warn(`Failed to read crash dump subdirectory`,{subPath:n,error:e});continue}let a=i.filter(e=>e.isFile()&&e.name.endsWith(`.dmp`));this.logger.debug(`Scanned subdirectory`,{subPath:n,totalEntries:i.length,dmpCount:a.length});for(let e of a)t.push(m.join(n,e.name))}return this.logger.debug(`findAllDumps() complete`,{totalFound:t.length}),t}});let Or=!1;const $=/* @__PURE__ */ new WeakSet;function kr(){if(!Or){for(let e of ce.getAllWebContents())Ar(e);O.on(`web-contents-created`,(e,t)=>{Ar(t)}),Or=!0}}function Ar(e){let t=Object.getPrototypeOf(e);if($.has(t))return;let n=t.isFocused;t.isFocused=function(){return!jr(this)&&n.call(this)},$.add(t)}function jr(e){let t=e;for(;t;){if(t.isOffscreen())return!0;if(t.getType()!==`webview`)return!1;t=t.hostWebContents??null}return!1}let Mr=!1,Nr={},Pr,Fr=new A,Ir;function Lr(e){zr(e),kr();let t=Rr(e),{init:n=!0,debug:r=!1,silent:i=!0}=t,a=Vr(e);if(L.getInstance().init(e.applicationId,r,i),Zn.getInstance().init(e.applicationId,r,!0,!0),a&&Wr(st(e.applicationId),!1).catch(()=>{}),Mr)return Pr;function o(){if(Mr){L.getInstance().warn(`Overlayed already initialized`);return}Fn(),e.analytics?.crashes!==!1&&q.getInstance().enabled&&!xn.getInstance().initialized&&xn.getInstance().init({stateDir:m.join(we(e.applicationId),`crash-tracking`)});let n=Sn.get({createIfMissing:!1});if(n){let t=En({currentAccount:n.currentAccount,accounts:n.accounts,expected:{applicationId:e.applicationId,baseUrl:$e}});t&&tt(()=>t.account.apiKey)}let r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map,a=Tr(),s=On(t.modules,r,Fr),c=kn(),l=Pn(t.keybinds),u=er(t.navigationGuard),d=nr(),f=X(),p=rr(),h=cr(t),g=gr(),_=fr(t.featureFlags),v=Er();L.getInstance().log(`Overlayed initialized`),Hr(t),ur(t,r,i,Fr,Nr),Mr=!0,Pr={...s,...c,ads:f,keybinds:l,windows:u,input:d,cortex:p,hasAnyActiveProcesses:()=>Gt.getInstance().hasAnyActiveGames,hasAnyActiveGames:()=>J.getInstance().isInGame,init:o,log:h,initialized:Mr,notices:g,featureFlags:_,updater:a,application:v,crashDumps:{on:(e,t)=>Dr.getInstance().on(e,t),off:(e,t)=>Dr.getInstance().off(e,t),submit:e=>Dr.getInstance().submit(e)}},Pr.universal.on(`logged_in`,e=>{q.getInstance().track(`account_id`,{account_id:e.content.accountId,game:e.game})})}return n&&a?(o(),Pr):new Proxy({init:o},{get:(e,t)=>{if(t===`init`)return e[t];if(!Mr)throw Error(a?`overlayed was called before initialized: ${t}`:Br);return Pr[t]}})}function Rr(e){return{...e,modules:[...e.modules,z()]}}global.OVERLAYED=new Proxy({},{get:()=>{throw Error(`function overlayed was not called`)}});function zr(e){if(!he(e.applicationId))throw Error(`Invalid applicationId, must be a valid ULID.`)}const Br="Overlayed metadata has not been initialized yet. Run `overlayed init` to set up your local development environment.";function Vr(e){let t=Ur(),n=`2.9.2`,r=st(e.applicationId);function i(){return{package_version:n,application_id:r,application_version:t?.release.version??`0.0.0`}}return L.getInstance().log(`ua object`,i()),rt(()=>i()),t===null?(global.OVERLAYED=new Proxy({},{get:()=>{throw Error(Br)}}),Wr(r,!0),!1):(global.OVERLAYED={APPLICATION_ID:r,APP_BUILD_CHANNEL:t.release.channel,APP_VERSION:t.release.version,PACKAGE_VERSION:n,FRONTEND_VERSION:`0.0.0`,sessionId:Rt(),electron:e.electron},global.OVERLAYED_META=t,global.OVERLAYED_RUNTIME={userId:Lt(),webVitals:e.analytics?.webVitals!==!1},L.getInstance().log(`meta`,t),!0)}function Hr(e){L.getInstance().warn(`Bootstrapping`);let t=e.universal?[`*`]:e.modules.map(e=>e.key);J.getInstance().setSubscribedGames(t),L.getInstance().warn(`Initializing update manager`),wr.getInstance().init(),L.getInstance().warn(`Initialized update manager`),Xn.getInstance().init({manualUpdates:e.site?.manualUpdates??!1}),en.getInstance().init(),J.getInstance().init(),Dr.getInstance().init(),Gt.getInstance().init(),Kt.getInstance().init({subscribedGames:t}),q.getInstance().track(`start`,{}),tn.getInstance().check(e.applicationId);try{Ir&&clearInterval(Ir),Ir=setInterval(()=>{try{zt()}catch{}},3e4),Ir.unref()}catch(e){L.getInstance().log(`failed to start sessionLastUsed interval`,e)}async function n(){let e={};e.os=te.platform().trim(),e.os_version=process.getSystemVersion().trim(),e.architecture=te.arch().trim();let t=te.cpus();t.length>0?(e.cpu=t[0].model.trim(),e.cpu_cores=t.length,e.cpu_speed=t[0].speed):L.getInstance().warn(`Failed to collect CPU info`);let n=await le.graphics();L.getInstance().info(`GPU info`,n);let r=n.controllers.sort((e,t)=>(t.vram??0)-(e.vram??0))[0];r?(e.gpu=r.model.trim(),e.gpu_memory=r.vram??0):L.getInstance().warn(`Failed to find primary GPU`),e.display_count=n.displays.length;let i=n.displays.find(e=>e.main)??n.displays[0];i?(e.primary_display_resolution_x=i.resolutionX??void 0,e.primary_display_resolution_y=i.resolutionY??void 0,e.primary_display_refresh_rate=i.currentRefreshRate??void 0):L.getInstance().warn(`Failed to find main display`),e.ram=process.getSystemMemoryInfo().total;let a=te.homedir(),o=await E.statfs(a);return o&&`blocks`in o&&`bsize`in o&&`bavail`in o?(e.disk=o.blocks*o.bsize,e.disk_free=o.bavail*o.bsize):L.getInstance().warn(`Failed to collect disk info`),L.getInstance().log(`Retrieved system information`,e),e}O.on(`ready`,()=>{n().then(e=>{q.getInstance().track(`system_info`,e)}).catch(e=>{L.getInstance().log(`Failed to retrieve system information`,e)})}),O.on(`quit`,()=>{q.getInstance().track(`electron_quit`,{}),Gr()}),process.on(`exit`,()=>{q.getInstance().track(`exit`,{}),Gr()})}function Ur(){if(O.isPackaged)try{let e=m.join(process.resourcesPath,`meta.json`);return JSON.parse(y.readFileSync(e,`utf-8`))}catch(e){throw Error(`Failed to read application metadata from resources/meta.json`,{cause:e})}{let e=m.join(process.cwd(),`.overlayed`,`meta.json`);return y.existsSync(e)?JSON.parse(y.readFileSync(e,`utf-8`)):null}}async function Wr(e,t=!1){if(!O.isPackaged)try{L.getInstance().log(`Fetching application metadata from API...`);let n=je({...(await ct(e)).data,siteUrl:``});t&&(L.getInstance().log(v.yellowBright(`Uninitialized development environment detected. Created .overlayed folder. In the future, run ${v.bold(`overlayed init`)} to do so. \n\nThe process will now exit to load the cached metadata.\n\n${v.italic(`Note: This will never happen in a packaged application, and will only happen once in local development so long as the .overlayed folder exists.`)}`)),process.exit(0)),global.OVERLAYED_META=n}catch(e){L.getInstance().error(`Failed to fetch application meta`,e),t&&(console.error(`
|
|
17
|
+
`)).digest(`hex`).slice(0,32)}function dn(e){try{let t=e();return typeof t==`string`?t:``}catch{return``}}function fn(e){try{return e instanceof Error}catch{return!1}}function pn(e){let t,n,r;fn(e)?(t=dn(()=>e.name)||`Error`,n=dn(()=>e.message),r=dn(()=>e.stack)||void 0):(t=e===null?`null`:typeof e,n=typeof e==`string`?e:dn(()=>JSON.stringify(e))||dn(()=>String(e))||`[unserializable]`);let i={name:cn(t,an.errorName),message:cn(n,an.message),fingerprint:``};return r&&(i.stack=cn(r,an.stack)),i.fingerprint=un(i.name,i.message,i.stack),i}function mn(e){return URL.canParse(e)?rn(new URL(e)):``}const hn=n({kind:`'uncaught_exception' | 'unhandled_rejection'`,name:`string`,message:`string`,"stack?":`string`,fingerprint:`string`,crashedAt:`number`}),gn=n({pid:`number`,sessionId:`string`,releaseId:`string`,appVersion:`string`,startedAt:`number`,lastHeartbeatAt:`number`,inGame:`boolean`,"game?":`string`,"exception?":hn,"shutdown?":`boolean`,"quit?":`boolean`}),_n=/* @__PURE__ */ new Set([`clean-exit`]),vn=/* @__PURE__ */ new WeakMap;function yn(e,t){vn.set(e,{inGame:t,createdAt:Date.now()})}function bn(e,t){return{type:e,properties:t,created_at:/* @__PURE__ */ new Date}}const xn=M(class extends Ze{state=null;statePath=null;heartbeatInterval;survivalTimeout;exceptionCount=0;exceptionCountByFingerprint=/* @__PURE__ */ new Map;boundOnRenderProcessGone=this.onRenderProcessGone.bind(this);boundOnChildProcessGone=this.onChildProcessGone.bind(this);boundOnUncaughtException=this.onUncaughtException.bind(this);boundOnGameStateChange=this.onGameStateChange.bind(this);boundOnBrowserWindowCreated=this.onBrowserWindowCreated.bind(this);boundOnShutdown=this.onShutdown.bind(this);boundOnExit=this.onExit.bind(this);boundOnQuit=this.onQuit.bind(this);constructor(){super(`AppCrashManager`)}init(e){super.init(e),O.on(`render-process-gone`,this.boundOnRenderProcessGone),O.on(`child-process-gone`,this.boundOnChildProcessGone),process.on(`uncaughtExceptionMonitor`,this.boundOnUncaughtException),this.reportPreviousSessions(e.stateDir),this.startSession(e.stateDir)}destroy(){O.off(`render-process-gone`,this.boundOnRenderProcessGone),O.off(`child-process-gone`,this.boundOnChildProcessGone),O.off(`browser-window-created`,this.boundOnBrowserWindowCreated),O.off(`quit`,this.boundOnQuit),process.off(`uncaughtExceptionMonitor`,this.boundOnUncaughtException),process.off(`exit`,this.boundOnExit),J.getInstance().off([`gameReady`,`gameClose`],this.boundOnGameStateChange),O.isReady()&&se.off(`shutdown`,this.boundOnShutdown),clearInterval(this.heartbeatInterval),clearTimeout(this.survivalTimeout),this.heartbeatInterval=void 0,this.survivalTimeout=void 0,this.state=null,this.statePath=null,this.exceptionCount=0,this.exceptionCountByFingerprint.clear(),super.destroy()}startSession(e){let t=Date.now();this.statePath=m.join(e,`${process.pid}-${t}.json`),this.state={pid:process.pid,sessionId:global.OVERLAYED.sessionId,releaseId:global.OVERLAYED_META.release.id??``,appVersion:global.OVERLAYED.APP_VERSION,startedAt:t,lastHeartbeatAt:t,inGame:!1},this.updateGameState(),this.writeState(),this.heartbeatInterval=setInterval(()=>{this.state&&(this.state.lastHeartbeatAt=Date.now(),this.writeState())},3e4),this.heartbeatInterval.unref(),J.getInstance().on([`gameReady`,`gameClose`],this.boundOnGameStateChange),O.on(`quit`,this.boundOnQuit),process.on(`exit`,this.boundOnExit),O.on(`browser-window-created`,this.boundOnBrowserWindowCreated);for(let e of oe.getAllWindows())e.once(`session-end`,this.boundOnShutdown);O.whenReady().then(()=>{this.state&&se.on(`shutdown`,this.boundOnShutdown)})}async reportPreviousSessions(e){let t;try{t=y.readdirSync(e)}catch{return}let n=[];for(let r of t){let t=/^(.+\.json)\.claimed-(\d+)$/.exec(r);if(!r.endsWith(`.json`)&&(!t||this.isProcessAlive(Number(t[2]))))continue;let i=m.join(e,t?t[1]:r),a=m.join(e,r),o=this.readState(a);if(o===void 0||o!==null&&!t&&this.isLiveInstance(o))continue;if(o===null||(o.shutdown||o.quit)&&!o.exception){this.removeFile(a);continue}let s=`${i}.claimed-${process.pid}`;try{y.renameSync(a,s)}catch{continue}n.push({originalPath:i,claimedPath:s,state:o})}let r=q.getInstance().meta;for(let{originalPath:e,claimedPath:t,state:i}of n)try{if(!r)throw Error(`Cortex meta is not set`);await Tt({...r,messages:this.getPreviousSessionMessages(i)}),this.removeFile(t)}catch(n){this.logger.warn(`Failed to report previous session, retrying on next launch`,n);try{y.renameSync(t,e)}catch{}}}getPreviousSessionMessages(e){let t=[],n=e.exception?.crashedAt,r={crashed_session_id:e.sessionId,crashed_release_id:e.releaseId,crashed_app_version:e.appVersion};if(e.exception){let{kind:n,name:i,message:a,stack:o,fingerprint:s}=e.exception;t.push(bn(`main_exception`,{kind:n,name:i,message:a,...o===void 0?{}:{stack:o},fingerprint:s,fatal:!0,...r,crashed_at:e.exception.crashedAt,was_in_game:e.inGame}))}let i={...r,started_at:e.startedAt,last_heartbeat_at:e.lastHeartbeatAt,uptime_ms:Math.max(0,(n??e.lastHeartbeatAt)-e.startedAt),was_in_game:e.inGame,has_minidump:!1};return e.game&&(i.game=e.game),n!==void 0&&(i.crashed_at=n),this.logger.warn(`Previous session did not exit cleanly`,i),t.push(bn(`unclean_exit`,i)),t}onRenderProcessGone(e,t,n){if(_n.has(n.reason))return;let r=vn.get(t),i=``;try{i=t.getURL()}catch{}this.logger.warn(`Render process gone`,{reason:n.reason,exitCode:n.exitCode,url:i}),q.getInstance().track(`renderer_crash`,{reason:n.reason.slice(0,an.reason),exit_code:n.exitCode,page:mn(i),window_type:r?.inGame?`in_game`:`desktop`,...r?{window_age_ms:Date.now()-r.createdAt}:{}})}onChildProcessGone(e,t){_n.has(t.reason)||(this.logger.warn(`Child process gone`,t),q.getInstance().track(`child_process_crash`,{process_type:t.type.slice(0,an.processType),reason:t.reason.slice(0,an.reason),exit_code:t.exitCode,...t.serviceName?{service_name:t.serviceName.slice(0,an.processName)}:{},...t.name?{name:t.name.slice(0,an.processName)}:{}}))}onUncaughtException(e,t){try{let n={kind:t===`unhandledRejection`?`unhandled_rejection`:`uncaught_exception`,...pn(e),crashedAt:Date.now()};if(!this.state){this.trackNonFatalException(n);return}this.state.exception&&(this.trackNonFatalException(this.state.exception),clearTimeout(this.survivalTimeout)),this.state.exception=n,this.writeState(),this.survivalTimeout=setTimeout(()=>{if(this.survivalTimeout=void 0,!this.state?.exception)return;let e=this.state.exception;delete this.state.exception,this.writeState(),this.trackNonFatalException(e)},5e3),this.survivalTimeout.unref()}catch{}}trackNonFatalException({kind:e,name:t,message:n,stack:r,fingerprint:i}){let a=this.exceptionCountByFingerprint.get(i)??0;this.exceptionCount>=50||a>=5||(this.exceptionCount++,this.exceptionCountByFingerprint.set(i,a+1),q.getInstance().track(`main_exception`,{kind:e,name:t,message:n,...r===void 0?{}:{stack:r},fingerprint:i,fatal:!1}))}onGameStateChange(){this.updateGameState(),this.writeState()}updateGameState(){if(!this.state)return;let e=J.getInstance(),[t]=e.getActiveGames();this.state.inGame=e.isInGame,t?this.state.game=String(t).slice(0,an.game):delete this.state.game}onBrowserWindowCreated(e,t){t.once(`session-end`,this.boundOnShutdown)}onShutdown(){this.state&&!this.state.shutdown&&(this.state.shutdown=!0,this.writeState())}onExit(e){this.state&&!this.state.exception&&e===0&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0,this.statePath&&this.removeFile(this.statePath))}onQuit(e,t){this.state&&t===0&&(this.state.quit=!0,this.writeState())}isProcessAlive(e){if(e===process.pid)return!1;try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}isLiveInstance(e){return Date.now()-e.lastHeartbeatAt<=9e4&&this.isProcessAlive(e.pid)}readState(e){let t;try{t=y.readFileSync(e,`utf8`)}catch{return}try{let e=gn(JSON.parse(t));return e instanceof n.errors?(this.logger.warn(`Ignoring invalid session state file`,e.summary),null):e}catch(e){return this.logger.warn(`Ignoring unreadable session state file`,e),null}}writeState(){if(this.state&&this.statePath)try{let e=`${this.statePath}.tmp`;y.mkdirSync(m.dirname(this.statePath),{recursive:!0}),y.writeFileSync(e,JSON.stringify(this.state)),y.renameSync(e,this.statePath)}catch(e){this.logger.warn(`Failed to write session state file`,e)}}removeFile(e){try{y.rmSync(e,{force:!0})}catch(e){this.logger.warn(`Failed to remove session state file`,e)}}}),Sn=new ve({path:f.normalize(`${process.env.APPDATA||process.env.HOME||`.`}/.overlayed/config.json`),default:void 0,schema:t({Account:n({email:`string`,apiKey:`string`,"applicationId?":`string`,"applicationIds?":`string[]`,"baseUrl?":`string`})}).type({currentAccount:`Account | undefined`,accounts:`Account[]`}).or(`undefined`)});function Cn(e){return wn(e).map(e=>String(e).toUpperCase())}function wn(e){let{applicationId:t,applicationIds:n}=e;return Array.isArray(n)&&n.length>0?n:t===void 0?n===void 0||Array.isArray(n)?[]:[n]:[t]}function Tn(e,t,n){let r=Cn(e),i=t===void 0||r.length===0||r.includes(t),a=(e.baseUrl??`https://api.overlayed.gg`)===n;return i&&a}function En(e){let{currentAccount:t,accounts:n,expected:r}=e,i=r.applicationId===void 0?void 0:String(r.applicationId).toUpperCase(),a=e=>Tn(e,i,r.baseUrl);if(t&&a(t))return{account:t,source:`current`};let o=n.find(a);if(o)return{account:o,source:`other`}}function Dn(e,t){return`${e}:${t}`}function On(e,t,n){return e.reduce((e,r)=>{let i=r.key;return e[i]={on(e,n){let r=Dn(i,e),a=t.get(r)??/* @__PURE__ */ new Set;a.add(n),t.set(r,a)},onAny(e){let n=Dn(i,`*`),r=t.get(n)??/* @__PURE__ */ new Set;r.add(e),t.set(n,r)},off(e,n){let r=Dn(i,e),a=t.get(r);a&&(a.delete(n),a.size===0&&t.delete(r))},offAny(e){let n=Dn(i,`*`),r=t.get(n);r&&(r.delete(e),r.size===0&&t.delete(n))},readyForGameEvents:()=>{n.emit(`flushEvents`,i)}},e},{})}function kn(){let e=_e.getInstance(),t=J.getInstance();return{on:(n,r)=>{switch(n){case`fatal`:e.on(`fatal`,r);break;case`error`:e.on(`error`,r);break;case`warning`:e.on(`warning`,r);break;case`gameLaunch`:t.on(`gameLaunch`,r);break;case`gameClose`:t.on(`gameClose`,r);break;case`gameReady`:t.on(`gameReady`,r);break;default:throw Error(`Event type not implemented ${n}`,{cause:[n,r]})}},off:(n,r)=>{switch(n){case`fatal`:e.off(`fatal`,r);break;case`error`:e.off(`error`,r);break;case`warning`:e.off(`warning`,r);break;case`gameLaunch`:t.off(`gameLaunch`,r);break;case`gameClose`:t.off(`gameClose`,r);break;case`gameReady`:t.off(`gameReady`,r);break;default:throw Error(`Event type not implemented ${n}`,{cause:[n,r]})}}}}const An=/* @__PURE__ */ new Map([[1,`LeftButton`],[2,`RightButton`],[3,`Cancel`],[4,`MiddleButton`],[5,`ExtraButton1`],[6,`ExtraButton2`],[8,`Backspace`],[9,`Tab`],[12,`Clear`],[13,`Enter`],[16,`ShiftLeft`],[17,`ControlLeft`],[18,`AltLeft`],[19,`Pause`],[20,`CapsLock`],[21,`KanaMode`],[23,`JunjaMode`],[24,`Finalize`],[25,`HanjaMode`],[27,`Escape`],[28,`Convert`],[29,`NonConvert`],[30,`Accept`],[31,`ModeChange`],[32,`Space`],[33,`PageUp`],[34,`PageDown`],[35,`End`],[36,`Home`],[37,`ArrowLeft`],[38,`ArrowUp`],[39,`ArrowRight`],[40,`ArrowDown`],[41,`Select`],[42,`PrintScreen`],[43,`Execute`],[44,`Snapshot`],[45,`Insert`],[46,`Delete`],[47,`Help`],[48,`Digit0`],[49,`Digit1`],[50,`Digit2`],[51,`Digit3`],[52,`Digit4`],[53,`Digit5`],[54,`Digit6`],[55,`Digit7`],[56,`Digit8`],[57,`Digit9`],[65,`KeyA`],[66,`KeyB`],[67,`KeyC`],[68,`KeyD`],[69,`KeyE`],[70,`KeyF`],[71,`KeyG`],[72,`KeyH`],[73,`KeyI`],[74,`KeyJ`],[75,`KeyK`],[76,`KeyL`],[77,`KeyM`],[78,`KeyN`],[79,`KeyO`],[80,`KeyP`],[81,`KeyQ`],[82,`KeyR`],[83,`KeyS`],[84,`KeyT`],[85,`KeyU`],[86,`KeyV`],[87,`KeyW`],[88,`KeyX`],[89,`KeyY`],[90,`KeyZ`],[91,`MetaLeft`],[92,`MetaRight`],[93,`ContextMenu`],[95,`Sleep`],[96,`Numpad0`],[97,`Numpad1`],[98,`Numpad2`],[99,`Numpad3`],[100,`Numpad4`],[101,`Numpad5`],[102,`Numpad6`],[103,`Numpad7`],[104,`Numpad8`],[105,`Numpad9`],[106,`NumpadMultiply`],[107,`NumpadAdd`],[108,`NumpadSeparator`],[109,`NumpadSubtract`],[110,`NumpadDecimal`],[111,`NumpadDivide`],[112,`F1`],[113,`F2`],[114,`F3`],[115,`F4`],[116,`F5`],[117,`F6`],[118,`F7`],[119,`F8`],[120,`F9`],[121,`F10`],[122,`F11`],[123,`F12`],[124,`F13`],[125,`F14`],[126,`F15`],[127,`F16`],[128,`F17`],[129,`F18`],[130,`F19`],[131,`F20`],[132,`F21`],[133,`F22`],[134,`F23`],[135,`F24`],[144,`NumLock`],[145,`ScrollLock`],[146,`NEC_Equal`],[147,`Fujitsu_Masshou`],[148,`Fujitsu_Touroku`],[149,`Fujitsu_Loya`],[150,`Fujitsu_Roya`],[160,`ShiftLeft`],[161,`ShiftRight`],[162,`ControlLeft`],[163,`ControlRight`],[164,`AltLeft`],[165,`AltRight`],[166,`BrowserBack`],[167,`BrowserForward`],[168,`BrowserRefresh`],[169,`BrowserStop`],[170,`BrowserSearch`],[171,`BrowserFavorites`],[172,`BrowserHome`],[173,`VolumeMute`],[174,`VolumeDown`],[175,`VolumeUp`],[176,`MediaTrackNext`],[177,`MediaTrackPrevious`],[178,`MediaStop`],[179,`MediaPlayPause`],[180,`LaunchMail`],[181,`LaunchMediaSelect`],[182,`LaunchApplication1`],[183,`LaunchApplication2`],[186,`OEM_1`],[187,`Equal`],[188,`Comma`],[189,`Minus`],[190,`Period`],[191,`Slash`],[192,`Backquote`],[219,`BracketLeft`],[220,`Backslash`],[221,`BracketRight`],[222,`Quote`],[223,`IntlRo`],[225,`OEM_AX`],[226,`IntlBackslash`],[227,`ICO_HELP`],[228,`ICO_00`],[229,`Process`],[230,`ICO_CLEAR`],[231,`Packet`],[233,`OEM_Reset`],[234,`OEM_Jump`],[235,`OEM_PA1`],[236,`OEM_PA2`],[237,`OEM_PA3`],[238,`OEM_WS_Ctrl`],[239,`OEM_CU_Sel`],[240,`OEM_ATTN`],[241,`OEM_Finish`],[242,`OEM_Copy`],[243,`OEM_Auto`],[244,`OEM_ENLW`],[245,`BackTab`],[246,`ATTN`],[247,`CRSel`],[248,`EXSel`],[249,`EREOF`],[250,`MediaPlay`],[251,`Zoom`],[252,`Noname`],[253,`PA1`],[254,`OEM_Clear`]]),jn=new Map(An.entries().map(([e,t])=>[t,e])),Mn=n({"[string]":{keys:`string[]`,mode:n(`'toggle' | 'hold'`).pipe(e=>e??`toggle`)}});var Nn=class extends B{preferencesKeybindToCallbacks=/* @__PURE__ */ new Map;pressedKeys=/* @__PURE__ */ new Set;activeKeybinds=/* @__PURE__ */ new Set;triggeredToggleKeybinds=/* @__PURE__ */ new Set;boundHandleKeyboardFocus=this.handleKeyboardFocus.bind(this);boundHandleKeyDown=this.handleKeyDown.bind(this);boundHandleKeyUp=this.handleKeyUp.bind(this);keybindsFile;keybindListeningPaused=!1;constructor(e){super(`KeybindManager`),this.keybindsFile=new ve({path:Pt([`keybinds.json`]),schema:Mn,default:e})}init(){super.init();let e=Jt.getInstance().getInterface(`OGG_SIEGE`);e.instance.on(`keyboardFocus`,this.boundHandleKeyboardFocus),e.instance.on(`keyDown`,this.boundHandleKeyDown),e.instance.on(`keyUp`,this.boundHandleKeyUp)}async onKeybindToggled(e,t){let n=this.preferencesKeybindToCallbacks.get(e)??{toggle:[],down:[],up:[]};n.toggle.push(t),this.preferencesKeybindToCallbacks.set(e,n)}async onKeybindDown(e,t){let n=this.preferencesKeybindToCallbacks.get(e)??{toggle:[],down:[],up:[]};n.down.push(t),this.preferencesKeybindToCallbacks.set(e,n)}async onKeybindUp(e,t){let n=this.preferencesKeybindToCallbacks.get(e)??{toggle:[],down:[],up:[]};n.up.push(t),this.preferencesKeybindToCallbacks.set(e,n)}async updateKeybind(e,t){this.keybindsFile.set({[e]:t})}async updateKeybinds(e){let t=Object.fromEntries(Object.entries(e).filter(([e,t])=>t!==void 0));this.keybindsFile.set({...this.keybindsFile.get(),...t})}getConfig(){return this.keybindsFile.get()}destroy(){let e=Jt.getInstance().getInterface(`OGG_SIEGE`);e.instance.off(`keyboardFocus`,this.boundHandleKeyboardFocus),e.instance.off(`keyDown`,this.boundHandleKeyDown),e.instance.off(`keyUp`,this.boundHandleKeyUp),super.destroy()}handleKeyDown(e){if(this.keybindListeningPaused)return;let t=An.get(e.key);t?(this.pressedKeys.add(t),this.checkKeybindings()):this.logger.error(`Unknown key down`,e)}handleKeyboardFocus(){this.pressedKeys.clear(),this.activeKeybinds.clear(),this.triggeredToggleKeybinds.clear()}async handleKeyUp(e){if(this.keybindListeningPaused)return;let t=An.get(e.key);if(!t)return;this.pressedKeys.delete(t);let n=this.keybindsFile.get();for(let[e]of this.preferencesKeybindToCallbacks.entries())n[e].keys.includes(t)&&this.triggeredToggleKeybinds.delete(e);this.checkKeybindUps()}async checkKeybindUps(){let e=this.keybindsFile.get();for(let[t,n]of this.preferencesKeybindToCallbacks.entries()){if(!n.up||n.up.length===0)continue;let r=e[t];if(this.activeKeybinds.has(t)&&r.keys.some(e=>!this.pressedKeys.has(e))){this.activeKeybinds.delete(t);for(let e of n.up)e();this.logger.log(`Keybind up triggered`,this.getKeybindToString(r))}}}async checkKeybindings(){let e=this.keybindsFile.get();for(let[t,n]of this.preferencesKeybindToCallbacks.entries()){let r=e[t];if(r.keys.length===this.pressedKeys.size&&r.keys.every(e=>jn.has(e)?this.pressedKeys.has(e):!1)){this.triggerKeybind(r,n,t);return}}for(let[t,n]of this.preferencesKeybindToCallbacks.entries()){let r=e[t];r.keys.every(e=>jn.has(e)?this.pressedKeys.has(e):(this.logger.error(`Unknown key`,e,r),!1))&&this.triggerKeybind(r,n,t)}}triggerKeybind(e,t,n){let r=e.mode;if(r===`toggle`&&t.toggle&&t.toggle.length>0&&!this.triggeredToggleKeybinds.has(n)){let r;for(let e of t.toggle){let t=e();typeof t==`string`&&r===void 0&&(r=t)}this.triggeredToggleKeybinds.add(n),this.logger.log(r?`Keybind pressed rejected: ${r}`:`Keybind pressed accepted`,this.getKeybindToString(e))}if(r===`hold`&&t.down&&t.down.length>0&&!this.activeKeybinds.has(n)){let r;for(let e of t.down){let t=e();if(typeof t==`string`){r=t;break}}r?this.logger.log(`Keybind down rejected: ${r}`,this.getKeybindToString(e)):(this.activeKeybinds.add(n),this.logger.log(`Keybind down accepted`,this.getKeybindToString(e)))}}getKeybindToString(e){return`(${e.keys.join(`+`)}${e.mode?` ${e.mode}`:``})`}};function Pn(e){let t=new Nn(e),n={};for(let r in e)n[r]={on:(e,n)=>{switch(e){case`down`:t.onKeybindDown(r,n);break;case`up`:t.onKeybindUp(r,n);break;case`toggle`:t.onKeybindToggled(r,n);break;default:throw Error(`Event type not implemented ${e}`,{cause:[e,n]})}}};let r={...n,getConfig:()=>t.getConfig(),pauseKeybindListening:()=>{t.keybindListeningPaused=!0},resumeKeybindListening:()=>{t.keybindListeningPaused=!1},updateKeybind:(e,n)=>{t.updateKeybind(e,n)},updateKeybinds:e=>{t.updateKeybinds(e)}};return t.init(),O.on(`quit`,()=>{t.destroy()}),r}function Y(){return Jt.getInstance().getInterface(`OGG_SIEGE`)}function Fn(){let e=J.getInstance(),t=_e.getInstance(),n=q.getInstance();if(!O.isPackaged)L.getInstance().info(`Cortex is disabled in development`),n.enabled=!1;else{try{n.meta=In()}catch(e){L.getInstance().error(`Failed to setup cortex`,e);return}e.on([`gameReady`,`gameClose`],()=>{n.meta||=In(),n.meta.in_game=e.isInGame}),t.on(`fatal`,e=>{n.track(`fatal`,{message:e.message,code:e.code,data:JSON.stringify(e.data)})}),t.on(`error`,e=>{n.track(`error`,{code:e.code,message:e.message,data:JSON.stringify(e.data)})}),t.on(`warning`,e=>{n.track(`warning`,{message:e.message,code:e.code,data:JSON.stringify(e.data)})})}}function In(){if(!global.OVERLAYED_META.release.id)throw Error(`Release ID is required`);return{app_id:global.OVERLAYED.APPLICATION_ID,user_id:Lt(),release_id:global.OVERLAYED_META.release.id,app_channel:global.OVERLAYED.APP_BUILD_CHANNEL,app_version:global.OVERLAYED.APP_VERSION,package_version:global.OVERLAYED.PACKAGE_VERSION,frontend_version:global.OVERLAYED.FRONTEND_VERSION,frontend_release_id:global.OVERLAYED.FRONTEND_RELEASE_ID,session_id:global.OVERLAYED.sessionId,in_game:!1}}const Ln=/* @__PURE__ */ new Set([`http:`,`https:`]);function Rn(){let e=global.OVERLAYED_META?.application?.siteUrl;if(e&&URL.canParse(e))return new URL(e).origin}function zn(e){return URL.canParse(e)?new URL(e):void 0}function Bn(e){return e===`mouseDown`}function Vn(e){let t,n=()=>{t=Date.now()};return e.on(`before-input-event`,(e,t)=>{t.type===`keyDown`&&!t.isAutoRepeat&&n()}),e.on(`input-event`,(e,t)=>{Bn(t.type)&&n()}),e.on(`before-mouse-event`,(e,t)=>{Bn(t.type)&&n()}),{isActive:(e=-1/0)=>t!==void 0&&t>=e&&Date.now()-t<=5e3,consume:()=>{t=void 0}}}function Hn(e,t){return Un(e.webContents,t),e}function Un(e,t,n){let{allowedHosts:r=[],windowOpenHandler:i,logger:a}=t,{shell:o}=global.OVERLAYED.electron,s=Rn(),c=n===void 0?void 0:zn(n),l=c&&Ln.has(c.protocol)?c.origin:void 0,u=Vn(e),d=t=>{let n=zn(e.getURL());return n?.protocol===`file:`&&t.protocol===`file:`?!0:Ln.has(t.protocol)?s&&t.origin===s||l&&t.origin===l||r.includes(t.host)?!0:n!==void 0&&Ln.has(n.protocol)&&t.origin===n.origin:!1},f=(e,t,n)=>{e.preventDefault(),a.warn(`[navigation-guard] Blocked main-frame navigation to ${t} (${n})`),q.getInstance().track(`navigation_blocked`,{url:t,reason:n})},p=n!==void 0,m=n!==void 0;e.on(`will-navigate`,e=>{let t=zn(e.url);t&&d(t)?p=!0:f(e,e.url,t?`cross_origin`:`unparseable`)}),e.on(`will-redirect`,e=>{if(!e.isMainFrame||!p)return;let t=zn(e.url);t&&d(t)||f(e,e.url,t?`cross_origin_redirect`:`unparseable`)}),e.on(`did-start-navigation`,e=>{e.isMainFrame&&!e.isSameDocument&&(p=m,m=!1)});let h,g=()=>{let e=Date.now();if(!u.isActive())return h=e,{action:`deny`,reason:`no_user_activation`};let t=(h??-1/0)+1e4;return u.isActive(t)?{action:`external`}:{action:`deny`,reason:`popup_cooldown`}},_=e=>{let t=i?.({url:e});if(t===`allow`)return{action:`allow`};if(t===`deny`)return{action:`deny`,reason:`application`};let n=zn(e);return n?t===`external`?Ln.has(n.protocol)?{action:`external`}:{action:`deny`,reason:`unsupported_scheme`}:d(n)?{action:`allow`}:Ln.has(n.protocol)?g():{action:`deny`,reason:`unsupported_scheme`}:{action:`deny`,reason:`unparseable`}},v=(e,n)=>{let{url:r}=e,i=_(r);if(i.action===`deny`)return a.warn(`[navigation-guard] Denied window.open to ${r} (${i.reason})`),q.getInstance().track(`window_open_denied`,{url:r,reason:i.reason}),{action:`deny`};let s=n?.(e);if(s?.action===`deny`)return s;if(i.action===`allow`){a.info(`[navigation-guard] Allowing in-app window for ${r}`);let e=s?.createWindow;return!s||!e?s??{action:`allow`}:{...s,createWindow:n=>{let i=e(n);return Un(i,t,r),i}}}return u.consume(),a.info(`[navigation-guard] Opening external url in system browser: ${r}`),q.getInstance().track(`window_open_external`,{url:r}),o.openExternal(r).catch(e=>{a.warn(`[navigation-guard] Failed to open external url ${r}: ${String(e)}`)}),{action:`deny`}},ee=e.setWindowOpenHandler.bind(e);e.setWindowOpenHandler=e=>{ee(t=>v(t,e))},ee(e=>v(e)),e.on(`did-create-window`,(e,n)=>{Un(e.webContents,t,n.url)})}const Wn=n({page:`0 < string <= 512`,"lcp?":`number`,"inp?":`number`,"fcp?":`number`,"ttfb?":`number`,"cls?":`number`,"fcpPaint?":`number`,"lcpPaint?":`number`}),Gn=/* @__PURE__ */ new WeakMap;let Kn=!1;function qn(e,t){return e!==void 0&&Number.isFinite(e)&&e>=0&&e<=t}function Jn(e,t){if(t===void 0)return!1;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.at<=t)return!r.visible&&(e[n+1]?.at??Date.now())-t>500}return!1}function Yn(e,t){let r=Gn.get(e.sender);if(r===void 0)return;let i=Wn(t);if(i instanceof n.errors)return;let a={page:i.page,window_type:r.inGame?`in_game`:`desktop`},o=Jn(r.visibility,i.fcpPaint),s=o||Jn(r.visibility,i.lcpPaint),c=!1;for(let e of nn){if(e===`fcp`&&o||e===`lcp`&&s)continue;let t=i[e];qn(t,6e4)&&(a[e]=Math.round(t),c=!0)}qn(i.cls,10)&&(a.cls=Math.round(i.cls*1e4)/1e4,c=!0),c&&q.getInstance().track(`web_vitals`,a)}function Xn(e,t){let n=[{at:Date.now(),visible:e.isVisible()}],r=()=>{if(e.isDestroyed())return;let t=e.isVisible();n.at(-1).visible!==t&&(n.push({at:Date.now(),visible:t}),n.length>1024&&n.shift())};for(let t of[`show`,`hide`,`minimize`,`restore`])e.on(t,r);Gn.set(e.webContents,{inGame:t,visibility:n}),Kn||(Kn=!0,global.OVERLAYED.electron.ipcMain.on(`overlayed:web-vitals`,Yn))}const Zn=M(class extends B{CHECK_INTERVAL=9e5;RETRY_INTERVAL=15e3;_updateCheckInterval=null;_latestCheckResponse=null;_activeCheckResponse=null;initialReleaseId=null;get manualUpdatesEnabled(){return this.options?.manualUpdates??!1}get activeReleaseId(){return this._activeCheckResponse?.release_id??this.initialReleaseId}constructor(){super(`SiteManager`)}init(e){super.init(e),e?.manualUpdates&&this.enableManualUpdates()}destroy(){super.destroy(),this._updateCheckInterval&&=(clearInterval(this._updateCheckInterval),null)}allowSiteUpdateOnNextLoad(){this.options?.manualUpdates?this._latestCheckResponse?this._activeCheckResponse?.release_id===this._latestCheckResponse.release_id?this.logger.warn(`allowSiteUpdateOnNextLoad called but theres no update available`):(this._activeCheckResponse=this._latestCheckResponse,q.getInstance().track(`site_update_applied`,{version:this._latestCheckResponse.version,release_id:this._latestCheckResponse.release_id}),this.setFrontendCortexMeta(this._latestCheckResponse.release_id,this._latestCheckResponse.version)):this.logger.warn(`allowSiteUpdateOnNextLoad called but no update has been checked yet`):this.logger.warn(`allowSiteUpdateOnNextLoad called but manual updates are disabled`)}setFrontendCortexMeta(e,t){let n=q.getInstance();n.meta||=In(),e&&(global.OVERLAYED.FRONTEND_RELEASE_ID=e,n.meta.frontend_release_id=e),t&&(global.OVERLAYED.FRONTEND_VERSION=t,n.meta.frontend_version=t),e&&t&&n.track(`frontend_version_changed`,{version:t,release_id:e})}enableManualUpdates(){this.logger.log(`Enabling manual site updates`),this.checkForUpdates(),this._updateCheckInterval=setInterval(()=>{this.checkForUpdates(!0)},this.CHECK_INTERVAL)}async checkForUpdates(e=!1){let t=global.OVERLAYED_META?.application?.siteUrl;if(!t)this.logger.log(`No siteUrl configured, skipping check`);else{q.getInstance().track(`site_check_for_update`,{});try{let n=new URL(`/check`,t).toString();this.logger.log(`Checking site URL`,n);let r={"Overlayed-User-Agent":it({package_version:global.OVERLAYED.PACKAGE_VERSION,application_id:global.OVERLAYED.APPLICATION_ID,application_version:global.OVERLAYED.APP_VERSION}),"Overlayed-Cortex-User-Id":global.OVERLAYED_RUNTIME.userId},i=K();i&&(r[`Overlayed-Access-Token`]=i);let a=global.OVERLAYED_META.release.channelId;a&&(r[`Overlayed-Channel-Id`]=a);let o=await fetch(n,{headers:r});if(!o.ok){this.logger.warn(`Site check failed with status`,o.status),q.getInstance().track(`site_check_error`,{status:o.status}),e&&this.scheduleRetry();return}let s=await o.json();if(this.logger.log(`Site check response`,s),!s.release_id){this.logger.error(`Site check response missing release_id`);return}if(!this._latestCheckResponse){this._latestCheckResponse=s;return}return this._latestCheckResponse.release_id===s.release_id?void 0:(this.logger.log(`New site version detected`,s),this._latestCheckResponse=s,q.getInstance().track(`site_update_ready`,{version:s.version,release_id:s.release_id}),this.emit(`siteUpdateReady`,{releaseId:s.release_id,version:s.version}),s)}catch(e){let t=e instanceof Error?e.message:String(e);q.getInstance().track(`site_check_error`,{message:t}),this.logger.error(`Site check failed`,{error:e,message:t}),this.scheduleRetry()}}}scheduleRetry(){setTimeout(()=>{this.checkForUpdates()},this.RETRY_INTERVAL)}}),Qn=M(I,`browser-windows.log`);let $n;function er(){return $n||($n=class e extends global.OVERLAYED.electron.BrowserWindow{static session=void 0;constructor(t){let n=e.resolveCustomOptions(t);super(n)}static resolveCustomOptions(t){let n=global.OVERLAYED_META,r=global.OVERLAYED_RUNTIME;return{...t,webPreferences:{...t.webPreferences,session:e.getSession(),additionalArguments:[...(t.webPreferences?.additionalArguments||[]).filter(e=>!e.startsWith(`--overlayed-meta=`)&&!e.startsWith(`--overlayed-runtime=`)),...global.OVERLAYED.electron.app.isPackaged?[]:[`--overlayed-meta=${JSON.stringify(n)}`],`--overlayed-runtime=${JSON.stringify(r)}`]}}}static getSession(){if(!global.OVERLAYED_META?.application?.siteUrl)return;if(e.session)return e.session;e.session=global.OVERLAYED.electron.session.fromPartition(`persist:overlayed-${global.OVERLAYED.APPLICATION_ID}`);let t=Zn.getInstance(),n=it({package_version:global.OVERLAYED.PACKAGE_VERSION,application_id:global.OVERLAYED.APPLICATION_ID,application_version:global.OVERLAYED.APP_VERSION}),r={urls:[global.OVERLAYED_META.application.siteUrl+`/*`]},i=global.OVERLAYED_RUNTIME.userId;return e.session.webRequest.onBeforeSendHeaders(r,(e,r)=>{let a=K();a&&(e.requestHeaders[`Overlayed-Access-Token`]=a);let o=global.OVERLAYED_META.release.channelId;o&&(e.requestHeaders[`Overlayed-Channel-Id`]=o),t.manualUpdatesEnabled&&t.activeReleaseId&&(e.requestHeaders[`Overlayed-Release-Id`]=t.activeReleaseId),e.requestHeaders[`Overlayed-Cortex-User-Id`]=i,e.requestHeaders[`Overlayed-User-Agent`]=n,r({requestHeaders:e.requestHeaders})}),t.manualUpdatesEnabled&&e.session.webRequest.onHeadersReceived(r,(e,n)=>{if(t.initialReleaseId){n(e);return}let r=e.responseHeaders?.[`Overlayed-Release-Id`]?.[0];r&&(t.initialReleaseId=mt(r));let i=e.responseHeaders?.[`Overlayed-Release-Version`]?.[0];t.setFrontendCortexMeta(r,i),n(e)}),e.session}},$n)}function tr(e){function t(t,n,r){t.webContents.setAudioMuted(r?.muted!==!1);let i=Qn.getInstance();return Hn(t,{...e,logger:i}),global.OVERLAYED_RUNTIME.webVitals!==!1&&Xn(t,n),yn(t.webContents,n),t.once(`closed`,()=>{t.isDestroyed()||q.getInstance().track(`window_closed`,{url:t.webContents.getURL(),in_game:n})}),t.on(`unresponsive`,()=>{t.isDestroyed()||q.getInstance().track(`window_unresponsive`,{url:t.webContents.getURL(),in_game:n})}),t.webContents.on(`console-message`,(e,n,r,a,o)=>{let s=t.isDestroyed()?`destroyed`:t.webContents.getURL();i[n===3?`error`:n===2?`warn`:`log`](`[${s}] [${o}:${a}] ${r}`)}),q.getInstance().track(`window_created`,{url:t.webContents.getURL(),in_game:n}),t}return{getProductionSiteUrl:()=>{let e=global.OVERLAYED_META.application.siteUrl;return URL.canParse(e)?new URL(e):new URL(`https://default.overlayedapps.com`)},createWindow:(e,n)=>t(new(er())(e),!1,n),createInGameWindow:(e,n)=>{let r=er();return t(Y().instance.newWindowInternal(r,e),!0,n)},on:(e,t)=>Y().instance.on(e,t),off:(e,t)=>Y().instance.off(e,t),once:(e,t)=>Y().instance.once(e,t),addListener:(e,t)=>Y().instance.addListener(e,t),removeListener:(e,t)=>Y().instance.removeListener(e,t),removeAllListeners:()=>Y().instance.removeAllListeners(),prependListener:(e,t)=>Y().instance.prependListener(e,t),prependOnceListener:(e,t)=>Y().instance.prependOnceListener(e,t),getActiveGameInfo:()=>{let e=Y(),t=Re.getInstance();return{resolution:e.resolution,isConnected:t.hasConnection}}}}const nr=M(class extends Ze{renderInterface;globalCursorOverrideCount=/* @__PURE__ */ new Set;globalMouseBlockCount=/* @__PURE__ */ new Set;globalKeyboardBlockCount=/* @__PURE__ */ new Set;keyInputBlocks={};constructor(e){super(`OverridesManager`),this.renderInterface=Jt.getInstance().getInterface(e)}scope(e){return{setGlobalCursorOverride:t=>this.setGlobalCursorOverride(e,t),setGlobalMouseBlock:t=>this.setGlobalMouseBlock(e,t),setGlobalKeyboardBlock:t=>this.setGlobalKeyboardBlock(e,t),setKeyInputBlock:(t,n)=>this.setKeyInputBlock(e,t,n)}}setGlobalCursorOverride(e,t){t?this.globalCursorOverrideCount.add(e):this.globalCursorOverrideCount.delete(e),t&&this.globalCursorOverrideCount.size===1?this.renderInterface.instance.setGlobalCursorOverride(!0):!t&&this.globalCursorOverrideCount.size===0&&this.renderInterface.instance.setGlobalCursorOverride(!1)}setGlobalMouseBlock(e,t){t?this.globalMouseBlockCount.add(e):this.globalMouseBlockCount.delete(e),t&&this.globalMouseBlockCount.size===1?this.renderInterface.instance.setGlobalMouseBlock(!0):!t&&this.globalMouseBlockCount.size===0&&this.renderInterface.instance.setGlobalMouseBlock(!1)}setGlobalKeyboardBlock(e,t){t?this.globalKeyboardBlockCount.add(e):this.globalKeyboardBlockCount.delete(e),t&&this.globalKeyboardBlockCount.size===1?this.renderInterface.instance.setGlobalKeyboardBlock(!0):!t&&this.globalKeyboardBlockCount.size===0&&this.renderInterface.instance.setGlobalKeyboardBlock(!1)}setKeyInputBlock(e,t,n){this.keyInputBlocks[t]||(this.keyInputBlocks[t]=/* @__PURE__ */ new Set),n?this.keyInputBlocks[t].add(e):this.keyInputBlocks[t].delete(e),n&&this.keyInputBlocks[t].size===1?this.renderInterface.instance.setKeyInputBlock(t,!0):!n&&this.keyInputBlocks[t].size===0&&this.renderInterface.instance.setKeyInputBlock(t,!1)}},`OGG_SIEGE`);function rr(){return{scope:e=>nr.getInstance().scope(e),raw:{setGlobalMouseBlock:e=>Y().instance.setGlobalMouseBlock(e),setGlobalKeyboardBlock:e=>Y().instance.setGlobalKeyboardBlock(e),setGlobalCursorOverride:e=>Y().instance.setGlobalCursorOverride(e),setKeyInputBlock:(e,t)=>Y().instance.setKeyInputBlock(e,t),getGlobalMouseBlock:()=>Y().instance.getGlobalMouseBlock(),getGlobalKeyboardBlock:()=>Y().instance.getGlobalKeyboardBlock(),getGlobalCursorOverride:()=>Y().instance.getGlobalCursorOverride(),getKeyInputBlock:e=>Y().instance.getKeyInputBlock(e)}}}function X(){return{track:(e,t)=>{q.getInstance().track(`custom__${String(e)}`,t)}}}function ir(){return{registerWindow:()=>{}}}const ar=/(\d{4})-(\d{2})-(\d{2})\.log$/;function or(e){let t=e.match(ar);if(!t)return!1;let[,n,r,i]=t,a=Number(n),o=Number(r),s=Number(i);if(o<1||o>12||s<1||s>31)return!1;let c=new Date(a,o-1,s);if(isNaN(c.getTime())||c.getFullYear()!==a||c.getMonth()!==o-1||c.getDate()!==s)return!1;let l=/* @__PURE__ */ new Date;return l.setDate(l.getDate()-7),l.setHours(0,0,0,0),c>=l}function sr(e){let{silent:t=!1,additionalFiles:n}=e??{},r=Te(global.OVERLAYED.APPLICATION_ID),i=Ee(r,{recursive:!0}),a=Ce(),o=Ee(a,{recursive:!0});t||(L.getInstance().info(`Logs path: `,r),L.getInstance().info(`Overlayed logs path: `,a));let s=new ae;return i.forEach(([e,n])=>{t||L.getInstance().info(`Zipping: `,n);let r=x(n);s.file(g(n),r,{compression:`DEFLATE`})}),o.forEach(([e,n])=>{if(!or(g(n))){t||L.getInstance().info(`Skipping old/unrecognized log: `,n);return}t||L.getInstance().info(`Zipping: `,n);let r=x(n);s.file(g(n),r,{compression:`DEFLATE`})}),n&&Object.entries(n).forEach(([e,n])=>{t||L.getInstance().info(`Zipping extra file: `,e),s.file(e,n,{compression:`DEFLATE`})}),s}async function cr(e,t,n){let r=global.OVERLAYED_META.release.id?mt(global.OVERLAYED_META.release.id):void 0,i=Lt();return dt(global.OVERLAYED.APPLICATION_ID,{file:Buffer.from(n,`base64`),data:{release_id:r,type:e,cortex_user_id:i,...t}}).then(e=>(L.getInstance().info(`Feedback submitted`,e),e.data.id)).catch(e=>{console.error(JSON.stringify(e,null,2)),L.getInstance().error(`Failed to submit feedback`,e)})}function lr(e){let t=new I(`app.log`);return t.init(global.OVERLAYED.APPLICATION_ID,e.debug),{scope:e=>t.scope(e),info:e=>t.info(e),warn:e=>t.warn(e),error:e=>t.error(e),debug:e=>t.debug(e),submitFeedback:async(e,t,n)=>{let r=global.OVERLAYED_META.release.id?mt(global.OVERLAYED_META.release.id):void 0;return r&&O.isPackaged&&q.getInstance().track(e===`bug_report`?`bug_report_submitted`:`suggestion_submitted`,{release_id:r}),await cr(e,t,await sr(n).generateAsync({type:`base64`}))},getLogsZip:e=>sr(e)}}const ur=1e3;function dr(e,t,r,i,a){let o=Re.getInstance(),s=L.getInstance().scope(`SetupPipeServer`);s.log(`Initializing`);function c(e,t){let n=r.get(t);if(!n)r.set(t,[e]);else{if(n.length>=ur){_e.getInstance().warn(`Event buffer full, removing oldest event`,`EVENT_BUFFER_FULL`,{summary:`Event buffer overflow for module ${t}. Buffer size: ${n.length}, max: ${ur}`});return}n.push(e)}}function l(e,r,i){let o=i.events.event,l=o(e);if(l instanceof n.errors){if(`type`in l.byPath)return;s.warn(`Invalid event`,{summary:l.summary}),q.getInstance().track(`invalid_game_event`,{game:r.game,type:r.type,summary:l.summary}),_e.getInstance().warn(`Invalid event`,`INVALID_EVENT`,{summary:l.summary});return}if(!a[i.key]){c(e,i.key);return}if(l.type===`unsupported_game_version`){let{content:e}=l;q.getInstance().track(`unsupported_game_version`,{game:l.game,hash:e.processHash,version:e.gameVersion})}let u=Dn(i.key,l.type),d=Dn(i.key,`*`),f=t.get(u),p=t.get(d),m=[...Array.from(f??[]),...Array.from(p??[])];m.length===0?s.info(`No handlers found for event`,{event:l}):m.forEach(e=>{e(l)})}function u(t){s.info(t);let r=Ft(t);if(r instanceof n.errors){q.getInstance().track(`invalid_game_event`,{}),_e.getInstance().warn(`Invalid event`,`INVALID_EVENT`,{summary:r.summary});return}let i=Xe.includes(r.type),a=e.modules.find(e=>e.key===`universal`),o=e.modules.find(e=>e.key===r.game),c=[];i&&a&&c.push(a),o&&o!==a&&(!i||r.type in o.events)&&c.push(o),c.length===0?s.warn(`Invalid module`,{module:i?`universal`:r.game}):c.forEach(e=>l(t,r,e))}return i.on(`flushEvents`,t=>{if(a[t])return;a[t]=!0;let i=r.get(t);if(!i)return;L.getInstance().info(`Flushing ${i.length} events for module ${t}`);let o=e.modules.find(e=>e.key===t);o&&i.forEach(e=>{let t=Ft(e);t instanceof n.errors||l(e,t,o)}),r.delete(t)}),o.on(`data`,e=>e.forEach(u)),o.on(`error`,e=>{s.error(`Pipe server error`,e),_e.getInstance().error(`Pipe server error`,`PIPE_SERVER_ERROR`,{error:e})}),o.on(`connected`,()=>{s.log(`Pipe server connected`)}),o.on(`disconnected`,()=>{s.log(`Pipe server disconnected`)}),o}const fr=M(class extends B{FETCH_INTERVAL=6e5;_fetchInterval=null;_flags=/* @__PURE__ */ new Map;_overrides=/* @__PURE__ */ new Map;_defaults=/* @__PURE__ */ new Map;_boundOnGameReady=this.onGameEvent.bind(this);_boundOnGameClose=this.onGameEvent.bind(this);_readyResolve;ready;constructor(){super(`FeatureFlagManager`),this.ready=new Promise(e=>{this._readyResolve=e}),this.fetchFlags(),this.setupInterval(),J.getInstance().on(`gameReady`,this._boundOnGameReady),J.getInstance().on(`gameClose`,this._boundOnGameClose)}destroy(){this._fetchInterval&&=(clearInterval(this._fetchInterval),null),J.getInstance().off(`gameReady`,this._boundOnGameReady),J.getInstance().off(`gameClose`,this._boundOnGameClose),super.destroy()}setDefaults(e){this._defaults=new Map(Object.entries(e))}async refresh(){await this.fetchFlags()}override(e,t){let n=this.get(e);this._overrides.set(e,t),n!==t&&(this.emit(e,t),this.emit(`updated`,!0))}clearOverride(e){if(!this._overrides.has(e))return;let t=this.get(e);this._overrides.delete(e);let n=this.get(e);t!==n&&(this.emit(e,n),this.emit(`updated`,!0))}clearOverrides(){if(this._overrides.size===0)return;let e=/* @__PURE__ */ new Map;for(let t of this._overrides.keys())e.set(t,this.get(t));this._overrides.clear();let t=!1;for(let[n,r]of e){let e=this.get(n);r!==e&&(this.emit(n,e),t=!0)}t&&this.emit(`updated`,!0)}isOverridden(e){return this._overrides.has(e)}getAllOverrides(){return Object.fromEntries(this._overrides)}inspect(e){let t=this._overrides.get(e),n=this._flags.get(e),r=this._defaults.get(e);return{effective:t??n??r??!1,override:t,actual:n,default:r}}get(e){let t=this._overrides.get(e),n=this._flags.get(e),r=this._defaults.get(e);return t??n??r??!1}getAll(){let e=Object.fromEntries(this._defaults);for(let[t,n]of this._flags)e[t]=n;for(let[t,n]of this._overrides)e[t]=n;return e}onGameEvent(){this.fetchFlags()}setupInterval(){this._fetchInterval=setInterval(()=>{this.fetchFlags()},this.FETCH_INTERVAL)}async fetchFlags(){try{let e=J.getInstance().getActiveGames(),{data:t}=await ft(global.OVERLAYED.APPLICATION_ID,{cortex_user_id:global.OVERLAYED_RUNTIME.userId,release_id:global.OVERLAYED_META.release.id??void 0,channel_id:global.OVERLAYED_META.release.channelId??void 0,active_games:e.map(e=>e.toString())??void 0}),n=/* @__PURE__ */ new Map;for(let e of t)n.set(e.name,e.enabled);for(let[e,t]of n){if(this._overrides.has(e))continue;let n=this._flags.get(e);n!==void 0&&n!==t&&this.emit(e,t)}for(let[e]of this._flags)this._overrides.has(e)||n.has(e)||this.emit(e,this._defaults.get(e)??!1);this._flags=n;for(let e of this._defaults.keys())this._flags.has(e)||this.logger.warn(`Registered feature flag "${e}" was not found in the API response`);this.emit(`updated`,!0)}catch(e){this.logger.error(`Failed to fetch feature flags`,e)}finally{this._readyResolve()}}});function pr(e){let t=fr.getInstance();return e&&t.setDefaults(e),{on:(e,n)=>t.on(e,n),off:(e,n)=>t.off(e,n),ready:t.ready,get:e=>t.get(e),getAll:()=>t.getAll(),refresh:()=>t.refresh(),override:(e,n)=>t.override(e,n),clearOverride:e=>t.clearOverride(e),clearOverrides:()=>t.clearOverrides(),isOverridden:e=>t.isOverridden(e),getAllOverrides:()=>t.getAllOverrides(),inspect:e=>t.inspect(e)}}function mr(){let e=Zn.getInstance();return{on:(t,n)=>{e.on(t,n)},off:(t,n)=>{e.off(t,n)},allowSiteUpdateOnNextLoad:()=>{e.allowSiteUpdateOnNextLoad()}}}const hr=n({dismissedNotices:pe(n.string).array()}),gr=M(class extends B{NOTICE_FETCH_INTERVAL=6e5;MAX_DISMISSED_NOTICES=100;_noticeFetchInterval=null;_notices=[];_noticesFile;_boundOnGameReady=this.onGameReady.bind(this);get notices(){let e=this._noticesFile.get().dismissedNotices;return this._notices.filter(t=>!e.includes(t.id))}constructor(){super(`NoticeManager`),this._noticesFile=this.getNoticesFile(),this._noticesFile.load(),this.fetchNotices(),this.setupNoticeInterval(),J.getInstance().on(`gameReady`,this._boundOnGameReady)}destroy(){this._noticeFetchInterval&&=(clearInterval(this._noticeFetchInterval),null),J.getInstance().off(`gameReady`,this._boundOnGameReady),super.destroy()}dismissNotice(e){let t=this._notices.find(t=>t.id===e);if(!t||!t.dismissible)return;let n=this._noticesFile.get().dismissedNotices;n.unshift(e),this._noticesFile.set({dismissedNotices:n.slice(0,this.MAX_DISMISSED_NOTICES)}),this.emitNoticesUpdated()}onGameReady(){this.fetchNotices()}setupNoticeInterval(){this._noticeFetchInterval=setInterval(()=>{this.fetchNotices()},this.NOTICE_FETCH_INTERVAL)}getNoticesFile(){return new ve({path:Pt([`notices.json`]),schema:hr,default:{dismissedNotices:[]}})}async fetchNotices(){let e=J.getInstance().getActiveGames();try{let{data:t}=await pt(global.OVERLAYED.APPLICATION_ID,{release_id:global.OVERLAYED_META.release.id?mt(global.OVERLAYED_META.release.id):void 0,games:e});this._notices=t,this.emitNoticesUpdated()}catch(e){this.logger.error(`Failed to fetch notices`,e)}}emitNoticesUpdated(){this.emit(`noticesUpdated`,{notices:this.notices})}});function _r(){let e=gr.getInstance();return{on:(t,n)=>{e.on(t,n)},off:(t,n)=>{e.off(t,n)},dismissNotice:t=>{e.dismissNotice(t)},getNotices:()=>e.notices}}const{Provider:vr}=ue;var yr=class extends vr{options;updater;logger=L.getInstance().scope(`OverlayedProvider`);constructor(e,t,n){super(n),this.options=e,this.updater=t}async getLatestVersion(){let e=await this.checkWithAccess();if(`error`in e){let t=e.error,n=t instanceof Error?t.stack||t.message:String(t);throw q.getInstance().track(`update_release_check_error`,{message:n}),Error(`Unable to find the latest version (${this.options.release_id}), please ensure release exists. ${n}`)}let t=e.response;this.logger.log(`checkApplicationRelease response`,t.data),q.getInstance().track(`update_release_check_success`,{version:t.data.release.version,channel:t.data.release.channel,fallback:!!t.data.fallback}),t.data.fallback&&this.logger.warn(`Update fallback detected, switching to default channel`);let n=xr(t.data.release.version,this.options.release_version),r=!!this.options.requested_channel||t.data.rollback===!0||n===!1;this.updater.allowDowngrade=r;let i={path:``,sha512:t.data.download_hash??``,version:`${t.data.release.version}-${t.data.release.channel}`,releaseName:t.data.release.id,releaseDate:t.data.release.created_at,files:[{url:t.data.download_url,sha512:t.data.download_hash??``}]};return!r&&n&&br.add(i),i}resolveFiles(e){return[{info:e.files[0],url:new URL(e.files[0].url)}]}async checkWithAccess(){let{access:e}=this.options,t=await this.checkRelease(this.options.access_token);if(!e)return t;let n=Sr(t);if(!n)return`response`in t&&e.onAccessGranted(),t;this.logger.log(`Release check needs an access token`,n);let r=await e.fetchAccessToken(),i=r&&r!==this.options.access_token?await this.checkRelease(r):t,a=Sr(i);return r&&`response`in i&&!a?e.onAccessGranted(r):Cr(n)&&Cr(a)&&e.onAccessDenied(),i}async checkRelease(e){try{return{response:await lt(this.options.application_id,{release_id:this.options.release_id,cortex_user_id:this.options.cortex_user_id,access_token:e,requested_channel:this.options.requested_channel})}}catch(e){return{error:e}}}};const br=/* @__PURE__ */ new WeakSet;function Z(e){return br.has(e)}function xr(e,t){return!de.valid(e)||!de.valid(t)?e!==t&&void 0:de.lt(e,t)}function Sr(e){if(`response`in e)return e.response.data.fallback?`fallback`:void 0;let{error:t}=e;if(!Dt(t)||t.response?.status!==403&&t.response?.status!==404||typeof t.response.data!=`object`||!t.response.data||!Ot(t.response))return;let{kind:n}=t.response.data;if(t.response.status===403&&n===`public_releases_disabled`||t.response.status===404&&n===`no_releases_available`)return n}function Cr(e){return e===`fallback`||e===`public_releases_disabled`}function wr(e){return{provider:`custom`,updateProvider:yr,...e}}function Q(){return ue.autoUpdater}const Tr=M(class extends B{TOKEN_REFRESH_INTERVAL=9e5;TOKEN_EXPIRY_BUFFER=3e5;accessTokenFetcher=void 0;_tokenRefreshInterval=null;_downloadStarted=!1;_isUpdateSupported=null;_accessDeniedChannels=/* @__PURE__ */ new Set;constructor(){super(`UpdateManager`)}init(){super.init(),this.registerListenerForwarders(),this.migrateAccessTokenChannel(),this.setupTokenRefreshInterval(),Q().disableDifferentialDownload=!0;let e=Q().isUpdateSupported;this._isUpdateSupported=e,Q().isUpdateSupported=t=>!Z(t)&&e(t)}destroy(){Q().removeAllListeners(),this._isUpdateSupported&&=(Q().isUpdateSupported=this._isUpdateSupported,null),this._tokenRefreshInterval&&=(clearInterval(this._tokenRefreshInterval),null),super.destroy()}setupTokenRefreshInterval(){this._tokenRefreshInterval=setInterval(()=>{this.checkAndRefreshToken()},this.TOKEN_REFRESH_INTERVAL)}async checkAndRefreshToken(){let e=K(),t=Bt();if(!e||!t||!this.accessTokenFetcher||!this.isAccessTokenExpiring(e))return;this.logger.log(`Refreshing access token for channel`,t);let n=await this.fetchAccessToken(t);n!==void 0&&K()===e&&Vt(n,t)}async checkForUpdates(e){this.logger.log(`Starting checkForUpdates`);let t=e??global.OVERLAYED_META.release.channel;return q.getInstance().track(`check_for_update`,{channel:t}),this._downloadStarted=!1,e?(Q().allowDowngrade=!0,Q().channel=e):(Q().channel=global.OVERLAYED_META.release.channel,Q().allowDowngrade=!1),this.setFeedUrl({channel:t,requestedChannel:e}),this.logger.log(`Checking for updates`),Q().checkForUpdates()}async switchChannel(e){return this.logger.log(`Switching channel`,e),q.getInstance().track(`update_channel_switch`,{from_channel:global.OVERLAYED_META.release.channel,to_channel:e}),this._downloadStarted=!1,Q().allowDowngrade=!0,Q().channel=e,this.setFeedUrl({channel:e,requestedChannel:e}),Q().checkForUpdates()}quitAndInstall(e,t){this.logger.log(`quitAndInstall`,{isSilent:e,isForceRunAfter:t});let[n,r]=this.canUpdate();if(!n)throw this.logger.warn(`Cannot update`,{denialReason:r}),q.getInstance().track(`update_install_blocked`,{reason:r}),Error(r);return this.logger.log(`Quitting and installing`),q.getInstance().track(`update_install`,{}),Q().quitAndInstall(e,t)}canUpdate(){return J.getInstance().isInGame?[!1,`User is in game`]:[!0,null]}downloadUpdate(e){return Q().downloadUpdate(e)}setAccessTokenFetcher(e){this.accessTokenFetcher=e}setFeedUrl(e){if(this.accessTokenFetcher||(this.logger.warn(`accessTokenFetcher is not set, private channels will not work.`),Vt(null)),!global.OVERLAYED_META.release.id){this.logger.warn(`Tried to set feed URL in development mode`);return}let t=this.getHeldAccessToken(e.channel);Q().setFeedURL(wr({application_id:global.OVERLAYED.APPLICATION_ID,release_id:global.OVERLAYED_META.release.id,release_version:global.OVERLAYED_META.release.version,cortex_user_id:global.OVERLAYED_RUNTIME.userId,access_token:t,requested_channel:e.requestedChannel,access:this.createReleaseCheckAccess(e.channel)}))}getHeldAccessToken(e){let t=K();if(t&&Bt()===e&&!this.isAccessTokenExpiring(t))return t}createReleaseCheckAccess(e){if(this.accessTokenFetcher)return{fetchAccessToken:async()=>await this.fetchAccessToken(e)??null,onAccessGranted:t=>{this._accessDeniedChannels.delete(e),t&&Vt(t,e)},onAccessDenied:()=>{K()&&Bt()===e&&Vt(null),!this._accessDeniedChannels.has(e)&&(this._accessDeniedChannels.add(e),q.getInstance().track(`update_token_invalid`,{channel:e}),this.emit(`authTokenInvalid`,{}))}}}async fetchAccessToken(e){if(!this.accessTokenFetcher)return null;try{let t=await this.accessTokenFetcher(e)??null;return this.logger.log(`New token fetched`,t?.slice(0,5)+`...`),t}catch(e){let t=e instanceof Error?e.message:String(e);q.getInstance().track(`update_token_fetch_error`,{message:t}),this.logger.error(`Error fetching new token`,{error:e,message:t});return}}migrateAccessTokenChannel(){let e=K(),t=Bt(),n=global.OVERLAYED_META.release.channel;e&&!t?Vt(e,n):e&&t!==n&&Vt(null)}isAccessTokenExpiring(e){let t=this.getAccessTokenExpirationDate(e);return!t||t.getTime()<Date.now()+this.TOKEN_EXPIRY_BUFFER}registerListenerForwarders(){Q().on(`checking-for-update`,()=>{this.logger.info(`Checking for updates`),this.emit(`checkingForUpdates`,{})}),Q().on(`download-progress`,e=>{this._downloadStarted||(this._downloadStarted=!0,q.getInstance().track(`update_download_started`,{version:Q().currentVersion?.version??``})),this.emit(`downloadProgress`,{info:e});let t=`Download speed: ${e.bytesPerSecond} - Downloaded ${e.percent}%`;t+=` (${e.transferred}/${e.total})`,this.logger.log(t)}),Q().on(`error`,(e,t)=>{this.logger.error(`Error`,e,t),q.getInstance().track(`update_download_error`,{message:t??e.message}),this.emit(`error`,{error:e,message:t})}),Q().on(`update-not-available`,e=>{this.logger.info(`Update not available`,e),q.getInstance().track(`update_not_available`,{version:e.version}),this.emit(`updateNotAvailable`,{info:e})}),Q().on(`update-available`,e=>{this.logger.info(`Update available`,e),q.getInstance().track(`update_available`,{version:e.version,channel:Q().channel??``}),this.emit(`updateAvailable`,{info:e})}),Q().on(`update-downloaded`,e=>{this.logger.info(`Update downloaded`,e),q.getInstance().track(`update_download_complete`,{version:e.version}),this.emit(`updateDownloaded`,{event:e})}),Q().on(`update-cancelled`,e=>{this.logger.info(`Update cancelled`,e),q.getInstance().track(`update_cancelled`,{version:e.version}),this.emit(`updateCancelled`,{info:e})})}getAccessTokenExpirationDate(e){try{let t=e.split(`.`)[1];if(!t)return null;let n=atob(t.replace(/-/g,`+`).replace(/_/g,`/`)),r=JSON.parse(n);return r.exp?/* @__PURE__ */ new Date(r.exp*1e3):null}catch{return null}}});function Er(){let e=Tr.getInstance();return{site:mr(),on:(t,n)=>{e.on(t,n)},off:(t,n)=>{e.off(t,n)},setAccessTokenFetcher:t=>e.setAccessTokenFetcher(t),checkForUpdates:()=>e.checkForUpdates(),switchChannel:t=>e.checkForUpdates(t),quitAndInstall:(t,n)=>e.quitAndInstall(t,n),canUpdate:()=>e.canUpdate(),downloadUpdate:t=>e.downloadUpdate(t)}}function Dr(){return{getChannel:()=>global.OVERLAYED_META.release.channel,getVersion:()=>global.OVERLAYED_META.release.version,getReleaseId:()=>global.OVERLAYED_META.release.id}}const Or=M(class extends B{_knownModificationTimes=/* @__PURE__ */ new Map;_confirmedDumps=/* @__PURE__ */ new Set;_pendingReports=/* @__PURE__ */ new Map;_snapshotTimestamp=0;boundOnGameReady=this.onGameReady.bind(this);boundOnGameClose=this.onGameClose.bind(this);constructor(){super(`CrashDumpManager`)}init(){super.init(),this.logger.debug(`init() registering game event listeners`),J.getInstance().on(`gameReadyInternal`,this.boundOnGameReady),J.getInstance().on(`gameCloseInternal`,this.boundOnGameClose),this.logger.debug(`init() complete`)}destroy(){this.logger.debug(`destroy() called`,{pendingReports:this._pendingReports.size,confirmedDumps:this._confirmedDumps.size,knownModificationTimes:this._knownModificationTimes.size}),J.getInstance().off(`gameReadyInternal`,this.boundOnGameReady),J.getInstance().off(`gameCloseInternal`,this.boundOnGameClose),this._knownModificationTimes.clear(),this._confirmedDumps.clear(),this._pendingReports.clear(),this._snapshotTimestamp=0,this.logger.debug(`destroy() cleanup complete`),super.destroy()}async submit(e){this.logger.debug(`submit() called`,{id:e,pendingCount:this._pendingReports.size});let t=this._pendingReports.get(e);if(!t){this.logger.warn(`submit called with unknown id`,e);return}let{response:n,dumpPath:r}=t;this.logger.debug(`Resolved pending report for submission`,{id:e,dumpPath:r});let i=global.OVERLAYED.APPLICATION_ID,a=Lt();if(this.logger.debug(`Resolved identifiers for submission`,{applicationId:i,cortexUserId:a}),n.crash_dump_upload_request)try{this.logger.debug(`Reading crash dump file`,{dumpPath:r});let t=await E.readFile(r);this.logger.debug(`Uploading crash dump`,{dumpPath:r,size:t.byteLength}),await vt(n.crash_dump_upload_request,new Uint8Array(t)),this.logger.debug(`Crash dump uploaded, confirming`,{id:e}),await ut(i,e,{cortex_user_id:a,file_type:`crash_dump`}),this.logger.debug(`Crash dump confirmed`,{id:e})}catch(e){this.logger.error(`Failed to upload crash dump`,{dumpPath:r,error:e})}else this.logger.warn(`No crash dump upload request in response`,{id:e});this._pendingReports.delete(e),this._confirmedDumps.add(r),this.logger.debug(`Report state updated, attempting dump file cleanup`,{id:e,dumpPath:r});try{await E.unlink(r),this.logger.debug(`Dump file cleaned up successfully`,{dumpPath:r})}catch(e){this.logger.warn(`Failed to clean up dump file after submission`,{dumpPath:r,error:e})}this.logger.log(`Crash report submitted successfully`,r)}async onGameReady({game:e}){this.logger.debug(`onGameReady() fired`,{game:e.identifier}),await this.snapshotModificationTimes(),this.logger.debug(`onGameReady() snapshot complete`,{game:e.identifier})}async onGameClose({game:e}){this.logger.debug(`onGameClose() fired`,{game:e.identifier}),await this.scanForNewDumps(xt(e.identifier)),this.logger.debug(`onGameClose() scan complete`,{game:e.identifier})}async snapshotModificationTimes(){let e=F();this._snapshotTimestamp=Date.now(),this.logger.debug(`snapshotModificationTimes() called`,{crashDumpsPath:e,snapshotTimestamp:this._snapshotTimestamp});try{await E.access(e)}catch{this.logger.debug(`Crash dumps directory does not exist, skipping snapshot`,{crashDumpsPath:e});return}let t=await this.findAllDumps(e);this.logger.debug(`Found dumps for snapshot`,{count:t.length});for(let e of t)try{let t=await E.stat(e);if(t.mtimeMs>=this._snapshotTimestamp-3e4){this.logger.debug(`Skipping recent dump from snapshot`,{dumpPath:e,mtimeMs:t.mtimeMs,snapshotTimestamp:this._snapshotTimestamp});continue}this._knownModificationTimes.set(e,t.mtimeMs),this.logger.debug(`Recorded modification time`,{dumpPath:e,mtimeMs:t.mtimeMs})}catch(t){this.logger.warn(`Failed to stat dump file during snapshot`,{dumpPath:e,error:t})}this.logger.debug(`Snapshot complete`,{totalTracked:this._knownModificationTimes.size})}async scanForNewDumps(e){let t=F();this.logger.debug(`scanForNewDumps() called`,{game:e,crashDumpsPath:t});try{await E.access(t)}catch{this.logger.debug(`Crash dumps directory does not exist, skipping scan`,{crashDumpsPath:t});return}let n=new Set([...this._pendingReports.values()].map(e=>e.dumpPath)),r=await this.findAllDumps(t);this.logger.debug(`Scan found dumps`,{total:r.length,pendingCount:n.size,confirmedCount:this._confirmedDumps.size});for(let t of r){if(this._confirmedDumps.has(t)){this.logger.debug(`Skipping already confirmed dump`,{dumpPath:t});continue}if(n.has(t)){this.logger.debug(`Skipping already pending dump`,{dumpPath:t});continue}let r;try{r=await E.stat(t)}catch(e){this.logger.warn(`Failed to stat dump file during scan`,{dumpPath:t,error:e});continue}let i=r.mtimeMs,a=this._knownModificationTimes.get(t);if(this.logger.debug(`Comparing modification times`,{dumpPath:t,modificationTime:i,knownModificationTime:a}),a===void 0||i>a){this.logger.debug(`Dump is new or modified`,{dumpPath:t,isNew:a===void 0});try{let n=r.size,i=m.basename(m.dirname(t)),a=m.basename(t,m.extname(t));this.logger.debug(`Preparing crash report`,{dumpPath:t,crashDumpSize:n,crashSource:i});let o=(await sr().generateAsync({type:`uint8array`})).byteLength,s=global.OVERLAYED.APPLICATION_ID,c=Lt(),l=global.OVERLAYED_META.release.id;if(!l)throw Error(`Missing release id, the API rejects crash reports without one`);this.logger.debug(`Creating game crash report via API`,{applicationId:s,cortexUserId:c,game:e,crashSource:i,crashDumpSize:n,logsSize:o});let{data:u}=await U(s,{cortex_user_id:c,game:e,crash_source:i,crash_identifier:a,release_id:l,logs_size:o,crash_dump_size:n});this._pendingReports.set(u.id,{response:u,dumpPath:t}),this.logger.debug(`Crash report created, emitting 'new' event`,{id:u.id,game:e}),this.logger.log(`New crash dump detected`,{dumpPath:t,game:e,id:u.id}),this.emit(`new`,{id:u.id,game:e})}catch(e){this.logger.error(`Failed to create game crash report`,{dumpPath:t,error:e})}}else this.logger.debug(`Dump unchanged, skipping`,{dumpPath:t});this._knownModificationTimes.set(t,i)}this.logger.debug(`scanForNewDumps() complete`,{game:e,pendingReports:this._pendingReports.size})}async findAllDumps(e){this.logger.debug(`findAllDumps() called`,{basePath:e});let t=[],n;try{n=await E.readdir(e,{withFileTypes:!0})}catch(n){return this.logger.warn(`Failed to read crash dumps directory`,{basePath:e,error:n}),t}this.logger.debug(`Top-level entries in crash dumps directory`,{count:n.length,directories:n.filter(e=>e.isDirectory()).map(e=>e.name)});for(let r of n)if(r.isDirectory()){let n=m.join(e,r.name),i;try{i=await E.readdir(n,{withFileTypes:!0})}catch(e){this.logger.warn(`Failed to read crash dump subdirectory`,{subPath:n,error:e});continue}let a=i.filter(e=>e.isFile()&&e.name.endsWith(`.dmp`));this.logger.debug(`Scanned subdirectory`,{subPath:n,totalEntries:i.length,dmpCount:a.length});for(let e of a)t.push(m.join(n,e.name))}return this.logger.debug(`findAllDumps() complete`,{totalFound:t.length}),t}});let $=!1;const kr=/* @__PURE__ */ new WeakSet;function Ar(){if(!$){for(let e of ce.getAllWebContents())jr(e);O.on(`web-contents-created`,(e,t)=>{jr(t)}),$=!0}}function jr(e){let t=Object.getPrototypeOf(e);if(kr.has(t))return;let n=t.isFocused;t.isFocused=function(){return!Mr(this)&&n.call(this)},kr.add(t)}function Mr(e){let t=e;for(;t;){if(t.isOffscreen())return!0;if(t.getType()!==`webview`)return!1;t=t.hostWebContents??null}return!1}let Nr=!1,Pr={},Fr,Ir=new A,Lr;function Rr(e){Br(e),Ar();let t=zr(e),{init:n=!0,debug:r=!1,silent:i=!0}=t,a=Hr(e);if(L.getInstance().init(e.applicationId,r,i),Qn.getInstance().init(e.applicationId,r,!0,!0),a&&Gr(st(e.applicationId),!1).catch(()=>{}),Nr)return Fr;function o(){if(Nr){L.getInstance().warn(`Overlayed already initialized`);return}Fn(),e.analytics?.crashes!==!1&&q.getInstance().enabled&&!xn.getInstance().initialized&&xn.getInstance().init({stateDir:m.join(we(e.applicationId),`crash-tracking`)});let n=Sn.get({createIfMissing:!1});if(n){let t=En({currentAccount:n.currentAccount,accounts:n.accounts,expected:{applicationId:e.applicationId,baseUrl:$e}});t&&tt(()=>t.account.apiKey)}let r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map,a=Er(),s=On(t.modules,r,Ir),c=kn(),l=Pn(t.keybinds),u=tr(t.navigationGuard),d=rr(),f=ir(),p=X(),h=lr(t),g=_r(),_=pr(t.featureFlags),v=Dr();L.getInstance().log(`Overlayed initialized`),Ur(t),dr(t,r,i,Ir,Pr),Nr=!0,Fr={...s,...c,ads:f,keybinds:l,windows:u,input:d,cortex:p,hasAnyActiveProcesses:()=>Gt.getInstance().hasAnyActiveGames,hasAnyActiveGames:()=>J.getInstance().isInGame,init:o,log:h,initialized:Nr,notices:g,featureFlags:_,updater:a,application:v,crashDumps:{on:(e,t)=>Or.getInstance().on(e,t),off:(e,t)=>Or.getInstance().off(e,t),submit:e=>Or.getInstance().submit(e)}},Fr.universal.on(`logged_in`,e=>{q.getInstance().track(`account_id`,{account_id:e.content.accountId,game:e.game})})}return n&&a?(o(),Fr):new Proxy({init:o},{get:(e,t)=>{if(t===`init`)return e[t];if(!Nr)throw Error(a?`overlayed was called before initialized: ${t}`:Vr);return Fr[t]}})}function zr(e){return{...e,modules:[...e.modules,z()]}}global.OVERLAYED=new Proxy({},{get:()=>{throw Error(`function overlayed was not called`)}});function Br(e){if(!he(e.applicationId))throw Error(`Invalid applicationId, must be a valid ULID.`)}const Vr="Overlayed metadata has not been initialized yet. Run `overlayed init` to set up your local development environment.";function Hr(e){let t=Wr(),n=`2.9.4`,r=st(e.applicationId);function i(){return{package_version:n,application_id:r,application_version:t?.release.version??`0.0.0`}}return L.getInstance().log(`ua object`,i()),rt(()=>i()),t===null?(global.OVERLAYED=new Proxy({},{get:()=>{throw Error(Vr)}}),Gr(r,!0),!1):(global.OVERLAYED={APPLICATION_ID:r,APP_BUILD_CHANNEL:t.release.channel,APP_VERSION:t.release.version,PACKAGE_VERSION:n,FRONTEND_VERSION:`0.0.0`,sessionId:Rt(),electron:e.electron},global.OVERLAYED_META=t,global.OVERLAYED_RUNTIME={userId:Lt(),webVitals:e.analytics?.webVitals!==!1},L.getInstance().log(`meta`,t),!0)}function Ur(e){L.getInstance().warn(`Bootstrapping`);let t=e.universal?[`*`]:e.modules.map(e=>e.key);J.getInstance().setSubscribedGames(t),L.getInstance().warn(`Initializing update manager`),Tr.getInstance().init(),L.getInstance().warn(`Initialized update manager`),Zn.getInstance().init({manualUpdates:e.site?.manualUpdates??!1}),en.getInstance().init(),J.getInstance().init(),Or.getInstance().init(),Gt.getInstance().init(),Kt.getInstance().init({subscribedGames:t}),q.getInstance().track(`start`,{}),tn.getInstance().check(e.applicationId);try{Lr&&clearInterval(Lr),Lr=setInterval(()=>{try{zt()}catch{}},3e4),Lr.unref()}catch(e){L.getInstance().log(`failed to start sessionLastUsed interval`,e)}async function n(){let e={};e.os=te.platform().trim(),e.os_version=process.getSystemVersion().trim(),e.architecture=te.arch().trim();let t=te.cpus();t.length>0?(e.cpu=t[0].model.trim(),e.cpu_cores=t.length,e.cpu_speed=t[0].speed):L.getInstance().warn(`Failed to collect CPU info`);let n=await le.graphics();L.getInstance().info(`GPU info`,n);let r=n.controllers.sort((e,t)=>(t.vram??0)-(e.vram??0))[0];r?(e.gpu=r.model.trim(),e.gpu_memory=r.vram??0):L.getInstance().warn(`Failed to find primary GPU`),e.display_count=n.displays.length;let i=n.displays.find(e=>e.main)??n.displays[0];i?(e.primary_display_resolution_x=i.resolutionX??void 0,e.primary_display_resolution_y=i.resolutionY??void 0,e.primary_display_refresh_rate=i.currentRefreshRate??void 0):L.getInstance().warn(`Failed to find main display`),e.ram=process.getSystemMemoryInfo().total;let a=te.homedir(),o=await E.statfs(a);return o&&`blocks`in o&&`bsize`in o&&`bavail`in o?(e.disk=o.blocks*o.bsize,e.disk_free=o.bavail*o.bsize):L.getInstance().warn(`Failed to collect disk info`),L.getInstance().log(`Retrieved system information`,e),e}O.on(`ready`,()=>{n().then(e=>{q.getInstance().track(`system_info`,e)}).catch(e=>{L.getInstance().log(`Failed to retrieve system information`,e)})}),O.on(`quit`,()=>{q.getInstance().track(`electron_quit`,{}),Kr()}),process.on(`exit`,()=>{q.getInstance().track(`exit`,{}),Kr()})}function Wr(){if(O.isPackaged)try{let e=m.join(process.resourcesPath,`meta.json`);return JSON.parse(y.readFileSync(e,`utf-8`))}catch(e){throw Error(`Failed to read application metadata from resources/meta.json`,{cause:e})}{let e=m.join(process.cwd(),`.overlayed`,`meta.json`);return y.existsSync(e)?JSON.parse(y.readFileSync(e,`utf-8`)):null}}async function Gr(e,t=!1){if(!O.isPackaged)try{L.getInstance().log(`Fetching application metadata from API...`);let n=je({...(await ct(e)).data,siteUrl:``});t&&(L.getInstance().log(v.yellowBright(`Uninitialized development environment detected. Created .overlayed folder. In the future, run ${v.bold(`overlayed init`)} to do so. \n\nThe process will now exit to load the cached metadata.\n\n${v.italic(`Note: This will never happen in a packaged application, and will only happen once in local development so long as the .overlayed folder exists.`)}`)),process.exit(0)),global.OVERLAYED_META=n}catch(e){L.getInstance().error(`Failed to fetch application meta`,e),t&&(console.error(`
|
|
18
18
|
Failed to fetch application metadata. Please ensure you're authenticated with 'overlayed login'.
|
|
19
|
-
`),process.exit(1))}}async function
|
|
19
|
+
`),process.exit(1))}}async function Kr(){try{zt()}catch{}try{Lr&&clearInterval(Lr),Lr=void 0}catch{}J.getInstance().endActiveSessions(),q.getInstance().flush(),Kt.getInstance().destroy(),Or.getInstance().destroy(),J.getInstance().destroy(),en.getInstance().destroy(),Gt.getInstance().destroy(),Jt.getInstance().getInterface(`OGG_SIEGE`).destroy(),Re.getInstance().destroy(),_e.getInstance().destroy(),Tr.getInstance().destroy(),Zn.getInstance().destroy(),fr.getInstance().destroy()}export{ze as RenderInterface,Ve as VirtualKey,ke as defineConfig,Rr as overlayed};
|
package/dist/preload.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{contextBridge as e,ipcRenderer as t}from"electron";let n=-1;const r=e=>{addEventListener(`pageshow`,t=>{t.persisted&&(n=t.timeStamp,e(t))},!0)},i=(e,t,n,r)=>{let i,a;return o=>{t.value>=0&&(o||r)&&(a=t.value-(i??0),(a||i===void 0)&&(i=t.value,t.delta=a,t.rating=((e,t)=>e>t[1]?`poor`:e>t[0]?`needs-improvement`:`good`)(t.value,n),e(t)))}},a=e=>{requestAnimationFrame(()=>requestAnimationFrame(e))},o=()=>{let e=performance.getEntriesByType(`navigation`)[0];if(e&&e.responseStart>0&&e.responseStart<performance.now())return e},s=()=>o()?.activationStart??0,c=(e,t=-1)=>{let r=o(),i=`navigate`;return n>=0?i=`back-forward-cache`:r&&(document.prerendering||s()>0?i=`prerender`:document.wasDiscarded?i=`restore`:r.type&&(i=r.type.replace(/_/g,`-`))),{name:e,value:t,rating:`good`,delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+0xe8d4a51000}`,navigationType:i}},l=/* @__PURE__ */ new WeakMap;function u(e,t){let n=l.get(t);return n||(n=/* @__PURE__ */ new WeakMap,l.set(t,n)),n.get(e)||n.set(e,new t),n.get(e)}var d=class{t;i=0;o=[];h(e){if(e.hadRecentInput)return;let t=this.o[0],n=this.o.at(-1);this.i&&t&&n&&e.startTime-n.startTime<1e3&&e.startTime-t.startTime<5e3?(this.i+=e.value,this.o.push(e)):(this.i=e.value,this.o=[e]),this.t?.(e)}};const f=(e,t,n={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(e)){let r=new PerformanceObserver(e=>{queueMicrotask(()=>{t(e.getEntries())})});return r.observe({type:e,buffered:!0,...n}),r}}catch{}},p=e=>{let t=!1;return()=>{t||=(e(),!0)}};let m=-1;const h=/* @__PURE__ */ new Set,g=()=>document.visibilityState!==`hidden`||document.prerendering?1/0:0,_=e=>{if(document.visibilityState===`hidden`){if(e.type===`visibilitychange`)for(let e of h)e();isFinite(m)||(m=e.type===`visibilitychange`?e.timeStamp:0,removeEventListener(`prerenderingchange`,_,!0))}},v=()=>{if(m<0){let e=s();m=(document.prerendering?void 0:globalThis.performance.getEntriesByType(`visibility-state`).find(t=>t.name===`hidden`&&t.startTime>=e)?.startTime)??g(),addEventListener(`visibilitychange`,_,!0),addEventListener(`prerenderingchange`,_,!0),r(()=>{setTimeout(()=>{m=g()})})}return{get firstHiddenTime(){return m},onHidden(e){h.add(e)}}},y=e=>{document.prerendering?addEventListener(`prerenderingchange`,e,!0):e()},b=[1800,3e3],x=(e,t={})=>{y(()=>{let n=v(),o,l=c(`FCP`),u=f(`paint`,e=>{for(let t of e)t.name===`first-contentful-paint`&&(u.disconnect(),t.startTime<n.firstHiddenTime&&(l.value=Math.max(t.startTime-s(),0),l.entries.push(t),o(!0)))});u&&(o=i(e,l,b,t.reportAllChanges),r(n=>{l=c(`FCP`),o=i(e,l,b,t.reportAllChanges),a(()=>{l.value=performance.now()-n.timeStamp,o(!0)})}))})},S=[.1,.25],C=(e,t={})=>{let n=v();x(p(()=>{let o,s=c(`CLS`,0),l=u(t,d),p=e=>{for(let t of e)l.h(t);l.i>s.value&&(s.value=l.i,s.entries=l.o,o())},m=f(`layout-shift`,p);m&&(o=i(e,s,S,t.reportAllChanges),n.onHidden(()=>{p(m.takeRecords()),o(!0)}),r(()=>{l.i=0,s=c(`CLS`,0),o=i(e,s,S,t.reportAllChanges),a(o)}),setTimeout(o))}))};let w=0,T=1/0,E=0;const D=e=>{for(let t of e)t.interactionId&&(T=Math.min(T,t.interactionId),E=Math.max(E,t.interactionId),w=E?(E-T)/7+1:0)};let O;const k=()=>O?w:performance.interactionCount??0,A=()=>{`interactionCount`in performance||O||(O=f(`event`,D,{durationThreshold:0}))};let j=0;var M=class{l=[];u=/* @__PURE__ */ new Map;m;p;v(){j=k(),this.l.length=0,this.u.clear()}T(){let e=Math.min(this.l.length-1,Math.floor((k()-j)/50));return this.l[e]}h(e){if(this.m?.(e),!e.interactionId&&e.entryType!==`first-input`)return;let t=this.l.at(-1),n=this.u.get(e.interactionId);if(n||this.l.length<10||e.duration>t.L){if(n?e.duration>n.L?(n.entries=[e],n.L=e.duration):e.duration===n.L&&e.startTime===n.entries[0].startTime&&n.entries.push(e):(n={id:e.interactionId,entries:[e],L:e.duration},this.u.set(n.id,n),this.l.push(n)),this.l.sort((e,t)=>t.L-e.L),this.l.length>10){let e=this.l.splice(10);for(let t of e)this.u.delete(t.id)}this.p?.(n)}}};const N=e=>{let t=globalThis.requestIdleCallback||setTimeout,n=globalThis.cancelIdleCallback||clearTimeout;if(document.visibilityState===`hidden`)e();else{let r=p(e),i=-1,a=()=>{n(i),r()};addEventListener(`visibilitychange`,a,{once:!0,capture:!0}),i=t(()=>{removeEventListener(`visibilitychange`,a,{capture:!0}),r()})}},P=[200,500],F=(e,t={})=>{if(!globalThis.PerformanceEventTiming||!(`interactionId`in PerformanceEventTiming.prototype))return;let n=v();y(()=>{A();let a,o=c(`INP`),s=u(t,M),l=e=>{N(()=>{for(let t of e)s.h(t);let t=s.T();t&&t.L!==o.value&&(o.value=t.L,o.entries=t.entries,a())})},d=f(`event`,l,{durationThreshold:t.durationThreshold??40});a=i(e,o,P,t.reportAllChanges),d&&(d.observe({type:`first-input`,buffered:!0}),n.onHidden(()=>{l(d.takeRecords()),a(!0)}),r(()=>{s.v(),o=c(`INP`),a=i(e,o,P,t.reportAllChanges)}))})};var I=class{m;h(e){this.m?.(e)}};const L=[2500,4e3],R=(e,t={})=>{y(()=>{let n=v(),o,l=c(`LCP`),d=u(t,I),m=e=>{t.reportAllChanges||(e=e.slice(-1));for(let t of e)d.h(t),t.startTime<n.firstHiddenTime&&(l.value=Math.max(t.startTime-s(),0),l.entries=[t],o())},h=f(`largest-contentful-paint`,m);if(h){o=i(e,l,L,t.reportAllChanges);let n=p(()=>{m(h.takeRecords()),h.disconnect(),o(!0)}),s=e=>{e.isTrusted&&(N(n),removeEventListener(e.type,s,{capture:!0}))};for(let e of[`keydown`,`click`,`visibilitychange`])addEventListener(e,s,{capture:!0});r(n=>{l=c(`LCP`),o=i(e,l,L,t.reportAllChanges),a(()=>{l.value=performance.now()-n.timeStamp,o(!0)})})}})},z=[800,1800],B=e=>{document.prerendering?y(()=>B(e)):document.readyState===`complete`?setTimeout(e):addEventListener(`load`,()=>B(e),!0)},V=(e,t={})=>{let n=c(`TTFB`),a=i(e,n,z,t.reportAllChanges);B(()=>{let l=o();l&&(n.value=Math.max(l.responseStart-s(),0),n.entries=[l],a(!0),r(()=>{n=c(`TTFB`,0),a=i(e,n,z,t.reportAllChanges),a(!0)}))})};function H({protocol:e,pathname:t,hash:n}){let r=e===`file:`?t.slice(t.lastIndexOf(`/`)):t;if(n.startsWith(`#/`)){let e=n.indexOf(`?`);r+=e===-1?n:n.slice(0,e)}return r.slice(0,512)}function U(e){return!(typeof e==`object`&&e&&`webVitals`in e&&e.webVitals===!1)}function W(){let e={},n,r=!1,
|
|
1
|
+
import{contextBridge as e,ipcRenderer as t}from"electron";let n=-1;const r=e=>{addEventListener(`pageshow`,t=>{t.persisted&&(n=t.timeStamp,e(t))},!0)},i=(e,t,n,r)=>{let i,a;return o=>{t.value>=0&&(o||r)&&(a=t.value-(i??0),(a||i===void 0)&&(i=t.value,t.delta=a,t.rating=((e,t)=>e>t[1]?`poor`:e>t[0]?`needs-improvement`:`good`)(t.value,n),e(t)))}},a=e=>{requestAnimationFrame(()=>requestAnimationFrame(e))},o=()=>{let e=performance.getEntriesByType(`navigation`)[0];if(e&&e.responseStart>0&&e.responseStart<performance.now())return e},s=()=>o()?.activationStart??0,c=(e,t=-1)=>{let r=o(),i=`navigate`;return n>=0?i=`back-forward-cache`:r&&(document.prerendering||s()>0?i=`prerender`:document.wasDiscarded?i=`restore`:r.type&&(i=r.type.replace(/_/g,`-`))),{name:e,value:t,rating:`good`,delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+0xe8d4a51000}`,navigationType:i}},l=/* @__PURE__ */ new WeakMap;function u(e,t){let n=l.get(t);return n||(n=/* @__PURE__ */ new WeakMap,l.set(t,n)),n.get(e)||n.set(e,new t),n.get(e)}var d=class{t;i=0;o=[];h(e){if(e.hadRecentInput)return;let t=this.o[0],n=this.o.at(-1);this.i&&t&&n&&e.startTime-n.startTime<1e3&&e.startTime-t.startTime<5e3?(this.i+=e.value,this.o.push(e)):(this.i=e.value,this.o=[e]),this.t?.(e)}};const f=(e,t,n={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(e)){let r=new PerformanceObserver(e=>{queueMicrotask(()=>{t(e.getEntries())})});return r.observe({type:e,buffered:!0,...n}),r}}catch{}},p=e=>{let t=!1;return()=>{t||=(e(),!0)}};let m=-1;const h=/* @__PURE__ */ new Set,g=()=>document.visibilityState!==`hidden`||document.prerendering?1/0:0,_=e=>{if(document.visibilityState===`hidden`){if(e.type===`visibilitychange`)for(let e of h)e();isFinite(m)||(m=e.type===`visibilitychange`?e.timeStamp:0,removeEventListener(`prerenderingchange`,_,!0))}},v=()=>{if(m<0){let e=s();m=(document.prerendering?void 0:globalThis.performance.getEntriesByType(`visibility-state`).find(t=>t.name===`hidden`&&t.startTime>=e)?.startTime)??g(),addEventListener(`visibilitychange`,_,!0),addEventListener(`prerenderingchange`,_,!0),r(()=>{setTimeout(()=>{m=g()})})}return{get firstHiddenTime(){return m},onHidden(e){h.add(e)}}},y=e=>{document.prerendering?addEventListener(`prerenderingchange`,e,!0):e()},b=[1800,3e3],x=(e,t={})=>{y(()=>{let n=v(),o,l=c(`FCP`),u=f(`paint`,e=>{for(let t of e)t.name===`first-contentful-paint`&&(u.disconnect(),t.startTime<n.firstHiddenTime&&(l.value=Math.max(t.startTime-s(),0),l.entries.push(t),o(!0)))});u&&(o=i(e,l,b,t.reportAllChanges),r(n=>{l=c(`FCP`),o=i(e,l,b,t.reportAllChanges),a(()=>{l.value=performance.now()-n.timeStamp,o(!0)})}))})},S=[.1,.25],C=(e,t={})=>{let n=v();x(p(()=>{let o,s=c(`CLS`,0),l=u(t,d),p=e=>{for(let t of e)l.h(t);l.i>s.value&&(s.value=l.i,s.entries=l.o,o())},m=f(`layout-shift`,p);m&&(o=i(e,s,S,t.reportAllChanges),n.onHidden(()=>{p(m.takeRecords()),o(!0)}),r(()=>{l.i=0,s=c(`CLS`,0),o=i(e,s,S,t.reportAllChanges),a(o)}),setTimeout(o))}))};let w=0,T=1/0,E=0;const D=e=>{for(let t of e)t.interactionId&&(T=Math.min(T,t.interactionId),E=Math.max(E,t.interactionId),w=E?(E-T)/7+1:0)};let O;const k=()=>O?w:performance.interactionCount??0,A=()=>{`interactionCount`in performance||O||(O=f(`event`,D,{durationThreshold:0}))};let j=0;var M=class{l=[];u=/* @__PURE__ */ new Map;m;p;v(){j=k(),this.l.length=0,this.u.clear()}T(){let e=Math.min(this.l.length-1,Math.floor((k()-j)/50));return this.l[e]}h(e){if(this.m?.(e),!e.interactionId&&e.entryType!==`first-input`)return;let t=this.l.at(-1),n=this.u.get(e.interactionId);if(n||this.l.length<10||e.duration>t.L){if(n?e.duration>n.L?(n.entries=[e],n.L=e.duration):e.duration===n.L&&e.startTime===n.entries[0].startTime&&n.entries.push(e):(n={id:e.interactionId,entries:[e],L:e.duration},this.u.set(n.id,n),this.l.push(n)),this.l.sort((e,t)=>t.L-e.L),this.l.length>10){let e=this.l.splice(10);for(let t of e)this.u.delete(t.id)}this.p?.(n)}}};const N=e=>{let t=globalThis.requestIdleCallback||setTimeout,n=globalThis.cancelIdleCallback||clearTimeout;if(document.visibilityState===`hidden`)e();else{let r=p(e),i=-1,a=()=>{n(i),r()};addEventListener(`visibilitychange`,a,{once:!0,capture:!0}),i=t(()=>{removeEventListener(`visibilitychange`,a,{capture:!0}),r()})}},P=[200,500],F=(e,t={})=>{if(!globalThis.PerformanceEventTiming||!(`interactionId`in PerformanceEventTiming.prototype))return;let n=v();y(()=>{A();let a,o=c(`INP`),s=u(t,M),l=e=>{N(()=>{for(let t of e)s.h(t);let t=s.T();t&&t.L!==o.value&&(o.value=t.L,o.entries=t.entries,a())})},d=f(`event`,l,{durationThreshold:t.durationThreshold??40});a=i(e,o,P,t.reportAllChanges),d&&(d.observe({type:`first-input`,buffered:!0}),n.onHidden(()=>{l(d.takeRecords()),a(!0)}),r(()=>{s.v(),o=c(`INP`),a=i(e,o,P,t.reportAllChanges)}))})};var I=class{m;h(e){this.m?.(e)}};const L=[2500,4e3],R=(e,t={})=>{y(()=>{let n=v(),o,l=c(`LCP`),d=u(t,I),m=e=>{t.reportAllChanges||(e=e.slice(-1));for(let t of e)d.h(t),t.startTime<n.firstHiddenTime&&(l.value=Math.max(t.startTime-s(),0),l.entries=[t],o())},h=f(`largest-contentful-paint`,m);if(h){o=i(e,l,L,t.reportAllChanges);let n=p(()=>{m(h.takeRecords()),h.disconnect(),o(!0)}),s=e=>{e.isTrusted&&(N(n),removeEventListener(e.type,s,{capture:!0}))};for(let e of[`keydown`,`click`,`visibilitychange`])addEventListener(e,s,{capture:!0});r(n=>{l=c(`LCP`),o=i(e,l,L,t.reportAllChanges),a(()=>{l.value=performance.now()-n.timeStamp,o(!0)})})}})},z=[800,1800],B=e=>{document.prerendering?y(()=>B(e)):document.readyState===`complete`?setTimeout(e):addEventListener(`load`,()=>B(e),!0)},V=(e,t={})=>{let n=c(`TTFB`),a=i(e,n,z,t.reportAllChanges);B(()=>{let l=o();l&&(n.value=Math.max(l.responseStart-s(),0),n.entries=[l],a(!0),r(()=>{n=c(`TTFB`,0),a=i(e,n,z,t.reportAllChanges),a(!0)}))})};function H({protocol:e,pathname:t,hash:n}){let r=e===`file:`?t.slice(t.lastIndexOf(`/`)):t;if(n.startsWith(`#/`)){let e=n.indexOf(`?`);r+=e===-1?n:n.slice(0,e)}return r.slice(0,512)}function U(e){return!(typeof e==`object`&&e&&`webVitals`in e&&e.webVitals===!1)}function W(e){let t=e.entries.at(-1);if(!(t===void 0||!(`paintTime`in t)||typeof t.paintTime!=`number`||t.paintTime<=0)&&!(t.startTime-t.paintTime<=500))return Math.round(performance.timeOrigin+t.paintTime)}function G(){let e={},n={},r,i=!1,a=(e,t)=>{let r=W(t);r===void 0?delete n[e]:n[e]=r},o=t=>{r??=H(location);let n=t.value;switch(t.name){case`CLS`:e.cls=Math.round(n*1e4)/1e4;break;case`LCP`:e.lcp=Math.round(n),a(`lcpPaint`,t);break;case`INP`:e.inp=Math.round(n);break;case`FCP`:e.fcp=Math.round(n),a(`fcpPaint`,t);break;case`TTFB`:e.ttfb=Math.round(n)}},s=()=>{if(i||r===void 0)return;i=!0,removeEventListener(`visibilitychange`,c,!0),removeEventListener(`pagehide`,c,!0);let a={page:r,...e,...n};try{t.send(`overlayed:web-vitals`,a)}catch{}},c=()=>{document.visibilityState===`hidden`&&s()};R(o),C(o),F(o,{reportAllChanges:!0}),x(o),V(o),addEventListener(`visibilitychange`,c,!0),addEventListener(`pagehide`,c,!0)}const K=process.argv.find(e=>e.startsWith(`--overlayed-meta=`)),q=process.argv.find(e=>e.startsWith(`--overlayed-runtime=`));let J,Y;try{J=K?JSON.parse(K.slice(K.indexOf(`=`)+1)):void 0}catch(e){console.error(`[overlayed] Failed to parse meta argument:`,K,e)}try{Y=q?JSON.parse(q.slice(q.indexOf(`=`)+1)):void 0}catch(e){console.error(`[overlayed] Failed to parse runtime argument:`,q,e)}J&&e.exposeInMainWorld(`__overlayed`,J),Y&&e.exposeInMainWorld(`__overlayedRuntime`,Y),U(Y)&&G();
|
package/dist/sand.d.ts
CHANGED
|
@@ -121,6 +121,32 @@ export declare function module(): {
|
|
|
121
121
|
content: {
|
|
122
122
|
extractionId: SandExtractionId;
|
|
123
123
|
};
|
|
124
|
+
} | {
|
|
125
|
+
game: "sand";
|
|
126
|
+
type: "match_ended";
|
|
127
|
+
creationTime: number;
|
|
128
|
+
} | {
|
|
129
|
+
game: "sand";
|
|
130
|
+
type: "tech_tree_changed";
|
|
131
|
+
creationTime: number;
|
|
132
|
+
content: {
|
|
133
|
+
unlocked: number;
|
|
134
|
+
total: number;
|
|
135
|
+
nodes: {
|
|
136
|
+
id: SandTechNodeId;
|
|
137
|
+
name: string;
|
|
138
|
+
tier: number;
|
|
139
|
+
isUnlocked: boolean;
|
|
140
|
+
isAvailable: boolean;
|
|
141
|
+
}[];
|
|
142
|
+
};
|
|
143
|
+
} | {
|
|
144
|
+
game: "sand";
|
|
145
|
+
type: "trampler_lost";
|
|
146
|
+
creationTime: number;
|
|
147
|
+
content: {
|
|
148
|
+
tramplerId: SandTramplerId;
|
|
149
|
+
};
|
|
124
150
|
} | {
|
|
125
151
|
game: "sand";
|
|
126
152
|
type: "logged_in";
|
|
@@ -177,21 +203,6 @@ export declare function module(): {
|
|
|
177
203
|
amount: number;
|
|
178
204
|
delta: number;
|
|
179
205
|
};
|
|
180
|
-
} | {
|
|
181
|
-
game: "sand";
|
|
182
|
-
type: "tech_tree_changed";
|
|
183
|
-
creationTime: number;
|
|
184
|
-
content: {
|
|
185
|
-
unlocked: number;
|
|
186
|
-
total: number;
|
|
187
|
-
nodes: {
|
|
188
|
-
id: SandTechNodeId;
|
|
189
|
-
name: string;
|
|
190
|
-
tier: number;
|
|
191
|
-
isUnlocked: boolean;
|
|
192
|
-
isAvailable: boolean;
|
|
193
|
-
}[];
|
|
194
|
-
};
|
|
195
206
|
} | {
|
|
196
207
|
game: "sand";
|
|
197
208
|
type: "tech_tree_item_unlocked";
|
|
@@ -237,10 +248,6 @@ export declare function module(): {
|
|
|
237
248
|
};
|
|
238
249
|
}[];
|
|
239
250
|
};
|
|
240
|
-
} | {
|
|
241
|
-
game: "sand";
|
|
242
|
-
type: "match_ended";
|
|
243
|
-
creationTime: number;
|
|
244
251
|
} | {
|
|
245
252
|
game: "sand";
|
|
246
253
|
type: "world_time_changed";
|
|
@@ -324,13 +331,6 @@ export declare function module(): {
|
|
|
324
331
|
z: number;
|
|
325
332
|
};
|
|
326
333
|
};
|
|
327
|
-
} | {
|
|
328
|
-
game: "sand";
|
|
329
|
-
type: "trampler_lost";
|
|
330
|
-
creationTime: number;
|
|
331
|
-
content: {
|
|
332
|
-
tramplerId: SandTramplerId;
|
|
333
|
-
};
|
|
334
334
|
} | {
|
|
335
335
|
game: "sand";
|
|
336
336
|
type: "inventory_changed";
|
|
@@ -1087,6 +1087,32 @@ declare const sandEvents: import("arktype").Module<{
|
|
|
1087
1087
|
content: {
|
|
1088
1088
|
extractionId: SandExtractionId;
|
|
1089
1089
|
};
|
|
1090
|
+
} | {
|
|
1091
|
+
game: "sand";
|
|
1092
|
+
type: "match_ended";
|
|
1093
|
+
creationTime: number;
|
|
1094
|
+
} | {
|
|
1095
|
+
game: "sand";
|
|
1096
|
+
type: "tech_tree_changed";
|
|
1097
|
+
creationTime: number;
|
|
1098
|
+
content: {
|
|
1099
|
+
unlocked: number;
|
|
1100
|
+
total: number;
|
|
1101
|
+
nodes: {
|
|
1102
|
+
id: SandTechNodeId;
|
|
1103
|
+
name: string;
|
|
1104
|
+
tier: number;
|
|
1105
|
+
isUnlocked: boolean;
|
|
1106
|
+
isAvailable: boolean;
|
|
1107
|
+
}[];
|
|
1108
|
+
};
|
|
1109
|
+
} | {
|
|
1110
|
+
game: "sand";
|
|
1111
|
+
type: "trampler_lost";
|
|
1112
|
+
creationTime: number;
|
|
1113
|
+
content: {
|
|
1114
|
+
tramplerId: SandTramplerId;
|
|
1115
|
+
};
|
|
1090
1116
|
} | {
|
|
1091
1117
|
game: "sand";
|
|
1092
1118
|
type: "logged_in";
|
|
@@ -1143,21 +1169,6 @@ declare const sandEvents: import("arktype").Module<{
|
|
|
1143
1169
|
amount: number;
|
|
1144
1170
|
delta: number;
|
|
1145
1171
|
};
|
|
1146
|
-
} | {
|
|
1147
|
-
game: "sand";
|
|
1148
|
-
type: "tech_tree_changed";
|
|
1149
|
-
creationTime: number;
|
|
1150
|
-
content: {
|
|
1151
|
-
unlocked: number;
|
|
1152
|
-
total: number;
|
|
1153
|
-
nodes: {
|
|
1154
|
-
id: SandTechNodeId;
|
|
1155
|
-
name: string;
|
|
1156
|
-
tier: number;
|
|
1157
|
-
isUnlocked: boolean;
|
|
1158
|
-
isAvailable: boolean;
|
|
1159
|
-
}[];
|
|
1160
|
-
};
|
|
1161
1172
|
} | {
|
|
1162
1173
|
game: "sand";
|
|
1163
1174
|
type: "tech_tree_item_unlocked";
|
|
@@ -1203,10 +1214,6 @@ declare const sandEvents: import("arktype").Module<{
|
|
|
1203
1214
|
};
|
|
1204
1215
|
}[];
|
|
1205
1216
|
};
|
|
1206
|
-
} | {
|
|
1207
|
-
game: "sand";
|
|
1208
|
-
type: "match_ended";
|
|
1209
|
-
creationTime: number;
|
|
1210
1217
|
} | {
|
|
1211
1218
|
game: "sand";
|
|
1212
1219
|
type: "world_time_changed";
|
|
@@ -1290,13 +1297,6 @@ declare const sandEvents: import("arktype").Module<{
|
|
|
1290
1297
|
z: number;
|
|
1291
1298
|
};
|
|
1292
1299
|
};
|
|
1293
|
-
} | {
|
|
1294
|
-
game: "sand";
|
|
1295
|
-
type: "trampler_lost";
|
|
1296
|
-
creationTime: number;
|
|
1297
|
-
content: {
|
|
1298
|
-
tramplerId: SandTramplerId;
|
|
1299
|
-
};
|
|
1300
1300
|
} | {
|
|
1301
1301
|
game: "sand";
|
|
1302
1302
|
type: "inventory_changed";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@overlayed/app",
|
|
3
|
-
"version": "2.9.
|
|
3
|
+
"version": "2.9.4",
|
|
4
4
|
"description": "Overlayed app",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"typescript"
|
|
@@ -89,9 +89,9 @@
|
|
|
89
89
|
"@overlayed/native-managers": "0.0.4",
|
|
90
90
|
"@overlayed/sand": "0.0.0",
|
|
91
91
|
"@overlayed/shared-node": "0.0.4",
|
|
92
|
-
"@overlayed/utils": "0.0.4",
|
|
93
92
|
"@overlayed/siege": "0.0.5",
|
|
94
93
|
"@overlayed/universal": "0.0.0",
|
|
94
|
+
"@overlayed/utils": "0.0.4",
|
|
95
95
|
"@overlayed/utils-node": "0.0.4"
|
|
96
96
|
},
|
|
97
97
|
"peerDependencies": {
|