@overlayed/app 0.13.1 → 0.14.1
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.ts +499 -401
- package/dist/index.js +1 -30
- package/dist/preload.d.ts +1 -1
- package/dist/siege.d.ts +2400 -3034
- package/package.json +14 -9
package/dist/index.js
CHANGED
|
@@ -1,30 +1 @@
|
|
|
1
|
-
import{createRequire as e}from"node:module";import{type as t}from"arktype";import n,{createWriteStream as r,existsSync as i,mkdirSync as a,readdirSync as o,unlinkSync as s,writeFileSync as c}from"fs";import{join as l}from"path";import u,{resolve as d}from"node:path";import ee from"events";import{copyFileSync as f,createReadStream as p,existsSync as m,mkdirSync as te,readFileSync as ne,readdirSync as re,writeFileSync as ie}from"node:fs";import h from"fs/promises";import ae from"jszip";import{createHash as oe}from"node:crypto";import se,{app as ce}from"electron";var le=Object.create,ue=Object.defineProperty,de=Object.getOwnPropertyDescriptor,fe=Object.getOwnPropertyNames,pe=Object.getPrototypeOf,me=Object.prototype.hasOwnProperty,he=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ge=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=fe(t),a=0,o=i.length,s;a<o;a++)s=i[a],!me.call(e,s)&&s!==n&&ue(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=de(t,s))||r.enumerable});return e},_e=(e,t,n)=>(n=e==null?{}:le(pe(e)),ge(t||!e||!e.__esModule?ue(n,`default`,{value:e,enumerable:!0}):n,e));function ve(e){return{all:e=e||new Map,on:function(t,n){var r=e.get(t);r?r.push(n):e.set(t,[n])},off:function(t,n){var r=e.get(t);r&&(n?r.splice(r.indexOf(n)>>>0,1):e.set(t,[]))},emit:function(t,n){var r=e.get(t);r&&r.slice().map(function(e){e(n)}),(r=e.get(`*`))&&r.slice().map(function(e){e(t,n)})}}}var ye=class{data=[];constructor(){}get size(){return this.data.length}add(e){this.data.push(e)}next(){return this.data.shift()}clear(){this.data.length=0}*flush(){for(;this.size>0;){let e=this.next();e&&(yield e)}}},be=class{emitter;constructor(){this.emitter=ve()}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}emit(e,t){this.emitter.emit(e,t)}removeAllListeners(){this.emitter.all.clear()}};function xe(e,...t){let n=class extends e{static _instance;static getInstance(){return this._instance||(this._instance=new e(...t)),this._instance}static clearInstance(){this._instance=void 0}};return n}var Se=class extends be{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()})}};xe(Se);var Ce=class e extends be{stream;logPath;baseFileName;currentDate;rotationCheckInterval;isRotating=!1;constructor(e,t){super(),this.logPath=e,this.baseFileName=t.replace(`.log`,``),this.currentDate=this.getDateString(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(`log`,...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)}getFileName(e){return`${this.baseFileName}-${e}.log`}ensureLogDirectory(){try{a(this.logPath,{recursive:!0})}catch(e){throw console.error(`Failed to create log directory ${this.logPath}:`,e),e}}ensureLogFile(){let e=l(this.logPath,this.getFileName(this.currentDate));if(!i(e))try{c(e,``,`utf8`)}catch(t){throw console.error(`Failed to create log file ${e}:`,t),t}}getDateString(e){return e.toISOString().split(`T`)[0]}createStream(){let e=l(this.logPath,this.getFileName(this.currentDate));return r(e,{flags:`a`,encoding:`utf8`})}async rotateLogs(){if(this.isRotating)return;this.isRotating=!0;let e=this.getDateString(new Date);e!==this.currentDate&&await new Promise(t=>{this.stream.end(()=>{this.currentDate=e,this.stream=this.createStream(),this.cleanupOldLogs(),t()})}),this.isRotating=!1}startRotationCheck(){return setInterval(()=>this.rotateLogs(),6e4)}cleanupOldLogs(){let e=o(this.logPath),t=new Date;t.setDate(t.getDate()-3),e.filter(e=>e.startsWith(this.baseFileName)&&e.endsWith(`.log`)).filter(e=>{let n=e.replace(`${this.baseFileName}-`,``).replace(`.log`,``),r=new Date(n);return r<t}).forEach(e=>{try{s(l(this.logPath,e))}catch(t){console.error(`Failed to delete old log file ${e}:`,t)}})}write(e,...t){let n=new Date,r=n.toISOString().replace(`T`,` `).replace(/\.\d+Z$/,``)+`.${n.getMilliseconds().toString().padStart(3,`0`)}`,i=t.map(e=>typeof e==`object`?JSON.stringify(e,void 0,2):String(e)).join(` `),a=`[${r}] [${e}] ${i}\n`;this.stream.write(a,e=>{e?this.emit(`error`,e):this.emit(`write`,a)})}};const we=()=>u.join(process.env.APPDATA??``,`overlayed`),Te=e=>u.join(we(),`apps`,e),Ee=e=>u.join(Te(e),`logs`);var De=class{fileLogger;path;appId;messageQueue=new ye;fileName;constructor(e){this.fileName=e}init(e){this.appId=e,this.path=Ee(e),this.fileLogger=new Ce(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=`[${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)}}error(...e){this.handle(`error`,...e)}warn(...e){this.handle(`warn`,...e)}info(...e){this.handle(`log`,...e)}debug(...e){this.handle(`debug`,...e)}log(...e){this.handle(`log`,...e)}handle(e,...t){console[e](...t),this.fileLogger?this.fileLogger[e](...t):this.messageQueue.add({type:e,args:t})}};xe(De,`main.log`);const Oe=e(import.meta.url),{PipeEventServer:ke,PipeEventClient:Ae,PipeEventBase:je,ProcessMonitor:Me,Process:Ne,InjectionMethod:Pe,AccessLevel:Fe,HardwareInterface:Ie}=Oe(`@overlayed/app/dist/native-interface/build/overlayed_native_interface_x64.node`);var Le=class extends be{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=null)}init(){this.server=new ke(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.server.on(`disconnected`,()=>{this._hasConnection=!1})}};const Re=xe(Le,`stats-cc`);function ze(e){return{all:e=e||new Map,on:function(t,n){var r=e.get(t);r?r.push(n):e.set(t,[n])},off:function(t,n){var r=e.get(t);r&&(n?r.splice(r.indexOf(n)>>>0,1):e.set(t,[]))},emit:function(t,n){var r=e.get(t);r&&r.slice().map(function(e){e(n)}),(r=e.get(`*`))&&r.slice().map(function(e){e(t,n)})}}}var Be=class{data=[];constructor(){}get size(){return this.data.length}add(e){this.data.push(e)}next(){return this.data.shift()}clear(){this.data.length=0}*flush(){for(;this.size>0;){let e=this.next();e&&(yield e)}}},Ve=class{emitter;constructor(){this.emitter=ze()}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}emit(e,t){this.emitter.emit(e,t)}removeAllListeners(){this.emitter.all.clear()}},He=class{listeners;constructor(){this.listeners=new Map}on(e,t){let n=this.listeners.get(e)||new Set;n.add(t),this.listeners.set(e,n)}off(e,t){let n=this.listeners.get(e);n&&n.delete(t)}async emit(e,...t){let n=this.listeners.get(e)||new Set,r=this.listeners.get(`*`)||new Set,i=[...Array.from(n),...Array.from(r)];if(i.length===0)return[];let a=await Promise.all(i.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}}));return a}removeAllListeners(){this.listeners.clear()}};function g(e,...t){let n=class extends e{static _instance;static getInstance(){return this._instance||(this._instance=new e(...t)),this._instance}static clearInstance(){this._instance=void 0}};return n}var Ue=class extends Ve{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()})}};const _=g(Ue);var We=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){this.reportInvalidConfigFile(t.issues);return}this.data=this.onBeforeSave(e),this.save(e)}get(){return this.data?this.data:this.load()}getKey(e){let t=this.get();return t[e]}save(e){let t=this.onBeforeSave(e);try{n.writeFileSync(this.getFilePath(),JSON.stringify(t,void 0,2))}catch{return}return this.data=t}load(){if(!this.fileExists(this.getFilePath())||!this.canReadWriteFile(this.getFilePath())){this.save(this._defaultValue);let e=this.onAfterLoad(this._defaultValue);return this.data=e,e}try{let e=n.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 n=t(`string.json.parse`).to(`object`),r=n(e);if(r instanceof t.errors)return this._defaultValue;let i=this._schema[`~standard`].validate(r);if(i instanceof Promise)throw Error(`StructuredConfigFile does not support async validation`);return i.issues?this.migrate(r,this._defaultValue):this.migrate(i.value,this._defaultValue)}catch{return this._defaultValue}}canReadWriteFile(e){try{return n.accessSync(e,n.constants.R_OK|n.constants.W_OK),!0}catch{return!1}}fileExists(e){try{return n.accessSync(e,n.constants.F_OK),!0}catch{return!1}}migrate(e,t){let n={...e};for(let r in t){if(!Object.prototype.hasOwnProperty.call(t,r))continue;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){_.getInstance().error(`Invalid config file`,`INVALID_CONFIG_FILE`,{issues:e.map(e=>e.message),filePath:this._path,data:this.data})}},Ge=class e extends Ve{stream;logPath;baseFileName;currentDate;rotationCheckInterval;isRotating=!1;constructor(e,t){super(),this.logPath=e,this.baseFileName=t.replace(`.log`,``),this.currentDate=this.getDateString(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(`log`,...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)}getFileName(e){return`${this.baseFileName}-${e}.log`}ensureLogDirectory(){try{a(this.logPath,{recursive:!0})}catch(e){throw console.error(`Failed to create log directory ${this.logPath}:`,e),e}}ensureLogFile(){let e=l(this.logPath,this.getFileName(this.currentDate));if(!i(e))try{c(e,``,`utf8`)}catch(t){throw console.error(`Failed to create log file ${e}:`,t),t}}getDateString(e){return e.toISOString().split(`T`)[0]}createStream(){let e=l(this.logPath,this.getFileName(this.currentDate));return r(e,{flags:`a`,encoding:`utf8`})}async rotateLogs(){if(this.isRotating)return;this.isRotating=!0;let e=this.getDateString(new Date);e!==this.currentDate&&await new Promise(t=>{this.stream.end(()=>{this.currentDate=e,this.stream=this.createStream(),this.cleanupOldLogs(),t()})}),this.isRotating=!1}startRotationCheck(){return setInterval(()=>this.rotateLogs(),6e4)}cleanupOldLogs(){let e=o(this.logPath),t=new Date;t.setDate(t.getDate()-3),e.filter(e=>e.startsWith(this.baseFileName)&&e.endsWith(`.log`)).filter(e=>{let n=e.replace(`${this.baseFileName}-`,``).replace(`.log`,``),r=new Date(n);return r<t}).forEach(e=>{try{s(l(this.logPath,e))}catch(t){console.error(`Failed to delete old log file ${e}:`,t)}})}write(e,...t){let n=new Date,r=n.toISOString().replace(`T`,` `).replace(/\.\d+Z$/,``)+`.${n.getMilliseconds().toString().padStart(3,`0`)}`,i=t.map(e=>typeof e==`object`?JSON.stringify(e,void 0,2):String(e)).join(` `),a=`[${r}] [${e}] ${i}\n`;this.stream.write(a,e=>{e?this.emit(`error`,e):this.emit(`write`,a)})}};const Ke=()=>u.join(process.env.APPDATA??``,`overlayed`),qe=()=>u.join(Ke(),`logs`),Je=e=>u.join(Ke(),`apps`,e),Ye=e=>u.join(Je(e),`logs`);var Xe=class{fileLogger;path;appId;messageQueue=new Be;fileName;constructor(e){this.fileName=e}init(e){this.appId=e,this.path=Ye(e),this.fileLogger=new Ge(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=`[${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)}}error(...e){this.handle(`error`,...e)}warn(...e){this.handle(`warn`,...e)}info(...e){this.handle(`log`,...e)}debug(...e){this.handle(`debug`,...e)}log(...e){this.handle(`log`,...e)}handle(e,...t){console[e](...t),this.fileLogger?this.fileLogger[e](...t):this.messageQueue.add({type:e,args:t})}};const v=g(Xe,`main.log`);var Ze=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=5,i=new Map,a=new Set,o=new Set,s=[];for(let e=0;e<n;e++)s.push(e);let c=async n=>{let c=n*t,l=Math.min(c+t,this.blob.size),u=this.blob.slice(c,l);try{await e(u,n),o.add(n),this.emit(`chunkComplete`,n),a.delete(n)}catch(e){let t=i.get(n)||0;t<r?(i.set(n,t+1),await new Promise(e=>setTimeout(e,(t+1)*1e3)),s.push(n)):(o.add(n),this.emit(`error`,e),this.shouldStop=!0,a.delete(n))}},l=[],u=async()=>{for(;(s.length>0||a.size>0)&&!this.shouldStop;){if(s.length===0){await new Promise(e=>setTimeout(e,10));continue}let e=s.shift();o.has(e)||a.has(e)||(a.add(e),await c(e))}};for(let e=0;e<this.maxConcurrent;e++)l.push(u());await Promise.all(l)}};function Qe(e){return m(e)?re(e).map(t=>[e,t]):[]}var $e=class{logger;initialized=!1;constructor(e){this.logger=v.getInstance().scope(e)}init(){this.logger.log(`Initializing`),this.initialized=!0}destroy(){this.logger.log(`Destroying`),this.initialized=!1}},et=class extends Ve{logger;initialized=!1;constructor(e){super(),this.logger=v.getInstance().scope(e)}init(){this.logger.log(`Initializing`),this.initialized=!0}destroy(){this.logger.log(`Destroying`),this.initialized=!1,this.removeAllListeners()}},tt=class extends He{logger;initialized=!1;constructor(e){super(),this.logger=v.getInstance().scope(e)}init(){this.logger.log(`Initializing`),this.initialized=!0}destroy(){this.logger.log(`Destroying`),this.initialized=!1,this.removeAllListeners()}},nt=`object`,rt=`function`,it=`prototype`,at=`text`,ot=`json`,st=`abort`,ct=`paramsSerializer`,lt=`addEventListener`,ut=`status`,y=`headers`,dt=Object,ft=void 0,pt=null,mt=dt[it],ht=dt.keys,gt=Array.isArray,_t=`method`,vt=`HEAD`,yt=`GET`,bt=`OPTIONS`,xt=`POST`,St=`PUT`,Ct=`PATCH`,wt=`DELETE`;function Tt(e,t){let n=new AbortController;function r(e){n.abort(e),a()}let i=[];for(let t of e){if((t==null?void 0:t.aborted)===!0){r(t.reason);break}if(t!=null&&t[lt]){let e=()=>{r(t.reason)};i.push(()=>{var n;(n=t.removeEventListener)==null||n.call(t,st,e)}),t[lt](st,e)}}function a(){i.forEach(e=>e()),t?.()}let o=n.signal;return o.clear=a,o}var Et=dt.getPrototypeOf,Dt=e=>{if(e!==pt&&typeof e===nt){if(typeof Et===rt){let t=Et(e);return t===mt||t===pt}return mt.toString.call(e)===`[${nt} Object]`}return!1},Ot=(...e)=>e.reduce((e,t)=>{if(gt(t))throw TypeError(`Arguments must be ${nt}s, not arrays.`);return ht(t).forEach(n=>{[`__proto__`,`constructor`,it].includes(n)||(gt(e[n])&>(t[n])?e[n]=Array.from(new Set(e[n].concat(t[n]))):Dt(e[n])&&Dt(t[n])?e[n]=Ot(e[n],t[n]):e[n]=t[n])}),e},{});function kt(e,t=!0,n=pt,r){if(e===ft||e===pt)return``;let i=[],a=t?encodeURIComponent:e=>e,o=gt(e),{arrayFormat:s,allowDots:c,serializeDate:l}=r||{},u=e=>{if(c&&!o)return`.${e}`;if(o){if(s===`brackets`)return`[]`;if(s===`repeat`)return``}return`[${e}]`};for(let o in e)if(mt.hasOwnProperty.call(e,o)){let s=e[o];if(s!==ft){let e=n?`${n}${u(o)}`:a(o);if(!isNaN(s)&&s instanceof Date&&(s=l?l(s):s.toISOString()),typeof s===nt){let n=kt(s,t,e,r);n!==``&&i.push(n)}else i.push(`${a(e)}=${a(s)}`)}}return i.join(`&`)}function At(e){return gt(e)?e.map(At):(e&&typeof e===nt&&ht(e).forEach(t=>{let n=e[t];n===ft?delete e[t]:At(n)}),e)}function jt(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Mt(e,t){return e?t?(e.endsWith(`/`)?e:e+`/`)+(t[0]===`/`?t.slice(1):t):e:t||``}var Nt=`XiorError`,Pt=`XiorTimeoutError`,Ft=class extends Error{constructor(e,t,n){super(e),this.name=Nt,this.request=t,this.config=t,this.response=n}},It=class extends Ft{constructor(e,t,n){super(e,t,n),this.name=Pt}},Lt=Object.defineProperty,Rt=Object.defineProperties,zt=Object.getOwnPropertyDescriptors,Bt=Object.getOwnPropertySymbols,Vt=Object.prototype.hasOwnProperty,Ht=Object.prototype.propertyIsEnumerable,Ut=(e,t,n)=>t in e?Lt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Wt=(e,t)=>{for(var n in t||(t={}))Vt.call(t,n)&&Ut(e,n,t[n]);if(Bt)for(var n of Bt(t))Ht.call(t,n)&&Ut(e,n,t[n]);return e},Gt=(e,t)=>Rt(e,zt(t)),Kt=(e,t)=>{var n={};for(var r in e)Vt.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&Bt)for(var r of Bt(e))t.indexOf(r)<0&&Ht.call(e,r)&&(n[r]=e[r]);return n},qt=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),Jt=`application/`,Yt=`${Jt}x-www-form-urlencoded`,Xt=RegExp,Zt=new Xt(`^${Yt}`,`i`),Qt=`${Jt}${ot}`,$t=new Xt(`^${Jt}.*${ot}.*`,`i`);function en(e=yt){return[vt,yt,bt].includes(e)}var tn=typeof URLSearchParams!=`${ft}`;function nn(e){return qt(this,null,function*(){let t=e[ct]||kt,n=e.encodeURI!==!1,r=e[_t]&&e[_t].toUpperCase(),i=e.url,a=i,o=tn&&e.data instanceof URLSearchParams,s=o?dt.fromEntries(e.data.entries()):e.data,c=s,l=e!=null&&e[y]?Wt({},e[y]):{},u=e.params,d=en(r);if(s&&typeof s.append!==rt){let n=``,r=`content-type`;if(e!=null&&e[y]){let t=ht(e[y]).find(e=>e.toLowerCase()===r);t&&(r=t,n=e[y][t])}(!n||o)&&(n=d||o?Yt:Qt,l[r]=n),typeof s===nt&&(d&&u&&(u=Ot(s,u)),$t.test(n)?c=JSON.stringify(At(s)):!d&&Zt.test(n)&&(c=t(s)))}if(u&&ht(u).length>0){let e=t(u,n);i+=i.includes(`?`)?`&${e}`:`?${e}`}return Gt(Wt({},e),{_data:c,_url:i,data:s,url:a,method:r,[y]:l,isGet:d})})}var rn=typeof AbortController!=`${ft}`;function an(e,t){return qt(this,null,function*(){let n;if(!t||!e.ok||[at,ot].includes(t)){if(n=yield e[at](),n&&t!==at)try{n=JSON.parse(n)}catch(e){}}else{if(t===`blob`)return e.blob();if(t===`arraybuffer`)return e.arrayBuffer()}return n})}var on=e=>new sn(e),sn=class{constructor(e){this.REQI=[],this.RESI=[],this.P=[],this.config=e,this.defaults={params:{},[y]:{}}}get interceptors(){return{request:{use:(e,t,n)=>(this.REQI.push(e),e),eject:e=>{this.REQI=this.REQI.filter(t=>t!==e)},clear:()=>{this.REQI=[]}},response:{use:(e,t)=>(this.RESI.push({fn:e,onRejected:t}),e),eject:e=>{this.RESI=this.RESI.filter(t=>t.fn!==e)},clear:()=>{this.RESI=[]}}}}get plugins(){return{use:e=>(this.P.push(e),e),eject:e=>{this.P=this.P.filter(t=>t!==e)},clear:()=>{this.P=[]}}}request(e){return qt(this,null,function*(){let t=Ot(this.config||{},this.defaults,typeof e==`string`?{url:e}:e),n=`credentials`;t.withCredentials&&!t[n]&&(t[n]=`include`),t[ct]||(t[ct]=kt);for(let e of this.REQI)t=yield e(t);let r=this._.bind(this);this.P.forEach(e=>{r=e(r,this)});let i=r(t);if(!t._did){let e=0,t=[];for(this.RESI.forEach(function(e){t.push(e.fn,e.onRejected)});t.length>e;)i=i.then(t[e++],t[e++])}return i})}_(e){return qt(this,null,function*(){let t=yield nn(e),{url:n,method:r,headers:i,timeout:a,signal:o,data:s,_data:c,_url:l,isGet:u,fetch:d}=t,ee=Kt(t,[`url`,`method`,`headers`,`timeout`,`signal`,`data`,`_data`,`_url`,`isGet`,`fetch`]);e._url=l;let f,p=[],m=ft;if(a&&rn){let t=new AbortController;m=setTimeout(()=>{t.abort(new It(`timeout of ${a}ms exceeded`,e))},a),p.push(t.signal)}o&&p.push(o),f=p[0],p.length>1&&(f=Tt(p,()=>{clearTimeout(m)}));let te=l||n,ne=`baseURL`;return e[ne]&&!jt(te)&&(te=Mt(e[ne],te)),(d||fetch)(te,Gt(Wt({body:u?ft:c},ee),{signal:f,method:r,headers:i})).then(t=>qt(this,null,function*(){let{responseType:n}=e,r={data:yield an(t,n),response:t,config:e,request:e,[ut]:t[ut],statusText:t.statusText,[y]:t[y]};if(!t.ok){let n=new Ft(t[ut]?`Request failed with status code ${t[ut]}`:`Network error`,e,r);return Promise.reject(n)}return r})).finally(()=>{var e;m&&clearTimeout(m),(e=f==null?void 0:f.clear)==null||e.call(f)})})}cG(e){return(t,n)=>this.request(n?Gt(Wt({},n),{method:e,url:t}):{method:e,url:t})}cP(e){return(t,n,r)=>this.request(r?Gt(Wt({},r),{method:e,url:t,data:n}):{method:e,url:t,data:n})}get(e,t){return this.cG(yt)(e,t)}head(e,t){return this.cG(vt)(e,t)}post(e,t,n){return this.cP(xt)(e,t,n)}put(e,t,n){return this.cP(St)(e,t,n)}patch(e,t,n){return this.cP(Ct)(e,t,n)}delete(e,t){return this.cG(wt)(e,t)}options(e,t){return this.cG(bt)(e,t)}};sn.create=on,sn.VERSION=`0.7.7`;var cn=Object.assign(sn.create(),{create:sn.create,VERSION:sn.VERSION}),ln=cn;const un=ln.create({baseURL:`https://updater.stats.cc`,headers:{Accept:`application/json`,"Accept-Encoding":`gzip, deflate, br`}});let dn;function fn(e){dn=e}const pn=ln.create({baseURL:`https://api.overlayed.gg`,headers:{Accept:`application/json`,"Accept-Encoding":`gzip, deflate, br`}});un.interceptors.request.use(e=>{let t=dn?.();return t?(e.headers??={},e.headers.Authorization=t,e):e});function mn(e){return pn.get(`/v1/public/applications/${e}`)}function hn(e,t){return un.get(`/v1/native/${_n(e)}/version.txt`,{params:{channel:t},responseType:`text`})}function gn(e,t){return un.get(`/v1/native/${_n(e)}/files`,{params:{channel:t},responseType:`arraybuffer`})}function _n(e){return e===`01JXPFK6YQ3N00N2Y9JHFNG55D`||e===`01JZEBPGHT5M4Y6SGY4P7Q9EZT`?`siege-game-module`:e}function vn(){return pn.get(`/v1/public/raven/config`)}const yn=e=>Array.isArray(e)?e:[e],bn=(e,t)=>{let n=[[],[]];for(let r of e)t(r)?n[0].push(r):n[1].push(r);return n},xn=Array,Sn=(e,t)=>e.includes(t),Cn=(e,t=0)=>[...Array(e)].map((e,n)=>n+t),b=(e,t,n)=>e===void 0?t===void 0?[]:Array.isArray(t)?t:[t]:(n?.prepend?Array.isArray(t)?e.unshift(...t):e.unshift(t):Array.isArray(t)?e.push(...t):e.push(t),e),wn=(e,t)=>t==null?e??[]:e==null?yn(t):e.concat(t),Tn=(...e)=>e.reduce(wn,[]),En=(e,t,n)=>{if(e===void 0)return Array.isArray(t)?t:[t];let r=n?.isEqual??((e,t)=>e===t);return yn(t).forEach(t=>{e.some(e=>r(e,t))||e.push(t)}),e},Dn=(e,t)=>e.reduce((e,n)=>{let r=n[t];return e[r]=b(e[r],n),e},{}),On=(e,t,n)=>e.length===t.length&&e.every(n?.isEqual?(e,r)=>n.isEqual(e,t[r]):(e,n)=>e===t[n]),kn=(e,t)=>x(e)===t,x=e=>{let t=typeof e;return t===`object`?e===null?`null`:`object`:t===`function`?`object`:t},An={boolean:`boolean`,null:`null`,undefined:`undefined`,bigint:`a bigint`,number:`a number`,object:`an object`,string:`a string`,symbol:`a symbol`},jn={...An,function:`a function`};var Mn=class extends Error{};const S=e=>Nn(e,Mn),Nn=(e,t=Error)=>{throw new t(e)};var Pn=class extends Error{name=`ParseError`};const C=e=>Nn(e,Pn),Fn=e=>` ${e}`,w=(e,t)=>{let n={},r=Array.isArray(e),i=!1;return Object.entries(e).forEach((e,a)=>{let o=r?t(a,e[1]):t(...e,a);i||=typeof o[0]==`number`;let s=Array.isArray(o[0])||o.length===0?o:[o];s.forEach(([e,t])=>{typeof e==`object`?n[e.group]=b(n[e.group],t):n[e]=t})}),i?Object.values(n):n},In=Object.entries,T=(e,t)=>e in t,Ln=(e,t)=>t in e;var Rn=class{constructor(e){Object.assign(this,e)}};const zn=class{};var Bn=class extends zn{};const Vn=(e,t)=>{let n={},r={},i;for(i in e)i in t?n[i]=e[i]:r[i]=e[i];return[n,r]},Hn=(e,t)=>Vn(e,t)[1],Un=e=>Object.keys(e).length===0,Wn=e=>[...Object.entries(e),...Object.getOwnPropertySymbols(e).map(t=>[t,e[t]])],Gn=(e,t)=>Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)),Kn=e=>{let t=Object.keys(e).sort(),n={};for(let r=0;r<t.length;r++)n[t[r]]=e[t[r]];return n},E=Fn(`represents an uninitialized value`),qn=e=>Object.values(e).filter(t=>typeof t==`number`?!0:typeof e[t]!=`number`),Jn={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},Yn=globalThis.File??Blob,Xn={ArrayBuffer,Blob,File:Yn,FormData,Headers,Request,Response,URL},Zn={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},Qn={...Jn,...Xn,...Zn,String,Number,Boolean},$n=e=>{let t=Object.getPrototypeOf(e);for(;t?.constructor&&(!T(t.constructor.name,Qn)||!(e instanceof Qn[t.constructor.name]));)t=Object.getPrototypeOf(t);let n=t?.constructor?.name;if(!(n===void 0||n===`Object`))return n},er=e=>typeof e==`object`&&e?$n(e)??`object`:x(e),D=Array.isArray,tr={Array:`an array`,Function:`a function`,Date:`a Date`,RegExp:`a RegExp`,Error:`an Error`,Map:`a Map`,Set:`a Set`,String:`a String object`,Number:`a Number object`,Boolean:`a Boolean object`,Promise:`a Promise`,WeakMap:`a WeakMap`,WeakSet:`a WeakSet`},nr={ArrayBuffer:`an ArrayBuffer instance`,Blob:`a Blob instance`,File:`a File instance`,FormData:`a FormData instance`,Headers:`a Headers instance`,Request:`a Request instance`,Response:`a Response instance`,URL:`a URL instance`},rr={Int8Array:`an Int8Array`,Uint8Array:`a Uint8Array`,Uint8ClampedArray:`a Uint8ClampedArray`,Int16Array:`an Int16Array`,Uint16Array:`a Uint16Array`,Int32Array:`an Int32Array`,Uint32Array:`a Uint32Array`,Float32Array:`a Float32Array`,Float64Array:`a Float64Array`,BigInt64Array:`a BigInt64Array`,BigUint64Array:`a BigUint64Array`},ir={...tr,...nr,...rr},ar=e=>{let t=Object(e).name??null;return t&&T(t,Qn)&&Qn[t]===e?t:null},or=e=>{let t=Object.getPrototypeOf(e),n=[];for(;t!==null;)n.push(t.constructor),t=Object.getPrototypeOf(t);return n},sr=(e,t)=>{let n=e.prototype;for(;n!==null;){if(n===t.prototype)return!0;n=Object.getPrototypeOf(n)}return!1},cr=e=>lr(e,new Map),lr=(e,t)=>{if(typeof e!=`object`||!e)return e;if(t?.has(e))return t.get(e);let n=ar(e.constructor);if(n===`Date`)return new Date(e.getTime());if(n&&n!==`Array`)return e;let r=Array.isArray(e)?e.slice():Object.create(Object.getPrototypeOf(e)),i=Object.getOwnPropertyDescriptors(e);if(t)for(let n in t.set(e,r),i){let e=i[n];if(`get`in e||`set`in e)continue;e.value=lr(e.value,t)}return Object.defineProperties(r,i),r},ur=e=>{let t=E;return()=>t===E?t=e():t},dr=e=>typeof e==`function`&&e.length===0,fr=(e,t)=>{try{return e()}catch(e){return t?.(e)}},pr=class extends Function{constructor(...e){let t=e.slice(0,-1),n=e.at(-1);try{super(...t,n)}catch(t){return S(`Encountered an unexpected error while compiling your definition:
|
|
2
|
-
Message: ${t}
|
|
3
|
-
Source: (${e.slice(0,-1)}) => {
|
|
4
|
-
${e.at(-1)}
|
|
5
|
-
}`)}}};var mr=class{constructor(e,...[t]){return Object.assign(Object.setPrototypeOf(e.bind(t?.bind??this),this.constructor.prototype),t?.attach)}};const hr=ur(()=>{try{return Function(`return false`)()}catch{return!0}});Fn(`brand`),Fn(`arkInferred`),Fn(`args`);var O=class{constructor(){}};const gr=e=>e[0].toUpperCase()+e.slice(1),_r=e=>new RegExp(vr(e),typeof e==`string`?``:e.flags),vr=e=>{let t=typeof e==`string`?e:e.source;return`^(?:${t})$`},k={negativeLookahead:e=>`(?!${e})`,nonCapturingGroup:e=>`(?:${e})`},yr=`\\`,br={" ":1,"\n":1," ":1},xr=/^-0\.?0*$/.source,Sr=/[1-9]\d*/.source,Cr=/\.\d+/.source,wr=/\.\d*[1-9]/.source,Tr=e=>_r(k.negativeLookahead(xr)+k.nonCapturingGroup(`-?`+k.nonCapturingGroup(k.nonCapturingGroup(`0|`+Sr)+k.nonCapturingGroup(e.decimalPattern)+`?`)+(e.allowDecimalOnly?`|`+e.decimalPattern:``)+`?`)),Er=Tr({decimalPattern:wr,allowDecimalOnly:!1}),Dr=Er.test.bind(Er),Or=Tr({decimalPattern:Cr,allowDecimalOnly:!0});Or.test.bind(Or);const kr=/^-?\d*\.?\d*$/,Ar=e=>e.length!==0&&kr.test(e),jr=_r(k.negativeLookahead(`^-0$`)+`-?`+k.nonCapturingGroup(k.nonCapturingGroup(`0|`+Sr))),Mr=jr.test.bind(jr),Nr=/^-?\d+$/,Pr=Nr.test.bind(Nr),Fr={number:`a number`,bigint:`a bigint`,integer:`an integer`},Ir=(e,t)=>`'${e}' was parsed as ${Fr[t]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,Lr=(e,t)=>t===`number`?Dr(e):Mr(e),Rr=(e,t)=>t===`number`?Number(e):Number.parseInt(e),zr=(e,t)=>t===`number`?Ar(e):Pr(e),Br=(e,t)=>Ur(e,`number`,t),Vr=(e,t)=>Ur(e,`number`,{...t,strict:!0}),Hr=(e,t)=>Ur(e,`integer`,t),Ur=(e,t,n)=>{let r=Rr(e,t);return!Number.isNaN(r)&&zr(e,t)?n?.strict?Lr(e,t)?r:C(Ir(e,t)):r:n?.errorOnFail?C(n?.errorOnFail===!0?`Failed to parse ${Fr[t]} from '${e}'`:n?.errorOnFail):void 0},Wr=e=>{if(e[e.length-1]!==`n`)return;let t=e.slice(0,-1),n;try{n=BigInt(t)}catch{return}if(jr.test(t))return n;if(Nr.test(t))return C(Ir(e,`bigint`))},Gr=`0.45.0`,Kr={version:Gr,filename:fr(()=>import.meta.filename??void 0,()=>globalThis.__filename??`unknown`),FileConstructor:Yn},qr=Kr,Jr=new WeakMap,Yr=Object.create(null),Xr=e=>{let t=Jr.get(e);if(t)return t;let n=Qr(e);return Yr[n]?n=`${n}${Yr[n]++}`:Yr[n]=1,qr[n]=e,Jr.set(e,n),n},Zr=e=>/^[a-zA-Z_$][a-zA-Z_$0-9]*$/.test(e),Qr=e=>{switch(typeof e){case`object`:{if(e===null)break;let t=$n(e)??`object`;return t[0].toLowerCase()+t.slice(1)}case`function`:return Zr(e.name)?e.name:`fn`;case`symbol`:return e.description&&Zr(e.description)?e.description:`symbol`}return S(`Unexpected attempt to register serializable value of type ${x(e)}`)},$r=e=>typeof e==`string`?JSON.stringify(e):typeof e==`bigint`?`${e}n`:`${e}`,ei=(e,t={})=>ni(e,{onUndefined:`$ark.undefined`,onBigInt:e=>`$ark.bigint-${e}`,...t},[]),A=(e,t)=>{switch(x(e)){case`object`:let n=e,r=n.constructor.name;return r===`Object`||r===`Array`?JSON.stringify(ni(n,ti,[]),null,t):n instanceof Date?ri(n):typeof n.expression==`string`?n.expression:r;case`symbol`:return ti.onSymbol(e);default:return $r(e)}},ti={onCycle:()=>`(cycle)`,onSymbol:e=>`Symbol(${Xr(e)})`,onFunction:e=>`Function(${Xr(e)})`},ni=(e,t,n)=>{switch(x(e)){case`object`:{let r=e;if(`toJSON`in r&&typeof r.toJSON==`function`)return r.toJSON();if(typeof r==`function`)return ti.onFunction(r);if(n.includes(r))return`(cycle)`;let i=[...n,r];if(Array.isArray(r))return r.map(e=>ni(e,t,i));if(r instanceof Date)return r.toDateString();let a={};for(let e in r)a[e]=ni(r[e],t,i);for(let e of Object.getOwnPropertySymbols(r))a[t.onSymbol?.(e)??e.toString()]=ni(r[e],t,i);return a}case`symbol`:return ti.onSymbol(e);case`bigint`:return t.onBigInt?.(e)??`${e}n`;case`undefined`:return t.onUndefined??`undefined`;case`string`:return e.replaceAll(`\\`,`\\\\`);default:return e}},ri=e=>{let t=e.getFullYear(),n=e.getMonth(),r=e.getDate(),i=e.getHours(),a=e.getMinutes(),o=e.getSeconds(),s=e.getMilliseconds();if(n===0&&r===1&&i===0&&a===0&&o===0&&s===0)return`${t}`;let c=`${ii[n]} ${r}, ${t}`;if(i===0&&a===0&&o===0&&s===0)return c;let l=e.toLocaleTimeString(),u=l.endsWith(` AM`)||l.endsWith(` PM`)?l.slice(-3):``;return u&&(l=l.slice(0,-u.length)),s?l+=`.${oi(s,3)}`:ai.test(l)&&(l=l.slice(0,-3)),`${l+u}, ${c}`},ii=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],ai=/:\d\d:00$/,oi=(e,t)=>String(e).padStart(t,`0`),si=(e,t,...[n])=>{let r=n?.stringifySymbol??A,i=e;switch(typeof t){case`string`:i=Zr(t)?e===``?t:`${e}.${t}`:`${e}[${JSON.stringify(t)}]`;break;case`number`:i=`${e}[${t}]`;break;case`symbol`:i=`${e}[${r(t)}]`;break;default:n?.stringifyNonKey?i=`${e}[${n.stringifyNonKey(t)}]`:C(`${A(t)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return i},ci=(e,...t)=>e.reduce((e,n)=>si(e,n,...t),``);var li=class extends xn{cache={};constructor(...e){super(),this.push(...e)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let e=0;e<this.length;e++)this.cache.json.push(typeof this[e]==`symbol`?A(this[e]):this[e]);return this.cache.json}stringify(){return this.cache.stringify?this.cache.stringify:this.cache.stringify=ci(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let e=``,t=[e];return this.forEach(n=>{e=si(e,n),t.push(e)}),this.cache.stringifyAncestors=t}},ui=class{chars;i;def;constructor(e){this.def=e,this.chars=[...e],this.i=0}shift(){return this.chars[this.i++]??``}get lookahead(){return this.chars[this.i]??``}get nextLookahead(){return this.chars[this.i+1]??``}get length(){return this.chars.length}shiftUntil(e){let t=``;for(;this.lookahead;){if(e(this,t))if(t[t.length-1]===yr)t=t.slice(0,-1);else break;t+=this.shift()}return t}shiftUntilLookahead(e){return typeof e==`string`?this.shiftUntil(t=>t.lookahead===e):this.shiftUntil(t=>t.lookahead in e)}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in br))}jumpToIndex(e){this.i=e<0?this.length+e:e}jumpForward(e){this.i+=e}get location(){return this.i}get unscanned(){return this.chars.slice(this.i,this.length).join(``)}get scanned(){return this.chars.slice(0,this.i).join(``)}sliceChars(e,t){return this.chars.slice(e,t).join(``)}lookaheadIs(e){return this.lookahead===e}lookaheadIsIn(e){return this.lookahead in e}};const di=Fn(`implementedTraits`),fi=e=>t=>kn(t,`object`)?di in t.constructor&&t.constructor[di].includes(e)?!0:or(t).includes(e):!1;(class extends zn{static get[Symbol.hasInstance](){return fi(this)}traitsOf(){return di in this.constructor?this.constructor[di]:[]}});let pi=`$ark`,mi=2;for(;pi in globalThis;)pi=`$ark${mi++}`;const hi=pi;globalThis[hi]=qr;const j=qr;if(mi!==2){let e=globalThis,t=[e.$ark];for(let n=2;n<mi;n++)e[`$ark${n}`]&&t.push(e[`$ark${n}`]);console.warn(`Multiple @ark registries detected. This can lead to unexpected behavior.`);let n=Dn(t,`filename`),r=Object.keys(n);for(let e of r)n[e].length>1&&console.warn(`File ${e} was initialized multiple times, likely due to being imported from both CJS and ESM contexts.`);r.length>1&&console.warn(`Registries were initialized at the following paths:`+r.map(e=>` ${e} (@ark/util version ${n[e][0].version})`).join(`
|
|
6
|
-
`))}const gi=e=>`${hi}.${e}`,M=e=>gi(Xr(e));var _i=class extends Bn{argNames;body=``;constructor(...e){super(),this.argNames=e;for(let t of e){if(t in this)throw Error(`Arg name '${t}' would overwrite an existing property on FunctionBody`);this[t]=t}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(e,t=!1){return yi(e,t)}index(e,t=!1){return xi(`${e}`,t)}line(e){return this.body+=`${` `.repeat(this.indentation)}${e}\n`,this}const(e,t){return this.line(`const ${e} = ${t}`),this}let(e,t){return this.line(`let ${e} = ${t}`)}set(e,t){return this.line(`${e} = ${t}`)}if(e,t){return this.block(`if (${e})`,t)}elseIf(e,t){return this.block(`else if (${e})`,t)}else(e){return this.block(`else`,e)}for(e,t,n=0){return this.block(`for (let i = ${n}; ${e}; i++)`,t)}forIn(e,t){return this.block(`for (const k in ${e})`,t)}block(e,t,n=``){return this.line(`${e} {`),this.indent(),t(this),this.dedent(),this.line(`}${n}`)}return(e=``){return this.line(`return ${e}`)}write(e=`anonymous`){return`${e}(${this.argNames.join(`, `)}) {
|
|
7
|
-
${this.body}}`}compile(){return new pr(...this.argNames,this.body)}};const vi=e=>kn(e,`object`)||typeof e==`symbol`?M(e):$r(e),yi=(e,t=!1)=>typeof e==`string`&&Zr(e)?`${t?`?`:``}.${e}`:xi(bi(e),t),bi=e=>typeof e==`symbol`?M(e):JSON.stringify(e),xi=(e,t=!1)=>`${t?`?.`:``}[${e}]`;var Si=class extends _i{traversalKind;optimistic;constructor(e){super(`data`,`ctx`),this.traversalKind=e.kind,this.optimistic=e.optimistic===!0}invoke(e,t){let n=t?.arg??this.data,r=typeof e==`string`?!0:this.requiresContextFor(e),i=typeof e==`string`?e:e.id;return r?`${this.referenceToId(i,t)}(${n}, ${this.ctx})`:`${this.referenceToId(i,t)}(${n})`}referenceToId(e,t){let n=t?.kind??this.traversalKind,r=`this.${e}${n}`;return t?.bind?`${r}.bind(${t?.bind})`:r}requiresContextFor(e){return this.traversalKind===`Apply`||e.allowsRequiresContext}initializeErrorCount(){return this.const(`errorCount`,`ctx.currentErrorCount`)}returnIfFail(){return this.if(`ctx.currentErrorCount > errorCount`,()=>this.return())}returnIfFailFast(){return this.if(`ctx.failFast && ctx.currentErrorCount > errorCount`,()=>this.return())}traverseKey(e,t,n){let r=this.requiresContextFor(n);return r&&this.line(`${this.ctx}.path.push(${e})`),this.check(n,{arg:t}),r&&this.line(`${this.ctx}.path.pop()`),this}check(e,t){return this.traversalKind===`Allows`?this.if(`!${this.invoke(e,t)}`,()=>this.return(!1)):this.line(this.invoke(e,t))}};const Ci=e=>w(e,(e,t)=>[e,D(t)?[...t]:t]),N=Fn(`arkKind`),P=(e,t)=>e?.[N]===t,F=e=>P(e,`root`)||P(e,`constraint`),wi=[`unit`,`proto`,`domain`],Ti=[`required`,`optional`,`index`,`sequence`],Ei=[`pattern`,`divisor`,`exactLength`,`max`,`min`,`maxLength`,`minLength`,`before`,`after`],Di=[...Ei,...Ti,`structure`,`predicate`],Oi=[`alias`,`union`,`morph`,`unit`,`intersection`,`proto`,`domain`],ki=[...Oi,...Di],Ai=w(Di,(e,t)=>[t,1]),ji=w([...Ti,`undeclared`],(e,t)=>[t,1]),Mi=w(ki,(e,t)=>[t,e]),Ni=e=>typeof e==`string`&&e in Mi,Pi=e=>Mi[e],Fi=e=>Oi.slice(Pi(e)+1);[...Fi(`union`)],[...Fi(`morph`)];const Ii=e=>typeof e==`string`||typeof e==`boolean`||e===null?e:typeof e==`number`?Number.isNaN(e)?`NaN`:e===1/0?`Infinity`:e===-1/0?`-Infinity`:e:vi(e),Li=e=>{let t=`{ `;for(let[n,r]of Object.entries(e))t+=`${n}: ${vi(r)}, `;return t+` }`},I=e=>{let t=e;return t.hasAssociatedError&&(t.defaults.expected??=e=>`description`in e?e.description:t.defaults.description(e),t.defaults.actual??=e=>A(e),t.defaults.problem??=e=>`must be ${e.expected}${e.actual?` (was ${e.actual})`:``}`,t.defaults.message??=e=>{if(e.path.length===0)return e.problem;let t=`${e.propString} ${e.problem}`;return t[0]===`[`?`value at ${t}`:t}),t};j.config??={};const Ri=(e,t)=>{if(!t)return e;let n={...e},r;for(r in t){let i={...e.keywords};if(r===`keywords`){for(let e in t[r]){let n=t.keywords[e];if(n===void 0)continue;i[e]=typeof n==`string`?{description:n}:n}n.keywords=i}else n[r]=Ni(r)?{...e[r],...t[r]}:t[r]}return n};var zi=class e extends Bn{[N]=`error`;path;data;nodeConfig;input;ctx;constructor({prefixPath:e,relativePath:t,...n},r){super(),this.input=n,this.ctx=r,Gn(this,n);let i=r.data;n.code===`union`&&(n.errors=n.errors.flatMap(n=>{let r=n.hasCode(`union`)?n.errors:[n];return!e&&!t?r:r.map(n=>n.transform(n=>({...n,path:Tn(e,n.path,t)})))})),this.nodeConfig=r.config[this.code];let a=[...n.path??r.path];t&&a.push(...t),e&&a.unshift(...e),this.path=new li(...a),this.data=`data`in n?n.data:i}transform(t){return new e(t({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(e){return this.code===e}get propString(){return ci(this.path)}get expected(){if(this.input.expected)return this.input.expected;let e=this.meta?.expected??this.nodeConfig.expected;return typeof e==`function`?e(this.input):e}get actual(){if(this.input.actual)return this.input.actual;let e=this.meta?.actual??this.nodeConfig.actual;return typeof e==`function`?e(this.data):e}get problem(){if(this.input.problem)return this.input.problem;let e=this.meta?.problem??this.nodeConfig.problem;return typeof e==`function`?e(this):e}get message(){if(this.input.message)return this.input.message;let e=this.meta?.message??this.nodeConfig.message;return typeof e==`function`?e(this):e}get flat(){return this.hasCode(`intersection`)?[...this.errors]:[this]}toJSON(){return{data:this.data,path:this.path,...this.input,expected:this.expected,actual:this.actual,problem:this.problem,message:this.message}}toString(){return this.message}throw(){throw this}},Bi=class e extends xn{ctx;constructor(e){super(),this.ctx=e}byPath=Object.create(null);get flatByPath(){return w(this.byPath,(e,t)=>[e,t.flat])}get flatProblemsByPath(){return w(this.byPath,(e,t)=>[e,t.flat.map(e=>e.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new Vi(this)}add(e){this.includes(e)||this._add(e)}transform(t){let n=new e(this.ctx);return this.forEach(e=>n.add(t(e))),n}merge(e){e.forEach(e=>{this.includes(e)||this._add(new zi({...e,path:[...this.ctx.path,...e.path]},this.ctx))})}affectsPath(e){return this.length===0?!1:e.stringifyAncestors().some(e=>e in this.byPath)||e.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map(e=>e.toJSON())]}toString(){return this.join(`
|
|
8
|
-
`)}_add(e){let t=this.byPath[e.propString];if(t){let n=new zi({code:`intersection`,errors:t.hasCode(`intersection`)?[...t.errors,e]:[t,e]},this.ctx),r=this.indexOf(t);this.mutable[r===-1?this.length:r]=n,this.byPath[e.propString]=n,this.addAncestorPaths(e)}else this.byPath[e.propString]=e,this.addAncestorPaths(e),this.mutable.push(e);this.count++}addAncestorPaths(e){e.path.stringifyAncestors().forEach(t=>{this.byAncestorPath[t]=b(this.byAncestorPath[t],e)})}},Vi=class extends Error{name=`TraversalError`;constructor(e){e.length===1?super(e.summary):super(`
|
|
9
|
-
`+e.map(e=>` • ${Hi(e)}`).join(`
|
|
10
|
-
`)),Object.defineProperty(this,`arkErrors`,{value:e,enumerable:!1})}};const Hi=e=>e.toString().split(`
|
|
11
|
-
`).join(`
|
|
12
|
-
`);var Ui=class{path=[];errors=new Bi(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(e,t){this.root=e,this.config=t}get data(){let e=this.root;for(let t of this.path)e=e?.[t];return e}get propString(){return ci(this.path)}reject(e){return this.error(e),!1}mustBe(e){return this.error(e),!1}error(e){let t=typeof e==`object`?e.code?e:{...e,code:`predicate`}:{code:`predicate`,expected:e};return this.errorFromContext(t)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches.at(-1)}queueMorphs(e){let t={path:new li(...this.path),morphs:e};this.currentBranch?this.currentBranch.queuedMorphs.push(t):this.queuedMorphs.push(t)}finalize(e){return this.queuedMorphs.length&&(typeof this.root==`object`&&this.root!==null&&this.config.clone&&(this.root=this.config.clone(this.root)),this.applyQueuedMorphs()),this.hasError()?e?e(this.errors):this.errors:this.root}get currentErrorCount(){return this.currentBranch?this.currentBranch.error?1:0:this.errors.count}get failFast(){return this.branches.length!==0}pushBranch(){this.branches.push({error:void 0,queuedMorphs:[]})}popBranch(){return this.branches.pop()}get external(){return this}errorFromNodeContext(e){return this.errorFromContext(e)}errorFromContext(e){let t=new zi(e,this);return this.currentBranch?this.currentBranch.error=t:this.errors.add(t),t}applyQueuedMorphs(){for(;this.queuedMorphs.length;){let e=this.queuedMorphs;this.queuedMorphs=[];for(let{path:t,morphs:n}of e){if(this.errors.affectsPath(t))continue;this.applyMorphsAtPath(t,n)}}}applyMorphsAtPath(e,t){let n=e.at(-1),r;if(n!==void 0){r=this.root;for(let t=0;t<e.length-1;t++)r=r[e[t]]}this.path=[...e];for(let e of t){let t=F(e),i=e(r===void 0?this.root:r[n],this);if(i instanceof zi){this.errors.add(i);break}if(i instanceof Bi){t||this.errors.merge(i);break}r===void 0?this.root=i:r[n]=i,this.applyQueuedMorphs()}}};const L=(e,t,n)=>{if(!n)return t();n.path.push(e);let r=t();return n.path.pop(),r};var Wi=class extends mr{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(e,t){super((e,t,n=this.onFail)=>t?(this.traverseApply(e,t),t.hasError()?t.errors:t.data):this.rootApply(e,n),{attach:e}),this.attachments=e,this.$=t,this.onFail=this.meta.onFail??this.$.resolvedConfig.onFail,this.includesTransform=this.hasKind(`morph`)||this.hasKind(`structure`)&&this.structuralMorph!==void 0,this.includesContextualPredicate=this.hasKind(`predicate`)&&this.inner.predicate.length!==1,this.isCyclic=this.kind===`alias`,this.referencesById={[this.id]:this},this.shallowReferences=this.hasKind(`structure`)?[this,...this.children]:this.children.reduce((e,t)=>Xi(e,t.shallowReferences),[this]);let n=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let e=0;e<this.children.length;e++){if(this.includesTransform||=this.children[e].includesTransform,this.includesContextualPredicate||=this.children[e].includesContextualPredicate,this.isCyclic||=this.children[e].isCyclic,!n){let t=this.children[e].flatRefs;for(let e=0;e<t.length;e++){let n=t[e];if(!this.flatRefs.some(e=>Ji(e,n))){this.flatRefs.push(n);for(let e of n.node.branches)(e.hasKind(`morph`)||e.hasKind(`intersection`)&&e.structure?.structuralMorph!==void 0)&&this.flatMorphs.push({path:n.path,propString:n.propString,node:e})}}}Object.assign(this.referencesById,this.children[e].referencesById)}this.flatRefs.sort((e,t)=>e.path.length>t.path.length?1:e.path.length<t.path.length?-1:e.propString>t.propString?1:e.propString<t.propString||e.node.expression<t.node.expression?-1:1),this.allowsRequiresContext=this.includesContextualPredicate||this.isCyclic,this.rootApplyStrategy=!this.allowsRequiresContext&&this.flatMorphs.length===0?this.shallowMorphs.length===0?`allows`:this.shallowMorphs.every(e=>e.length===1||e.name===`$arkStructuralMorph`)?this.hasKind(`union`)?this.branches.some(e=>e.shallowMorphs.length>1)?`contextual`:`branchedOptimistic`:this.shallowMorphs.length>1?`contextual`:`optimistic`:`contextual`:`contextual`,this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?e=>this.traverseAllows(e,new Ui(e,this.$.resolvedConfig)):e=>this.traverseAllows(e)}createRootApply(){switch(this.rootApplyStrategy){case`allows`:return(e,t)=>{if(this.allows(e))return e;let n=new Ui(e,this.$.resolvedConfig);return this.traverseApply(e,n),n.finalize(t)};case`contextual`:return(e,t)=>{let n=new Ui(e,this.$.resolvedConfig);return this.traverseApply(e,n),n.finalize(t)};case`optimistic`:this.contextFreeMorph=this.shallowMorphs[0];let e=this.$.resolvedConfig.clone;return(t,n)=>{if(this.allows(t))return this.contextFreeMorph(e&&(typeof t==`object`&&t||typeof t==`function`)?e(t):t);let r=new Ui(t,this.$.resolvedConfig);return this.traverseApply(t,r),r.finalize(n)};case`branchedOptimistic`:return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,S(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}withMeta(e){return this.$.node(this.kind,{...this.inner,meta:typeof e==`function`?e({...this.meta}):e})}compiledMeta=JSON.stringify(this.metaJson);cacheGetter(e,t){return Object.defineProperty(this,e,{value:t}),t}get description(){return this.cacheGetter(`description`,this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=Pi(this.kind);precompilation;assert=(e,t)=>this(e,t,e=>e.throw());traverse(e,t){return this(e,t,null)}get in(){return this.cacheGetter(`in`,this.getIo(`in`))}get out(){return this.cacheGetter(`out`,this.getIo(`out`))}getIo(e){if(!this.includesTransform)return this;let t={};for(let[n,r]of this.innerEntries){let i=this.impl.keys[n];if(i.reduceIo)i.reduceIo(e,t,r);else if(i.child){let i=r;t[n]=D(i)?i.map(t=>t[e]):i[e]}else t[n]=r}return this.$.node(this.kind,t)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(e){let t=F(e)?e:this.$.parseDefinition(e);return this.innerHash===t.innerHash}ifEquals(e){return this.equals(e)?this:void 0}hasKind(e){return this.kind===e}assertHasKind(e){return this.kind!==e&&Nn(`${this.kind} node was not of asserted kind ${e}`),this}hasKindIn(...e){return e.includes(this.kind)}assertHasKindIn(...e){return Sn(e,this.kind)||Nn(`${this.kind} node was not one of asserted kinds ${e}`),this}isBasis(){return Sn(wi,this.kind)}isConstraint(){return Sn(Di,this.kind)}isStructural(){return Sn(Ti,this.kind)}isRefinement(){return Sn(Ei,this.kind)}isRoot(){return Sn(Oi,this.kind)}isUnknown(){return this.hasKind(`intersection`)&&this.children.length===0}isNever(){return this.hasKind(`union`)&&this.children.length===0}hasUnit(e){return this.hasKind(`unit`)&&this.allows(e)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(e){let t=Gi.normalize(e),n=Gi.applyBoundary[t.boundary??`references`](this);return t.kind&&(n=n.filter(e=>e.kind===t.kind)),t.where&&(n=n.filter(t.where)),Gi.applyMethod[t.method??`filter`](n,this,e)}transform(e,t){return this._transform(e,this._createTransformContext(t))}_createTransformContext(e){return{...e,root:this,seen:{},path:[],parseOptions:{prereduced:e?.prereduced??!1},undeclaredKeyHandling:void 0}}_transform(e,t){let n=t.bindScope??this.$;if(t.seen[this.id])return this.$.lazilyResolve(t.seen[this.id]);if(t.shouldTransform?.(this,t)===!1)return this;let r;t.seen[this.id]=()=>r,this.hasKind(`structure`)&&this.undeclared!==t.undeclaredKeyHandling&&(t={...t,undeclaredKeyHandling:this.undeclared});let i=w(this.inner,(n,r)=>{if(!this.impl.keys[n].child)return[n,r];let i=r;if(!D(i)){let r=i._transform(e,t);return r?[n,r]:[]}if(i.length===0)return[n,r];let a=i.flatMap(n=>{let r=n._transform(e,t);return r??[]});return a.length?[n,a]:[]});delete t.seen[this.id];let a=Object.assign(i,{meta:this.meta}),o=e(this.kind,a,t);if(o===null)return null;if(F(o))return r=o;let s=Object.keys(o),c=s.length===0||s.length===1&&s[0]===`meta`;return c&&!Un(this.inner)?null:(this.kind===`required`||this.kind===`optional`||this.kind===`index`)&&!(`value`in o)?t.undeclaredKeyHandling?{...o,value:j.intrinsic.unknown}:null:(this.kind===`morph`&&(o.in??=j.intrinsic.unknown),r=n.node(this.kind,o,t.parseOptions))}configureDescendants(e,t=`references`){let n=Gi.normalize(t),r=typeof e==`string`?(t,n)=>({...n,meta:{...n.meta,description:e}}):typeof e==`function`?(t,n)=>({...n,meta:e(n.meta)}):(t,n)=>({...n,meta:{...n.meta,...e}});if(n.boundary===`self`)return this.$.node(this.kind,r(this.kind,{...this.inner,meta:this.meta}));let i=n.boundary===`child`?(e,t)=>t.root.children.includes(e):n.boundary===`shallow`?e=>e.kind!==`structure`:()=>!0;return this.$.finalize(this.transform(r,{shouldTransform:i}))}};const Gi={applyBoundary:{self:e=>[e],child:e=>[...e.children],shallow:e=>[...e.shallowReferences],references:e=>[...e.references]},applyMethod:{filter:e=>e,assertFilter:(e,t,n)=>(e.length===0&&Nn(Ki(t,n)),e),find:e=>e[0],assertFind:(e,t,n)=>(e.length===0&&Nn(Ki(t,n)),e[0])},normalize:e=>typeof e==`function`?{boundary:`references`,method:`filter`,where:e}:typeof e==`string`?T(e,Gi.applyBoundary)?{method:`filter`,boundary:e}:{boundary:`references`,method:`filter`,kind:e}:{boundary:`references`,method:`filter`,...e}},Ki=(e,t)=>`${e} had no references matching ${A(t)}.`,qi=e=>ci(e,{stringifyNonKey:e=>e.expression}),R=(e,t)=>({path:e,node:t,propString:qi(e)}),Ji=(e,t)=>e.propString===t.propString&&e.node.equals(t.node),Yi=(e,t)=>En(e,t,{isEqual:Ji}),Xi=(e,t)=>En(e,t,{isEqual:(e,t)=>e.equals(t)});var z=class e extends Array{static init(t,n,r,i){return new e({kind:t,l:n,r,path:i?.path??[],optional:i?.optional??!1})}add(e,t,n,r){return this.push({kind:e,l:t,r:n,path:r?.path??[],optional:r?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:e,l:t,r:n}=this[0],r=ci(e);return $i(`Intersection${r&&` at ${r}`} of ${Zi(t,n)}`)}return`The following intersections result in unsatisfiable types:\n• ${this.map(({path:e,l:t,r:n})=>`${e}: ${Zi(t,n)}`).join(`
|
|
13
|
-
• `)}`}throw(){return C(this.describeReasons())}invert(){let t=this.map(e=>({...e,l:e.r,r:e.l}));return t instanceof e?t:new e(...t)}withPrefixKey(e,t){return this.map(n=>({...n,path:[e,...n.path],optional:n.optional||t===`optional`}))}toNeverIfDisjoint(){return j.intrinsic.never}};const Zi=(e,t)=>`${Qi(e)} and ${Qi(t)}`,Qi=e=>F(e)?e.expression:D(e)?e.map(Qi).join(` | `)||`never`:String(e),$i=e=>`${e} results in an unsatisfiable type`,ea={},B=(e,t,n)=>V(e,t,{$:n,invert:!1,pipe:!1}),ta=(e,t,n)=>V(e,t,{$:n,invert:!1,pipe:!0}),V=(e,t,n)=>{let r=n.pipe?`|>`:`&`,i=`${e.hash}${r}${t.hash}`;if(ea[i]!==void 0)return ea[i];if(!n.pipe){let n=`${t.hash}${r}${e.hash}`;if(ea[n]!==void 0){let e=ea[n],t=e instanceof z?e.invert():e;return ea[i]=t,t}}let a=!n.pipe||!e.includesTransform&&!t.includesTransform;if(a&&e.equals(t))return e;let o=a?na(e,t,n):e.hasKindIn(...Oi)?ra(e,t,n):na(e,t,n);return F(o)&&(e.equals(o)?o=e:t.equals(o)&&(o=t)),ea[i]=o,o},na=(e,t,n)=>{let r=e.precedence<t.precedence?e.kind:t.kind,i=e.impl.intersections[t.kind]??t.impl.intersections[e.kind];if(i===void 0)return null;if(r===e.kind)return i(e,t,n);{let r=i(t,e,{...n,invert:!n.invert});return r instanceof z&&(r=r.invert()),r}},ra=(e,t,n)=>e.includesTransform||t.includesTransform?n.invert?ia(t,e,n):ia(e,t,n):na(e,t,n),ia=(e,t,n)=>e.distribute(e=>aa(e,t,n),r=>{let i=r.filter(F);if(i.length===0)return z.init(`union`,e.branches,t.branches);if(i.length<e.branches.length||!e.branches.every((e,t)=>e.in.equals(i[t].in)))return n.$.parseSchema(i);let a;if(i.length===1){let e=i[0];return a?n.$.node(`morph`,{...e.inner,in:e.in.withMeta(a)}):e}let o={branches:i};return a&&(o.meta=a),n.$.parseSchema(o)}),aa=(e,t,n)=>{let r=e.hasKind(`morph`);if(r){let r=[...e.morphs];if(e.lastMorphIfNode){let i=V(e.lastMorphIfNode,t,n);if(i instanceof z)return i;r[r.length-1]=i}else r.push(t);return n.$.node(`morph`,{morphs:r,in:e.inner.in})}if(t.hasKind(`morph`)){let r=V(e,t.in,n);return r instanceof z?r:n.$.node(`morph`,{morphs:[t],in:r})}return n.$.node(`morph`,{morphs:[t],in:e})};var oa=class extends Wi{constructor(e,t){super(e,t),Object.defineProperty(this,N,{value:`constraint`,enumerable:!1})}impliedSiblings;intersect(e){return B(this,e,this.$)}},sa=class extends oa{traverseApply=(e,t)=>{this.traverseAllows(e,t)||t.errorFromNodeContext(this.errorContext)};compile(e){e.traversalKind===`Allows`?e.return(this.compiledCondition):e.if(this.compiledNegation,()=>e.line(`${e.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return Li(this.errorContext)}};const H=e=>(t,n)=>{if(D(t)){if(t.length===0)return;let r=t.map(t=>n.$.node(e,t));return e===`predicate`?r:r.sort((e,t)=>e.hash<t.hash?-1:1)}let r=n.$.node(e,t);return r.hasOpenIntersection()?[r]:r},ca=e=>{let t=e.r.shift();if(!t){let t=e.l.length===0&&e.kind===`structure`?j.intrinsic.unknown.internal:e.ctx.$.node(e.kind,Object.assign(e.baseInner,ua(e.l)),{prereduced:!0});for(let n of e.roots){if(t instanceof z)return t;t=V(n,t,e.ctx)}return t}let n=!1;for(let r=0;r<e.l.length;r++){let i=V(e.l[r],t,e.ctx);if(i!==null){if(i instanceof z)return i;if(n){if(!e.l.includes(i))return S(`Unexpectedly encountered multiple distinct intersection results for refinement ${i}`)}else{if(i.isRoot())return e.roots.push(i),e.l.splice(r),ca(e);e.l[r]=i,n=!0}}}return n||e.l.push(t),e.kind===`intersection`&&t.impliedSiblings?.forEach(t=>En(e.r,t)),ca(e)},la=e=>{let t=Object.entries(e).flatMap(([e,t])=>e in Ai?t:[]).sort((e,t)=>e.precedence<t.precedence?-1:e.precedence>t.precedence?1:e.kind===`predicate`&&t.kind===`predicate`?0:e.hash<t.hash?-1:1);return t},ua=e=>{let t={};for(let n of e)if(n.hasOpenIntersection())t[n.kind]=b(t[n.kind],n);else{if(t[n.kind])return S(`Unexpected intersection of closed refinements of kind ${n.kind}`);t[n.kind]=n}return t},da=(...e)=>C(fa(...e)),fa=(e,t,n)=>{let r=n.hasKind(`morph`)?n.shortDescription:n.isUnknown()?`unknown`:n.exclude(t).shortDescription;return`${gr(e)} operand must be ${t.description} (was ${r})`},pa=(e,t,n)=>new ha(e,t,n,n,null);var ma=class extends mr{},ha=class extends mr{[N]=`generic`;paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(e,t,n,r,i){super((...e)=>{let n=w(this.names,(t,n)=>{let r=this.arg$.parse(e[t]);return r.extends(this.constraints[t])||C(ga(n,this.constraints[t].expression,r.expression)),[n,r]});if(this.defIsLazy()){let e=this.bodyDef(n);return this.$.parse(e)}return this.$.parse(t,{args:n})}),this.paramDefs=e,this.bodyDef=t,this.$=n,this.arg$=r,this.hkt=i,this.description=i?new i().description??`a generic type for ${i.constructor.name}`:`a generic type`,this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof ma}cacheGetter(e,t){return Object.defineProperty(this,e,{value:t}),t}get json(){return this.cacheGetter(`json`,{params:this.params.map(e=>e[1].isUnknown()?e[0]:[e[0],e[1].json]),body:ei(this.bodyDef)})}get params(){return this.cacheGetter(`params`,this.paramDefs.map(e=>typeof e==`string`?[e,j.intrinsic.unknown]:[e[0],this.$.parse(e[1])]))}get names(){return this.cacheGetter(`names`,this.params.map(e=>e[0]))}get constraints(){return this.cacheGetter(`constraints`,this.params.map(e=>e[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}};const ga=(e,t,n)=>`${e} must be assignable to ${t} (was ${n})`,_a={morph:"it represents a transformation, while JSON Schema only allows validation. Consider creating a Schema from one of its endpoints using `.in` or `.out`.",cyclic:`cyclic types are not yet convertible to JSON Schema. If this feature is important to you, please add your feedback at https://github.com/arktypeio/arktype/issues/1087`},va=(e,t)=>{let n=`${e} is not convertible to JSON Schema`;if(t){let e=T(t,_a)?_a[t]:t;n+=` because ${e}`}return n},U={writeUnjsonifiableMessage:va,UnjsonifiableError:class extends Error{},throwUnjsonifiableError:(...e)=>Nn(va(...e)),throwInternalOperandError:(e,t)=>S(`Unexpected JSON Schema input for ${e}: ${A(t)}`)},ya=I({kind:`predicate`,hasAssociatedError:!0,collapsibleKey:`predicate`,keys:{predicate:{}},normalize:e=>typeof e==`function`?{predicate:e}:e,defaults:{description:e=>`valid according to ${e.predicate.name||`an anonymous predicate`}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});var ba=class extends oa{serializedPredicate=M(this.predicate);compiledCondition=`${this.serializedPredicate}(data, ctx)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=null;expression=this.serializedPredicate;traverseAllows=this.predicate;errorContext={code:`predicate`,description:this.description,meta:this.meta};compiledErrorContext=Li(this.errorContext);traverseApply=(e,t)=>{!this.predicate(e,t.external)&&!t.hasError()&&t.errorFromNodeContext(this.errorContext)};compile(e){if(e.traversalKind===`Allows`){e.return(this.compiledCondition);return}e.if(`${this.compiledNegation} && !ctx.hasError()`,()=>e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(){return U.throwUnjsonifiableError(`Predicate ${this.expression}`)}};const xa={implementation:ya,Node:ba},Sa=I({kind:`divisor`,collapsibleKey:`rule`,keys:{rule:{}},normalize:e=>typeof e==`number`?{rule:e}:e,hasAssociatedError:!0,defaults:{description:e=>e.rule===1?`an integer`:e.rule===2?`even`:`a multiple of ${e.rule}`},intersections:{divisor:(e,t,n)=>n.$.node(`divisor`,{rule:Math.abs(e.rule*t.rule/Ta(e.rule,t.rule))})},obviatesBasisDescription:!0});var Ca=class extends sa{traverseAllows=e=>e%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=j.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(e){return e.type=`integer`,this.rule===1||(e.multipleOf=this.rule),e}};const wa={implementation:Sa,Node:Ca},Ta=(e,t)=>{let n,r=e,i=t;for(;i!==0;)n=i,i=r%i,r=n;return r};var Ea=class extends sa{boundOperandKind=Fa[this.kind];compiledActual=this.boundOperandKind===`value`?`data`:this.boundOperandKind===`length`?`data.length`:`data.valueOf()`;comparator=Ia(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${Da[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind===`date`?La(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator[0]===`<`?`upper`:`lower`;isStricterThan(e){let t=this.limitKind===`upper`?this.numericLimit<e.numericLimit:this.numericLimit>e.numericLimit;return t||this.numericLimit===e.numericLimit&&this.exclusive===!0&&!e.exclusive}overlapsRange(e){return!(this.isStricterThan(e)||this.numericLimit===e.numericLimit&&(this.exclusive||e.exclusive))}overlapIsUnit(e){return this.numericLimit===e.numericLimit&&!this.exclusive&&!e.exclusive}};const Da={"<":`>=`,"<=":`>`,">":`<=`,">=":`<`},Oa={min:`max`,minLength:`maxLength`,after:`before`},ka={parse:e=>e||void 0},Aa=e=>t=>{if(typeof t==`number`)return{rule:t};let{exclusive:n,...r}=t;return n?{...r,rule:e===`minLength`?r.rule+1:r.rule-1}:r},ja=e=>t=>{if(typeof t==`number`||typeof t==`string`||t instanceof Date)return{rule:t};let{exclusive:n,...r}=t;if(!n)return r;let i=typeof r.rule==`number`?r.rule:typeof r.rule==`string`?new Date(r.rule).valueOf():r.rule.valueOf();return n?{...r,rule:e===`after`?i+1:i-1}:r},Ma=e=>typeof e==`string`||typeof e==`number`?new Date(e):e,Na=(e,t)=>`${e} bound must be a positive integer (was ${t})`,Pa=e=>t=>((!Number.isInteger(t)||t<0)&&C(Na(e,t)),t),Fa={min:`value`,max:`value`,minLength:`length`,maxLength:`length`,after:`date`,before:`date`},Ia=(e,t)=>`${T(e,Oa)?`>`:`<`}${t?``:`=`}`,La=e=>typeof e==`string`?e:new Date(e).toLocaleString(),Ra=e=>`Bounded expression ${e} must be exactly one of number, string, Array, or Date`,za=I({kind:`after`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{parse:Ma,serialize:e=>e.toISOString()}},normalize:ja(`after`),defaults:{description:e=>`${e.collapsibleLimitString} or later`,actual:ri},intersections:{after:(e,t)=>e.isStricterThan(t)?e:t}});var Ba=class extends Ea{impliedBasis=j.intrinsic.Date.internal;collapsibleLimitString=ri(this.rule);traverseAllows=e=>e>=this.rule;reduceJsonSchema(){return U.throwUnjsonifiableError(`Date instance`)}};const Va={implementation:za,Node:Ba},Ha=I({kind:`before`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{parse:Ma,serialize:e=>e.toISOString()}},normalize:ja(`before`),defaults:{description:e=>`${e.collapsibleLimitString} or earlier`,actual:ri},intersections:{before:(e,t)=>e.isStricterThan(t)?e:t,after:(e,t,n)=>e.overlapsRange(t)?e.overlapIsUnit(t)?n.$.node(`unit`,{unit:e.rule}):null:z.init(`range`,e,t)}});var Ua=class extends Ea{collapsibleLimitString=ri(this.rule);traverseAllows=e=>e<=this.rule;impliedBasis=j.intrinsic.Date.internal;reduceJsonSchema(){return U.throwUnjsonifiableError(`Date instance`)}};const Wa={implementation:Ha,Node:Ua},Ga=I({kind:`exactLength`,collapsibleKey:`rule`,keys:{rule:{parse:Pa(`exactLength`)}},normalize:e=>typeof e==`number`?{rule:e}:e,hasAssociatedError:!0,defaults:{description:e=>`exactly length ${e.rule}`,actual:e=>`${e.length}`},intersections:{exactLength:(e,t,n)=>z.init(`unit`,n.$.node(`unit`,{unit:e.rule}),n.$.node(`unit`,{unit:t.rule}),{path:[`length`]}),minLength:(e,t)=>e.rule>=t.rule?e:z.init(`range`,e,t),maxLength:(e,t)=>e.rule<=t.rule?e:z.init(`range`,e,t)}});var Ka=class extends sa{traverseAllows=e=>e.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=j.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(e){switch(e.type){case`string`:return e.minLength=this.rule,e.maxLength=this.rule,e;case`array`:return e.minItems=this.rule,e.maxItems=this.rule,e;default:return U.throwInternalOperandError(`exactLength`,e)}}};const qa={implementation:Ga,Node:Ka},Ja=I({kind:`max`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{},exclusive:ka},normalize:e=>typeof e==`number`?{rule:e}:e,defaults:{description:e=>e.rule===0?e.exclusive?`negative`:`non-positive`:`${e.exclusive?`less than`:`at most`} ${e.rule}`},intersections:{max:(e,t)=>e.isStricterThan(t)?e:t,min:(e,t,n)=>e.overlapsRange(t)?e.overlapIsUnit(t)?n.$.node(`unit`,{unit:e.rule}):null:z.init(`range`,e,t)},obviatesBasisDescription:!0});var Ya=class extends Ea{impliedBasis=j.intrinsic.number.internal;traverseAllows=this.exclusive?e=>e<this.rule:e=>e<=this.rule;reduceJsonSchema(e){return this.exclusive?e.exclusiveMaximum=this.rule:e.maximum=this.rule,e}};const Xa={implementation:Ja,Node:Ya},Za=I({kind:`maxLength`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{parse:Pa(`maxLength`)}},reduce:(e,t)=>e.rule===0?t.node(`exactLength`,e):void 0,normalize:Aa(`maxLength`),defaults:{description:e=>`at most length ${e.rule}`,actual:e=>`${e.length}`},intersections:{maxLength:(e,t)=>e.isStricterThan(t)?e:t,minLength:(e,t,n)=>e.overlapsRange(t)?e.overlapIsUnit(t)?n.$.node(`exactLength`,{rule:e.rule}):null:z.init(`range`,e,t)}});var Qa=class extends Ea{impliedBasis=j.intrinsic.lengthBoundable.internal;traverseAllows=e=>e.length<=this.rule;reduceJsonSchema(e){switch(e.type){case`string`:return e.maxLength=this.rule,e;case`array`:return e.maxItems=this.rule,e;default:return U.throwInternalOperandError(`maxLength`,e)}}};const $a={implementation:Za,Node:Qa},eo=I({kind:`min`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{},exclusive:ka},normalize:e=>typeof e==`number`?{rule:e}:e,defaults:{description:e=>e.rule===0?e.exclusive?`positive`:`non-negative`:`${e.exclusive?`more than`:`at least`} ${e.rule}`},intersections:{min:(e,t)=>e.isStricterThan(t)?e:t},obviatesBasisDescription:!0});var to=class extends Ea{impliedBasis=j.intrinsic.number.internal;traverseAllows=this.exclusive?e=>e>this.rule:e=>e>=this.rule;reduceJsonSchema(e){return this.exclusive?e.exclusiveMinimum=this.rule:e.minimum=this.rule,e}};const no={implementation:eo,Node:to},ro=I({kind:`minLength`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{parse:Pa(`minLength`)}},reduce:e=>e.rule===0?j.intrinsic.unknown:void 0,normalize:Aa(`minLength`),defaults:{description:e=>e.rule===1?`non-empty`:`at least length ${e.rule}`,actual:e=>e.length===0?``:`${e.length}`},intersections:{minLength:(e,t)=>e.isStricterThan(t)?e:t}});var io=class extends Ea{impliedBasis=j.intrinsic.lengthBoundable.internal;traverseAllows=e=>e.length>=this.rule;reduceJsonSchema(e){switch(e.type){case`string`:return e.minLength=this.rule,e;case`array`:return e.minItems=this.rule,e;default:return U.throwInternalOperandError(`minLength`,e)}}};const ao={implementation:ro,Node:io},oo={min:no.implementation,max:Xa.implementation,minLength:ao.implementation,maxLength:$a.implementation,exactLength:qa.implementation,after:Va.implementation,before:Wa.implementation},so={min:no.Node,max:Xa.Node,minLength:ao.Node,maxLength:$a.Node,exactLength:qa.Node,after:Va.Node,before:Wa.Node},co=I({kind:`pattern`,collapsibleKey:`rule`,keys:{rule:{},flags:{}},normalize:e=>typeof e==`string`?{rule:e}:e instanceof RegExp?e.flags?{rule:e.source,flags:e.flags}:{rule:e.source}:e,obviatesBasisDescription:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:e=>`matched by ${e.rule}`},intersections:{pattern:()=>null}});var lo=class extends sa{instance=new RegExp(this.rule,this.flags);expression=`${this.instance}`;traverseAllows=this.instance.test.bind(this.instance);compiledCondition=`${this.expression}.test(data)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=j.intrinsic.string.internal;reduceJsonSchema(e){return e.pattern?U.throwUnjsonifiableError(`Intersection of patterns ${e.pattern} & ${this.rule}`):(e.pattern=this.rule,e)}};const uo={implementation:co,Node:lo},fo=(e,t)=>{let n=po(e);return t&&!t.includes(n)?C(`Root of kind ${n} should be one of ${t}`):n},po=e=>{if(P(e,`root`))return e.kind;if(typeof e==`string`)return e[0]===`$`?`alias`:`domain`;if(typeof e==`function`)return`proto`;if(typeof e!=`object`||!e)return C(mo(e));if(`morphs`in e)return`morph`;if(`branches`in e||D(e))return`union`;if(`unit`in e)return`unit`;if(`reference`in e)return`alias`;let t=Object.keys(e);return t.length===0||t.some(e=>e in Ai)?`intersection`:`proto`in e?`proto`:`domain`in e?`domain`:C(mo(e))},mo=e=>`${A(e)} is not a valid type schema`,ho={},go=e=>D(e)?e.map(e=>e.collapsibleJson):e.collapsibleJson,W={};j.nodesByRegisteredId=W;const _o=e=>(ho[e]??=0,`${e}${++ho[e]}`),vo=e=>{let t=hc[e.kind],n=t.applyConfig?.(e.def,e.$.resolvedConfig)??e.def,r={},{meta:i,...a}=n,o=i===void 0?{}:typeof i==`string`?{description:i}:i,s=In(a).sort(([e],[t])=>Ni(e)?Ni(t)?Pi(e)-Pi(t):1:Ni(t)||e<t?-1:1).filter(([e,t])=>{if(e.startsWith(`meta.`)){let n=e.slice(5);return o[n]=t,!1}return!0});for(let n of s){let i=n[0],a=t.keys[i];if(!a)return C(`Key ${i} is not valid on ${e.kind} schema`);let o=a.parse?a.parse(n[1],e):n[1];o!==E&&(o!==void 0||a.preserveUndefined)&&(r[i]=o)}if(t.reduce&&!e.prereduced){let n=t.reduce(r,e.$);if(n)return n instanceof z?n.throw():xo(n,o)}let c=yo({id:e.id,kind:e.kind,inner:r,meta:o,$:e.$});return c},yo=({id:e,kind:t,inner:n,meta:r,$:i,ignoreCache:a})=>{let o=hc[t],s=In(n),c=[],l={};s.forEach(([e,t])=>{let n=o.keys[e],r=n.serialize??(n.child?go:Ii);if(l[e]=r(t),n.child===!0){let e=t;D(e)?c.push(...e):c.push(e)}else typeof n.child==`function`&&c.push(...n.child(t))}),o.finalizeInnerJson&&(l=o.finalizeInnerJson(l));let u={...l},d={};Un(r)||(d=w(r,(e,t)=>[e,e===`examples`?t:Ii(t)]),u.meta=So(d,`description`,!0)),l=So(l,o.collapsibleKey,!1);let ee=JSON.stringify({kind:t,...l});u=So(u,o.collapsibleKey,!1);let f=So(u,o.collapsibleKey,!0),p=JSON.stringify({kind:t,...u});if(i.nodesByHash[p]&&!a)return i.nodesByHash[p];let m={id:e,kind:t,impl:o,inner:n,innerEntries:s,innerJson:l,innerHash:ee,meta:r,metaJson:d,json:u,hash:p,collapsibleJson:f,children:c};if(t!==`intersection`)for(let e in n)e!==`in`&&e!==`out`&&(m[e]=n[e]);let te=new gc[t](m,i);return i.nodesByHash[p]=te},bo=(e,t)=>e.id===t?e:(F(W[t])&&S(`Unexpected attempt to overwrite node id ${t}`),yo({id:t,kind:e.kind,inner:e.inner,meta:e.meta,$:e.$,ignoreCache:!0})),xo=(e,t,n)=>(n&&F(W[n])&&S(`Unexpected attempt to overwrite node id ${n}`),yo({id:n??_o(t.alias??e.kind),kind:e.kind,inner:e.inner,meta:t,$:e.$})),So=(e,t,n)=>{let r=Object.keys(e);if(r.length===1&&r[0]===t){let r=e[t];if(n||kn(r,`object`)&&(Object.keys(r).length===1||Array.isArray(r)))return r}return e},Co=(e,t,n)=>{if(e.key!==t.key)return null;let r=e.key,i=V(e.value,t.value,n),a=e.required||t.required?`required`:`optional`;if(i instanceof z)if(a===`optional`)i=j.intrinsic.never.internal;else return i.withPrefixKey(e.key,e.required&&t.required?`required`:`optional`);if(a===`required`)return n.$.node(`required`,{key:r,value:i});let o=e.hasDefault()?t.hasDefault()?e.default===t.default?e.default:C(To(e.default,t.default)):e.default:t.hasDefault()?t.default:E;return n.$.node(`optional`,{key:r,value:i,default:o})};var wo=class extends oa{required=this.kind===`required`;optional=this.kind===`optional`;impliedBasis=j.intrinsic.object.internal;serializedKey=vi(this.key);compiledKey=typeof this.key==`string`?this.key:this.serializedKey;flatRefs=b(this.value.flatRefs.map(e=>R([this.key,...e.path],e.node)),R([this.key],this.value));_transform(e,t){t.path.push(this.key);let n=super._transform(e,t);return t.path.pop(),n}hasDefault(){return`default`in this.inner}traverseAllows=(e,t)=>this.key in e?L(this.key,()=>this.value.traverseAllows(e[this.key],t),t):this.optional;traverseApply=(e,t)=>{this.key in e?L(this.key,()=>this.value.traverseApply(e[this.key],t),t):this.hasKind(`required`)&&t.errorFromNodeContext(this.errorContext)};compile(e){e.if(`${this.serializedKey} in data`,()=>e.traverseKey(this.serializedKey,`data${e.prop(this.key)}`,this.value)),this.hasKind(`required`)&&e.else(()=>e.traversalKind===`Apply`?e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):e.return(!1)),e.traversalKind===`Allows`&&e.return(!0)}};const To=(e,t)=>`Invalid intersection of default values ${A(e)} & ${A(t)}`,Eo=I({kind:`optional`,hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(e,t)=>t.$.parseSchema(e)},default:{preserveUndefined:!0}},normalize:e=>e,defaults:{description:e=>`${e.compiledKey}?: ${e.value.description}`},intersections:{optional:Co}});var Do=class extends wo{constructor(...e){super(...e),`default`in this.inner&&Mo(this.value,this.inner.default,this.key)}get outProp(){if(!this.hasDefault())return this;let{default:e,...t}=this.inner;return this.cacheGetter(`outProp`,this.$.node(`required`,t,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${A(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=Ao(this);defaultValueMorphRef=this.defaultValueMorph&&M(this.defaultValueMorph)};const Oo={implementation:Eo,Node:Do},ko={},Ao=e=>{if(!e.hasDefault())return;let t=`{${e.compiledKey}: ${e.value.id} = ${Ii(e.default)}}`;return ko[t]??=jo(e.key,e.value,e.default)},jo=(e,t,n)=>{if(typeof n==`function`)return t.includesTransform?(r,i)=>(L(e,()=>t(r[e]=n(),i),i),r):t=>(t[e]=n(),t);let r=t.includesTransform?t.assert(n):n;return kn(r,`object`)?(r,i)=>(L(e,()=>t(r[e]=n,i),i),r):t=>(t[e]=r,t)},Mo=(e,t,n)=>{let r=dr(t);kn(t,`object`)&&!r&&C(No(n));let i=e.in(r?t():t);if(i instanceof Bi){n===null&&C(`Default ${i.summary}`);let e=i.transform(e=>e.transform(e=>({...e,prefixPath:[n]})));C(`Default for ${e.summary}`)}return t},No=e=>{let t=e===null?``:typeof e==`number`?`for value at [${e}] `:`for ${vi(e)} `;return`Non-primitive default ${t}must be specified as a function like () => ({my: 'object'})`};var Po=class extends Wi{constructor(e,t){super(e,t),Object.defineProperty(this,N,{value:`root`,enumerable:!1})}get internal(){return this}get"~standard"(){return{vendor:`arktype`,version:1,validate:e=>{let t=this(e);return t instanceof Bi?t:{value:t}}}}as(){return this}brand(e){return e===``?C(Fo):this}readonly(){return this}branches=this.hasKind(`union`)?this.inner.branches:[this];distribute(e,t){let n=this.branches.map(e);return t?.(n)??n}toJsonSchema(){let e=this.innerToJsonSchema();return Object.assign(e,this.metaJson)}intersect(e){let t=this.$.parseDefinition(e),n=this.rawIntersect(t);return n instanceof z?n:this.$.finalize(n)}rawIntersect(e){return B(this,e,this.$)}toNeverIfDisjoint(){return this}and(e){let t=this.intersect(e);return t instanceof z?t.throw():t}rawAnd(e){let t=this.rawIntersect(e);return t instanceof z?t.throw():t}or(e){let t=this.$.parseDefinition(e);return this.$.finalize(this.rawOr(t))}rawOr(e){let t=[...this.branches,...e.branches];return this.$.node(`union`,t)}map(e){return this.$.schema(this.applyStructuralOperation(`map`,[e]))}pick(...e){return this.$.schema(this.applyStructuralOperation(`pick`,e))}omit(...e){return this.$.schema(this.applyStructuralOperation(`omit`,e))}required(){return this.$.schema(this.applyStructuralOperation(`required`,[]))}partial(){return this.$.schema(this.applyStructuralOperation(`partial`,[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let e=this.applyStructuralOperation(`keyof`,[]).reduce((e,t)=>e.intersect(t).toNeverIfDisjoint(),j.intrinsic.unknown.internal);return e.branches.length===0&&C($i(`keyof ${this.expression}`)),this._keyof=this.$.finalize(e)}get props(){return this.branches.length===1?[...this.applyStructuralOperation(`props`,[])[0]]:C(zo(this.expression))}merge(e){let t=this.$.parseDefinition(e);return this.$.schema(t.distribute(e=>this.applyStructuralOperation(`merge`,[Ro(e)??C(Bo(`merge`,e.expression))])))}applyStructuralOperation(e,t){return this.distribute(n=>{if(n.equals(j.intrinsic.object)&&e!==`merge`)return n;let r=Ro(n);if(r||C(Bo(e,n.expression)),e===`keyof`)return r.keyof();if(e===`get`)return r.get(...t);if(e===`props`)return r.props;let i=e===`required`?`require`:e===`partial`?`optionalize`:e;return this.$.node(`intersection`,{...n.inner,structure:r[i](...t)})})}get(...e){return e[0]===void 0?this:this.$.schema(this.applyStructuralOperation(`get`,e))}extract(e){let t=this.$.parseDefinition(e);return this.$.schema(this.branches.filter(e=>e.extends(t)))}exclude(e){let t=this.$.parseDefinition(e);return this.$.schema(this.branches.filter(e=>!e.extends(t)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(e){let t=this.intersect(e);return!(t instanceof z)}extends(e){let t=this.intersect(e);return!(t instanceof z)&&this.equals(t)}ifExtends(e){return this.extends(e)?this:void 0}subsumes(e){let t=this.$.parseDefinition(e);return t.extends(this)}configure(e,t=`shallow`){return this.configureDescendants(e,t)}describe(e,t=`shallow`){return this.configure({description:e},t)}optional(){return[this,`?`]}default(e){return Mo(this,e,null),[this,`=`,e]}from(e){return this.assert(e)}_pipe(...e){let t=e.reduce((e,t)=>e.rawPipeOnce(t),this);return this.$.finalize(t)}tryPipe(...e){let t=e.reduce((e,t)=>e.rawPipeOnce(P(t,`root`)?t:(e,n)=>{try{return t(e,n)}catch(e){return n.error({code:`predicate`,predicate:t,actual:`aborted due to error:\n ${e}\n`})}}),this);return this.$.finalize(t)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(e){return this.$.finalize(this.toNode(this.$.parseDefinition(e)))}toNode(e){let t=ta(this,e,this.$);return t instanceof z?t.throw():t}rawPipeOnce(e){return P(e,`root`)?this.toNode(e):this.distribute(t=>t.hasKind(`morph`)?this.$.node(`morph`,{in:t.inner.in,morphs:[...t.morphs,e]}):this.$.node(`morph`,{in:t,morphs:[e]}),this.$.parseSchema)}narrow(e){return this.constrainOut(`predicate`,e)}constrain(e,t){return this._constrain(`root`,e,t)}constrainIn(e,t){return this._constrain(`in`,e,t)}constrainOut(e,t){return this._constrain(`out`,e,t)}_constrain(e,t,n){let r=this.$.node(t,n);if(r.isRoot())return r.isUnknown()?this:S(`Unexpected constraint node ${r}`);let i=e===`root`?this:this[e];if(i.hasKind(`morph`)||r.impliedBasis&&!i.extends(r.impliedBasis))return da(t,r.impliedBasis,this);let a=this.$.node(`intersection`,{[r.kind]:r}),o=e===`out`?ta(this,a,this.$):B(this,a,this.$);return o instanceof z&&o.throw(),this.$.finalize(o)}onUndeclaredKey(e){let t=typeof e==`string`?e:e.rule,n=typeof e==`string`?!1:e.deep;return this.$.finalize(this.transform((e,n)=>e===`structure`?t===`ignore`?Hn(n,{undeclared:1}):{...n,undeclared:t}:n,n?void 0:{shouldTransform:e=>!Sn(Ti,e.kind)}))}onDeepUndeclaredKey(e){return this.onUndeclaredKey({rule:e,deep:!0})}filter(e){return this.constrainIn(`predicate`,e)}divisibleBy(e){return this.constrain(`divisor`,e)}matching(e){return this.constrain(`pattern`,e)}atLeast(e){return this.constrain(`min`,e)}atMost(e){return this.constrain(`max`,e)}moreThan(e){return this.constrain(`min`,Io(e))}lessThan(e){return this.constrain(`max`,Io(e))}atLeastLength(e){return this.constrain(`minLength`,e)}atMostLength(e){return this.constrain(`maxLength`,e)}moreThanLength(e){return this.constrain(`minLength`,Io(e))}lessThanLength(e){return this.constrain(`maxLength`,Io(e))}exactlyLength(e){return this.constrain(`exactLength`,e)}atOrAfter(e){return this.constrain(`after`,e)}atOrBefore(e){return this.constrain(`before`,e)}laterThan(e){return this.constrain(`after`,Io(e))}earlierThan(e){return this.constrain(`before`,Io(e))}};const Fo=`Expected a non-empty brand name after #`,Io=e=>typeof e==`object`&&!(e instanceof Date)?{...e,exclusive:!0}:{rule:e,exclusive:!0},Lo=(e,t)=>P(t,`root`)?P(e,`root`)?e.extends(t):t.allows(e):P(e,`root`)?e.hasUnit(t):t===e,Ro=e=>e.hasKind(`morph`)?null:e.hasKind(`intersection`)?e.inner.structure??(e.basis?.domain===`object`?e.$.bindReference(j.intrinsic.emptyStructure):null):e.isBasis()&&e.domain===`object`?e.$.bindReference(j.intrinsic.emptyStructure):null,zo=e=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
|
|
14
|
-
${e}`,Bo=(e,t)=>`${e} operand must be an object (was ${t})`,Vo=(e,t)=>w(Fi(e),(e,n)=>[n,t]),Ho=e=>typeof e==`string`?{reference:e}:e,Uo=e=>e instanceof z?j.intrinsic.never.internal:e,Wo=I({kind:`alias`,hasAssociatedError:!1,collapsibleKey:`reference`,keys:{reference:{serialize:e=>e.startsWith(`$`)?e:`$ark.${e}`},resolve:{}},normalize:Ho,defaults:{description:e=>e.reference},intersections:{alias:(e,t,n)=>n.$.lazilyResolve(()=>Uo(V(e.resolution,t.resolution,n)),`${e.reference}${n.pipe?`=>`:`&`}${t.reference}`),...Vo(`alias`,(e,t,n)=>t.isUnknown()?e:t.isNever()?t:t.isBasis()&&!t.overlaps(j.intrinsic.object)?z.init(`assignability`,j.intrinsic.object,t):n.$.lazilyResolve(()=>Uo(V(e.resolution,t,n)),`${e.reference}${n.pipe?`=>`:`&`}${t.id}`))}});var Go=class extends Po{expression=this.reference;structure=void 0;get resolution(){let e=this._resolve();return W[this.id]=e}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]===`$`)return this.$.resolveRoot(this.reference.slice(1));let e=this.reference,t=W[e],n=[];for(;P(t,`context`);){if(n.includes(t.id))return C(Ko(t.id,n));n.push(t.id),t=W[t.id]}return P(t,`root`)?t:S(`Unexpected resolution for reference ${this.reference}
|
|
15
|
-
Seen: [${n.join(`->`)}]
|
|
16
|
-
Resolution: ${A(t)}`)}get resolutionId(){if(this.reference.includes(`&`)||this.reference.includes(`=>`))return this.resolution.id;if(this.reference[0]!==`$`)return this.reference;let e=this.reference.slice(1),t=this.$.resolutions[e];return typeof t==`string`?t:P(t,`root`)?t.id:S(`Unexpected resolution for reference ${this.reference}: ${A(t)}`)}get shortDescription(){return An.object}innerToJsonSchema(){return U.throwUnjsonifiableError(this.expression,`cyclic`)}traverseAllows=(e,t)=>{let n=t.seen[this.reference];return n?.includes(e)?!0:(t.seen[this.reference]=b(n,e),this.resolution.traverseAllows(e,t))};traverseApply=(e,t)=>{let n=t.seen[this.reference];n?.includes(e)||(t.seen[this.reference]=b(n,e),this.resolution.traverseApply(e,t))};compile(e){let t=this.resolutionId;e.if(`ctx.seen.${t} && ctx.seen.${t}.includes(data)`,()=>e.return(!0)),e.if(`!ctx.seen.${t}`,()=>e.line(`ctx.seen.${t} = []`)),e.line(`ctx.seen.${t}.push(data)`),e.return(e.invoke(t))}};const Ko=(e,t)=>`Alias '${e}' has a shallow resolution cycle: ${[...t,e].join(`->`)}`,qo={implementation:Wo,Node:Go};var Jo=class extends Po{traverseApply=(e,t)=>{this.traverseAllows(e,t)||t.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return Li(this.errorContext)}compile(e){e.traversalKind===`Allows`?e.return(this.compiledCondition):e.if(this.compiledNegation,()=>e.line(`${e.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}};const Yo=I({kind:`domain`,hasAssociatedError:!0,collapsibleKey:`domain`,keys:{domain:{},numberAllowsNaN:{}},normalize:e=>typeof e==`string`?{domain:e}:Ln(e,`numberAllowsNaN`)&&e.domain!==`number`?C(Zo.writeBadAllowNanMessage(e.domain)):e,applyConfig:(e,t)=>e.numberAllowsNaN===void 0&&e.domain===`number`&&t.numberAllowsNaN?{...e,numberAllowsNaN:!0}:e,defaults:{description:e=>An[e.domain],actual:e=>Number.isNaN(e)?`NaN`:An[x(e)]},intersections:{domain:(e,t)=>e.domain===`number`&&t.domain===`number`?e.numberAllowsNaN?t:e:z.init(`domain`,e,t)}});var Xo=class extends Jo{requiresNaNCheck=this.domain===`number`&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?e=>typeof e==`number`&&!Number.isNaN(e):e=>x(e)===this.domain;compiledCondition=this.domain===`object`?`((typeof data === "object" && data !== null) || typeof data === "function")`:`typeof data === "${this.domain}"${this.requiresNaNCheck?` && !Number.isNaN(data)`:``}`;compiledNegation=this.domain===`object`?`((typeof data !== "object" || data === null) && typeof data !== "function")`:`typeof data !== "${this.domain}"${this.requiresNaNCheck?` || Number.isNaN(data)`:``}`;expression=this.numberAllowsNaN?`number | NaN`:this.domain;get nestableExpression(){return this.numberAllowsNaN?`(${this.expression})`:this.expression}get shortDescription(){return An[this.domain]}innerToJsonSchema(){return this.domain===`bigint`||this.domain===`symbol`?U.throwUnjsonifiableError(this.domain):{type:this.domain}}};const Zo={implementation:Yo,Node:Xo,writeBadAllowNanMessage:e=>`numberAllowsNaN may only be specified with domain "number" (was ${e})`},Qo=I({kind:`intersection`,hasAssociatedError:!0,normalize:e=>{if(F(e))return e;let{structure:t,...n}=e,r=!!t,i=t??{},a=w(n,(e,t)=>T(e,ji)?(r&&C(`Flattened structure key ${e} cannot be specified alongside a root 'structure' key.`),i[e]=t,[]):[e,t]);return(P(i,`constraint`)||!Un(i))&&(a.structure=i),a},finalizeInnerJson:({structure:e,...t})=>kn(e,`object`)?{...e,...t}:t,keys:{domain:{child:!0,parse:(e,t)=>t.$.node(`domain`,e)},proto:{child:!0,parse:(e,t)=>t.$.node(`proto`,e)},structure:{child:!0,parse:(e,t)=>t.$.node(`structure`,e),serialize:e=>{if(!e.sequence?.minLength)return e.collapsibleJson;let{sequence:t,...n}=e.collapsibleJson,{minVariadicLength:r,...i}=t,a=i.variadic&&Object.keys(i).length===1?i.variadic:i;return{...n,sequence:a}}},divisor:{child:!0,parse:H(`divisor`)},max:{child:!0,parse:H(`max`)},min:{child:!0,parse:H(`min`)},maxLength:{child:!0,parse:H(`maxLength`)},minLength:{child:!0,parse:H(`minLength`)},exactLength:{child:!0,parse:H(`exactLength`)},before:{child:!0,parse:H(`before`)},after:{child:!0,parse:H(`after`)},pattern:{child:!0,parse:H(`pattern`)},predicate:{child:!0,parse:H(`predicate`)}},reduce:(e,t)=>ns({},e,{$:t,invert:!1,pipe:!1}),defaults:{description:e=>{if(e.children.length===0)return`unknown`;if(e.structure)return e.structure.description;let t=[];if(e.basis&&!e.refinements.some(e=>e.impl.obviatesBasisDescription)&&t.push(e.basis.description),e.refinements.length){let n=e.refinements.toSorted((e,t)=>e.kind===`min`&&t.kind===`max`?-1:0).map(e=>e.description);t.push(...n)}return e.inner.predicate&&t.push(...e.inner.predicate.map(e=>e.description)),t.join(` and `)},expected:e=>` ◦ ${e.errors.map(e=>e.expected).join(`
|
|
17
|
-
◦ `)}`,problem:e=>`(${e.actual}) must be...\n${e.expected}`},intersections:{intersection:(e,t,n)=>ns(e.inner,t.inner,n),...Vo(`intersection`,(e,t,n)=>{if(e.children.length===0)return t;let{domain:r,proto:i,...a}=e.inner,o=i??r,s=o?V(o,t,n):t;return s instanceof z?s:e?.basis?.equals(s)?e:e.$.node(`intersection`,{...a,[s.kind]:s},{prereduced:!0})})}});var $o=class extends Po{basis=this.inner.domain??this.inner.proto??null;refinements=this.children.filter(e=>e.isRefinement());structure=this.inner.structure;expression=ts(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get shortDescription(){return this.basis?.shortDescription??`present`}innerToJsonSchema(){return this.children.reduce((e,t)=>t.isBasis()?t.toJsonSchema():t.reduceJsonSchema(e),{})}traverseAllows=(e,t)=>this.children.every(n=>n.traverseAllows(e,t));traverseApply=(e,t)=>{let n=t.currentErrorCount;if(!(this.basis&&(this.basis.traverseApply(e,t),t.currentErrorCount>n))){if(this.refinements.length){for(let r=0;r<this.refinements.length-1;r++)if(this.refinements[r].traverseApply(e,t),t.failFast&&t.currentErrorCount>n)return;if(this.refinements.at(-1).traverseApply(e,t),t.currentErrorCount>n)return}if(!(this.structure&&(this.structure.traverseApply(e,t),t.currentErrorCount>n))&&this.inner.predicate){for(let r=0;r<this.inner.predicate.length-1;r++)if(this.inner.predicate[r].traverseApply(e,t),t.failFast&&t.currentErrorCount>n)return;this.inner.predicate.at(-1).traverseApply(e,t)}}};compile(e){if(e.traversalKind===`Allows`){this.children.forEach(t=>e.check(t)),e.return(!0);return}if(e.initializeErrorCount(),this.basis&&(e.check(this.basis),this.children.length>1&&e.returnIfFail()),this.refinements.length){for(let t=0;t<this.refinements.length-1;t++)e.check(this.refinements[t]),e.returnIfFailFast();e.check(this.refinements.at(-1)),(this.structure||this.inner.predicate)&&e.returnIfFail()}if(this.structure&&(e.check(this.structure),this.inner.predicate&&e.returnIfFail()),this.inner.predicate){for(let t=0;t<this.inner.predicate.length-1;t++)e.check(this.inner.predicate[t]),e.returnIfFail();e.check(this.inner.predicate.at(-1))}}};const es={implementation:Qo,Node:$o},ts=e=>{let t=e.structure?.expression||`${e.basis?e.basis.nestableExpression+` `:``}${e.refinements.map(e=>e.expression).join(` & `)}`||`unknown`;return t===`Array == 0`&&(t=`[]`),t},ns=(e,t,n)=>{let r={},i=e.proto??e.domain,a=t.proto??t.domain,o=i?a?V(i,a,n):i:a;return o instanceof z?o:(o&&(r[o.kind]=o),ca({kind:`intersection`,baseInner:r,l:la(e),r:la(t),roots:[],ctx:n}))},rs=I({kind:`morph`,hasAssociatedError:!1,keys:{in:{child:!0,parse:(e,t)=>t.$.parseSchema(e)},morphs:{parse:yn,serialize:e=>e.map(e=>P(e,`root`)?e.json:M(e))},declaredIn:{child:!1,serialize:e=>e.json},declaredOut:{child:!1,serialize:e=>e.json}},normalize:e=>e,defaults:{description:e=>`a morph from ${e.in.description} to ${e.out?.description??`unknown`}`},intersections:{morph:(e,t,n)=>{if(!e.hasEqualMorphs(t))return C(cs(e.expression,t.expression));let r=V(e.in,t.in,n);if(r instanceof z)return r;let i={morphs:e.morphs};if(e.declaredIn||t.declaredIn){let r=V(e.in,t.in,n);if(r instanceof z)return r.throw();i.declaredIn=r}if(e.declaredOut||t.declaredOut){let r=V(e.out,t.out,n);if(r instanceof z)return r.throw();i.declaredOut=r}return r.distribute(e=>n.$.node(`morph`,{...i,in:e}),n.$.parseSchema)},...Vo(`morph`,(e,t,n)=>{let r=e.inner.in?V(e.inner.in,t,n):t;return r instanceof z?r:r.equals(e.inner.in)?e:n.$.node(`morph`,{...e.inner,in:r})})}});var os=class extends Po{serializedMorphs=this.morphs.map(M);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs.at(-1);lastMorphIfNode=P(this.lastMorph,`root`)?this.lastMorph:void 0;introspectableIn=this.inner.in;introspectableOut=this.lastMorphIfNode?Object.assign(this.referencesById,this.lastMorphIfNode.referencesById)&&this.lastMorphIfNode.out:void 0;get shallowMorphs(){return Array.isArray(this.inner.in?.shallowMorphs)?[...this.inner.in.shallowMorphs,...this.morphs]:this.morphs}get in(){return this.declaredIn??this.inner.in?.in??j.intrinsic.unknown.internal}get out(){return this.declaredOut??this.introspectableOut??j.intrinsic.unknown.internal}declareIn(e){return this.$.node(`morph`,{...this.inner,declaredIn:e})}declareOut(e){return this.$.node(`morph`,{...this.inner,declaredOut:e})}expression=`(In: ${this.in.expression}) => ${this.lastMorphIfNode?`To`:`Out`}<${this.out.expression}>`;get shortDescription(){return`a morph`}innerToJsonSchema(){return U.throwUnjsonifiableError(this.expression,`morph`)}compile(e){if(e.traversalKind===`Allows`){if(!this.introspectableIn)return;e.return(e.invoke(this.introspectableIn));return}this.introspectableIn&&e.line(e.invoke(this.introspectableIn)),e.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(e,t)=>!this.introspectableIn||this.introspectableIn.traverseAllows(e,t);traverseApply=(e,t)=>{this.introspectableIn&&this.introspectableIn.traverseApply(e,t),t.queueMorphs(this.morphs)};hasEqualMorphs(e){return On(this.morphs,e.morphs,{isEqual:(e,t)=>e===t||P(e,`root`)&&P(t,`root`)&&e.equals(t)})}};const ss={implementation:rs,Node:os},cs=(e,t)=>`The intersection of distinct morphs at a single path is indeterminate:
|
|
18
|
-
Left: ${e}
|
|
19
|
-
Right: ${t}`,ls=I({kind:`proto`,hasAssociatedError:!0,collapsibleKey:`proto`,keys:{proto:{serialize:e=>ar(e)??Ii(e)},dateAllowsInvalid:{}},normalize:e=>{let t=typeof e==`string`?{proto:Qn[e]}:typeof e==`function`?F(e)?e:{proto:e}:typeof e.proto==`string`?{...e,proto:Qn[e.proto]}:e;return typeof t.proto!=`function`&&C(ds.writeInvalidSchemaMessage(t.proto)),Ln(t,`dateAllowsInvalid`)&&t.proto!==Date&&C(ds.writeBadInvalidDateMessage(t.proto)),t},applyConfig:(e,t)=>e.dateAllowsInvalid===void 0&&e.proto===Date&&t.dateAllowsInvalid?{...e,dateAllowsInvalid:!0}:e,defaults:{description:e=>e.builtinName?ir[e.builtinName]:`an instance of ${e.proto.name}`,actual:e=>e instanceof Date&&e.toString()===`Invalid Date`?`an invalid Date`:er(e)},intersections:{proto:(e,t)=>e.proto===Date&&t.proto===Date?e.dateAllowsInvalid?t:e:sr(e.proto,t.proto)?e:sr(t.proto,e.proto)?t:z.init(`proto`,e,t),domain:(e,t)=>t.domain===`object`?e:z.init(`domain`,j.intrinsic.object.internal,t)}});var us=class extends Jo{builtinName=ar(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?e=>e instanceof Date&&e.toString()!==`Invalid Date`:e=>e instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?` && data.toString() !== "Invalid Date"`:``}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(){switch(this.builtinName){case`Array`:return{type:`array`};default:return U.throwUnjsonifiableError(this.description)}}expression=this.dateAllowsInvalid?`Date | InvalidDate`:this.proto.name;get nestableExpression(){return this.dateAllowsInvalid?`(${this.expression})`:this.expression}domain=`object`;get shortDescription(){return this.description}};const ds={implementation:ls,Node:us,writeBadInvalidDateMessage:e=>`dateAllowsInvalid may only be specified with constructor Date (was ${e.name})`,writeInvalidSchemaMessage:e=>`instanceOf operand must be a function (was ${x(e)})`},fs=I({kind:`union`,hasAssociatedError:!0,collapsibleKey:`branches`,keys:{ordered:{},branches:{child:!0,parse:(e,t)=>{let n=[];return e.forEach(e=>{let r=P(e,`root`)?e.branches:t.$.parseSchema(e).branches;r.forEach(e=>{if(e.hasKind(`morph`)){let r=n.findIndex(t=>t.hasKind(`morph`)&&t.hasEqualMorphs(e));if(r===-1)n.push(e);else{let i=n[r];n[r]=t.$.node(`morph`,{...i.inner,in:i.in.rawOr(e.in)})}}else n.push(e)})}),t.def.ordered||n.sort((e,t)=>e.hash<t.hash?-1:1),n}}},normalize:e=>D(e)?{branches:e}:e,reduce:(e,t)=>{let n=Ds(e);if(n.length===1)return n[0];if(n.length!==e.branches.length)return t.node(`union`,{...e,branches:n},{prereduced:!0})},defaults:{description:e=>e.distribute(e=>e.description,Ts),expected:e=>{let t=Dn(e.errors,`propString`),n=Object.entries(t).map(([e,t])=>{let n=[];t.forEach(e=>En(n,e.expected));let r=Ts(n),i=t.every(e=>e.actual===t[0].actual)?t[0].actual:A(t[0].data);return`${e&&`${e} `}must be ${r}${i&&` (was ${i})`}`});return Ts(n)},problem:e=>e.expected,message:e=>e.problem},intersections:{union:(e,t,n)=>{if(e.isNever!==t.isNever)return z.init(`presence`,e,t);let r;return e.ordered?(t.ordered&&C(js(e.expression,t.expression)),r=Es(t.branches,e.branches,n),r instanceof z&&r.invert()):r=Es(e.branches,t.branches,n),r instanceof z?r:n.$.parseSchema(e.ordered||t.ordered?{branches:r,ordered:!0}:{branches:r})},...Vo(`union`,(e,t,n)=>{let r=Es(e.branches,[t],n);return r instanceof z?r:r.length===1?r[0]:n.$.parseSchema(e.ordered?{branches:r,ordered:!0}:{branches:r})})}});var ps=class extends Po{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let e=[],t=-1;return this.branches.forEach(n=>{if(n.hasKind(`unit`)&&n.domain===`boolean`){t===-1?(t=e.length,e.push(n)):e[t]=j.intrinsic.boolean;return}e.push(n)}),e}unitBranches=this.branches.filter(e=>e.in.hasKind(`unit`));discriminant=this.discriminate();discriminantJson=this.discriminant?Ss(this.discriminant):null;expression=this.distribute(e=>e.nestableExpression,ws);createBranchedOptimisticRootApply(){return(e,t)=>{let n=this.traverseOptimistic(e);if(n!==E)return n;let r=new Ui(e,this.$.resolvedConfig);return this.traverseApply(e,r),r.finalize(t)}}get shallowMorphs(){return this.branches.reduce((e,t)=>En(e,t.shallowMorphs),[])}get shortDescription(){return this.distribute(e=>e.shortDescription,Ts)}innerToJsonSchema(){return this.branchGroups.length===1&&this.branchGroups[0].equals(j.intrinsic.boolean)?{type:`boolean`}:{anyOf:this.branchGroups.map(e=>e.toJsonSchema())}}traverseAllows=(e,t)=>this.branches.some(n=>n.traverseAllows(e,t));traverseApply=(e,t)=>{let n=[];for(let r=0;r<this.branches.length;r++){if(t.pushBranch(),this.branches[r].traverseApply(e,t),!t.hasError())return this.branches[r].includesTransform?t.queuedMorphs.push(...t.popBranch().queuedMorphs):t.popBranch();n.push(t.popBranch().error)}t.errorFromNodeContext({code:`union`,errors:n,meta:this.meta})};traverseOptimistic=e=>{for(let t=0;t<this.branches.length;t++){let n=this.branches[t];if(n.traverseAllows(e))return n.contextFreeMorph?n.contextFreeMorph(e):e}return E};compile(e){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(e);let t=this.discriminant.optionallyChainedPropString;this.discriminant.kind===`domain`&&(t=`typeof ${t} === "object" ? ${t} === null ? "null" : "object" : typeof ${t} === "function" ? "object" : typeof ${t}`);let n=this.discriminant.cases,r=Object.keys(n),{optimistic:i}=e;if(e.optimistic=!1,e.block(`switch(${t})`,()=>{for(let t in n){let r=n[t],a=t===`default`?t:`case ${t}`;e.line(`${a}: return ${r===!0?i?e.data:r:i?`${e.invoke(r)} ? ${r.contextFreeMorph?`${M(r.contextFreeMorph)}(${e.data})`:e.data} : "${E}"`:e.invoke(r)}`)}return e}),e.traversalKind===`Allows`){e.return(i?`"${E}"`:!1);return}let a=Ts(this.discriminant.kind===`domain`?r.map(e=>{let t=e.slice(1,-1);return t===`function`?An.object:An[t]}):r),o=this.discriminant.path.map(e=>typeof e==`symbol`?M(e):JSON.stringify(e)),s=JSON.stringify(a),c=this.discriminant.kind===`domain`?`${ys}[${t}]`:`${bs}(${t})`;e.line(`ctx.errorFromNodeContext({
|
|
20
|
-
code: "predicate",
|
|
21
|
-
expected: ${s},
|
|
22
|
-
actual: ${c},
|
|
23
|
-
relativePath: [${o}],
|
|
24
|
-
meta: ${this.compiledMeta}
|
|
25
|
-
})`)}compileIndiscriminable(e){if(e.traversalKind===`Apply`)e.const(`errors`,`[]`),this.branches.forEach(t=>e.line(`ctx.pushBranch()`).line(e.invoke(t)).if(`!ctx.hasError()`,()=>e.return(t.includesTransform?`ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)`:`ctx.popBranch()`)).line(`errors.push(ctx.popBranch().error)`)),e.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`);else{let{optimistic:t}=e;e.optimistic=!1,this.branches.forEach(n=>e.if(`${e.invoke(n)}`,()=>e.return(t?n.contextFreeMorph?`${M(n.contextFreeMorph)}(${e.data})`:e.data:!0))),e.return(t?`"${E}"`:!1)}}get nestableExpression(){return this.isBoolean?`boolean`:`(${this.expression})`}discriminate(){if(this.branches.length<2)return null;if(this.unitBranches.length===this.branches.length){let e=w(this.unitBranches,(e,t)=>[`${t.in.serializedValue}`,t.hasKind(`morph`)?t:!0]);return{kind:`unit`,path:[],optionallyChainedPropString:`data`,cases:e}}let e=[];for(let t=0;t<this.branches.length-1;t++){let n=this.branches[t];for(let r=t+1;r<this.branches.length;r++){let i=this.branches[r],a=B(n.in,i.in,n.$);if(a instanceof z)for(let n of a){if(!n.kind||n.optional)continue;let i,a;if(n.kind===`domain`){let e=n.l,t=n.r;i=`"${typeof e==`string`?e:e.domain}"`,a=`"${typeof t==`string`?t:t.domain}"`}else if(n.kind===`unit`)i=n.l.serializedValue,a=n.r.serializedValue;else continue;let o=e.find(e=>On(e.path,n.path)&&e.kind===n.kind);o?(o.cases[i]?o.cases[i].branchIndices=En(o.cases[i].branchIndices,t):o.cases[i]??={branchIndices:[t],condition:n.l},o.cases[a]?o.cases[a].branchIndices=En(o.cases[a].branchIndices,r):o.cases[a]??={branchIndices:[r],condition:n.r}):e.push({kind:n.kind,cases:{[i]:{branchIndices:[t],condition:n.l},[a]:{branchIndices:[r],condition:n.r}},path:n.path})}}}let t=this.ordered?gs(e,this.branches):e;if(!t.length)return null;let n=ms(t,this),r={};for(let e in n.best.cases){let t=hs(n,e);if(t===null){r[e]=!0;continue}if(t.length===this.branches.length)return null;this.ordered&&t.sort((e,t)=>e.originalIndex-t.originalIndex);let i=t.map(e=>e.branch),a=i.length===1?i[0]:this.$.node(`union`,this.ordered?{branches:i,ordered:!0}:i);Object.assign(this.referencesById,a.referencesById),r[e]=a}if(n.defaultEntries.length){let e=n.defaultEntries.map(e=>e.branch);r.default=this.$.node(`union`,this.ordered?{branches:e,ordered:!0}:e,{prereduced:!0}),Object.assign(this.referencesById,r.default.referencesById)}return Object.assign(n.location,{cases:r})}};const ms=(e,t)=>{let n=e.sort((e,t)=>Object.keys(t.cases).length-Object.keys(e.cases).length)[0],r={kind:n.kind,path:n.path,optionallyChainedPropString:vs(n.path)},i=t.branches.map((e,t)=>({originalIndex:t,branch:e}));return{best:n,location:r,defaultEntries:i,node:t}},hs=(e,t)=>{let n=e.best.cases[t],r=_s(n.condition,e.location.path,e.node.$),i=[],a=[];for(let t=0;t<e.defaultEntries.length;t++){let o=e.defaultEntries[t];if(n.branchIndices.includes(o.originalIndex)){let t=ks(e.node.branches[o.originalIndex],e.location);t===null?i=null:i?.push({originalIndex:o.originalIndex,branch:t})}else if(o.branch.hasKind(`alias`)&&r.hasKind(`domain`)&&r.domain===`object`)i?.push(o);else{if(o.branch.in.overlaps(r)){let t=ks(o.branch,e.location);i?.push({originalIndex:o.originalIndex,branch:t})}a.push(o)}}return e.defaultEntries=a,i},gs=(e,t)=>{let n=e.filter(e=>{let n=Object.values(e.cases).map(e=>e.branchIndices);for(let e=0;e<n.length-1;e++){let r=n[e];for(let i=e+1;i<n.length;i++){let e=n[i];for(let n of r)for(let r of e)if(n>r&&t[n].overlaps(t[r]))return!1}}return!0});return n},_s=(e,t,n)=>{let r=e===`undefined`?n.node(`unit`,{unit:void 0}):e===`null`?n.node(`unit`,{unit:null}):e===`boolean`?n.units([!0,!1]):e;for(let e=t.length-1;e>=0;e--){let i=t[e];r=n.node(`intersection`,typeof i==`number`?{proto:`Array`,sequence:[...Cn(i).map(e=>({})),r]}:{domain:`object`,required:[{key:i,value:r}]})}return r},vs=e=>e.reduce((e,t)=>e+yi(t,!0),`data`),ys=M(jn),bs=M(A),xs={implementation:fs,Node:ps},Ss=e=>({kind:e.kind,path:e.path.map(e=>typeof e==`string`?e:vi(e)),cases:w(e.cases,(e,t)=>[e,t===!0?t:t.hasKind(`union`)&&t.discriminantJson?t.discriminantJson:t.json])}),Cs={delimiter:` | `,finalDelimiter:` | `},ws=e=>Ts(e,Cs),Ts=(e,t)=>{let n=t?.delimiter??`, `,r=t?.finalDelimiter??` or `;if(e.length===0)return`never`;if(e.length===1)return e[0];if(e.length===2&&e[0]===`false`&&e[1]===`true`||e[0]===`true`&&e[1]===`false`)return`boolean`;let i={},a=e.filter(e=>i[e]?!1:i[e]=!0),o=a.pop();return`${a.join(n)}${a.length?r:``}${o}`},Es=(e,t,n)=>{let r=t.map(()=>[]);for(let i=0;i<e.length;i++){let a={};for(let o=0;o<t.length;o++){if(r[o]===null)continue;if(e[i].equals(t[o])){r[o]=null,a={};break}let s=V(e[i],t[o],n);if(!(s instanceof z)){if(s.equals(e[i])){r[o].push(e[i]),a={};break}s.equals(t[o])?r[o]=null:a[o]=s}}for(let e in a)r[e][i]=a[e]}let i=r.flatMap((e,n)=>e?.flatMap(e=>e.branches)??t[n]);return i.length===0?z.init(`union`,e,t):i},Ds=({branches:e,ordered:t})=>{if(e.length<2)return e;let n=e.map(()=>!0);for(let r=0;r<e.length;r++)for(let i=r+1;i<e.length&&n[r]&&n[i];i++){if(e[r].equals(e[i])){n[i]=!1;continue}let a=B(e[r].in,e[i].in,e[0].$);a instanceof z||(t||Os(e[r],e[i]),a.equals(e[r].in)?n[r]=!!t:a.equals(e[i].in)&&(n[i]=!1))}return e.filter((e,t)=>n[t])},Os=(e,t)=>{!e.includesTransform&&!t.includesTransform||(On(e.shallowMorphs,t.shallowMorphs)||C(As(e.expression,t.expression)),On(e.flatMorphs,t.flatMorphs,{isEqual:(e,t)=>e.propString===t.propString&&(e.node.hasKind(`morph`)&&t.node.hasKind(`morph`)?e.node.hasEqualMorphs(t.node):e.node.hasKind(`intersection`)&&t.node.hasKind(`intersection`)?e.node.structure?.structuralMorphRef===t.node.structure?.structuralMorphRef:!1)})||C(As(e.expression,t.expression)))},ks=(e,t)=>e.transform((e,t)=>e===`domain`||e===`unit`?null:t,{shouldTransform:(e,n)=>{let r=vs(n.path);return t.optionallyChainedPropString.startsWith(r)?e.hasKind(`domain`)&&e.domain===`object`||(e.hasKind(`domain`)||t.kind===`unit`)&&r===t.optionallyChainedPropString?!0:e.children.length!==0&&e.kind!==`index`:!1}}),As=(e,t)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
|
|
26
|
-
Left: ${e}
|
|
27
|
-
Right: ${t}`,js=(e,t)=>`The intersection of two ordered unions is indeterminate:
|
|
28
|
-
Left: ${e}
|
|
29
|
-
Right: ${t}`,Ms=I({kind:`unit`,hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:e=>e instanceof Date?e.toISOString():Ii(e)}},normalize:e=>e,defaults:{description:e=>A(e.unit),problem:({expected:e,actual:t})=>`${e===t?`must be reference equal to ${e} (serialized to the same value)`:`must be ${e} (was ${t})`}`},intersections:{unit:(e,t)=>z.init(`unit`,e,t),...Vo(`unit`,(e,t)=>{if(t.allows(e.unit))return e;let n=t.hasKind(`intersection`)?t.basis:t;if(n){let t=n.hasKind(`domain`)?n:j.intrinsic.object;if(e.domain!==t.domain){let n=e.domain===`undefined`||e.domain===`null`||e.domain===`boolean`?e.domain:j.intrinsic[e.domain];return z.init(`domain`,n,t)}}return z.init(`assignability`,e,t.hasKind(`intersection`)?t.children.find(t=>!t.allows(e.unit)):t)})}});var Ns=class extends Jo{compiledValue=this.json.unit;serializedValue=typeof this.unit==`string`||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=Fs(this.unit,this.serializedValue);compiledNegation=Fs(this.unit,this.serializedValue,`negated`);expression=A(this.unit);domain=x(this.unit);get shortDescription(){return this.domain===`object`?An.object:this.description}innerToJsonSchema(){return j.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:U.throwUnjsonifiableError(this.shortDescription)}traverseAllows=this.unit instanceof Date?e=>e instanceof Date&&e.toISOString()===this.compiledValue:Number.isNaN(this.unit)?e=>Number.isNaN(e):e=>e===this.unit};const Ps={implementation:Ms,Node:Ns},Fs=(e,t,n)=>{if(e instanceof Date){let e=`data instanceof Date && data.toISOString() === ${t}`;return n?`!(${e})`:e}return Number.isNaN(e)?`${n?`!`:``}Number.isNaN(data)`:`data ${n?`!`:`=`}== ${t}`},Is=I({kind:`index`,hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(e,t)=>{let n=t.$.parseSchema(e);if(!n.extends(j.intrinsic.key))return C(Bs(n.expression));let r=n.branches.filter(e=>e.hasKind(`unit`));return r.length?C(zs(r.map(e=>A(e.unit)))):n}},value:{child:!0,parse:(e,t)=>t.$.parseSchema(e)}},normalize:e=>e,defaults:{description:e=>`[${e.signature.expression}]: ${e.value.description}`},intersections:{index:(e,t,n)=>{if(e.signature.equals(t.signature)){let r=V(e.value,t.value,n),i=r instanceof z?j.intrinsic.never.internal:r;return n.$.node(`index`,{signature:e.signature,value:i})}return e.signature.extends(t.signature)&&e.value.subsumes(t.value)?t:t.signature.extends(e.signature)&&t.value.subsumes(e.value)?e:null}}});var Ls=class extends oa{impliedBasis=j.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=b(this.value.flatRefs.map(e=>R([this.signature,...e.path],e.node)),R([this.signature],this.value));traverseAllows=(e,t)=>Wn(e).every(e=>this.signature.traverseAllows(e[0],t)?L(e[0],()=>this.value.traverseAllows(e[1],t),t):!0);traverseApply=(e,t)=>Wn(e).forEach(e=>{this.signature.traverseAllows(e[0],t)&&L(e[0],()=>this.value.traverseApply(e[1],t),t)});_transform(e,t){t.path.push(this.signature);let n=super._transform(e,t);return t.path.pop(),n}compile(){}};const Rs={implementation:Is,Node:Ls},zs=e=>`Index keys ${e.join(`, `)} should be specified as named props.`,Bs=e=>`Indexed key definition '${e}' must be a string or symbol`,Vs=I({kind:`required`,hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(e,t)=>t.$.parseSchema(e)}},normalize:e=>e,defaults:{description:e=>`${e.compiledKey}: ${e.value.description}`,expected:e=>e.missingValueDescription,actual:()=>`missing`},intersections:{required:Co,optional:Co}});var Hs=class extends wo{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:`required`,missingValueDescription:this.value.shortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=Li(this.errorContext)};const Us={implementation:Vs,Node:Hs},Ws=I({kind:`sequence`,hasAssociatedError:!1,collapsibleKey:`variadic`,keys:{prefix:{child:!0,parse:(e,t)=>{if(e.length!==0)return e.map(e=>t.$.parseSchema(e))}},optionals:{child:!0,parse:(e,t)=>{if(e.length!==0)return e.map(e=>t.$.parseSchema(e))}},defaultables:{child:e=>e.map(e=>e[0]),parse:(e,t)=>{if(e.length!==0)return e.map(e=>{let n=t.$.parseSchema(e[0]);return Mo(n,e[1],null),[n,e[1]]})},serialize:e=>e.map(e=>[e[0].collapsibleJson,Ii(e[1])])},variadic:{child:!0,parse:(e,t)=>t.$.parseSchema(e,t)},minVariadicLength:{parse:e=>e===0?void 0:e},postfix:{child:!0,parse:(e,t)=>{if(e.length!==0)return e.map(e=>t.$.parseSchema(e))}}},normalize:e=>{if(typeof e==`string`)return{variadic:e};if(`variadic`in e||`prefix`in e||`defaultables`in e||`optionals`in e||`postfix`in e||`minVariadicLength`in e){if(e.postfix?.length){if(!e.variadic)return C(Qs);if(e.optionals?.length||e.defaultables?.length)return C(Zs)}return e.minVariadicLength&&!e.variadic?C(`minVariadicLength may not be specified without a variadic element`):e}return{variadic:e}},reduce:(e,t)=>{let n=e.minVariadicLength??0,r=e.prefix?.slice()??[],i=e.defaultables?.slice()??[],a=e.optionals?.slice()??[],o=e.postfix?.slice()??[];if(e.variadic){for(;a.at(-1)?.equals(e.variadic);)a.pop();if(a.length===0&&i.length===0)for(;r.at(-1)?.equals(e.variadic);)r.pop(),n++;for(;o[0]?.equals(e.variadic);)o.shift(),n++}else a.length===0&&i.length===0&&r.push(...o.splice(0));if(n!==e.minVariadicLength||e.prefix&&e.prefix.length!==r.length)return t.node(`sequence`,{...e,prefix:r,defaultables:i,optionals:a,postfix:o,minVariadicLength:n},{prereduced:!0})},defaults:{description:e=>{if(e.isVariadicOnly)return`${e.variadic.nestableExpression}[]`;let t=e.tuple.map(e=>e.kind===`defaultables`?`${e.node.nestableExpression} = ${A(e.default)}`:e.kind===`optionals`?`${e.node.nestableExpression}?`:e.kind===`variadic`?`...${e.node.nestableExpression}[]`:e.node.expression).join(`, `);return`[${t}]`}},intersections:{sequence:(e,t,n)=>{let r=$s({l:e.tuple,r:t.tuple,disjoint:new z,result:[],fixedVariants:[],ctx:n}),i=r.disjoint.length===0?[r,...r.fixedVariants]:r.fixedVariants;return i.length===0?r.disjoint:i.length===1?n.$.node(`sequence`,Xs(i[0].result)):n.$.node(`union`,i.map(e=>({proto:Array,sequence:Xs(e.result)})))}}});var Gs=class extends oa{impliedBasis=j.intrinsic.Array.internal;tuple=Ys(this.inner);prefixLength=this.prefix?.length??0;defaultablesLength=this.defaultables?.length??0;optionalsLength=this.optionals?.length??0;postfixLength=this.postfix?.length??0;defaultablesAndOptionals=[];prevariadic=this.tuple.filter(e=>e.kind===`defaultables`||e.kind===`optionals`?(this.defaultablesAndOptionals.push(e.node),!0):e.kind===`prefix`);variadicOrPostfix=wn(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return Yi(this.flatRefs,this.prevariadic.flatMap((e,t)=>b(e.node.flatRefs.map(e=>R([`${t}`,...e.path],e.node)),R([`${t}`],e.node)))),Yi(this.flatRefs,this.variadicOrPostfix.flatMap(e=>b(e.flatRefs.map(e=>R([j.intrinsic.nonNegativeIntegerString.internal,...e.path],e.node)),R([j.intrinsic.nonNegativeIntegerString.internal],e)))),this.flatRefs}isVariadicOnly=this.prevariadic.length+this.postfixLength===0;minVariadicLength=this.inner.minVariadicLength??0;minLength=this.prefixLength+this.minVariadicLength+this.postfixLength;minLengthNode=this.minLength===0?null:this.$.node(`minLength`,this.minLength);maxLength=this.variadic?null:this.tuple.length;maxLengthNode=this.maxLength===null?null:this.$.node(`maxLength`,this.maxLength);impliedSiblings=this.minLengthNode?this.maxLengthNode?[this.minLengthNode,this.maxLengthNode]:[this.minLengthNode]:this.maxLengthNode?[this.maxLengthNode]:[];defaultValueMorphs=qs(this);defaultValueMorphsReference=this.defaultValueMorphs.length?M(this.defaultValueMorphs):void 0;elementAtIndex(e,t){if(t<this.prevariadic.length)return this.tuple[t];let n=e.length-this.postfixLength;return t>=n?{kind:`postfix`,node:this.postfix[t-n]}:{kind:`variadic`,node:this.variadic??S(`Unexpected attempt to access index ${t} on ${this}`)}}traverseAllows=(e,t)=>{for(let n=0;n<e.length;n++)if(!this.elementAtIndex(e,n).node.traverseAllows(e[n],t))return!1;return!0};traverseApply=(e,t)=>{let n=0;for(;n<e.length;n++)L(n,()=>this.elementAtIndex(e,n).node.traverseApply(e[n],t),t)};get element(){return this.cacheGetter(`element`,this.$.node(`union`,this.children))}compile(e){this.prefix?.forEach((t,n)=>e.traverseKey(`${n}`,`data[${n}]`,t)),this.defaultablesAndOptionals.forEach((t,n)=>{let r=`${n+this.prefixLength}`;e.if(`${r} >= ${e.data}.length`,()=>e.traversalKind===`Allows`?e.return(!0):e.return()),e.traverseKey(r,`data[${r}]`,t)}),this.variadic&&(this.postfix&&e.const(`firstPostfixIndex`,`${e.data}.length${this.postfix?`- ${this.postfix.length}`:``}`),e.for(`i < ${this.postfix?`firstPostfixIndex`:`data.length`}`,()=>e.traverseKey(`i`,`data[i]`,this.variadic),this.prevariadic.length),this.postfix?.forEach((t,n)=>{let r=`firstPostfixIndex + ${n}`;e.traverseKey(r,`data[${r}]`,t)})),e.traversalKind===`Allows`&&e.return(!0)}_transform(e,t){t.path.push(j.intrinsic.nonNegativeIntegerString.internal);let n=super._transform(e,t);return t.path.pop(),n}expression=this.description;reduceJsonSchema(e){return this.prefix&&(e.prefixItems=this.prefix.map(e=>e.toJsonSchema())),this.optionals?U.throwUnjsonifiableError(`Optional tuple element${this.optionalsLength>1?`s`:``} ${this.optionals.join(`, `)}`):(this.variadic?(e.items=this.variadic?.toJsonSchema(),this.minLength&&(e.minItems=this.minLength),this.maxLength&&(e.maxItems=this.maxLength)):(e.items=!1,delete e.minItems,delete e.maxItems),this.postfix?U.throwUnjsonifiableError(`Postfix tuple element${this.postfixLength>1?`s`:``} ${this.postfix.join(`, `)}`):e)}};const Ks={},qs=e=>{if(!e.defaultables)return[];let t=[],n=`[`,r=e.prefixLength+e.defaultablesLength-1;for(let i=e.prefixLength;i<=r;i++){let[r,a]=e.defaultables[i-e.prefixLength];t.push(jo(i,r,a)),n+=`${i}: ${r.id} = ${Ii(a)}, `}return n+=`]`,Ks[n]??=t},Js={implementation:Ws,Node:Gs},Ys=e=>{let t=[];return e.prefix?.forEach(e=>t.push({kind:`prefix`,node:e})),e.defaultables?.forEach(([e,n])=>t.push({kind:`defaultables`,node:e,default:n})),e.optionals?.forEach(e=>t.push({kind:`optionals`,node:e})),e.variadic&&t.push({kind:`variadic`,node:e.variadic}),e.postfix?.forEach(e=>t.push({kind:`postfix`,node:e})),t},Xs=e=>e.reduce((e,t)=>(t.kind===`variadic`?e.variadic=t.node:t.kind===`defaultables`?e.defaultables=b(e.defaultables,[[t.node,t.default]]):e[t.kind]=b(e[t.kind],t.node),e),{}),Zs=`A postfix required element cannot follow an optional or defaultable element`,Qs=`A postfix element requires a variadic element`,$s=e=>{let[t,...n]=e.l,[r,...i]=e.r;if(!t||!r)return e;let a=n.at(-1)?.kind===`postfix`,o=i.at(-1)?.kind===`postfix`,s=t.kind===`prefix`||r.kind===`prefix`?`prefix`:t.kind===`postfix`||r.kind===`postfix`?`postfix`:t.kind===`variadic`&&r.kind===`variadic`?`variadic`:a||o?`prefix`:t.kind===`defaultables`||r.kind===`defaultables`?`defaultables`:`optionals`;if(t.kind===`prefix`&&r.kind===`variadic`&&o){let t=$s({...e,fixedVariants:[],r:i.map(e=>({...e,kind:`prefix`}))});t.disjoint.length===0&&e.fixedVariants.push(t)}else if(r.kind===`prefix`&&t.kind===`variadic`&&a){let t=$s({...e,fixedVariants:[],l:n.map(e=>({...e,kind:`prefix`}))});t.disjoint.length===0&&e.fixedVariants.push(t)}let c=V(t.node,r.node,e.ctx);if(c instanceof z)if(s===`prefix`||s===`postfix`)e.disjoint.push(...c.withPrefixKey(s===`prefix`?e.result.length:`-${n.length+1}`,`required`)),e.result=[...e.result,{kind:s,node:j.intrinsic.never.internal}];else if(s===`optionals`||s===`defaultables`)return e;else return $s({...e,fixedVariants:[],l:n.map(e=>({...e,kind:`prefix`})),r:n.map(e=>({...e,kind:`prefix`}))});else s===`defaultables`?(t.kind===`defaultables`&&r.kind===`defaultables`&&t.default!==r.default&&C(To(t.default,r.default)),e.result=[...e.result,{kind:s,node:c,default:t.kind===`defaultables`?t.default:r.kind===`defaultables`?r.default:S(`Unexpected defaultable intersection from ${t.kind} and ${r.kind} elements.`)}]):e.result=[...e.result,{kind:s,node:c}];let l=e.l.length,u=e.r.length;return(t.kind!==`variadic`||l>=u&&(r.kind===`variadic`||u===1))&&(e.l=n),(r.kind!==`variadic`||u>=l&&(t.kind===`variadic`||l===1))&&(e.r=i),$s(e)},ec=e=>t=>{if(t.props.length||t.index){let n=t.index?.map(t=>t[e])??[];t.props.forEach(t=>n.push(t[e])),t.undeclared&&n.push(`+ (undeclared): ${t.undeclared}`);let r=`{ ${n.join(`, `)} }`;return t.sequence?`${r} & ${t.sequence.description}`:r}return t.sequence?.description??`{}`},tc=ec(`description`),nc=ec(`expression`),rc=I({kind:`structure`,hasAssociatedError:!1,normalize:e=>e,applyConfig:(e,t)=>!e.undeclared&&t.onUndeclaredKey!==`ignore`?{...e,undeclared:t.onUndeclaredKey}:e,keys:{required:{child:!0,parse:H(`required`),reduceIo:(e,t,n)=>{t.required=b(t.required,n.map(t=>t[e]))}},optional:{child:!0,parse:H(`optional`),reduceIo:(e,t,n)=>{if(e===`in`){t.optional=n.map(e=>e.in);return}n.forEach(e=>t[e.outProp.kind]=b(t[e.outProp.kind],e.outProp.out))}},index:{child:!0,parse:H(`index`)},sequence:{child:!0,parse:H(`sequence`)},undeclared:{parse:e=>e===`ignore`?void 0:e,reduceIo:(e,t,n)=>{n===`delete`&&(e===`in`?delete t.undeclared:t.undeclared=`reject`)}}},defaults:{description:tc},intersections:{structure:(e,t,n)=>{let r={...e.inner},i={...t.inner},a=new z;if(e.undeclared){let r=e.keyof();t.requiredKeys.forEach(e=>{r.allows(e)||a.add(`presence`,j.intrinsic.never.internal,t.propsByKey[e].value,{path:[e]})}),i.optional&&(i.optional=i.optional.filter(e=>r.allows(e.key))),i.index&&(i.index=i.index.flatMap(e=>{if(e.signature.extends(r))return e;let t=B(r,e.signature,n.$);if(t instanceof z)return[];let a=fc(t,e.value,n.$);return a.required&&(i.required=wn(i.required,a.required)),a.optional&&(i.optional=wn(i.optional,a.optional)),a.index??[]}))}if(t.undeclared){let i=t.keyof();e.requiredKeys.forEach(t=>{i.allows(t)||a.add(`presence`,e.propsByKey[t].value,j.intrinsic.never.internal,{path:[t]})}),r.optional&&(r.optional=r.optional.filter(e=>i.allows(e.key))),r.index&&(r.index=r.index.flatMap(e=>{if(e.signature.extends(i))return e;let t=B(i,e.signature,n.$);if(t instanceof z)return[];let a=fc(t,e.value,n.$);return a.required&&(r.required=wn(r.required,a.required)),a.optional&&(r.optional=wn(r.optional,a.optional)),a.index??[]}))}let o={};(e.undeclared||t.undeclared)&&(o.undeclared=e.undeclared===`reject`||t.undeclared===`reject`?`reject`:`delete`);let s=ca({kind:`structure`,baseInner:o,l:la(r),r:la(i),roots:[],ctx:n});return s instanceof z&&a.push(...s),a.length?a:s}}});var ic=class extends oa{impliedBasis=j.intrinsic.object.internal;impliedSiblings=this.children.flatMap(e=>e.impliedSiblings??[]);props=wn(this.required,this.optional);propsByKey=w(this.props,(e,t)=>[t.key,t]);propsByKeyReference=M(this.propsByKey);expression=nc(this);requiredKeys=this.required?.map(e=>e.key)??[];optionalKeys=this.optional?.map(e=>e.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let e=this.$.units(this.literalKeys).branches;return this.index?.forEach(({signature:t})=>{e=e.concat(t.branches)}),this._keyof=this.$.node(`union`,e)}map(e){return this.$.node(`structure`,this.props.flatMap(e).reduce((e,t)=>{let n=this.propsByKey[t.key];if(F(t))return t.kind!==`required`&&t.kind!==`optional`?C(`Map result must have kind "required" or "optional" (was ${t.kind})`):(e[t.kind]=b(e[t.kind],t),e);let r=t.kind??n?.kind??`required`,i=w(t,(e,t)=>e in Oo.implementation.keys?[e,t]:[]);return e[r]=b(e[r],this.$.node(r,i)),e},{}))}assertHasKeys(e){let t=e.filter(e=>!Lo(e,this.keyof()));if(t.length)return C(mc(this.expression,t))}get(e,...t){let n,r=!1,i=uc(e);if((typeof i==`string`||typeof i==`symbol`)&&this.propsByKey[i]&&(n=this.propsByKey[i].value,r=this.propsByKey[i].required),this.index?.forEach(e=>{Lo(i,e.signature)&&(n=n?.and(e.value)??e.value)}),this.sequence&&Lo(i,j.intrinsic.nonNegativeIntegerString))if(P(i,`root`))this.sequence.variadic&&(n=n?.and(this.sequence.element)??this.sequence.element);else{let e=Number.parseInt(i);if(e<this.sequence.prevariadic.length){let t=this.sequence.prevariadic[e].node;n=n?.and(t)??t,r||=e<this.sequence.prefixLength}else if(this.sequence.variadic){let e=this.$.node(`union`,this.sequence.variadicOrPostfix);n=n?.and(e)??e}}if(!n)return this.sequence?.variadic&&P(i,`root`)&&i.extends(j.intrinsic.number)?C(dc(i.expression,this.sequence.expression)):C(mc(this.expression,[i]));let a=n.get(...t);return r?a:a.or(j.intrinsic.undefined)}pick(...e){return this.assertHasKeys(e),this.$.node(`structure`,this.filterKeys(`pick`,e))}omit(...e){return this.assertHasKeys(e),this.$.node(`structure`,this.filterKeys(`omit`,e))}optionalize(){let{required:e,...t}=this.inner;return this.$.node(`structure`,{...t,optional:this.props.map(e=>e.hasKind(`required`)?this.$.node(`optional`,e.inner):e)})}require(){let{optional:e,...t}=this.inner;return this.$.node(`structure`,{...t,required:this.props.map(e=>e.hasKind(`optional`)?{key:e.key,value:e.value}:e)})}merge(e){let t=this.filterKeys(`omit`,[e.keyof()]);return e.required&&(t.required=b(t.required,e.required)),e.optional&&(t.optional=b(t.optional,e.optional)),e.index&&(t.index=b(t.index,e.index)),e.sequence&&(t.sequence=e.sequence),e.undeclared?t.undeclared=e.undeclared:delete t.undeclared,this.$.node(`structure`,t)}filterKeys(e,t){let n=Ci(this.inner),r=n=>{let r=t.some(e=>Lo(n,e));return e===`pick`?r:!r};return n.required&&(n.required=n.required.filter(e=>r(e.key))),n.optional&&(n.optional=n.optional.filter(e=>r(e.key))),n.index&&(n.index=n.index.filter(e=>r(e.signature))),n}traverseAllows=(e,t)=>this._traverse(`Allows`,e,t);traverseApply=(e,t)=>this._traverse(`Apply`,e,t);_traverse=(e,t,n)=>{let r=n?.currentErrorCount??0;for(let i=0;i<this.props.length;i++)if(e===`Allows`){if(!this.props[i].traverseAllows(t,n))return!1}else if(this.props[i].traverseApply(t,n),n.failFast&&n.currentErrorCount>r)return!1;if(this.sequence){if(e===`Allows`){if(!this.sequence.traverseAllows(t,n))return!1}else if(this.sequence.traverseApply(t,n),n.failFast&&n.currentErrorCount>r)return!1}if(this.index||this.undeclared===`reject`){let i=Object.keys(t);i.push(...Object.getOwnPropertySymbols(t));for(let a=0;a<i.length;a++){let o=i[a];if(this.index){for(let i of this.index)if(i.signature.traverseAllows(o,n)){if(e===`Allows`){let e=L(o,()=>i.value.traverseAllows(t[o],n),n);if(!e)return!1}else if(L(o,()=>i.value.traverseApply(t[o],n),n),n.failFast&&n.currentErrorCount>r)return!1}}if(this.undeclared===`reject`&&!this.declaresKey(o)&&(e===`Allows`||(n.errorFromNodeContext({code:`predicate`,expected:`removed`,actual:``,relativePath:[o],meta:this.meta}),n.failFast)))return!1}}return this.structuralMorph&&n&&!n.hasError()&&n.queueMorphs([this.structuralMorph]),!0};get defaultable(){return this.cacheGetter(`defaultable`,this.optional?.filter(e=>e.hasDefault())??[])}declaresKey=e=>e in this.propsByKey||this.index?.some(t=>t.signature.allows(e))||this.sequence!==void 0&&j.intrinsic.nonNegativeIntegerString.allows(e);_compileDeclaresKey(e){let t=[];return this.props.length&&t.push(`k in ${this.propsByKeyReference}`),this.index?.forEach(n=>t.push(e.invoke(n.signature,{kind:`Allows`,arg:`k`}))),this.sequence&&t.push(`$ark.intrinsic.nonNegativeIntegerString.allows(k)`),t.join(` || `)||`false`}get structuralMorph(){return this.cacheGetter(`structuralMorph`,sc(this))}structuralMorphRef=this.structuralMorph&&M(this.structuralMorph);compile(e){if(e.traversalKind===`Apply`&&e.initializeErrorCount(),this.props.forEach(t=>{e.check(t),e.traversalKind===`Apply`&&e.returnIfFailFast()}),this.sequence&&(e.check(this.sequence),e.traversalKind===`Apply`&&e.returnIfFailFast()),(this.index||this.undeclared===`reject`)&&(e.const(`keys`,`Object.keys(data)`),e.line(`keys.push(...Object.getOwnPropertySymbols(data))`),e.for(`i < keys.length`,()=>this.compileExhaustiveEntry(e))),e.traversalKind===`Allows`)return e.return(!0);this.structuralMorphRef&&e.if(`ctx && !ctx.hasError()`,()=>(e.line(`ctx.queueMorphs([`),cc(e,this),e.line(`])`)))}compileExhaustiveEntry(e){return e.const(`k`,`keys[i]`),this.index?.forEach(t=>{e.if(`${e.invoke(t.signature,{arg:`k`,kind:`Allows`})}`,()=>e.traverseKey(`k`,`data[k]`,t.value))}),this.undeclared===`reject`&&e.if(`!(${this._compileDeclaresKey(e)})`,()=>e.traversalKind===`Allows`?e.return(!1):e.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if(`ctx.failFast`,()=>e.return())),e}reduceJsonSchema(e){switch(e.type){case`object`:return this.reduceObjectJsonSchema(e);case`array`:return this.props.length||this.index?U.throwUnjsonifiableError(`Additional properties on array ${this.expression}`):this.sequence?.reduceJsonSchema(e)??e;default:return U.throwInternalOperandError(`structure`,e)}}reduceObjectJsonSchema(e){return this.props.length&&(e.properties={},this.props.forEach(t=>{if(typeof t.key==`symbol`)return U.throwUnjsonifiableError(`Symbolic key ${t.serializedKey}`);e.properties[t.key]=t.value.toJsonSchema()}),this.requiredKeys.length&&(e.required=this.requiredKeys)),this.index?.forEach(t=>{if(t.signature.equals(j.intrinsic.string))return e.additionalProperties=t.value.toJsonSchema();if(!t.signature.extends(j.intrinsic.string))return U.throwUnjsonifiableError(`Symbolic index signature ${t.signature.exclude(j.intrinsic.string)}`);t.signature.branches.forEach(n=>{if(!n.hasKind(`intersection`)||n.inner.pattern?.length!==1)return U.throwUnjsonifiableError(`Index signature ${n}`);e.patternProperties??={},e.patternProperties[n.inner.pattern[0].rule]=t.value.toJsonSchema()})}),this.undeclared&&!e.additionalProperties&&(e.additionalProperties=!1),e}};const ac={},oc=e=>{let t=``;for(let n=0;n<e.defaultable.length;n++)t+=e.defaultable[n].defaultValueMorphRef;return e.sequence?.defaultValueMorphsReference&&(t+=e.sequence?.defaultValueMorphsReference),e.undeclared===`delete`&&(t+=`delete !(`,e.required?.forEach(e=>t+=e.compiledKey+` | `),e.optional?.forEach(e=>t+=e.compiledKey+` | `),e.index?.forEach(e=>t+=e.signature.id+` | `),e.sequence&&(e.sequence.maxLength===null?t+=q.nonNegativeIntegerString.id:t+=e.sequence.tuple.forEach((e,n)=>t+=n+` | `)),t+=`)`),t},sc=e=>{let t=oc(e);if(!t)return;if(ac[t])return ac[t];let n=(t,n)=>{for(let r=0;r<e.defaultable.length;r++)e.defaultable[r].key in t||e.defaultable[r].defaultValueMorph(t,n);if(e.sequence?.defaultables)for(let r=t.length-e.sequence.prefixLength;r<e.sequence.defaultables.length;r++)e.sequence.defaultValueMorphs[r](t,n);if(e.undeclared===`delete`)for(let n in t)e.declaresKey(n)||delete t[n];return t};return ac[t]=n},cc=(e,t)=>{let n=t.defaultable.some(e=>e.defaultValueMorph.length===2)||t.sequence?.defaultValueMorphs.some(e=>e.length===2),r=`(data${n?`, ctx`:``})`;return e.block(`${r} => `,e=>{for(let n=0;n<t.defaultable.length;n++){let{serializedKey:i,defaultValueMorphRef:a}=t.defaultable[n];e.if(`!(${i} in data)`,e=>e.line(`${a}${r}`))}return t.sequence?.defaultables&&e.for(`i < ${t.sequence.defaultables.length}`,e=>e.set(`data[i]`,5),`data.length - ${t.sequence.prefixLength}`),t.undeclared===`delete`&&e.forIn(`data`,e=>e.if(`!(${t._compileDeclaresKey(e)})`,e=>e.line(`delete data[k]`))),e.return(`data`)})},lc={implementation:rc,Node:ic},uc=e=>(P(e,`root`)&&e.hasKind(`unit`)&&(e=e.unit),typeof e==`number`&&(e=`${e}`),e),dc=(e,t)=>`${e} is not allowed as an array index on ${t}. Use the 'nonNegativeIntegerString' keyword instead.`,fc=(e,t,n)=>{let[r,i]=bn(e.branches,e=>e.hasKind(`unit`));if(!r.length)return{index:n.node(`index`,{signature:e,value:t})};let a={};return r.forEach(e=>{let r=n.node(`required`,{key:e.unit,value:t});a[r.kind]=b(a[r.kind],r)}),i.length&&(a.index=n.node(`index`,{signature:i,value:t})),a},pc=e=>P(e,`root`)?e.expression:A(e),mc=(e,t)=>`Key${t.length===1?``:`s`} ${t.map(pc).join(`, `)} ${t.length===1?`does`:`do`} not exist on ${e}`,hc={...oo,alias:qo.implementation,domain:Zo.implementation,unit:Ps.implementation,proto:ds.implementation,union:xs.implementation,morph:ss.implementation,intersection:es.implementation,divisor:wa.implementation,pattern:uo.implementation,predicate:xa.implementation,required:Us.implementation,optional:Oo.implementation,index:Rs.implementation,sequence:Js.implementation,structure:lc.implementation};j.defaultConfig=Kn(Object.assign(w(hc,(e,t)=>[e,t.defaults]),{jitless:hr(),clone:cr,onUndeclaredKey:`ignore`,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{}})),j.resolvedConfig=Ri(j.defaultConfig,j.config);const gc={...so,alias:qo.Node,domain:Zo.Node,unit:Ps.Node,proto:ds.Node,union:xs.Node,morph:ss.Node,intersection:es.Node,divisor:wa.Node,pattern:uo.Node,predicate:xa.Node,required:Us.Node,optional:Oo.Node,index:Rs.Node,sequence:Js.Node,structure:lc.Node};var _c=class extends Rn{get[N](){return`module`}};const vc=(e,t)=>new _c(w(e,(e,n)=>[e,P(n,`module`)?vc(n,t):t.bindReference(n)])),yc=e=>D(e)?e:`branches`in e&&D(e.branches)?e.branches:void 0,bc=(e,t)=>C(`Node of kind ${t} is not valid as a ${e} definition`),xc=e=>`#${e} duplicates public alias ${e}`,Sc={};j.ambient??={};let Cc;const wc=e=>Tc(e,Dc(e)),Tc=(e,t)=>{let n=Ec(t);for(let r of e){if(r.precompilation)continue;r.traverseAllows=n[`${r.id}Allows`].bind(n),r.isRoot()&&!r.allowsRequiresContext&&(r.allows=r.traverseAllows),r.traverseApply=n[`${r.id}Apply`].bind(n),n[`${r.id}Optimistic`]&&(r.traverseOptimistic=n[`${r.id}Optimistic`].bind(n)),r.precompilation=t}},Ec=e=>new _i().return(e).compile()(),Dc=e=>e.reduce((e,t)=>{let n=new Si({kind:`Allows`}).indent();t.compile(n);let r=n.write(`${t.id}Allows`),i=new Si({kind:`Apply`}).indent();t.compile(i);let a=i.write(`${t.id}Apply`),o=`${e}${r},\n${a},\n`;if(!t.hasKind(`union`))return o;let s=new Si({kind:`Allows`,optimistic:!0}).indent();t.compile(s);let c=s.write(`${t.id}Optimistic`);return`${o}${c},\n`},`{
|
|
30
|
-
`)+`}`;var Oc=class{config;resolvedConfig;name;get[N](){return`scope`}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};constructor(e,t){this.config=Ri(j.config,t),this.resolvedConfig=Ri(j.resolvedConfig,t),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(Sc).length}`,this.name in Sc&&C(`A Scope already named ${this.name} already exists`),Sc[this.name]=this;let n=Object.entries(e).map(e=>this.preparseOwnAliasEntry(...e));n.forEach(([e,t])=>{let n=e;if(e[0]===`#`?(n=e.slice(1),n in this.aliases&&C(xc(n)),this.aliases[n]=t):(n in this.aliases&&C(xc(e)),this.aliases[n]=t,this.exportedNames.push(n)),!P(t,`module`)&&!P(t,`generic`)&&!dr(t)){let e=this.preparseOwnDefinitionFormat(t,{alias:n});P(e,`root`)?this.resolutions[n]=this.bindReference(e):this.resolutions[n]=this.createParseContext(e).id}}),Cc??=this.node(`union`,{branches:[`string`,`number`,`object`,`bigint`,`symbol`,{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[Cc.hash]=this.node(`intersection`,{},{prereduced:!0})}cacheGetter(e,t){return Object.defineProperty(this,e,{value:t}),t}get internal(){return this}_json;get json(){return this._json||this.export(),this._json}defineSchema(e){return e}generic=(...e)=>{let t=this;return(n,r)=>new ha(e,r?new ma(n):n,t,t,r??null)};units=(e,t)=>{let n=[];for(let t of e)n.includes(t)||n.push(t);let r=n.map(e=>this.node(`unit`,{unit:e},t));return this.node(`union`,r,{...t,prereduced:!0})};lazyResolutions=[];lazilyResolve(e,t){let n=this.node(`alias`,{reference:t??`synthetic`,resolve:e},{prereduced:!0});return this.resolved||this.lazyResolutions.push(n),n}schema=(e,t)=>this.finalize(this.parseSchema(e,t));parseSchema=(e,t)=>this.node(fo(e),e,t);preparseNode(e,t,n){let r=typeof e==`string`?e:fo(t,e);if(F(t)&&t.kind===r)return t;if(r===`alias`&&!n?.prereduced){let{reference:e}=qo.implementation.normalize(t,this);if(e.startsWith(`$`)){let n=this.resolveRoot(e.slice(1));t=n,r=n.kind}}else if(r===`union`&&kn(t,`object`)){let e=yc(t);e?.length===1&&(t=e[0],r=fo(t))}if(F(t)&&t.kind===r)return t;let i=hc[r],a=i.normalize?.(t,this)??t;return F(a)?a.kind===r?a:bc(r,a.kind):{...n,$:this,kind:r,def:a,prefix:n.alias??r}}bindReference(e){let t;return t=F(e)?e.$===this?e:new e.constructor(e.attachments,this):e.$===this?e:new ha(e.params,e.bodyDef,e.$,this,e.hkt),this.resolved||Object.assign(this.referencesById,t.referencesById),t}resolveRoot(e){return this.maybeResolveRoot(e)??C(Ic(e))}maybeResolveRoot(e){let t=this.maybeResolve(e);if(!P(t,`generic`))return t}maybeResolveSubalias(e){return Mc(this.aliases,e)??Mc(this.ambient,e)}get ambient(){return j.ambient}maybeResolve(e){let t=this.resolutions[e];if(t){if(typeof t!=`string`)return this.bindReference(t);let n=W[t];if(P(n,`root`))return this.resolutions[e]=n;if(P(n,`context`)){if(n.phase===`resolving`)return this.node(`alias`,{reference:`$${e}`},{prereduced:!0});if(n.phase===`resolved`)return S(`Unexpected resolved context for was uncached by its scope: ${A(n)}`);n.phase=`resolving`;let t=this.bindReference(this.parseOwnDefinitionFormat(n.def,n));return n.phase=`resolved`,W[t.id]=t,W[n.id]=t,this.resolutions[e]=t}return S(`Unexpected nodesById entry for ${t}: ${A(n)}`)}let n=this.aliases[e]??this.ambient?.[e];return n?(n=this.normalizeRootScopeValue(n),P(n,`generic`)?this.resolutions[e]=this.bindReference(n):P(n,`module`)?n.root?this.resolutions[e]=this.bindReference(n.root):C(Rc(e)):this.resolutions[e]=this.parse(n,{alias:e})):this.maybeResolveSubalias(e)}createParseContext(e){let t=e.id??_o(e.prefix);return W[t]=Object.assign(e,{[N]:`context`,$:this,id:t,phase:`unresolved`})}traversal(e){return new Ui(e,this.resolvedConfig)}import(...e){return new _c(w(this.export(...e),(e,t)=>[`#${e}`,t]))}precompilation;_exportedResolutions;_exports;export(...e){if(!this._exports){this._exports={};for(let e of this.exportedNames){let t=this.aliases[e];this._exports[e]=P(t,`module`)?vc(t,this):Ac(this.maybeResolve(e))}this.lazyResolutions.forEach(e=>e.resolution),this._exportedResolutions=Fc(this,this._exports),this._json=jc(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),this.resolvedConfig.jitless||(this.precompilation=Dc(this.references),Tc(this.references,this.precompilation)),this.resolved=!0}let t=e.length?e:this.exportedNames;return new _c(w(t,(e,t)=>[t,this._exports[t]]))}resolve(e){return this.export()[e]}node=(e,t,n={})=>{let r=this.preparseNode(e,t,n);if(F(r))return this.bindReference(r);let i=this.createParseContext(r),a=vo(i),o=this.bindReference(a);return W[i.id]=o};parse=(e,t={})=>this.finalize(this.parseDefinition(e,t));parseDefinition(e,t={}){if(P(e,`root`))return this.bindReference(e);let n=this.preparseOwnDefinitionFormat(e,t);if(P(n,`root`))return this.bindReference(n);let r=this.createParseContext(n);W[r.id]=r;let i=this.bindReference(this.parseOwnDefinitionFormat(e,r));return i.isCyclic&&(i=bo(i,r.id)),W[r.id]=i,i}finalize(e){return Ac(e),!e.precompilation&&!this.resolvedConfig.jitless&&wc(e.references),e}},kc=class extends Oc{parseOwnDefinitionFormat(e,t){return vo(t)}preparseOwnDefinitionFormat(e,t){return this.preparseNode(fo(e),e,t)}preparseOwnAliasEntry(e,t){return[e,t]}normalizeRootScopeValue(e){return e}};const Ac=e=>(e.references.filter(e=>e.hasKind(`alias`)).forEach(t=>{Object.assign(t.referencesById,t.resolution.referencesById),e.references.forEach(e=>{t.id in e.referencesById&&Object.assign(e.referencesById,t.referencesById)})}),e),jc=e=>w(e,(e,t)=>[e,P(t,`root`)||P(t,`generic`)?t.json:P(t,`module`)?jc(t):S(`Unexpected resolution ${A(t)}`)]),Mc=(e,t)=>{let n=t.indexOf(`.`);if(n===-1)return;let r=t.slice(0,n),i=e[r];if(i===void 0)return;if(!P(i,`module`))return C(Lc(r));let a=t.slice(n+1),o=i[a];if(o===void 0)return Mc(i,a);if(P(o,`root`)||P(o,`generic`))return o;if(P(o,`module`))return o.root??C(Rc(t));S(`Unexpected resolution for alias '${t}': ${A(o)}`)},Nc=(e,t)=>new kc(e,t),Pc=new kc({}),Fc=(e,t)=>{let n={};for(let r in t){let i=t[r];if(P(i,`module`)){let t=Fc(e,i),a=w(t,(e,t)=>[`${r}.${e}`,t]);Object.assign(n,a)}else P(i,`root`)||P(i,`generic`)?n[r]=i:S(`Unexpected scope resolution ${A(i)}`)}return n},Ic=e=>`'${e}' is unresolvable`,Lc=e=>`'${e}' must reference a module to be accessed using dot syntax`,Rc=e=>`Reference to submodule '${e}' must specify an alias`;Pc.export();const G=Pc.schema,zc=Pc.node;Pc.defineSchema;const K=Pc.generic,Bc=`^(?:0|[1-9]\\d*)$`,Vc=new RegExp(Bc);M(Vc);const Hc=Nc({bigint:`bigint`,boolean:[{unit:!1},{unit:!0}],false:{unit:!1},never:[],null:{unit:null},number:`number`,object:`object`,string:`string`,symbol:`symbol`,true:{unit:!0},unknown:{},undefined:{unit:void 0},Array,Date},{prereducedAliases:!0}).export();j.intrinsic={...Hc};const Uc=Nc({integer:{domain:`number`,divisor:1},lengthBoundable:[`string`,Array],key:[`string`,`symbol`],nonNegativeIntegerString:{domain:`string`,pattern:Bc}},{prereducedAliases:!0}).export();Object.assign(j.intrinsic,Uc);const Wc=Nc({jsonPrimitive:[`string`,`number`,{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:`object`,index:{signature:`string`,value:`$jsonData`}},jsonData:[`$jsonPrimitive`,`$jsonObject`]},{prereducedAliases:!0}).export(),q={...Hc,...Uc,...Wc,emptyStructure:zc(`structure`,{},{prereduced:!0})};j.intrinsic={...q};const Gc=e=>typeof e==`string`&&e[0]===`d`&&(e[1]===`'`||e[1]===`"`)&&e.at(-1)===e[1],Kc=e=>e.toString()!==`Invalid Date`,qc=e=>e.slice(2,-1),Jc=e=>`'${e}' could not be parsed by the Date constructor`,Yc=(e,t)=>Xc(e,t),Xc=(e,t)=>{let n=new Date(e);if(Kc(n))return n;let r=Br(e);if(r!==void 0){let e=new Date(r);if(Kc(e))return e}return t?C(t===!0?Jc(e):t):void 0},Zc=(e,t)=>{let n=e.scanner.shiftUntil(tl[el[t]]);if(e.scanner.lookahead===``)return e.error(rl(n,t));if(e.scanner.shift(),t===`/`){try{new RegExp(n)}catch(e){C(String(e))}e.root=e.ctx.$.node(`intersection`,{domain:`string`,pattern:n},{prereduced:!0})}else if(T(t,Qc))e.root=e.ctx.$.node(`unit`,{unit:n});else{let t=Yc(n,Jc(n));e.root=e.ctx.$.node(`unit`,{meta:n,unit:t})}},Qc={"'":1,'"':1},$c={"/":1,"'":1,'"':1},el={"d'":`'`,'d"':`"`,"'":`'`,'"':`"`,"/":`/`},tl={"'":e=>e.lookahead===`'`,'"':e=>e.lookahead===`"`,"/":e=>e.lookahead===`/`},nl={'"':`double-quote`,"'":`single-quote`,"/":`forward slash`},rl=(e,t)=>`${t}${e} requires a closing ${nl[el[t]]}`,il=e=>`Private type references should not include '#'. Use '${e}' instead.`,al=`Optional definitions like 'string?' are only valid as properties in an object or tuple`,ol=`Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple`,sl={">":!0,">=":!0},cl={"<":!0,"<=":!0},ll={"<":`>`,">":`<`,"<=":`>=`,">=":`<=`,"==":`==`},ul=e=>`Unmatched )${e===``?``:` before ${e}`}`,dl=e=>`Missing ${e}`,fl=(e,t)=>`Left bounds are only valid when paired with right bounds (try ...${t}${e})`,pl=e=>`Left-bounded expressions must specify their limits using < or <= (was ${e})`,ml=(e,t,n,r)=>`An expression may have at most one left bound (parsed ${e}${ll[t]}, ${n}${ll[r]})`,hl=(e,t,n)=>gl(e,t,n,[]),gl=(e,t,n,r)=>{let i=n.parseUntilFinalizer();return r.push(i.root),i.finalizer===`>`?r.length===t.params.length?r:n.error(_l(e,t.names,r.map(e=>e.expression))):i.finalizer===`,`?gl(e,t,n,r):i.error(dl(`>`))},_l=(e,t,n)=>`${e}<${t.join(`, `)}> requires exactly ${t.length} args (got ${n.length}${n.length===0?``:`: ${n.join(`, `)}`})`,vl=e=>{let t=e.scanner.shiftUntilNextTerminator();t===`keyof`?e.addPrefix(`keyof`):e.root=bl(e,t)},yl=(e,t,n)=>{n.scanner.shiftUntilNonWhitespace();let r=n.scanner.shift();if(r!==`<`)return n.error(_l(e,t.names,[]));let i=hl(e,t,n);return t(...i)},bl=(e,t)=>xl(e,t)??Sl(e,t)??e.error(t===``?e.scanner.lookahead===`#`?il(e.shiftedByOne().scanner.shiftUntilNextTerminator()):Cl(e):Ic(t)),xl=(e,t)=>{if(e.ctx.args?.[t]){let n=e.ctx.args[t];return typeof n==`string`?e.ctx.$.node(`alias`,{reference:n},{prereduced:!0}):n}let n=e.ctx.$.maybeResolve(t);if(P(n,`root`))return n;if(n!==void 0)return P(n,`generic`)?yl(t,n,e):C(`Unexpected resolution ${A(n)}`)},Sl=(e,t)=>{let n=Vr(t);if(n!==void 0)return e.ctx.$.node(`unit`,{unit:n});let r=Wr(t);if(r!==void 0)return e.ctx.$.node(`unit`,{unit:r})},Cl=e=>{let t=e.previousOperator();return t?wl(t,e.scanner.unscanned):Tl(e.scanner.unscanned)},wl=(e,t=``)=>`Token '${e}' requires a right operand${t?` before '${t}'`:``}`,Tl=e=>`Expected an expression${e?` before '${e}'`:``}`,El=e=>e.scanner.lookahead===``?e.error(Cl(e)):e.scanner.lookahead===`(`?e.shiftedByOne().reduceGroupOpen():e.scanner.lookaheadIsIn($c)?Zc(e,e.scanner.shift()):e.scanner.lookaheadIsIn(br)?El(e.shiftedByOne()):e.scanner.lookahead===`d`&&e.scanner.nextLookahead in Qc?Zc(e,`${e.scanner.shift()}${e.scanner.shift()}`):vl(e);var Dl=class e extends ui{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>this.lookahead in e.terminatingChars)}static terminatingChars={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...br};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(t,n)=>t===`>`?n[0]===`=`?n[1]===`=`:n.trimStart()===``||T(n.trimStart()[0],e.terminatingChars):t===`=`?n[0]!==`=`:t===`,`||t===`?`};const Ol=(e,t)=>{let n=Al(e,t);if(e.root.hasKind(`unit`)){if(typeof e.root.unit==`number`){e.reduceLeftBound(e.root.unit,n),e.unsetRoot();return}if(e.root.unit instanceof Date){let t=`d'${e.root.description??e.root.unit.toISOString()}'`;e.unsetRoot(),e.reduceLeftBound(t,n);return}}return Nl(e,n)},kl={"<":1,">":1,"=":1},Al=(e,t)=>e.scanner.lookaheadIs(`=`)?`${t}${e.scanner.shift()}`:t,jl=(e,t,n,r)=>n.extends(j.intrinsic.number)?typeof t==`number`?e===`==`?[`min`,`max`]:e[0]===`>`?[`min`]:[`max`]:C(Pl(e,t,r)):n.extends(j.intrinsic.lengthBoundable)?typeof t==`number`?e===`==`?[`exactLength`]:e[0]===`>`?[`minLength`]:[`maxLength`]:C(Pl(e,t,r)):n.extends(j.intrinsic.Date)?e===`==`?[`after`,`before`]:e[0]===`>`?[`after`]:[`before`]:C(Ra(n.expression)),Ml=e=>({rule:Gc(e.limit)?qc(e.limit):e.limit,exclusive:e.comparator.length===1}),Nl=(e,t)=>{let n=e.unsetRoot(),r=e.scanner.location;e.parseOperand();let i=e.unsetRoot(),a=e.scanner.sliceChars(r,e.scanner.location);if(e.root=n,!i.hasKind(`unit`)||typeof i.unit!=`number`&&!(i.unit instanceof Date))return e.error(Pl(t,a,`right`));let o=i.unit,s=t.length===1,c=jl(t,typeof o==`number`?o:a,n,`right`);for(let n of c)e.constrainRoot(n,t===`==`?{rule:o}:{rule:o,exclusive:s});if(!e.branches.leftBound)return;if(!T(t,cl))return e.error(pl(t));let l=jl(e.branches.leftBound.comparator,e.branches.leftBound.limit,n,`left`);e.constrainRoot(l[0],Ml(e.branches.leftBound)),e.branches.leftBound=null},Pl=(e,t,n)=>`Comparator ${n===`left`?ll[e]:e} must be ${n===`left`?`preceded`:`followed`} by a corresponding literal (was ${t})`,Fl=e=>{e.scanner.shiftUntilNonWhitespace();let t=e.scanner.shiftUntilNextTerminator();e.root=e.root.brand(t)},Il=e=>{let t=e.scanner.shiftUntilNextTerminator(),n=Hr(t,{errorOnFail:Ll(t)});n===0&&e.error(Ll(0)),e.root=e.root.constrain(`divisor`,n)},Ll=e=>`% operator must be followed by a non-zero integer literal (was ${e})`,Rl=e=>{let t=e.scanner.shift();return t===``?e.finalize(``):t===`[`?e.scanner.shift()===`]`?e.setRoot(e.root.array()):e.error(Bl):t===`|`?e.scanner.lookahead===`>`?e.shiftedByOne().pushRootToBranch(`|>`):e.pushRootToBranch(t):t===`&`?e.pushRootToBranch(t):t===`)`?e.finalizeGroup():Dl.lookaheadIsFinalizing(t,e.scanner.unscanned)?e.finalize(t):T(t,kl)?Ol(e,t):t===`%`?Il(e):t===`#`?Fl(e):t in br?Rl(e):e.error(zl(t))},zl=(e,t=``)=>`'${e}' is not allowed here${t&&` (should be ${t})`}`,Bl=`Missing expected ']'`,Vl=e=>{let t=e.unsetRoot();e.parseOperand();let n=e.unsetRoot();if(!n.hasKind(`unit`))return e.error(Hl(n.expression));let r=n.unit instanceof Date?()=>new Date(n.unit):n.unit;return[t,`=`,r]},Hl=e=>`Default value '${e}' must a literal value`,Ul=(e,t)=>{let n=t.$.maybeResolveRoot(e);if(n)return n;if(e.endsWith(`[]`)){let n=t.$.maybeResolveRoot(e.slice(0,-2));if(n)return n.array()}let r=new ql(new Dl(e),t),i=Wl(r);return r.finalizer===`>`&&C(zl(`>`)),i},Wl=e=>{e.parseOperand();let t=Gl(e).root;return t?(e.finalizer===`=`?t=Vl(e):e.finalizer===`?`&&(t=[t,`?`]),e.scanner.shiftUntilNonWhitespace(),e.scanner.lookahead&&C(zl(e.scanner.lookahead)),t):S(`Root was unexpectedly unset after parsing string '${e.scanner.scanned}'`)},Gl=e=>{for(;e.finalizer===void 0;)Kl(e);return e},Kl=e=>e.hasRoot()?e.parseOperator():e.parseOperand();var ql=class e{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(e,t){this.scanner=e,this.ctx=t}error(e){return C(e)}hasRoot(){return this.root!==void 0}setRoot(e){this.root=e}unsetRoot(){let e=this.root;return this.root=void 0,e}constrainRoot(...e){this.root=this.root.constrain(e[0],e[1])}finalize(e){if(this.groups.length)return this.error(dl(`)`));this.finalizeBranches(),this.finalizer=e}reduceLeftBound(e,t){let n=ll[t];if(!T(n,sl))return this.error(pl(t));if(this.branches.leftBound)return this.error(ml(this.branches.leftBound.limit,this.branches.leftBound.comparator,e,n));this.branches.leftBound={comparator:n,limit:e}}finalizeBranches(){if(this.assertRangeUnset(),this.branches.pipe){this.pushRootToBranch(`|>`),this.root=this.branches.pipe;return}if(this.branches.union){this.pushRootToBranch(`|`),this.root=this.branches.union;return}if(this.branches.intersection){this.pushRootToBranch(`&`),this.root=this.branches.intersection;return}this.applyPrefixes()}finalizeGroup(){this.finalizeBranches();let e=this.groups.pop();if(!e)return this.error(ul(this.scanner.unscanned));this.branches=e}addPrefix(e){this.branches.prefixes.push(e)}applyPrefixes(){for(;this.branches.prefixes.length;){let e=this.branches.prefixes.pop();this.root=e===`keyof`?this.root.keyof():S(`Unexpected prefix '${e}'`)}}pushRootToBranch(e){this.assertRangeUnset(),this.applyPrefixes();let t=this.root;this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(t)??t,e!==`&`&&(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,e!==`|`&&(this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null))}parseUntilFinalizer(){return Gl(new e(this.scanner,this.ctx))}parseOperator(){return Rl(this)}parseOperand(){return El(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(fl(this.branches.leftBound.limit,this.branches.leftBound.comparator))}reduceGroupOpen(){this.groups.push(this.branches),this.branches={prefixes:[],leftBound:null,union:null,intersection:null,pipe:null}}previousOperator(){return this.branches.leftBound?.comparator??this.branches.prefixes.at(-1)??(this.branches.intersection?`&`:this.branches.union?`|`:this.branches.pipe?`|>`:void 0)}shiftedByOne(){return this.scanner.shift(),this}};const Jl=`An empty string is not a valid generic parameter name`,Yl=(e,t,n)=>{e.shiftUntilNonWhitespace();let r=e.shiftUntilNextTerminator();return r===``?e.lookahead===``&&t.length?t:C(Jl):(e.shiftUntilNonWhitespace(),Zl(e,r,t,n))},Xl=`extends `,Zl=(e,t,n,r)=>{if(e.shiftUntilNonWhitespace(),e.unscanned.startsWith(Xl))e.jumpForward(8);else return e.lookahead===`,`&&e.shift(),n.push(t),Yl(e,n,r);let i=Gl(new ql(e,r));return n.push([t,i.root]),Yl(e,n,r)};var Ql=class extends mr{$;constructor(e){super((...t)=>new $l(e)(...t),{bind:e}),this.$=e}in(e){return new $l(this.$,e===void 0?void 0:this.$.parse(e))}at(e,t){return new $l(this.$).at(e,t)}case(e,t){return new $l(this.$).case(e,t)}},$l=class extends mr{$;in;key;branches=[];constructor(e,t){super(e=>this.caseEntries(Object.entries(e).map(([e,t])=>e===`default`?[e,t]:[this.$.parse(e),t]))),this.$=e,this.in=t}at(e,t){return this.key&&C(nu),this.branches.length&&C(tu),this.key=e,t?this.match(t):this}case(e,t){return this.caseEntry(this.$.parse(e),t)}caseEntry(e,t){let n=this.key?this.$.parse({[this.key]:e}):e,r=n.pipe(t);return this.branches.push(r),this}match(e){return this(e)}strings(e){return this.caseEntries(Object.entries(e).map(([e,t])=>e===`default`?[e,t]:[this.$.node(`unit`,{unit:e}),t]))}caseEntries(e){for(let t=0;t<e.length;t++){let[n,r]=e[t];if(n===`default`)return t!==e.length-1&&C(`default may only be specified as the last key of a switch definition`),this.default(r);if(typeof r!=`function`)return C(`Value for case "${n}" must be a function (was ${x(r)})`);this.caseEntry(n,r)}return this}default(e){typeof e==`function`&&this.case(q.unknown,e);let t={branches:this.branches,ordered:!0};(e===`never`||e===`assert`)&&(t.meta={onFail:eu});let n=this.$.node(`union`,t);if(!this.in)return this.$.finalize(n);let r=this.in.pipe(n);return(e===`never`||e===`assert`)&&(r=r.withMeta({onFail:eu})),this.$.finalize(r)}};const eu=e=>e.throw(),tu=`A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')`,nu=`At most one key matcher may be specified per expression`,ru=(e,t)=>{if(D(e)){if(e[1]===`=`)return[t.$.parseOwnDefinitionFormat(e[0],t),`=`,e[2]];if(e[1]===`?`)return[t.$.parseOwnDefinitionFormat(e[0],t),`?`]}return Vu(e,t)},iu=`Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }`,au=`Only required keys may specify default values, e.g. { value: 'number = 0' }`,ou=(e,t)=>{let n,r={},i=Wn(e);for(let[e,a]of i){let i=uu(e);if(i.kind===`spread`){if(!Un(r))return C(lu);let e=t.$.parseOwnDefinitionFormat(a,t);if(e.equals(q.object))continue;if(!e.hasKind(`intersection`)||!e.basis?.equals(q.object))return C(du(e.expression));n=e.structure;continue}if(i.kind===`undeclared`){a!==`reject`&&a!==`delete`&&a!==`ignore`&&C(cu(a)),r.undeclared=a;continue}let o=ru(a,t),s=i;if(i.kind===`required`){D(o)?su(r,`optional`,o[1]===`=`?{key:i.normalized,value:o[0],default:o[2]}:{key:i.normalized,value:o[0]},t):su(r,`required`,{key:i.normalized,value:o},t);continue}if(D(o)&&(o[1]===`?`&&C(iu),o[1]===`=`&&C(au)),i.kind===`optional`){su(r,`optional`,{key:i.normalized,value:o},t);continue}let c=t.$.parseOwnDefinitionFormat(s.normalized,t),l=fc(c,o,t.$);l.index&&(r.index=b(r.index,l.index)),l.required&&(r.required=b(r.required,l.required))}let a=t.$.node(`structure`,r);return t.$.parseSchema({domain:`object`,structure:n?.merge(a)??a})},su=(e,t,n,r)=>{e[t]=b(e[t],r.$.node(t,n))},cu=e=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${A(e)})`,lu=`Spread operator may only be used as the first key in an object`,uu=e=>typeof e==`symbol`?{kind:`required`,normalized:e}:e.at(-1)===`?`?e.at(-2)===yr?{kind:`required`,normalized:`${e.slice(0,-2)}?`}:{kind:`optional`,normalized:e.slice(0,-1)}:e[0]===`[`&&e.at(-1)===`]`?{kind:`index`,normalized:e.slice(1,-1)}:e[0]===yr&&e[1]===`[`&&e.at(-1)===`]`?{kind:`required`,normalized:e.slice(1)}:e===`...`?{kind:`spread`}:e===`+`?{kind:`undeclared`}:{kind:`required`,normalized:e===`\\...`?`...`:e===`\\+`?`+`:e},du=e=>`Spread operand must resolve to an object literal type (was ${e})`,fu=(e,t)=>Du(e)?Eu[e[0]](e,t):wu(e)?Cu[e[1]](e,t):null,pu=(e,t)=>t.$.parseOwnDefinitionFormat(e[1],t).keyof(),mu=(e,t)=>{if(e[2]===void 0)return C(wl(e[1],``));let n=t.$.parseOwnDefinitionFormat(e[0],t),r=t.$.parseOwnDefinitionFormat(e[2],t);if(e[1]===`|`)return t.$.node(`union`,{branches:[n,r]});let i=e[1]===`&`?B(n,r,t.$):ta(n,r,t.$);return i instanceof z?i.throw():i},hu=(e,t)=>t.$.parseOwnDefinitionFormat(e[0],t).array(),gu=(e,t)=>typeof e[2]==`function`?t.$.parseOwnDefinitionFormat(e[0],t).pipe(e[2]):C(_u(`=>`,e[2])),_u=(e,t)=>`${e===`:`?`Narrow`:`Morph`} expression requires a function following '${e}' (was ${typeof t})`,vu=(e,t)=>typeof e[2]==`function`?t.$.parseOwnDefinitionFormat(e[0],t).constrain(`predicate`,e[2]):C(_u(`:`,e[2])),yu=(e,t)=>t.$.parseOwnDefinitionFormat(e[0],t).configureDescendants(e[2],`shallow`),bu=e=>e,xu=bu({"[]":hu,"?":()=>C(al)}),Su=bu({"|":mu,"&":mu,":":vu,"=>":gu,"|>":mu,"@":yu,"=":()=>C(ol)}),Cu={...xu,...Su},wu=e=>Cu[e[1]]!==void 0,Tu=e=>e,Eu=Tu({keyof:pu,instanceof:(e,t)=>{if(typeof e[1]!=`function`)return C(Ou(er(e[1])));let n=e.slice(1).map(e=>typeof e==`function`?t.$.node(`proto`,{proto:e}):C(Ou(er(e))));return n.length===1?n[0]:t.$.node(`union`,{branches:n})},"===":(e,t)=>t.$.units(e.slice(1))}),Du=e=>Eu[e[0]]!==void 0,Ou=e=>`Expected a constructor following 'instanceof' operator (was ${e})`,ku=(e,t)=>{let n=[{}],r=0;for(;r<e.length;){let i=!1;e[r]===`...`&&r<e.length-1&&(i=!0,r++);let a=ru(e[r],t),[o,s,c]=D(a)?a:[a];if(r++,i){if(!o.extends(j.intrinsic.Array))return C(Fu(o.expression));n=n.flatMap(e=>o.distribute(t=>Pu(Ci(e),t)))}else n=n.map(e=>s===`?`?ju(e,o):s===`=`?Mu(e,o,c):Au(e,o))}return t.$.parseSchema(n.map(e=>Un(e)?{proto:Array,exactLength:0}:{proto:Array,sequence:e}))},Au=(e,t)=>e.defaultables||e.optionals?C(e.variadic?Zs:Lu):(e.variadic?e.postfix=b(e.postfix,t):e.prefix=b(e.prefix,t),e),ju=(e,t)=>e.variadic?C(Ru):(e.optionals=b(e.optionals,t),e),Mu=(e,t,n)=>e.variadic?C(Ru):e.optionals?C(zu):(e.defaultables=b(e.defaultables,[[t,n]]),e),Nu=(e,t)=>(e.postfix&&C(Iu),e.variadic?e.variadic.equals(t)||C(Iu):e.variadic=t.internal,e),Pu=(e,t)=>{let n=t.select({method:`find`,kind:`sequence`});return n?(n.prefix?.forEach(t=>Au(e,t)),n.optionals?.forEach(t=>ju(e,t)),n.variadic&&Nu(e,n.variadic),n.postfix?.forEach(t=>Au(e,t)),e):Nu(e,j.intrinsic.unknown)},Fu=e=>`Spread element must be an array (was ${e})`,Iu=`A tuple may have at most one variadic element`,Lu=`A required element may not follow an optional element`,Ru=`An optional element may not follow a variadic element`,zu=`A defaultable element may not follow an optional element without a default`,Bu={},Vu=(e,t)=>{if(typeof e==`string`){if(t.args&&Object.keys(t.args).some(t=>e.includes(t)))return Ul(e,t);let n=Bu[t.$.name]??={};return n[e]??=Ul(e,t)}return kn(e,`object`)?Hu(e,t):C(Wu(x(e)))},Hu=(e,t)=>{let n=$n(e);switch(n){case void 0:return P(e,`root`)?e:ou(e,t);case`Array`:return Uu(e,t);case`RegExp`:return t.$.node(`intersection`,{domain:`string`,pattern:e},{prereduced:!0});case`Function`:{let t=dr(e)?e():e;return P(t,`root`)?t:C(Wu(`Function`))}default:return C(Wu(n??A(e)))}},Uu=(e,t)=>fu(e,t)??ku(e,t),Wu=e=>`Type definitions must be strings or objects (was ${e})`;var Gu=class extends mr{constructor(e){let t=Object.assign({errors:Bi,hkt:O,$:e,raw:e.parse,module:e.constructor.module,scope:e.constructor.scope,define:e.define,match:e.match,generic:e.generic,schema:e.schema,keywords:e.ambient,unit:e.unit,enumerated:e.enumerated,instanceOf:e.instanceOf,valueOf:e.valueOf},e.ambientAttachments);super((...t)=>{if(t.length===1)return e.parse(t[0]);if(t.length===2&&typeof t[0]==`string`&&t[0][0]===`<`&&t[0].at(-1)===`>`){let n=t[0].slice(1,-1),r=e.parseGenericParams(n,{});return new ha(r,t[1],e,e,null)}return e.parse(t)},{bind:e,attach:t})}};const Ku=j;var qu=class e extends Oc{get ambientAttachments(){if(Ku.typeAttachments)return this.cacheGetter(`ambientAttachments`,w(Ku.typeAttachments,(e,t)=>[e,this.bindReference(t)]))}preparseOwnAliasEntry(e,t){let n=e.indexOf(`<`);if(n===-1){if(P(t,`module`)||P(t,`generic`))return[e,t];let n=this.name===`ark`?e:e===`root`?this.name:`${this.name}.${e}`,r=this.resolvedConfig.keywords?.[n];return r&&(t=[t,`@`,r]),[e,t]}e.at(-1)!==`>`&&C(`'>' must be the last character of a generic declaration in a scope`);let r=e.slice(0,n),i=e.slice(n+1,-1);return[r,()=>{let e=this.parseGenericParams(i,{alias:r}),n=pa(e,t,this);return n}]}parseGenericParams(e,t){return Yl(new Dl(e),[],this.createParseContext({...t,def:e,prefix:`generic`}))}normalizeRootScopeValue(e){return dr(e)&&!P(e,`generic`)?e():e}preparseOwnDefinitionFormat(e,t){return{...t,def:e,prefix:t.alias??`type`}}parseOwnDefinitionFormat(e,t){let n=t.alias&&t.alias in this.aliases;!n&&!t.args&&(t.args={this:t.id});let r=Vu(e,t);if(D(r)){if(r[1]===`=`)return C(ol);if(r[1]===`?`)return C(al)}return r}unit=e=>this.units([e]);valueOf=e=>this.units(qn(e));enumerated=(...e)=>this.units(e);instanceOf=e=>this.node(`proto`,{proto:e},{prereduced:!0});match=new Ql(this);declare=()=>({type:this.type});define(e){return e}type=new Gu(this);static scope=(t,n={})=>new e(t,n);static module=(e,t={})=>this.scope(e,t).export()};const Ju=Object.assign(qu.scope,{define:e=>e}),J=qu;var Yu=class extends O{};const Xu=K([`base`,q.object],[`props`,q.object])(e=>e.base.merge(e.props),Yu),Zu=J.module({Key:q.key,Merge:Xu});var Qu=class extends O{};const $u=K(`element`)(e=>{let t=e.element.exclude(q.Array),n=t.array();return t.rawOr(n).pipe(yn).distribute(e=>e.assertHasKind(`morph`).declareOut(n),G)},Qu),ed=J.module({root:q.Array,readonly:`root`,index:q.nonNegativeIntegerString,liftFrom:$u},{name:`Array`}),td=G([`string`,qr.FileConstructor]),nd=td.rawOr(td.array()),rd=G({meta:`an object representing parsed form data`,domain:`object`,index:{signature:`string`,value:nd}}),id=J.module({root:[`instanceof`,FormData],value:td,parsed:rd,parse:G({in:FormData,morphs:e=>{let t={};for(let[n,r]of e)if(n in t){let e=t[n];typeof e==`string`||e instanceof qr.FileConstructor?t[n]=[e,r]:e.push(r)}else t[n]=r;return t},declaredOut:rd})},{name:`FormData`}),ad=J.module({Int8:[`instanceof`,Int8Array],Uint8:[`instanceof`,Uint8Array],Uint8Clamped:[`instanceof`,Uint8ClampedArray],Int16:[`instanceof`,Int16Array],Uint16:[`instanceof`,Uint16Array],Int32:[`instanceof`,Int32Array],Uint32:[`instanceof`,Uint32Array],Float32:[`instanceof`,Float32Array],Float64:[`instanceof`,Float64Array],BigInt64:[`instanceof`,BigInt64Array],BigUint64:[`instanceof`,BigUint64Array]},{name:`TypedArray`}),od={Boolean:1,Number:1,String:1},sd=J.module({...w({...Jn,...Xn},(e,t)=>e in od?[]:[e,[`instanceof`,t]]),Array:ed,TypedArray:ad,FormData:id}),cd=G({domain:{domain:`number`,meta:`a number representing a Unix timestamp`},divisor:{rule:1,meta:`an integer representing a Unix timestamp`},min:{rule:-864e13,meta:`a Unix timestamp after -8640000000000000`},max:{rule:864e13,meta:`a Unix timestamp before 8640000000000000`},meta:`an integer representing a safe Unix timestamp`}),ld=G({domain:`number`,divisor:1}),ud=J.module({root:q.number,integer:ld,epoch:cd,safe:G({domain:{domain:`number`,numberAllowsNaN:!1},min:-9007199254740991,max:9007199254740991}),NaN:[`===`,NaN],Infinity:[`===`,1/0],NegativeInfinity:[`===`,-1/0]},{name:`number`}),Y=(e,t)=>zc(`intersection`,{domain:`string`,pattern:{rule:e.source,flags:e.flags,meta:t}}),dd=Y(jr,`a well-formed integer string`),fd=J.module({root:dd,parse:G({in:dd,morphs:(e,t)=>{let n=Number.parseInt(e);return Number.isSafeInteger(n)?n:t.error(`an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER`)},declaredOut:q.integer})},{name:`string.integer`}),pd=Y(/^[0-9a-fA-F]+$/,`hex characters only`),md=J.module({root:Y(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,`base64-encoded`),url:Y(/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2}(?:==|%3D%3D)?|[A-Za-z0-9_-]{3}(?:=|%3D)?)?$/,`base64url-encoded`)},{name:`string.base64`}),hd=Y(/^[A-Z].*$/,`capitalized`),gd=J.module({root:G({in:`string`,morphs:e=>e.charAt(0).toUpperCase()+e.slice(1),declaredOut:hd}),preformatted:hd},{name:`string.capitalize`}),_d=e=>{let t=e.replace(/[- ]+/g,``),n=0,r,i,a=!1;for(let e=t.length-1;e>=0;e--)r=t.substring(e,e+1),i=Number.parseInt(r,10),a?(i*=2,i>=10?n+=i%10+1:n+=i):n+=i,a=!a;return!!(n%10==0&&t)},vd=/^(?:4[0-9]{12}(?:[0-9]{3,6})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12,15}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11}|6[27][0-9]{14}|^(81[0-9]{14,17}))$/,yd=G({domain:`string`,pattern:{meta:`a credit card number`,rule:vd.source},predicate:{meta:`a credit card number`,predicate:_d}}),bd=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/,xd=e=>!Number.isNaN(new Date(e).valueOf()),Sd=G({domain:`string`,predicate:{meta:`a parsable date`,predicate:xd}}).assertHasKind(`intersection`),Cd=fd.root.internal.narrow((e,t)=>{let n=Number.parseInt(e),r=ud.epoch(n);return r instanceof Bi?(t.errors.merge(r),!1):!0}).withMeta({description:`an integer string representing a safe Unix timestamp`}).assertHasKind(`intersection`),wd=J.module({root:Cd,parse:G({in:Cd,morphs:e=>new Date(e),declaredOut:q.Date})},{name:`string.date.epoch`}),Td=Y(bd,`an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date`).internal.assertHasKind(`intersection`),Ed=J.module({root:Td,parse:G({in:Td,morphs:e=>new Date(e),declaredOut:q.Date})},{name:`string.date.iso`}),Dd=J.module({root:Sd,parse:G({declaredIn:Sd,in:`string`,morphs:(e,t)=>{let n=new Date(e);return Number.isNaN(n.valueOf())?t.error(`a parsable date`):n},declaredOut:q.Date}),iso:Ed,epoch:wd},{name:`string.date`}),Od=Y(/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/,`an email address`),kd=`(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])`,Ad=`(${kd}[.]){3}${kd}`,jd=RegExp(`^${Ad}$`),X=`(?:[0-9a-fA-F]{1,4})`,Md=RegExp(`^((?:${X}:){7}(?:${X}|:)|(?:${X}:){6}(?:${Ad}|:${X}|:)|(?:${X}:){5}(?::${Ad}|(:${X}){1,2}|:)|(?:${X}:){4}(?:(:${X}){0,1}:${Ad}|(:${X}){1,3}|:)|(?:${X}:){3}(?:(:${X}){0,2}:${Ad}|(:${X}){1,4}|:)|(?:${X}:){2}(?:(:${X}){0,3}:${Ad}|(:${X}){1,5}|:)|(?:${X}:){1}(?:(:${X}){0,4}:${Ad}|(:${X}){1,6}|:)|(?::((?::${X}){0,5}:${Ad}|(?::${X}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?\$`),Nd=J.module({root:[`v4 | v6`,`@`,`an IP address`],v4:Y(jd,`an IPv4 address`),v6:Y(Md,`an IPv6 address`)},{name:`string.ip`}),Pd=`a JSON string`,Fd=e=>{if(!(e instanceof SyntaxError))throw e;return`must be ${Pd} (${e})`},Id=G({meta:Pd,domain:`string`,predicate:{meta:Pd,predicate:(e,t)=>{try{return JSON.parse(e),!0}catch(e){return t.reject({code:`predicate`,expected:Pd,problem:Fd(e)})}}}}),Ld=(e,t)=>{if(e.length===0)return t.error({code:`predicate`,expected:Pd,actual:`empty`});try{return JSON.parse(e)}catch(e){return t.error({code:`predicate`,expected:Pd,problem:Fd(e)})}},Rd=J.module({root:Id,parse:G({meta:`safe JSON string parser`,in:`string`,morphs:Ld,declaredOut:q.jsonObject})},{name:`string.json`}),zd=Y(/^[a-z]*$/,`only lowercase letters`),Bd=J.module({root:G({in:`string`,morphs:e=>e.toLowerCase(),declaredOut:zd}),preformatted:zd},{name:`string.lower`}),Vd=[`NFC`,`NFD`,`NFKC`,`NFKD`],Hd=w(Vd,(e,t)=>[t,G({domain:`string`,predicate:e=>e.normalize(t)===e,meta:`${t}-normalized unicode`})]),Ud=w(Vd,(e,t)=>[t,G({in:`string`,morphs:e=>e.normalize(t),declaredOut:Hd[t]})]),Wd=J.module({root:Ud.NFC,preformatted:Hd.NFC},{name:`string.normalize.NFC`}),Gd=J.module({root:Ud.NFD,preformatted:Hd.NFD},{name:`string.normalize.NFD`}),Kd=J.module({root:Ud.NFKC,preformatted:Hd.NFKC},{name:`string.normalize.NFKC`}),qd=J.module({root:Ud.NFKD,preformatted:Hd.NFKD},{name:`string.normalize.NFKD`}),Jd=J.module({root:`NFC`,NFC:Wd,NFD:Gd,NFKC:Kd,NFKD:qd},{name:`string.normalize`}),Yd=Y(Or,`a well-formed numeric string`),Xd=J.module({root:Yd,parse:G({in:Yd,morphs:e=>Number.parseFloat(e),declaredOut:q.number})},{name:`string.numeric`}),Zd=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/,Qd=Y(Zd,`a semantic version (see https://semver.org/)`),$d=Y(/^\S.*\S$|^\S?$/,`trimmed`),ef=J.module({root:G({in:`string`,morphs:e=>e.trim(),declaredOut:$d}),preformatted:$d},{name:`string.trim`}),tf=Y(/^[A-Z]*$/,`only uppercase letters`),nf=J.module({root:G({in:`string`,morphs:e=>e.toUpperCase(),declaredOut:tf}),preformatted:tf},{name:`string.upper`}),rf=e=>{if(URL.canParse)return URL.canParse(e);try{return new URL(e),!0}catch{return!1}},af=G({domain:`string`,predicate:{meta:`a URL string`,predicate:rf}}),sf=J.module({root:af,parse:G({declaredIn:af,in:`string`,morphs:(e,t)=>{try{return new URL(e)}catch{return t.error(`a URL string`)}},declaredOut:G(URL)})},{name:`string.url`}),cf=J.module({root:[`versioned | nil | max`,`@`,`a UUID`],"#nil":`'00000000-0000-0000-0000-000000000000'`,"#max":`'ffffffff-ffff-ffff-ffff-ffffffffffff'`,"#versioned":/[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/i,v1:Y(/^[0-9a-f]{8}-[0-9a-f]{4}-1[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,`a UUIDv1`),v2:Y(/^[0-9a-f]{8}-[0-9a-f]{4}-2[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,`a UUIDv2`),v3:Y(/^[0-9a-f]{8}-[0-9a-f]{4}-3[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,`a UUIDv3`),v4:Y(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,`a UUIDv4`),v5:Y(/^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,`a UUIDv5`),v6:Y(/^[0-9a-f]{8}-[0-9a-f]{4}-6[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,`a UUIDv6`),v7:Y(/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,`a UUIDv7`),v8:Y(/^[0-9a-f]{8}-[0-9a-f]{4}-8[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,`a UUIDv8`)},{name:`string.uuid`}),lf=J.module({root:q.string,alpha:Y(/^[A-Za-z]*$/,`only letters`),alphanumeric:Y(/^[A-Za-z\d]*$/,`only letters and digits 0-9`),hex:pd,base64:md,capitalize:gd,creditCard:yd,date:Dd,digits:Y(/^\d*$/,`only digits 0-9`),email:Od,integer:fd,ip:Nd,json:Rd,lower:Bd,normalize:Jd,numeric:Xd,semver:Qd,trim:ef,upper:nf,url:sf,uuid:cf},{name:`string`}),uf=J.module({bigint:q.bigint,boolean:q.boolean,false:q.false,never:q.never,null:q.null,number:q.number,object:q.object,string:q.string,symbol:q.symbol,true:q.true,unknown:q.unknown,undefined:q.undefined}),df=J.module({root:q.unknown,any:q.unknown},{name:`unknown`}),ff=J.module({root:q.jsonObject,stringify:zc(`morph`,{in:q.jsonObject,morphs:e=>JSON.stringify(e),declaredOut:q.string})},{name:`object.json`}),pf=J.module({root:q.object,json:ff},{name:`object`});var mf=class extends O{description=`a generic type that instantiates an object from a single index signature and corresponding value type`};const hf=K([`K`,q.key],`V`)(e=>({domain:`object`,index:{signature:e.K,value:e.V}}),mf);var gf=class extends O{};const _f=K([`T`,q.object],[`K`,q.key])(e=>e.T.pick(e.K),gf);var vf=class extends O{};const yf=K([`T`,q.object],[`K`,q.key])(e=>e.T.omit(e.K),vf);var bf=class extends O{};const xf=K([`T`,q.object])(e=>e.T.partial(),bf);var Sf=class extends O{};const Cf=K([`T`,q.object])(e=>e.T.required(),Sf);var wf=class extends O{};const Tf=K(`T`,`U`)(e=>e.T.exclude(e.U),wf);var Ef=class extends O{};const Df=K(`T`,`U`)(e=>e.T.extract(e.U),Ef),Of=J.module({Exclude:Tf,Extract:Df,Omit:yf,Partial:xf,Pick:_f,Record:hf,Required:Cf}),kf=Ju({...uf,...Of,...sd,...Zu,string:lf,number:ud,object:pf,unknown:df},{prereducedAliases:!0,name:`ark`}),Z=kf.export();Object.assign(Ku.ambient,Z),Ku.typeAttachments={string:Z.string.root,number:Z.number.root,bigint:Z.bigint,boolean:Z.boolean,symbol:Z.symbol,undefined:Z.undefined,null:Z.null,object:Z.object.root,unknown:Z.unknown.root,false:Z.false,true:Z.true,never:Z.never,arrayIndex:Z.Array.index,Key:Z.Key,Record:Z.Record,Array:Z.Array.root,Date:Z.Date},Object.assign(kf.type,Ku.typeAttachments),kf.match,kf.generic,kf.schema,kf.define,kf.declare;function Af(e){return e}function jf(e){return e?t=>(e(t),t):Af}const Mf=jf();function Nf(e,t){return pn.get(`/v1/public/raven/games/${e}/builds/${t}`)}function Pf(e,t){return pn.post(`/v1/public/raven/games/${e}/builds/upload`,null,{params:t})}function Ff(e,t){let n=new FormData;return n.append(`file`,t.chunk),pn.patch(`/v1/public/raven/games/${e}/builds/upload`,n,{params:t})}function If(e){return e instanceof Error&&(e.name===`XiorError`||e.name===`XiorTimeoutError`)}function Lf(e){return!!(e&&`kind`in e.data&&`message`in e.data)}let Rf;function zf(e){Rf=e}var Bf=class extends et{UPDATE_CHECK_INTERVAL_MS=1e3*60*5;targetDir;updateInterval;constructor(){super(`NativeModuleManager`),this.targetDir=u.join(Ke(),`resources`),this.logger.log(`Target directory`,this.targetDir)}async initWithDlls(e){super.init(),await h.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),this.updateInterval=void 0),super.destroy()}async getCurrentVersion(e){try{let t=u.join(this.targetDir,e,`version.txt`);return await h.readFile(t,`utf-8`)}catch{return null}}getTargetPath(e){return u.join(this.targetDir,e)}getTargetVersionPath(e,t){return u.join(this.getTargetPath(e),t)}async checkForUpdates(e){let t=global.OVERLAYED.APP_BUILD_CHANNEL;if(this.logger.log(`Checking for updates`),!t){this.logger.error(`Invalid VITE_BUILD_CHANNEL`);return}await Rf?.();for(let n of e)try{let{data:e}=await hn(n,t),r=await this.getCurrentVersion(n);this.logger.log(`${n} > Update Check. current: ${r}, latest: ${e}`);let i=e!==r;this.logger.log(`${n} > Update found: ${r} -> ${e}`),await this.downloadAndExtractDll(n,e,t,i),this.logger.log(`${n} > Downloaded and extracted`),i&&(this.logger.log(`${n} > Cleaning up versions older than ${e}`),await this.cleanupOldVersions(n,e)),this.emit(`dllUpdated`,{identifier:n,version:e})}catch(e){this.logger.error(`${n} > Error checking/updating`,e)}}async downloadAndExtractDll(e,t,n,r){let{data:i}=await gn(e,n),a=this.getTargetPath(e),o=this.getTargetVersionPath(e,t);await h.mkdir(o,{recursive:!0});let s=new ae;await s.loadAsync(i);let c=Object.keys(s.files).map(async t=>{let n=s.files[t];if(n&&!n.dir){let i=u.join(o,t);if(!r)try{await h.access(i,h.constants.F_OK);return}catch{this.logger.warn(`${e} > File missing, re-downloading: ${i}`)}let a=await n.async(`nodebuffer`);await h.writeFile(i,a)}});await Promise.all(c);let l=u.join(a,`version.txt`);this.logger.log(`Saving version file`,l),await h.writeFile(l,t)}async cleanupOldVersions(e,t){let n=u.join(this.targetDir,e),r=await h.readdir(n,{withFileTypes:!0});for(let e of r)e.isDirectory()&&e.name!==t&&await h.rm(u.join(n,e.name),{recursive:!0,force:!0})}};const Vf=g(Bf);var Hf=class extends et{REFETCH_INTERVAL=1e3*60*5;FAILED_REFETCH_INTERVAL=1e3*30;_ravenConfig;_executableToGameMap=new Map;_executablesArray=[];_refetchIntervalHandler=null;_failedRefetchTimeoutHandler=null;constructor(){super(`RavenManager`)}init(){super.init(),this.fetchRavenConfig(),this._refetchIntervalHandler=setInterval(()=>{this._failedRefetchTimeoutHandler&&(clearTimeout(this._failedRefetchTimeoutHandler),this._failedRefetchTimeoutHandler=null),this.fetchRavenConfig()},this.REFETCH_INTERVAL)}getExecutableData(e){return this._executableToGameMap.get(e.toLowerCase())??null}get executables(){return this._executablesArray}get executablesMap(){return this._executableToGameMap}destroy(){this._refetchIntervalHandler&&clearInterval(this._refetchIntervalHandler),this._failedRefetchTimeoutHandler&&clearTimeout(this._failedRefetchTimeoutHandler),Vf.getInstance().destroy(),super.destroy()}async fetchRavenConfig(){try{let e=await vn(),t={games:[...e.data.games,{name:`Valorant`,identifier:Mf(`valorant`),executables:[`VALORANT-Win64-Shipping.exe`],modules:[]}]};this._ravenConfig=t,this.resetState();let n=new Set;for(let e of this._ravenConfig.games){for(let t of e.executables){let n=t.toLowerCase();this._executableToGameMap.set(n,e),this._executablesArray.push(n)}e.modules.forEach(e=>n.add(e))}await Vf.getInstance().initWithDlls(Array.from(n)),this.logger.log(`Raven updated`,this._ravenConfig),this.emit(`executablesUpdated`,{executables:this.executables,map:this._executableToGameMap})}catch(e){this.logger.error(`Failed to fetch Raven config`,e),this._failedRefetchTimeoutHandler=setTimeout(()=>this.fetchRavenConfig(),this.FAILED_REFETCH_INTERVAL)}}resetState(){this._executableToGameMap.clear(),this._executablesArray=[]}};const Uf=g(Hf),Wf=e(import.meta.url),{PipeEventServer:Gf,PipeEventClient:Kf,PipeEventBase:qf,ProcessMonitor:Jf,Process:Yf,InjectionMethod:Xf,AccessLevel:Zf,HardwareInterface:Qf}=Wf(`@overlayed/app/dist/native-interface/build/overlayed_native_interface_x64.node`);var $f=class extends et{_processMonitor;_processes=new Map;boundOnRavenManagerExecutablesUpdated=this.onRavenManagerExecutablesUpdated.bind(this);constructor(){super(`ProcessManager`),this._processMonitor=new Jf}get hasAnyActiveProcesses(){return this.activeProcesses.length>0}get activeProcesses(){return Array.from(this._processes.values()).flat().filter(e=>!e.destroyedAt)}init(){super.init(),Uf.getInstance().on(`executablesUpdated`,this.boundOnRavenManagerExecutablesUpdated),this._processMonitor.on(`create`,e=>{this.logger.log(`Process created`,e),this.addProcess(e),this.logger.log(`Active Process Count: ${this._processes.size}`),this.emit(`create`,{process:e})}),this._processMonitor.on(`destroy`,e=>{this.logger.log(`Process destroyed`,e),this.deleteProcess(e),this.logger.log(`Active Process Count: ${this._processes.size}`),this.emit(`destroy`,{process:e})})}destroy(){Uf.getInstance().off(`executablesUpdated`,this.boundOnRavenManagerExecutablesUpdated),this._processes.clear(),this._processMonitor.removeAllListeners(),super.destroy()}isProcessRunning(e){let t=this._processes.get(e);return t?.some(e=>!e.destroyedAt)??!1}onRavenManagerExecutablesUpdated(e){e.executables.forEach(e=>{this.logger.log(`Monitoring process`,e),this._processMonitor.registerProcess(e)})}addProcess(e){if(!e.name)return;let t=this._processes.get(e.name);if(!t){this._processes.set(e.name,[e]);return}this._processes.set(e.name,t.concat(e))}deleteProcess(e){if(!e.name)return;let t=this._processes.get(e.name),n=t?.filter(t=>t.id!==e.id)??[];n.length===0?this._processes.delete(e.name):this._processes.set(e.name,n)}};const ep=g($f),tp=e(import.meta.url),{RenderInterface:np,renderHookPath:rp}=tp(`@overlayed/app/dist/render-interface/build/overlayed_render_interface_x64.node`);var ip=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}}},ap=class{interfaces={};constructor(){}createInterface(e){return this.interfaces[e]||(this.interfaces[e]=new ip(new np(e,{access:1}))),this.interfaces[e]}getInterface(e){return this.interfaces[e]?this.interfaces[e]:this.createInterface(e)}};const op=g(ap);var sp=class{_clientId=null;_userId=null;options;eventQueue;set clientId(e){this._clientId=e}set userId(e){this._userId=e}constructor(e){this.options=this.resolveOptions(e),this.eventQueue=new Be,this.setupFlushInterval()}track(e,t){this.eventQueue.add({name:e,data:t,createdAt:new Date().toISOString()})}flush(){let e=Array.from(this.eventQueue.flush()),t=e.concat({name:`ping`,data:{},createdAt:new Date().toISOString()});return t}setupFlushInterval(){setInterval(()=>{this.flush()},this.options.batchIntervalSeconds*1e3)}resolveOptions(e){return{batchIntervalSeconds:e?.batchIntervalSeconds??15}}};const cp=g(sp),lp=e(import.meta.url),up=lp.resolve(`@overlayed/app/dist/render-interface/build/overlayed_render_hook_x64.dll`);var dp=class extends tt{boundOnProcessCreate=this.onProcessCreate.bind(this);boundOnProcessDestroy=this.onProcessDestroy.bind(this);subscribedGames=new Set;constructor(){super(`GameLaunchManager`)}setSubscribedGames(e){this.subscribedGames=new Set(e)}init(){super.init(),op.getInstance().createInterface(`OGG_SIEGE`),ep.getInstance().on(`create`,this.boundOnProcessCreate),ep.getInstance().on(`destroy`,this.boundOnProcessDestroy)}destroy(){ep.getInstance().off(`create`,this.boundOnProcessCreate),ep.getInstance().off(`destroy`,this.boundOnProcessDestroy),super.destroy()}async onProcessCreate({process:e}){let t=this.getRavenGame(e);if(!t)return;if(this.subscribedGames.size===0){this.logger.warn(`No subscribed games, skipping`);return}if(!this.subscribedGames.has(t.identifier)&&!this.subscribedGames.has(`*`))return;let n=new AbortController;if(await this.emit(`gameLaunch`,{game:t.identifier,reject:()=>n.abort}),n.signal.aborted)return;if(this.logger.log(`Game Launched`,t),this.logger.log(`Process is elevated: `,e.isElevated),this.logger.log(`Current process is elevated: `,Yf.currentProcess.isElevated),e.isElevated&&!Yf.currentProcess.isElevated){_.getInstance().fatal(`Game is elevated but the App is not`,`ELEVATION_MISMATCH`,{appElevated:!!Yf.currentProcess.isElevated,gameElevated:!!e.isElevated}),this.logger.log(`Game elevated but App is not`,{appElevated:Yf.currentProcess.isElevated,gameElevated:e.isElevated});return}let r=this.copyDll(up);if(r)try{await e.injectDll(r),this.logger.log(`Render Interface Injection Successful`,r)}catch(e){this.logger.error(`Render Interface Injection Failed`,e),this.logger.error(`Render Interface Injection Failed`,{renderInterfacePath:r})}let i=t?.modules.map(async t=>{let n=await Vf.getInstance().getCurrentVersion(t);if(!n)return this.logger.error(`No version found for DLL`,{identifier:t}),Promise.resolve();let r=Vf.getInstance().getTargetVersionPath(t,n);this.logger.log(`DLL Path`,r);let i=await this.getDllFiles(r);return this.logger.log(`DLL Files`,i),Promise.all(i.map(async t=>{let n=u.basename(t),i=u.join(r,n);if(!i)return Promise.resolve();this.logger.log(`Injecting: `,i);try{return e.injectDll(i).then(()=>{this.logger.log(`Injection Successful`,i)}).catch(e=>{this.logger.error(`Injection Failed [1]`,{targetPath:i},e)})}catch(e){return this.logger.error(`Injection Failed [2]`,{targetPath:i},e),Promise.reject(e)}}))});await Promise.allSettled(i),this.emit(`gameReadyInternal`,{ravenGame:t,process:e}),this.emit(`gameReady`,{game:t.identifier}),cp.getInstance().track(`game_launch`,{game:t.identifier})}copyDll(e){let t=u.basename(e),n=d(e),r=u.join(Ke(),`resources`),i=u.join(r,t);this.logger.info(`Copying`,n,`to`,i);try{m(r)||te(r,{recursive:!0});let e=ne(n);ie(i,e),f(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 getDllFiles(e){try{let t=await h.readdir(e);return t.filter(e=>e.endsWith(`.dll`)).map(t=>u.join(e,t))}catch(t){return this.logger.error(`Failed to read DLL directory`,t),this.logger.error(`Failed to read DLL directory`,{dllPath:e}),[]}}onProcessDestroy({process:e}){let t=this.getRavenGame(e);t&&(this.emit(`gameCloseInternal`,{ravenGame:t,process:e}),this.emit(`gameClose`,{game:t.identifier}),cp.getInstance().track(`game_close`,{game:t.identifier}))}getRavenGame(e){if(!e.name)return;let t=Uf.getInstance().getExecutableData(e.name);if(!t){this.logger.error(`No raven game found for process`,{process:e});return}return t}};const fp=g(dp);var pp=class extends $e{boundOnGameLaunch=this.onGameLaunch.bind(this);constructor(){super(`GameBuildManager`)}init(){super.init(),fp.getInstance().on(`gameReadyInternal`,this.boundOnGameLaunch)}destroy(){fp.getInstance().off(`gameReadyInternal`,this.boundOnGameLaunch),super.destroy()}async onGameLaunch(...e){let[{ravenGame:t,process:n}]=e;if(!n.path||!n.name){this.logger.error(`Process path or name not found, could not check for build hash`,void 0,n);return}let r=ne(n.path),i=oe(`sha256`).update(r).digest(`hex`);this.logger.log(`Process Path`,n.path),this.logger.log(`Process Name`,n.name),this.logger.log(`Build Hash`,i);let a=!1;try{let e=await Nf(t.identifier,i);a=e.data.upload}catch(e){this.logger.error(`Error checking game build hash`,e);return}if(!a){this.logger.log(`Build hash already exists, skipping upload`);return}let o=new ae;o.file(n.name,r);let s=await o.generateAsync({type:`blob`});try{this.logger.log(`Uploading build (size: `,s.size,` bytes)`);let e=new Ze(s,{chunkSizeMb:25,maxConcurrent:1}),n=await Pf(t.identifier,{build_hash:i,chunk_count:e.totalChunks,file_size_bytes:s.size});await e.chunk(async(e,r)=>{this.logger.log(`Uploading chunk`,r),await Ff(t.identifier,{chunk:e,build_hash:i,chunk_index:r,upload_token:n.data.upload_token})}),this.logger.log(`Build uploaded successfully`)}catch(e){If(e)?Lf(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)}}};const mp=g(pp);function hp(e=[]){return u.normalize(u.join(Je(global.OVERLAYED.APPLICATION_ID),...e))}const gp=t({game:`string`,type:`string`,creation_time:`number`});var Q=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}(Q||{});const _p=new Map([[Q.LeftButton,`LeftButton`],[Q.RightButton,`RightButton`],[Q.Cancel,`Cancel`],[Q.MiddleButton,`MiddleButton`],[Q.ExtraButton1,`ExtraButton1`],[Q.ExtraButton2,`ExtraButton2`],[Q.Back,`Backspace`],[Q.Tab,`Tab`],[Q.Clear,`Clear`],[Q.Return,`Enter`],[Q.Shift,`ShiftLeft`],[Q.Control,`ControlLeft`],[Q.Menu,`AltLeft`],[Q.Pause,`Pause`],[Q.CapsLock,`CapsLock`],[Q.Kana,`KanaMode`],[Q.Junja,`JunjaMode`],[Q.Final,`Finalize`],[Q.Hanja,`HanjaMode`],[Q.Escape,`Escape`],[Q.Convert,`Convert`],[Q.NonConvert,`NonConvert`],[Q.Accept,`Accept`],[Q.ModeChange,`ModeChange`],[Q.Space,`Space`],[Q.Prior,`PageUp`],[Q.Next,`PageDown`],[Q.End,`End`],[Q.Home,`Home`],[Q.Left,`ArrowLeft`],[Q.Up,`ArrowUp`],[Q.Right,`ArrowRight`],[Q.Down,`ArrowDown`],[Q.Select,`Select`],[Q.Print,`PrintScreen`],[Q.Execute,`Execute`],[Q.Snapshot,`Snapshot`],[Q.Insert,`Insert`],[Q.Delete,`Delete`],[Q.Help,`Help`],[Q.N0,`Digit0`],[Q.N1,`Digit1`],[Q.N2,`Digit2`],[Q.N3,`Digit3`],[Q.N4,`Digit4`],[Q.N5,`Digit5`],[Q.N6,`Digit6`],[Q.N7,`Digit7`],[Q.N8,`Digit8`],[Q.N9,`Digit9`],[Q.A,`KeyA`],[Q.B,`KeyB`],[Q.C,`KeyC`],[Q.D,`KeyD`],[Q.E,`KeyE`],[Q.F,`KeyF`],[Q.G,`KeyG`],[Q.H,`KeyH`],[Q.I,`KeyI`],[Q.J,`KeyJ`],[Q.K,`KeyK`],[Q.L,`KeyL`],[Q.M,`KeyM`],[Q.N,`KeyN`],[Q.O,`KeyO`],[Q.P,`KeyP`],[Q.Q,`KeyQ`],[Q.R,`KeyR`],[Q.S,`KeyS`],[Q.T,`KeyT`],[Q.U,`KeyU`],[Q.V,`KeyV`],[Q.W,`KeyW`],[Q.X,`KeyX`],[Q.Y,`KeyY`],[Q.Z,`KeyZ`],[Q.LeftWindows,`MetaLeft`],[Q.RightWindows,`MetaRight`],[Q.Application,`ContextMenu`],[Q.Sleep,`Sleep`],[Q.Numpad0,`Numpad0`],[Q.Numpad1,`Numpad1`],[Q.Numpad2,`Numpad2`],[Q.Numpad3,`Numpad3`],[Q.Numpad4,`Numpad4`],[Q.Numpad5,`Numpad5`],[Q.Numpad6,`Numpad6`],[Q.Numpad7,`Numpad7`],[Q.Numpad8,`Numpad8`],[Q.Numpad9,`Numpad9`],[Q.Multiply,`NumpadMultiply`],[Q.Add,`NumpadAdd`],[Q.Separator,`NumpadSeparator`],[Q.Subtract,`NumpadSubtract`],[Q.Decimal,`NumpadDecimal`],[Q.Divide,`NumpadDivide`],[Q.F1,`F1`],[Q.F2,`F2`],[Q.F3,`F3`],[Q.F4,`F4`],[Q.F5,`F5`],[Q.F6,`F6`],[Q.F7,`F7`],[Q.F8,`F8`],[Q.F9,`F9`],[Q.F10,`F10`],[Q.F11,`F11`],[Q.F12,`F12`],[Q.F13,`F13`],[Q.F14,`F14`],[Q.F15,`F15`],[Q.F16,`F16`],[Q.F17,`F17`],[Q.F18,`F18`],[Q.F19,`F19`],[Q.F20,`F20`],[Q.F21,`F21`],[Q.F22,`F22`],[Q.F23,`F23`],[Q.F24,`F24`],[Q.NumLock,`NumLock`],[Q.ScrollLock,`ScrollLock`],[Q.NEC_Equal,`NEC_Equal`],[Q.Fujitsu_Masshou,`Fujitsu_Masshou`],[Q.Fujitsu_Touroku,`Fujitsu_Touroku`],[Q.Fujitsu_Loya,`Fujitsu_Loya`],[Q.Fujitsu_Roya,`Fujitsu_Roya`],[Q.LeftShift,`ShiftLeft`],[Q.RightShift,`ShiftRight`],[Q.LeftControl,`ControlLeft`],[Q.RightControl,`ControlRight`],[Q.LeftMenu,`AltLeft`],[Q.RightMenu,`AltRight`],[Q.BrowserBack,`BrowserBack`],[Q.BrowserForward,`BrowserForward`],[Q.BrowserRefresh,`BrowserRefresh`],[Q.BrowserStop,`BrowserStop`],[Q.BrowserSearch,`BrowserSearch`],[Q.BrowserFavorites,`BrowserFavorites`],[Q.BrowserHome,`BrowserHome`],[Q.VolumeMute,`VolumeMute`],[Q.VolumeDown,`VolumeDown`],[Q.VolumeUp,`VolumeUp`],[Q.MediaNextTrack,`MediaTrackNext`],[Q.MediaPrevTrack,`MediaTrackPrevious`],[Q.MediaStop,`MediaStop`],[Q.MediaPlayPause,`MediaPlayPause`],[Q.LaunchMail,`LaunchMail`],[Q.LaunchMediaSelect,`LaunchMediaSelect`],[Q.LaunchApplication1,`LaunchApplication1`],[Q.LaunchApplication2,`LaunchApplication2`],[Q.OEM1,`OEM_1`],[Q.OEMPlus,`Equal`],[Q.OEMComma,`Comma`],[Q.OEMMinus,`Minus`],[Q.OEMPeriod,`Period`],[Q.OEM2,`Slash`],[Q.OEM3,`Backquote`],[Q.OEM4,`BracketLeft`],[Q.OEM5,`Backslash`],[Q.OEM6,`BracketRight`],[Q.OEM7,`Quote`],[Q.OEM8,`IntlRo`],[Q.OEMAX,`OEM_AX`],[Q.OEM102,`IntlBackslash`],[Q.ICOHelp,`ICO_HELP`],[Q.ICO00,`ICO_00`],[Q.ProcessKey,`Process`],[Q.ICOClear,`ICO_CLEAR`],[Q.Packet,`Packet`],[Q.OEMReset,`OEM_Reset`],[Q.OEMJump,`OEM_Jump`],[Q.OEMPA1,`OEM_PA1`],[Q.OEMPA2,`OEM_PA2`],[Q.OEMPA3,`OEM_PA3`],[Q.OEMWSCtrl,`OEM_WS_Ctrl`],[Q.OEMCUSel,`OEM_CU_Sel`],[Q.OEMATTN,`OEM_ATTN`],[Q.OEMFinish,`OEM_Finish`],[Q.OEMCopy,`OEM_Copy`],[Q.OEMAuto,`OEM_Auto`],[Q.OEMENLW,`OEM_ENLW`],[Q.OEMBackTab,`BackTab`],[Q.ATTN,`ATTN`],[Q.CRSel,`CRSel`],[Q.EXSel,`EXSel`],[Q.EREOF,`EREOF`],[Q.Play,`MediaPlay`],[Q.Zoom,`Zoom`],[Q.Noname,`Noname`],[Q.PA1,`PA1`],[Q.OEMClear,`OEM_Clear`]]),vp=new Map(_p.entries().map(([e,t])=>[t,e])),yp=t({"[string]":{keys:`string[]`,mode:t(`'toggle' | 'hold'`).pipe(e=>e??`toggle`)}});var bp=class extends et{preferencesKeybindToCallbacks=new Map;pressedKeys=new Set;activeKeybinds=new Set;triggeredToggleKeybinds=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 We({path:hp([`keybinds.json`]),schema:yp,default:e})}init(){super.init();let e=op.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)||{};n.toggle=t,this.preferencesKeybindToCallbacks.set(e,n)}async onKeybindDown(e,t){let n=this.preferencesKeybindToCallbacks.get(e)||{};n.down=t,this.preferencesKeybindToCallbacks.set(e,n)}async onKeybindUp(e,t){let n=this.preferencesKeybindToCallbacks.get(e)||{};n.up=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=op.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=_p.get(e.key);if(!t){this.logger.error(`Unknown key down`,e);return}this.pressedKeys.add(t),this.checkKeybindings()}handleKeyboardFocus(){this.pressedKeys.clear(),this.activeKeybinds.clear(),this.triggeredToggleKeybinds.clear()}async handleKeyUp(e){if(this.keybindListeningPaused)return;let t=_p.get(e.key);if(!t)return;this.pressedKeys.delete(t);let n=this.keybindsFile.get();for(let[e]of this.preferencesKeybindToCallbacks.entries()){let r=n[e];r.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)continue;let r=e[t];this.activeKeybinds.has(t)&&r.keys.some(e=>!this.pressedKeys.has(e))&&(this.activeKeybinds.delete(t),n.up(),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],i=r.keys.length===this.pressedKeys.size&&r.keys.every(e=>vp.has(e)?this.pressedKeys.has(e):!1);if(i){this.triggerKeybind(r,n,t);return}}for(let[t,n]of this.preferencesKeybindToCallbacks.entries()){let r=e[t],i=r.keys.every(e=>vp.has(e)?this.pressedKeys.has(e):(this.logger.error(`Unknown key`,e,r),!1));i&&this.triggerKeybind(r,n,t)}}triggerKeybind(e,t,n){let r=e.mode;if(r===`toggle`&&t.toggle&&!this.triggeredToggleKeybinds.has(n)){let r=t.toggle();this.triggeredToggleKeybinds.add(n),this.logger.log(r?`Keybind pressed rejected: ${r}`:`Keybind pressed accepted`,this.getKeybindToString(e))}if(r===`hold`&&t.down&&!this.activeKeybinds.has(n)){let r=t.down();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}`:``})`}},xp=class extends $e{renderInterface;globalCursorOverrideCount=new Set;globalMouseBlockCount=new Set;globalKeyboardBlockCount=new Set;keyInputBlocks={};constructor(e){super(`OverridesManager`),this.renderInterface=op.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]=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)}};const Sp=g(xp,`OGG_SIEGE`);var Cp=he((exports,t)=>{var n=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),r=n((e,t)=>{var n=new Set([`mouseDown`,`mouseUp`,`pointerDown`,`pointerUp`]),r=new WeakSet;function i(e,t,{allowHosts:i}={}){let{shell:a}=t;if(r.has(e))return;r.add(e);let o=e.webContents;function s(e){return!!(!c(e)||i?.includes(e.host))}function c(e){return new URL(o.getURL()).origin!==e.origin}let l=0;function u(){l=Date.now()}function d(){let e=Date.now()-l,t=e<150;return t||console.warn(`was not recently active`,e),t}if(process.platform===`win32`){let t={KEYDOWN:256,LBUTTONUP:514,MBUTTONUP:520,RBUTTONUP:517,XBUTTONUP:524,TOUCH:576};for(let n of Object.values(t))e.hookWindowMessage(n,u)}o.on(`input-event`,(e,t)=>{n.has(t.type)&&u()}),o.on(`will-navigate`,(e,t)=>{let n=e.url||t;if(console.log(`will-navigate`,n),!n)return;let r=new URL(n);if(!s(r)){if(!d()){console.log(`blocked navigation`,n),e.preventDefault();return}c(r)&&(console.log(`external navigation`,n),e.preventDefault(),a.openExternal(n))}}),o.session.on(`will-download`,(e,t)=>{let n=t.getURL();/^blob:/.test(n)||e.preventDefault()}),o.setWindowOpenHandler(e=>{console.log(`window-open`,e.url);let{url:t}=e,n=new URL(t);if(!s(n))return d()?(c(n)&&a.openExternal(e.url),{action:`deny`}):(console.log(`blocked navigation`,t),{action:`deny`})})}t.exports=i}),i=n((e,t)=>{var n=new Set([`Mozilla`,`AppleWebKit`,`Chrome`,`Safari`,`Gecko`,`Firefox`,`OPR`,`Edg`,`Version`,`Mobile`,`curl`,`PostmanRuntime`]);async function r(e,t,r){let{webContents:i}=e,a=await i.executeJavaScript(`navigator.userAgent`);a=a.match(/[^\/]+\/[^\s]+( \([^\)]+\))?/g).map(e=>e.trim()).filter(e=>{let[t]=e.split(`/`,1);return n.has(t)}).join(` `),i.setUserAgent(a),t.app.userAgentFallback=a}t.exports=r}),a=r(),o=i();function s(e,t,n={}){a(e,t,n.linkHandler),o(e,t,n.userAgent)}t.exports={setupRevUtils:s,setupLinkHandler:a,setUserAgent:o}}),wp=_e(Cp(),1);let Tp=!1,Ep;function Dp(e){let{init:t=!0}=e;if(Op(e),v.getInstance().init(e.applicationId),Tp)return Ep;function n(){Up(e);let t=new Map,r=jp(e.modules,t),i=Mp(),a=Fp(e.keybinds),o=Ip(),s=Lp(),c=zp(),l=Rp(),u=Bp();kp(e),Pp(e,t),Tp=!0,Ep={...r,...i,ads:c,keybinds:a,windows:o,input:s,cortex:l,hasAnyActiveProcesses:()=>ep.getInstance().hasAnyActiveProcesses,init:n,log:u,initialized:Tp}}return t?(n(),Ep):new Proxy({init:n},{get:(e,t)=>{if(t!==`init`&&!Tp)throw Error(`overlayed was called before initialized: ${t}`);return t===`init`?e[t]:Ep[t]}})}global.OVERLAYED=new Proxy({},{get:()=>{throw Error(`function overlayed was not called`)}});function Op(e){global.OVERLAYED={APPLICATION_ID:e.applicationId,APP_BUILD_CHANNEL:e.channel??`alpha`,APP_VERSION:e.version??ce.getVersion(),electron:e.electron}}function kp(e){let t=e.universal?[`*`]:e.modules.map(e=>e.key);fp.getInstance().setSubscribedGames(t),mp.getInstance().init(),fp.getInstance().init(),ep.getInstance().init(),Uf.getInstance().init();async function n(){let e=mn(global.OVERLAYED.APPLICATION_ID).then(e=>e.data),t=Qf.generateUniqueIdentifier();v.getInstance().log(`userId`,t);let n={...await e,userId:t};return v.getInstance().log(`appInfo`,n),n}let r;global.OVERLAYED.electron.ipcMain.handle(`getAppInfo`,async()=>(r=r??n(),r)),ce.on(`quit`,()=>{Ap()})}function Ap(){Uf.getInstance().destroy(),fp.getInstance().destroy(),mp.getInstance().destroy(),ep.getInstance().destroy(),op.getInstance().getInterface(`OGG_SIEGE`).destroy(),Re.getInstance().destroy(),_.getInstance().destroy()}function jp(e,t){return e.reduce((e,n)=>{let r=n.key;return e[r]={on(e,n){let i=Np(r,e),a=t.get(i)??new Set;a.add(n),t.set(i,a)},onAny(e){let n=Np(r,`*`),i=t.get(n)??new Set;i.add(e),t.set(n,i)},off(e,n){let i=Np(r,e),a=t.get(i)??new Set;a.delete(n),t.set(i,a)},offAny(e){let n=Np(r,`*`),i=t.get(n)??new Set;i.delete(e),t.set(n,i)}},e},{})}function Mp(){let e=_.getInstance(),t=fp.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]})}}}}function Np(e,t){return`${e}:${t}`}function Pp(e,n){let r=Re.getInstance();function i(r){let i=gp(r);if(i instanceof t.errors){_.getInstance().warn(`Invalid event`,`INVALID_EVENT`,{summary:i.summary});return}let a=e.modules.find(e=>e.key===i.game),o=a?.events.event;if(!o)return;let s=o(r);if(s instanceof t.errors){_.getInstance().warn(`Invalid event`,`INVALID_EVENT`,{summary:s.summary});return}let c=Np(a.key,s.type),l=Np(a.key,`*`),u=n.get(c),d=n.get(l),ee=[...Array.from(u??[]),...Array.from(d??[])];ee.length!==0&&ee.forEach(e=>{e(s)})}return r.on(`data`,e=>e.forEach(i)),r.on(`error`,e=>{_.getInstance().error(`Pipe server error`,`PIPE_SERVER_ERROR`,{error:e})}),r}function Fp(e){let t=new bp(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(),ce.on(`quit`,()=>{t.destroy()}),r}function Ip(){return{createWindow:e=>$().instance.newWindowInternal(se.BrowserWindow,e),on:(e,t)=>$().instance.on(e,t),off:(e,t)=>$().instance.off(e,t),once:(e,t)=>$().instance.once(e,t),addListener:(e,t)=>$().instance.addListener(e,t),removeListener:(e,t)=>$().instance.removeListener(e,t),removeAllListeners:()=>$().instance.removeAllListeners(),prependListener:(e,t)=>$().instance.prependListener(e,t),prependOnceListener:(e,t)=>$().instance.prependOnceListener(e,t),getActiveGameInfo:()=>{let e=$(),t=Re.getInstance();return{resolution:e.resolution,isConnected:t.hasConnection}}}}function Lp(){return{scope:e=>Sp.getInstance().scope(e),raw:{setGlobalMouseBlock:e=>$().instance.setGlobalMouseBlock(e),setGlobalKeyboardBlock:e=>$().instance.setGlobalKeyboardBlock(e),setGlobalCursorOverride:e=>$().instance.setGlobalCursorOverride(e),setKeyInputBlock:(e,t)=>$().instance.setKeyInputBlock(e,t),getGlobalMouseBlock:()=>$().instance.getGlobalMouseBlock(),getGlobalKeyboardBlock:()=>$().instance.getGlobalKeyboardBlock(),getGlobalCursorOverride:()=>$().instance.getGlobalCursorOverride(),getKeyInputBlock:e=>$().instance.getKeyInputBlock(e)}}}function Rp(){return{track:(e,t)=>cp.getInstance().track(`custom__${e}`,t)}}function zp(){return{registerWindow:e=>{(0,wp.setupRevUtils)(e,global.OVERLAYED.electron)}}}function Bp(){let e=new Xe(`app.log`);return e.init(global.OVERLAYED.APPLICATION_ID),{scope:t=>e.scope(t),info:t=>e.info(t),warn:t=>e.warn(t),error:t=>e.error(t),submitBugReport:async(e,t)=>{try{let n=Vp(t),r=await n.generateAsync({type:`base64`}),i=await Hp(e,r);return i?[void 0,{message:`Failed to submit bug report`,error:i}]:[!0,void 0]}catch(e){return[void 0,{message:`Failed to generate logs zip`,error:e}]}}}}function Vp(e){let t=Ye(global.OVERLAYED.APPLICATION_ID),n=Qe(t),r=qe(),i=Qe(r);v.getInstance().info(`Logs path: `,t),v.getInstance().info(`Overlayed logs path: `,r);let a=new ae;return[...n,...i].forEach(([e,t])=>{v.getInstance().info(`Zipping: `,e,t);let n=`${e}/${t}`,r=p(n);a.file(t,r,{compression:`DEFLATE`})}),Object.entries(e?.additionalFiles??{}).forEach(([e,t])=>{v.getInstance().info(`Zipping extra file: `,e),a.file(e,t,{compression:`DEFLATE`})}),a}async function Hp(e,t){let n={...e,version:`${global.OVERLAYED.APP_VERSION}@${global.OVERLAYED.APP_BUILD_CHANNEL}`,log_zip:`data:application/zip;base64,${t}`},r;return await fetch(`https://api.stats.cc/v1/overlay/contact`,{method:`POST`,body:JSON.stringify(n),redirect:`follow`,headers:{"Content-Type":`application/json`}}).then(async e=>{e.status>=300&&(r=await e.text())}).catch(e=>{r=e.message}),r}function Up(e){cp.getInstance().clientId=e.applicationId,cp.getInstance().userId=Qf.generateUniqueIdentifier(),_.getInstance().on(`fatal`,e=>{cp.getInstance().track(`fatal`,{message:e.message,code:e.code,data:e.data})}),_.getInstance().on(`error`,e=>{cp.getInstance().track(`error`,{message:e.message,code:e.code,data:e.data})}),_.getInstance().on(`warning`,e=>{cp.getInstance().track(`warning`,{message:e.message,code:e.code,data:e.data})})}function $(){return op.getInstance().getInterface(`OGG_SIEGE`)}export{Dp as overlayed,zf as setFetchLatestTokenCallback,fn as setUpdaterTokenResolver};
|
|
1
|
+
import{createRequire as e}from"node:module";import t from"mitt";import{Type as n,type as r}from"arktype";import i,{createWriteStream as a,existsSync as o,mkdirSync as s,readdirSync as c,unlinkSync as l,writeFileSync as u}from"fs";import{ensureFileSync as d}from"fs-extra";import{join as f}from"path";import p,{resolve as ee}from"node:path";import te from"events";import{copyFileSync as ne,createReadStream as re,existsSync as m,mkdirSync as ie,readFileSync as h,readdirSync as ae,writeFileSync as oe}from"node:fs";import"glob";import"jiti";import g from"xior";import _ from"fs/promises";import v from"jszip";import{createHash as se}from"node:crypto";import ce,{app as y}from"electron";var le=Object.create,b=Object.defineProperty,ue=Object.getOwnPropertyDescriptor,de=Object.getOwnPropertyNames,fe=Object.getPrototypeOf,pe=Object.prototype.hasOwnProperty,me=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),he=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=de(t),a=0,o=i.length,s;a<o;a++)s=i[a],!pe.call(e,s)&&s!==n&&b(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=ue(t,s))||r.enumerable});return e},ge=(e,t,n)=>(n=e==null?{}:le(fe(e)),he(t||!e||!e.__esModule?b(n,`default`,{value:e,enumerable:!0}):n,e)),_e=class{data=[];constructor(){}get size(){return this.data.length}add(e){this.data.push(e)}next(){return this.data.shift()}clear(){this.data.length=0}*flush(){for(;this.size>0;){let e=this.next();e&&(yield e)}}},x=class{emitter;constructor(){this.emitter=t()}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}emit(e,t){this.emitter.emit(e,t)}removeAllListeners(){this.emitter.all.clear()}},ve=class{listeners;constructor(){this.listeners=new Map}on(e,t){let n=this.listeners.get(e)||new Set;n.add(t),this.listeners.set(e,n)}off(e,t){let n=this.listeners.get(e);n&&n.delete(t)}async emit(e,...t){let n=this.listeners.get(e)||new Set,r=this.listeners.get(`*`)||new Set,i=[...Array.from(n),...Array.from(r)];if(i.length===0)return[];let a=await Promise.all(i.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}}));return a}removeAllListeners(){this.listeners.clear()}};function S(e,...t){let n=class extends e{static _instance;static getInstance(){return this._instance||(this._instance=new e(...t)),this._instance}static clearInstance(){this._instance=void 0}};return n}var ye=class extends x{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()})}};const C=S(ye);var be=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){this.reportInvalidConfigFile(t.issues);return}this.data=this.onBeforeSave(e),this.save(e)}get(){return this.data?this.data:this.load()}getKey(e){let t=this.get();return 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(){if(!this.fileExists(this.getFilePath())||!this.canReadWriteFile(this.getFilePath())){this.save(this._defaultValue);let e=this.onAfterLoad(this._defaultValue);return 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=r(`string.json.parse`).to(`object`),n=t(e);if(n instanceof r.errors)return this._defaultValue;let i=this._schema[`~standard`].validate(n);if(i instanceof Promise)throw Error(`StructuredConfigFile does not support async validation`);return i.issues?this.migrate(n,this._defaultValue):this.migrate(i.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){if(!Object.prototype.hasOwnProperty.call(t,r))continue;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){C.getInstance().error(`Invalid config file`,`INVALID_CONFIG_FILE`,{issues:e.map(e=>e.message),filePath:this._path,data:this.data})}},xe=class e extends x{stream;logPath;baseFileName;currentDate;rotationCheckInterval;isRotating=!1;constructor(e,t){super(),this.logPath=e,this.baseFileName=t.replace(`.log`,``),this.currentDate=this.getDateString(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(`log`,...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)}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=f(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.toISOString().split(`T`)[0]}createStream(){let e=f(this.logPath,this.getFileName(this.currentDate));return a(e,{flags:`a`,encoding:`utf8`})}async rotateLogs(){if(this.isRotating)return;this.isRotating=!0;let e=this.getDateString(new Date);e!==this.currentDate&&await new Promise(t=>{this.stream.end(()=>{this.currentDate=e,this.stream=this.createStream(),this.cleanupOldLogs(),t()})}),this.isRotating=!1}startRotationCheck(){return setInterval(()=>this.rotateLogs(),6e4)}cleanupOldLogs(){let e=c(this.logPath),t=new Date;t.setDate(t.getDate()-3),e.filter(e=>e.startsWith(this.baseFileName)&&e.endsWith(`.log`)).filter(e=>{let n=e.replace(`${this.baseFileName}-`,``).replace(`.log`,``),r=new Date(n);return r<t}).forEach(e=>{try{l(f(this.logPath,e))}catch(t){console.error(`Failed to delete old log file ${e}:`,t)}})}write(e,...t){let n=new Date,r=n.toISOString().replace(`T`,` `).replace(/\.\d+Z$/,``)+`.${n.getMilliseconds().toString().padStart(3,`0`)}`,i=t.map(e=>typeof e==`object`?JSON.stringify(e,void 0,2):String(e)).join(` `),a=`[${r}] [${e}] ${i}\n`;this.stream.write(a,e=>{e?this.emit(`error`,e):this.emit(`write`,a)})}};const w=()=>p.join(process.env.APPDATA??``,`overlayed`),Se=()=>p.join(w(),`logs`),T=e=>p.join(w(),`apps`,e),E=e=>p.join(T(e),`logs`);var D=class{fileLogger;path;appId;messageQueue=new _e;fileName;constructor(e){this.fileName=e}init(e){this.appId=e,this.path=E(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=`[${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)}}error(...e){this.handle(`error`,...e)}warn(...e){this.handle(`warn`,...e)}info(...e){this.handle(`log`,...e)}debug(...e){this.handle(`debug`,...e)}log(...e){this.handle(`log`,...e)}handle(e,...t){console[e](...t),this.fileLogger?this.fileLogger[e](...t):this.messageQueue.add({type:e,args:t})}};const O=S(D,`main.log`);var Ce=class extends te{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=5,i=new Map,a=new Set,o=new Set,s=[];for(let e=0;e<n;e++)s.push(e);let c=async n=>{let c=n*t,l=Math.min(c+t,this.blob.size),u=this.blob.slice(c,l);try{await e(u,n),o.add(n),this.emit(`chunkComplete`,n),a.delete(n)}catch(e){let t=i.get(n)||0;t<r?(i.set(n,t+1),await new Promise(e=>setTimeout(e,(t+1)*1e3)),s.push(n)):(o.add(n),this.emit(`error`,e),this.shouldStop=!0,a.delete(n))}},l=[],u=async()=>{for(;(s.length>0||a.size>0)&&!this.shouldStop;){if(s.length===0){await new Promise(e=>setTimeout(e,10));continue}let e=s.shift();o.has(e)||a.has(e)||(a.add(e),await c(e))}};for(let e=0;e<this.maxConcurrent;e++)l.push(u());await Promise.all(l)}};function k(e){return m(e)?ae(e).map(t=>[e,t]):[]}function we(e){return e}const Te=e(import.meta.url),{PipeEventServer:Ee,PipeEventClient:De,PipeEventBase:Oe,ProcessMonitor:ke,Process:Ae,InjectionMethod:je,AccessLevel:Me,HardwareInterface:Ne}=Te(`@overlayed/app/dist/native-interface/build/overlayed_native_interface_x64.node`);var Pe=class extends x{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=null)}init(){this.server=new Ee(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.server.on(`disconnected`,()=>{this._hasConnection=!1})}};const A=S(Pe,`stats-cc`);var j=class{logger;initialized=!1;constructor(e){this.logger=O.getInstance().scope(e)}init(){this.logger.log(`Initializing`),this.initialized=!0}destroy(){this.logger.log(`Destroying`),this.initialized=!1}},M=class extends x{logger;initialized=!1;constructor(e){super(),this.logger=O.getInstance().scope(e)}init(){this.logger.log(`Initializing`),this.initialized=!0}destroy(){this.logger.log(`Destroying`),this.initialized=!1,this.removeAllListeners()}},Fe=class extends ve{logger;initialized=!1;constructor(e){super(),this.logger=O.getInstance().scope(e)}init(){this.logger.log(`Initializing`),this.initialized=!0}destroy(){this.logger.log(`Destroying`),this.initialized=!1,this.removeAllListeners()}};const N=g.create({baseURL:`https://updater.stats.cc`,headers:{Accept:`application/json`,"Accept-Encoding":`gzip, deflate, br`}});let P;function Ie(e){P=e}N.interceptors.request.use(e=>{let t=P?.();return t?(e.headers??={},e.headers.Authorization=t,e):e});const F=g.create({baseURL:`https://api.overlayed.gg`,headers:{Accept:`application/json`,"Accept-Encoding":`gzip, deflate, br`}});let Le,Re;F.interceptors.request.use(e=>{let t=Le?.(),n=Re?.();return e.headers??={},t&&(e.headers.Authorization=t),n&&(e.headers[`X-Api-Key`]=n),e});function ze(e){return e}function I(e){return e?t=>(e(t),t):ze}I(),I();function Be(e){return F.get(`/v1/public/applications/${e}`)}I();function Ve(e,t){return N.get(`/v1/native/${L(e)}/version.txt`,{params:{channel:t},responseType:`text`})}function He(e,t){return N.get(`/v1/native/${L(e)}/files`,{params:{channel:t},responseType:`arraybuffer`})}function L(e){return e===`01JXPFK6YQ3N00N2Y9JHFNG55D`||e===`01JZEBPGHT5M4Y6SGY4P7Q9EZT`?`siege-game-module`:e}function Ue(){return F.get(`/v1/public/raven/config`)}const We=I();function Ge(e,t){return F.get(`/v1/public/raven/games/${e}/builds/${t}`)}function Ke(e,t){return F.post(`/v1/public/raven/games/${e}/builds/upload`,null,{params:t})}function qe(e,t){let n=new FormData;return n.append(`file`,t.chunk),F.patch(`/v1/public/raven/games/${e}/builds/upload`,n,{params:t})}function Je(e){return e instanceof Error&&(e.name===`XiorError`||e.name===`XiorTimeoutError`)}function Ye(e){return!!(e&&`kind`in e.data&&`message`in e.data)}let R;function Xe(e){R=e}var Ze=class extends M{UPDATE_CHECK_INTERVAL_MS=1e3*60*5;targetDir;updateInterval;constructor(){super(`NativeModuleManager`),this.targetDir=p.join(w(),`resources`),this.logger.log(`Target directory`,this.targetDir)}async initWithDlls(e){super.init(),await _.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),this.updateInterval=void 0),super.destroy()}async getCurrentVersion(e){try{let t=p.join(this.targetDir,e,`version.txt`);return await _.readFile(t,`utf-8`)}catch{return null}}getTargetPath(e){return p.join(this.targetDir,e)}getTargetVersionPath(e,t){return p.join(this.getTargetPath(e),t)}async checkForUpdates(e){let t=global.OVERLAYED.APP_BUILD_CHANNEL;if(this.logger.log(`Checking for updates`),!t){this.logger.error(`Invalid VITE_BUILD_CHANNEL`);return}await R?.();for(let n of e)try{let{data:e}=await Ve(n,t),r=await this.getCurrentVersion(n);this.logger.log(`${n} > Update Check. current: ${r}, latest: ${e}`);let i=e!==r;this.logger.log(`${n} > Update found: ${r} -> ${e}`),await this.downloadAndExtractDll(n,e,t,i),this.logger.log(`${n} > Downloaded and extracted`),i&&(this.logger.log(`${n} > Cleaning up versions older than ${e}`),await this.cleanupOldVersions(n,e)),this.emit(`dllUpdated`,{identifier:n,version:e})}catch(e){this.logger.error(`${n} > Error checking/updating`,e)}}async downloadAndExtractDll(e,t,n,r){let{data:i}=await He(e,n),a=this.getTargetPath(e),o=this.getTargetVersionPath(e,t);await _.mkdir(o,{recursive:!0});let s=new v;await s.loadAsync(i);let c=Object.keys(s.files).map(async t=>{let n=s.files[t];if(n&&!n.dir){let i=p.join(o,t);if(!r)try{await _.access(i,_.constants.F_OK);return}catch{this.logger.warn(`${e} > File missing, re-downloading: ${i}`)}let a=await n.async(`nodebuffer`);await _.writeFile(i,a)}});await Promise.all(c);let l=p.join(a,`version.txt`);this.logger.log(`Saving version file`,l),await _.writeFile(l,t)}async cleanupOldVersions(e,t){let n=p.join(this.targetDir,e),r=await _.readdir(n,{withFileTypes:!0});for(let e of r)e.isDirectory()&&e.name!==t&&await _.rm(p.join(n,e.name),{recursive:!0,force:!0})}};const z=S(Ze);var Qe=class extends M{REFETCH_INTERVAL=1e3*60*5;FAILED_REFETCH_INTERVAL=1e3*30;_ravenConfig;_executableToGameMap=new Map;_executablesArray=[];_refetchIntervalHandler=null;_failedRefetchTimeoutHandler=null;constructor(){super(`RavenManager`)}init(){super.init(),this.fetchRavenConfig(),this._refetchIntervalHandler=setInterval(()=>{this._failedRefetchTimeoutHandler&&(clearTimeout(this._failedRefetchTimeoutHandler),this._failedRefetchTimeoutHandler=null),this.fetchRavenConfig()},this.REFETCH_INTERVAL)}getExecutableData(e){return this._executableToGameMap.get(e.toLowerCase())??null}get executables(){return this._executablesArray}get executablesMap(){return this._executableToGameMap}destroy(){this._refetchIntervalHandler&&clearInterval(this._refetchIntervalHandler),this._failedRefetchTimeoutHandler&&clearTimeout(this._failedRefetchTimeoutHandler),z.getInstance().destroy(),super.destroy()}async fetchRavenConfig(){try{let e=await Ue(),t={games:[...e.data.games,{name:`Valorant`,identifier:We(`valorant`),executables:[`VALORANT-Win64-Shipping.exe`],modules:[]}]};this._ravenConfig=t,this.resetState();let n=new Set;for(let e of this._ravenConfig.games){for(let t of e.executables){let n=t.toLowerCase();this._executableToGameMap.set(n,e),this._executablesArray.push(n)}e.modules.forEach(e=>n.add(e))}await z.getInstance().initWithDlls(Array.from(n)),this.logger.log(`Raven updated`,this._ravenConfig),this.emit(`executablesUpdated`,{executables:this.executables,map:this._executableToGameMap})}catch(e){this.logger.error(`Failed to fetch Raven config`,e),this._failedRefetchTimeoutHandler=setTimeout(()=>this.fetchRavenConfig(),this.FAILED_REFETCH_INTERVAL)}}resetState(){this._executableToGameMap.clear(),this._executablesArray=[]}};const B=S(Qe),$e=e(import.meta.url),{PipeEventServer:et,PipeEventClient:tt,PipeEventBase:nt,ProcessMonitor:rt,Process:V,InjectionMethod:it,AccessLevel:at,HardwareInterface:H}=$e(`@overlayed/app/dist/native-interface/build/overlayed_native_interface_x64.node`);var ot=class extends M{_processMonitor;_processes=new Map;boundOnRavenManagerExecutablesUpdated=this.onRavenManagerExecutablesUpdated.bind(this);constructor(){super(`ProcessManager`),this._processMonitor=new rt}get hasAnyActiveProcesses(){return this.activeProcesses.length>0}get activeProcesses(){return Array.from(this._processes.values()).flat().filter(e=>!e.destroyedAt)}init(){super.init(),B.getInstance().on(`executablesUpdated`,this.boundOnRavenManagerExecutablesUpdated),this._processMonitor.on(`create`,e=>{this.logger.log(`Process created`,e),this.addProcess(e),this.logger.log(`Active Process Count: ${this._processes.size}`),this.emit(`create`,{process:e})}),this._processMonitor.on(`destroy`,e=>{this.logger.log(`Process destroyed`,e),this.deleteProcess(e),this.logger.log(`Active Process Count: ${this._processes.size}`),this.emit(`destroy`,{process:e})})}destroy(){B.getInstance().off(`executablesUpdated`,this.boundOnRavenManagerExecutablesUpdated),this._processes.clear(),this._processMonitor.removeAllListeners(),super.destroy()}isProcessRunning(e){let t=this._processes.get(e);return t?.some(e=>!e.destroyedAt)??!1}onRavenManagerExecutablesUpdated(e){e.executables.forEach(e=>{this.logger.log(`Monitoring process`,e),this._processMonitor.registerProcess(e)})}addProcess(e){if(!e.name)return;let t=this._processes.get(e.name);if(!t){this._processes.set(e.name,[e]);return}this._processes.set(e.name,t.concat(e))}deleteProcess(e){if(!e.name)return;let t=this._processes.get(e.name),n=t?.filter(t=>t.id!==e.id)??[];n.length===0?this._processes.delete(e.name):this._processes.set(e.name,n)}};const U=S(ot),st=e(import.meta.url),{RenderInterface:ct,renderHookPath:lt}=st(`@overlayed/app/dist/render-interface/build/overlayed_render_interface_x64.node`);var ut=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}}},dt=class{interfaces={};constructor(){}createInterface(e){return this.interfaces[e]||(this.interfaces[e]=new ut(new ct(e,{access:1}))),this.interfaces[e]}getInterface(e){return this.interfaces[e]?this.interfaces[e]:this.createInterface(e)}};const W=S(dt);var ft=class{_clientId=null;_userId=null;options;eventQueue;set clientId(e){this._clientId=e}set userId(e){this._userId=e}constructor(e){this.options=this.resolveOptions(e),this.eventQueue=new _e,this.setupFlushInterval()}track(e,t){this.eventQueue.add({name:e,data:t,createdAt:new Date().toISOString()})}flush(){let e=Array.from(this.eventQueue.flush()),t=e.concat({name:`ping`,data:{},createdAt:new Date().toISOString()});return t}setupFlushInterval(){setInterval(()=>{this.flush()},this.options.batchIntervalSeconds*1e3)}resolveOptions(e){return{batchIntervalSeconds:e?.batchIntervalSeconds??15}}};const G=S(ft),pt=e(import.meta.url),mt=pt.resolve(`@overlayed/app/dist/render-interface/build/overlayed_render_hook_x64.dll`);var ht=class extends Fe{boundOnProcessCreate=this.onProcessCreate.bind(this);boundOnProcessDestroy=this.onProcessDestroy.bind(this);subscribedGames=new Set;constructor(){super(`GameLaunchManager`)}setSubscribedGames(e){this.subscribedGames=new Set(e)}init(){super.init(),W.getInstance().createInterface(`OGG_SIEGE`),U.getInstance().on(`create`,this.boundOnProcessCreate),U.getInstance().on(`destroy`,this.boundOnProcessDestroy)}destroy(){U.getInstance().off(`create`,this.boundOnProcessCreate),U.getInstance().off(`destroy`,this.boundOnProcessDestroy),super.destroy()}async onProcessCreate({process:e}){let t=this.getRavenGame(e);if(!t)return;if(this.subscribedGames.size===0){this.logger.warn(`No subscribed games, skipping`);return}if(!this.subscribedGames.has(t.identifier)&&!this.subscribedGames.has(`*`))return;let n=new AbortController;if(await this.emit(`gameLaunch`,{game:t.identifier,reject:()=>n.abort}),n.signal.aborted)return;if(this.logger.log(`Game Launched`,t),this.logger.log(`Process is elevated: `,e.isElevated),this.logger.log(`Current process is elevated: `,V.currentProcess.isElevated),e.isElevated&&!V.currentProcess.isElevated){C.getInstance().fatal(`Game is elevated but the App is not`,`ELEVATION_MISMATCH`,{appElevated:!!V.currentProcess.isElevated,gameElevated:!!e.isElevated}),this.logger.log(`Game elevated but App is not`,{appElevated:V.currentProcess.isElevated,gameElevated:e.isElevated});return}let r=this.copyDll(mt);if(r)try{await e.injectDll(r),this.logger.log(`Render Interface Injection Successful`,r)}catch(e){this.logger.error(`Render Interface Injection Failed`,e),this.logger.error(`Render Interface Injection Failed`,{renderInterfacePath:r})}let i=t?.modules.map(async t=>{let n=await z.getInstance().getCurrentVersion(t);if(!n)return this.logger.error(`No version found for DLL`,{identifier:t}),Promise.resolve();let r=z.getInstance().getTargetVersionPath(t,n);this.logger.log(`DLL Path`,r);let i=await this.getDllFiles(r);return this.logger.log(`DLL Files`,i),Promise.all(i.map(async t=>{let n=p.basename(t),i=p.join(r,n);if(!i)return Promise.resolve();this.logger.log(`Injecting: `,i);try{return e.injectDll(i).then(()=>{this.logger.log(`Injection Successful`,i)}).catch(e=>{this.logger.error(`Injection Failed [1]`,{targetPath:i},e)})}catch(e){return this.logger.error(`Injection Failed [2]`,{targetPath:i},e),Promise.reject(e)}}))});await Promise.allSettled(i),this.emit(`gameReadyInternal`,{ravenGame:t,process:e}),this.emit(`gameReady`,{game:t.identifier}),G.getInstance().track(`game_launch`,{game:t.identifier})}copyDll(e){let t=p.basename(e),n=ee(e),r=p.join(w(),`resources`),i=p.join(r,t);this.logger.info(`Copying`,n,`to`,i);try{m(r)||ie(r,{recursive:!0});let e=h(n);oe(i,e),ne(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 getDllFiles(e){try{let t=await _.readdir(e);return t.filter(e=>e.endsWith(`.dll`)).map(t=>p.join(e,t))}catch(t){return this.logger.error(`Failed to read DLL directory`,t),this.logger.error(`Failed to read DLL directory`,{dllPath:e}),[]}}onProcessDestroy({process:e}){let t=this.getRavenGame(e);t&&(this.emit(`gameCloseInternal`,{ravenGame:t,process:e}),this.emit(`gameClose`,{game:t.identifier}),G.getInstance().track(`game_close`,{game:t.identifier}))}getRavenGame(e){if(!e.name)return;let t=B.getInstance().getExecutableData(e.name);if(!t){this.logger.error(`No raven game found for process`,{process:e});return}return t}};const K=S(ht);var gt=class extends j{boundOnGameLaunch=this.onGameLaunch.bind(this);constructor(){super(`GameBuildManager`)}init(){super.init(),K.getInstance().on(`gameReadyInternal`,this.boundOnGameLaunch)}destroy(){K.getInstance().off(`gameReadyInternal`,this.boundOnGameLaunch),super.destroy()}async onGameLaunch(...e){let[{ravenGame:t,process:n}]=e;if(!n.path||!n.name){this.logger.error(`Process path or name not found, could not check for build hash`,void 0,n);return}let r=h(n.path),i=se(`sha256`).update(r).digest(`hex`);this.logger.log(`Process Path`,n.path),this.logger.log(`Process Name`,n.name),this.logger.log(`Build Hash`,i);let a=!1;try{let e=await Ge(t.identifier,i);a=e.data.upload}catch(e){this.logger.error(`Error checking game build hash`,e);return}if(!a){this.logger.log(`Build hash already exists, skipping upload`);return}let o=new v;o.file(n.name,r);let s=await o.generateAsync({type:`blob`});try{this.logger.log(`Uploading build (size: `,s.size,` bytes)`);let e=new Ce(s,{chunkSizeMb:25,maxConcurrent:1}),n=await Ke(t.identifier,{build_hash:i,chunk_count:e.totalChunks,file_size_bytes:s.size});await e.chunk(async(e,r)=>{this.logger.log(`Uploading chunk`,r),await qe(t.identifier,{chunk:e,build_hash:i,chunk_index:r,upload_token:n.data.upload_token})}),this.logger.log(`Build uploaded successfully`)}catch(e){Je(e)?Ye(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)}}};const q=S(gt);function _t(e=[]){return p.normalize(p.join(T(global.OVERLAYED.APPLICATION_ID),...e))}const vt=r({game:`string`,type:`string`,creation_time:`number`});var J=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}(J||{});const Y=new Map([[J.LeftButton,`LeftButton`],[J.RightButton,`RightButton`],[J.Cancel,`Cancel`],[J.MiddleButton,`MiddleButton`],[J.ExtraButton1,`ExtraButton1`],[J.ExtraButton2,`ExtraButton2`],[J.Back,`Backspace`],[J.Tab,`Tab`],[J.Clear,`Clear`],[J.Return,`Enter`],[J.Shift,`ShiftLeft`],[J.Control,`ControlLeft`],[J.Menu,`AltLeft`],[J.Pause,`Pause`],[J.CapsLock,`CapsLock`],[J.Kana,`KanaMode`],[J.Junja,`JunjaMode`],[J.Final,`Finalize`],[J.Hanja,`HanjaMode`],[J.Escape,`Escape`],[J.Convert,`Convert`],[J.NonConvert,`NonConvert`],[J.Accept,`Accept`],[J.ModeChange,`ModeChange`],[J.Space,`Space`],[J.Prior,`PageUp`],[J.Next,`PageDown`],[J.End,`End`],[J.Home,`Home`],[J.Left,`ArrowLeft`],[J.Up,`ArrowUp`],[J.Right,`ArrowRight`],[J.Down,`ArrowDown`],[J.Select,`Select`],[J.Print,`PrintScreen`],[J.Execute,`Execute`],[J.Snapshot,`Snapshot`],[J.Insert,`Insert`],[J.Delete,`Delete`],[J.Help,`Help`],[J.N0,`Digit0`],[J.N1,`Digit1`],[J.N2,`Digit2`],[J.N3,`Digit3`],[J.N4,`Digit4`],[J.N5,`Digit5`],[J.N6,`Digit6`],[J.N7,`Digit7`],[J.N8,`Digit8`],[J.N9,`Digit9`],[J.A,`KeyA`],[J.B,`KeyB`],[J.C,`KeyC`],[J.D,`KeyD`],[J.E,`KeyE`],[J.F,`KeyF`],[J.G,`KeyG`],[J.H,`KeyH`],[J.I,`KeyI`],[J.J,`KeyJ`],[J.K,`KeyK`],[J.L,`KeyL`],[J.M,`KeyM`],[J.N,`KeyN`],[J.O,`KeyO`],[J.P,`KeyP`],[J.Q,`KeyQ`],[J.R,`KeyR`],[J.S,`KeyS`],[J.T,`KeyT`],[J.U,`KeyU`],[J.V,`KeyV`],[J.W,`KeyW`],[J.X,`KeyX`],[J.Y,`KeyY`],[J.Z,`KeyZ`],[J.LeftWindows,`MetaLeft`],[J.RightWindows,`MetaRight`],[J.Application,`ContextMenu`],[J.Sleep,`Sleep`],[J.Numpad0,`Numpad0`],[J.Numpad1,`Numpad1`],[J.Numpad2,`Numpad2`],[J.Numpad3,`Numpad3`],[J.Numpad4,`Numpad4`],[J.Numpad5,`Numpad5`],[J.Numpad6,`Numpad6`],[J.Numpad7,`Numpad7`],[J.Numpad8,`Numpad8`],[J.Numpad9,`Numpad9`],[J.Multiply,`NumpadMultiply`],[J.Add,`NumpadAdd`],[J.Separator,`NumpadSeparator`],[J.Subtract,`NumpadSubtract`],[J.Decimal,`NumpadDecimal`],[J.Divide,`NumpadDivide`],[J.F1,`F1`],[J.F2,`F2`],[J.F3,`F3`],[J.F4,`F4`],[J.F5,`F5`],[J.F6,`F6`],[J.F7,`F7`],[J.F8,`F8`],[J.F9,`F9`],[J.F10,`F10`],[J.F11,`F11`],[J.F12,`F12`],[J.F13,`F13`],[J.F14,`F14`],[J.F15,`F15`],[J.F16,`F16`],[J.F17,`F17`],[J.F18,`F18`],[J.F19,`F19`],[J.F20,`F20`],[J.F21,`F21`],[J.F22,`F22`],[J.F23,`F23`],[J.F24,`F24`],[J.NumLock,`NumLock`],[J.ScrollLock,`ScrollLock`],[J.NEC_Equal,`NEC_Equal`],[J.Fujitsu_Masshou,`Fujitsu_Masshou`],[J.Fujitsu_Touroku,`Fujitsu_Touroku`],[J.Fujitsu_Loya,`Fujitsu_Loya`],[J.Fujitsu_Roya,`Fujitsu_Roya`],[J.LeftShift,`ShiftLeft`],[J.RightShift,`ShiftRight`],[J.LeftControl,`ControlLeft`],[J.RightControl,`ControlRight`],[J.LeftMenu,`AltLeft`],[J.RightMenu,`AltRight`],[J.BrowserBack,`BrowserBack`],[J.BrowserForward,`BrowserForward`],[J.BrowserRefresh,`BrowserRefresh`],[J.BrowserStop,`BrowserStop`],[J.BrowserSearch,`BrowserSearch`],[J.BrowserFavorites,`BrowserFavorites`],[J.BrowserHome,`BrowserHome`],[J.VolumeMute,`VolumeMute`],[J.VolumeDown,`VolumeDown`],[J.VolumeUp,`VolumeUp`],[J.MediaNextTrack,`MediaTrackNext`],[J.MediaPrevTrack,`MediaTrackPrevious`],[J.MediaStop,`MediaStop`],[J.MediaPlayPause,`MediaPlayPause`],[J.LaunchMail,`LaunchMail`],[J.LaunchMediaSelect,`LaunchMediaSelect`],[J.LaunchApplication1,`LaunchApplication1`],[J.LaunchApplication2,`LaunchApplication2`],[J.OEM1,`OEM_1`],[J.OEMPlus,`Equal`],[J.OEMComma,`Comma`],[J.OEMMinus,`Minus`],[J.OEMPeriod,`Period`],[J.OEM2,`Slash`],[J.OEM3,`Backquote`],[J.OEM4,`BracketLeft`],[J.OEM5,`Backslash`],[J.OEM6,`BracketRight`],[J.OEM7,`Quote`],[J.OEM8,`IntlRo`],[J.OEMAX,`OEM_AX`],[J.OEM102,`IntlBackslash`],[J.ICOHelp,`ICO_HELP`],[J.ICO00,`ICO_00`],[J.ProcessKey,`Process`],[J.ICOClear,`ICO_CLEAR`],[J.Packet,`Packet`],[J.OEMReset,`OEM_Reset`],[J.OEMJump,`OEM_Jump`],[J.OEMPA1,`OEM_PA1`],[J.OEMPA2,`OEM_PA2`],[J.OEMPA3,`OEM_PA3`],[J.OEMWSCtrl,`OEM_WS_Ctrl`],[J.OEMCUSel,`OEM_CU_Sel`],[J.OEMATTN,`OEM_ATTN`],[J.OEMFinish,`OEM_Finish`],[J.OEMCopy,`OEM_Copy`],[J.OEMAuto,`OEM_Auto`],[J.OEMENLW,`OEM_ENLW`],[J.OEMBackTab,`BackTab`],[J.ATTN,`ATTN`],[J.CRSel,`CRSel`],[J.EXSel,`EXSel`],[J.EREOF,`EREOF`],[J.Play,`MediaPlay`],[J.Zoom,`Zoom`],[J.Noname,`Noname`],[J.PA1,`PA1`],[J.OEMClear,`OEM_Clear`]]),yt=new Map(Y.entries().map(([e,t])=>[t,e])),bt=r({"[string]":{keys:`string[]`,mode:r(`'toggle' | 'hold'`).pipe(e=>e??`toggle`)}});var xt=class extends M{preferencesKeybindToCallbacks=new Map;pressedKeys=new Set;activeKeybinds=new Set;triggeredToggleKeybinds=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 be({path:_t([`keybinds.json`]),schema:bt,default:e})}init(){super.init();let e=W.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)||{};n.toggle=t,this.preferencesKeybindToCallbacks.set(e,n)}async onKeybindDown(e,t){let n=this.preferencesKeybindToCallbacks.get(e)||{};n.down=t,this.preferencesKeybindToCallbacks.set(e,n)}async onKeybindUp(e,t){let n=this.preferencesKeybindToCallbacks.get(e)||{};n.up=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=W.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=Y.get(e.key);if(!t){this.logger.error(`Unknown key down`,e);return}this.pressedKeys.add(t),this.checkKeybindings()}handleKeyboardFocus(){this.pressedKeys.clear(),this.activeKeybinds.clear(),this.triggeredToggleKeybinds.clear()}async handleKeyUp(e){if(this.keybindListeningPaused)return;let t=Y.get(e.key);if(!t)return;this.pressedKeys.delete(t);let n=this.keybindsFile.get();for(let[e]of this.preferencesKeybindToCallbacks.entries()){let r=n[e];r.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)continue;let r=e[t];this.activeKeybinds.has(t)&&r.keys.some(e=>!this.pressedKeys.has(e))&&(this.activeKeybinds.delete(t),n.up(),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],i=r.keys.length===this.pressedKeys.size&&r.keys.every(e=>yt.has(e)?this.pressedKeys.has(e):!1);if(i){this.triggerKeybind(r,n,t);return}}for(let[t,n]of this.preferencesKeybindToCallbacks.entries()){let r=e[t],i=r.keys.every(e=>yt.has(e)?this.pressedKeys.has(e):(this.logger.error(`Unknown key`,e,r),!1));i&&this.triggerKeybind(r,n,t)}}triggerKeybind(e,t,n){let r=e.mode;if(r===`toggle`&&t.toggle&&!this.triggeredToggleKeybinds.has(n)){let r=t.toggle();this.triggeredToggleKeybinds.add(n),this.logger.log(r?`Keybind pressed rejected: ${r}`:`Keybind pressed accepted`,this.getKeybindToString(e))}if(r===`hold`&&t.down&&!this.activeKeybinds.has(n)){let r=t.down();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}`:``})`}},St=class extends j{renderInterface;globalCursorOverrideCount=new Set;globalMouseBlockCount=new Set;globalKeyboardBlockCount=new Set;keyInputBlocks={};constructor(e){super(`OverridesManager`),this.renderInterface=W.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]=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)}};const Ct=S(St,`OGG_SIEGE`);var wt=me((exports,t)=>{var n=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),r=n((e,t)=>{var n=new Set([`mouseDown`,`mouseUp`,`pointerDown`,`pointerUp`]),r=new WeakSet;function i(e,t,{allowHosts:i}={}){let{shell:a}=t;if(r.has(e))return;r.add(e);let o=e.webContents;function s(e){return!!(!c(e)||i?.includes(e.host))}function c(e){return new URL(o.getURL()).origin!==e.origin}let l=0;function u(){l=Date.now()}function d(){let e=Date.now()-l,t=e<150;return t||console.warn(`was not recently active`,e),t}if(process.platform===`win32`){let t={KEYDOWN:256,LBUTTONUP:514,MBUTTONUP:520,RBUTTONUP:517,XBUTTONUP:524,TOUCH:576};for(let n of Object.values(t))e.hookWindowMessage(n,u)}o.on(`input-event`,(e,t)=>{n.has(t.type)&&u()}),o.on(`will-navigate`,(e,t)=>{let n=e.url||t;if(console.log(`will-navigate`,n),!n)return;let r=new URL(n);if(!s(r)){if(!d()){console.log(`blocked navigation`,n),e.preventDefault();return}c(r)&&(console.log(`external navigation`,n),e.preventDefault(),a.openExternal(n))}}),o.session.on(`will-download`,(e,t)=>{let n=t.getURL();/^blob:/.test(n)||e.preventDefault()}),o.setWindowOpenHandler(e=>{console.log(`window-open`,e.url);let{url:t}=e,n=new URL(t);if(!s(n))return d()?(c(n)&&a.openExternal(e.url),{action:`deny`}):(console.log(`blocked navigation`,t),{action:`deny`})})}t.exports=i}),i=n((e,t)=>{var n=new Set([`Mozilla`,`AppleWebKit`,`Chrome`,`Safari`,`Gecko`,`Firefox`,`OPR`,`Edg`,`Version`,`Mobile`,`curl`,`PostmanRuntime`]);async function r(e,t,r){let{webContents:i}=e,a=await i.executeJavaScript(`navigator.userAgent`);a=a.match(/[^\/]+\/[^\s]+( \([^\)]+\))?/g).map(e=>e.trim()).filter(e=>{let[t]=e.split(`/`,1);return n.has(t)}).join(` `),i.setUserAgent(a),t.app.userAgentFallback=a}t.exports=r}),a=r(),o=i();function s(e,t,n={}){a(e,t,n.linkHandler),o(e,t,n.userAgent)}t.exports={setupRevUtils:s,setupLinkHandler:a,setUserAgent:o}}),Tt=ge(wt(),1);let X=!1,Z;function Et(e){let{init:t=!0}=e;if(Dt(e),O.getInstance().init(e.applicationId),X)return Z;function n(){Vt(e);let t=new Map,r=At(e.modules,t),i=jt(),a=Nt(e.keybinds),o=Pt(),s=Ft(),c=Lt(),l=It(),u=Rt();Ot(e),Mt(e,t),X=!0,Z={...r,...i,ads:c,keybinds:a,windows:o,input:s,cortex:l,hasAnyActiveProcesses:()=>U.getInstance().hasAnyActiveProcesses,init:n,log:u,initialized:X}}return t?(n(),Z):new Proxy({init:n},{get:(e,t)=>{if(t!==`init`&&!X)throw Error(`overlayed was called before initialized: ${t}`);return t===`init`?e[t]:Z[t]}})}global.OVERLAYED=new Proxy({},{get:()=>{throw Error(`function overlayed was not called`)}});function Dt(e){global.OVERLAYED={APPLICATION_ID:e.applicationId,APP_BUILD_CHANNEL:e.channel??`alpha`,APP_VERSION:e.version??y.getVersion(),electron:e.electron}}function Ot(e){let t=e.universal?[`*`]:e.modules.map(e=>e.key);K.getInstance().setSubscribedGames(t),q.getInstance().init(),K.getInstance().init(),U.getInstance().init(),B.getInstance().init();async function n(){let e=Be(global.OVERLAYED.APPLICATION_ID).then(e=>e.data),t=H.generateUniqueIdentifier();O.getInstance().log(`userId`,t);let n={...await e,userId:t};return O.getInstance().log(`appInfo`,n),n}let r;global.OVERLAYED.electron.ipcMain.handle(`getAppInfo`,async()=>(r=r??n(),r)),y.on(`quit`,()=>{kt()})}function kt(){B.getInstance().destroy(),K.getInstance().destroy(),q.getInstance().destroy(),U.getInstance().destroy(),W.getInstance().getInterface(`OGG_SIEGE`).destroy(),A.getInstance().destroy(),C.getInstance().destroy()}function At(e,t){return e.reduce((e,n)=>{let r=n.key;return e[r]={on(e,n){let i=Q(r,e),a=t.get(i)??new Set;a.add(n),t.set(i,a)},onAny(e){let n=Q(r,`*`),i=t.get(n)??new Set;i.add(e),t.set(n,i)},off(e,n){let i=Q(r,e),a=t.get(i)??new Set;a.delete(n),t.set(i,a)},offAny(e){let n=Q(r,`*`),i=t.get(n)??new Set;i.delete(e),t.set(n,i)}},e},{})}function jt(){let e=C.getInstance(),t=K.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]})}}}}function Q(e,t){return`${e}:${t}`}function Mt(e,t){let n=A.getInstance();function i(n){let i=vt(n);if(i instanceof r.errors){C.getInstance().warn(`Invalid event`,`INVALID_EVENT`,{summary:i.summary});return}let a=e.modules.find(e=>e.key===i.game),o=a?.events.event;if(!o)return;let s=o(n);if(s instanceof r.errors){C.getInstance().warn(`Invalid event`,`INVALID_EVENT`,{summary:s.summary});return}let c=Q(a.key,s.type),l=Q(a.key,`*`),u=t.get(c),d=t.get(l),f=[...Array.from(u??[]),...Array.from(d??[])];f.length!==0&&f.forEach(e=>{e(s)})}return n.on(`data`,e=>e.forEach(i)),n.on(`error`,e=>{C.getInstance().error(`Pipe server error`,`PIPE_SERVER_ERROR`,{error:e})}),n}function Nt(e){let t=new xt(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(),y.on(`quit`,()=>{t.destroy()}),r}function Pt(){return{createWindow:e=>$().instance.newWindowInternal(ce.BrowserWindow,e),on:(e,t)=>$().instance.on(e,t),off:(e,t)=>$().instance.off(e,t),once:(e,t)=>$().instance.once(e,t),addListener:(e,t)=>$().instance.addListener(e,t),removeListener:(e,t)=>$().instance.removeListener(e,t),removeAllListeners:()=>$().instance.removeAllListeners(),prependListener:(e,t)=>$().instance.prependListener(e,t),prependOnceListener:(e,t)=>$().instance.prependOnceListener(e,t),getActiveGameInfo:()=>{let e=$(),t=A.getInstance();return{resolution:e.resolution,isConnected:t.hasConnection}}}}function Ft(){return{scope:e=>Ct.getInstance().scope(e),raw:{setGlobalMouseBlock:e=>$().instance.setGlobalMouseBlock(e),setGlobalKeyboardBlock:e=>$().instance.setGlobalKeyboardBlock(e),setGlobalCursorOverride:e=>$().instance.setGlobalCursorOverride(e),setKeyInputBlock:(e,t)=>$().instance.setKeyInputBlock(e,t),getGlobalMouseBlock:()=>$().instance.getGlobalMouseBlock(),getGlobalKeyboardBlock:()=>$().instance.getGlobalKeyboardBlock(),getGlobalCursorOverride:()=>$().instance.getGlobalCursorOverride(),getKeyInputBlock:e=>$().instance.getKeyInputBlock(e)}}}function It(){return{track:(e,t)=>G.getInstance().track(`custom__${e}`,t)}}function Lt(){return{registerWindow:e=>{(0,Tt.setupRevUtils)(e,global.OVERLAYED.electron)}}}function Rt(){let e=new D(`app.log`);return e.init(global.OVERLAYED.APPLICATION_ID),{scope:t=>e.scope(t),info:t=>e.info(t),warn:t=>e.warn(t),error:t=>e.error(t),submitBugReport:async(e,t)=>{try{let n=zt(t),r=await n.generateAsync({type:`base64`}),i=await Bt(e,r);return i?[void 0,{message:`Failed to submit bug report`,error:i}]:[!0,void 0]}catch(e){return[void 0,{message:`Failed to generate logs zip`,error:e}]}}}}function zt(e){let t=E(global.OVERLAYED.APPLICATION_ID),n=k(t),r=Se(),i=k(r);O.getInstance().info(`Logs path: `,t),O.getInstance().info(`Overlayed logs path: `,r);let a=new v;return[...n,...i].forEach(([e,t])=>{O.getInstance().info(`Zipping: `,e,t);let n=`${e}/${t}`,r=re(n);a.file(t,r,{compression:`DEFLATE`})}),Object.entries(e?.additionalFiles??{}).forEach(([e,t])=>{O.getInstance().info(`Zipping extra file: `,e),a.file(e,t,{compression:`DEFLATE`})}),a}async function Bt(e,t){let n={...e,version:`${global.OVERLAYED.APP_VERSION}@${global.OVERLAYED.APP_BUILD_CHANNEL}`,log_zip:`data:application/zip;base64,${t}`},r;return await fetch(`https://api.stats.cc/v1/overlay/contact`,{method:`POST`,body:JSON.stringify(n),redirect:`follow`,headers:{"Content-Type":`application/json`}}).then(async e=>{e.status>=300&&(r=await e.text())}).catch(e=>{r=e.message}),r}function Vt(e){G.getInstance().clientId=e.applicationId,G.getInstance().userId=H.generateUniqueIdentifier(),C.getInstance().on(`fatal`,e=>{G.getInstance().track(`fatal`,{message:e.message,code:e.code,data:e.data})}),C.getInstance().on(`error`,e=>{G.getInstance().track(`error`,{message:e.message,code:e.code,data:e.data})}),C.getInstance().on(`warning`,e=>{G.getInstance().track(`warning`,{message:e.message,code:e.code,data:e.data})})}function $(){return W.getInstance().getInterface(`OGG_SIEGE`)}export{we as defineConfig,Et as overlayed,Xe as setFetchLatestTokenCallback,Ie as setUpdaterTokenResolver};
|