@overlayed/app 0.13.1 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +216 -8
- package/dist/index.js +24 -17
- package/dist/siege.d.ts +8 -9
- package/package.json +9 -9
package/dist/index.js
CHANGED
|
@@ -1,30 +1,37 @@
|
|
|
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:
|
|
1
|
+
import{createRequire as e}from"node:module";import{Type as t,type as n}from"arktype";import r,{createWriteStream as i,existsSync as a,lstatSync as o,mkdirSync as s,readdir as c,readdirSync as l,readlinkSync as u,realpathSync as d,unlinkSync as f,writeFileSync as p}from"fs";import{join as m}from"path";import h,{posix as g,resolve as _,win32 as v}from"node:path";import*as y from"node:fs";import{copyFileSync as ee,createReadStream as te,existsSync as ne,mkdirSync as re,readFileSync as ie,readdirSync as ae,writeFileSync as oe}from"node:fs";import{fileURLToPath as se}from"node:url";import{lstat as ce,readdir as le,readlink as ue,realpath as de}from"node:fs/promises";import{EventEmitter as fe}from"node:events";import pe from"node:stream";import{StringDecoder as me}from"node:string_decoder";import he from"events";import ge from"fs/promises";import _e from"jszip";import{createHash as ve}from"node:crypto";import ye,{app as be}from"electron";var xe=Object.create,Se=Object.defineProperty,Ce=Object.getOwnPropertyDescriptor,we=Object.getOwnPropertyNames,Te=Object.getPrototypeOf,Ee=Object.prototype.hasOwnProperty,De=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Oe=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=we(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Ee.call(e,s)&&s!==n&&Se(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Ce(t,s))||r.enumerable});return e},ke=(e,t,n)=>(n=e==null?{}:xe(Te(e)),Oe(t||!e||!e.__esModule?Se(n,`default`,{value:e,enumerable:!0}):n,e));function Ae(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 je=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)}}};const Me=(e,t,n)=>{let r=e instanceof RegExp?Ne(e,n):e,i=t instanceof RegExp?Ne(t,n):t,a=r!==null&&i!=null&&Pe(r,i,n);return a&&{start:a[0],end:a[1],pre:n.slice(0,a[0]),body:n.slice(a[0]+r.length,a[1]),post:n.slice(a[1]+i.length)}},Ne=(e,t)=>{let n=t.match(e);return n?n[0]:null},Pe=(e,t,n)=>{let r,i,a,o,s,c=n.indexOf(e),l=n.indexOf(t,c+1),u=c;if(c>=0&&l>0){if(e===t)return[c,l];for(r=[],a=n.length;u>=0&&!s;){if(u===c)r.push(u),c=n.indexOf(e,u+1);else if(r.length===1){let e=r.pop();e!==void 0&&(s=[e,l])}else i=r.pop(),i!==void 0&&i<a&&(a=i,o=l),l=n.indexOf(t,u+1);u=c<l&&c>=0?c:l}r.length&&o!==void 0&&(s=[a,o])}return s},Fe=`\0SLASH`+Math.random()+`\0`,Ie=`\0OPEN`+Math.random()+`\0`,Le=`\0CLOSE`+Math.random()+`\0`,Re=`\0COMMA`+Math.random()+`\0`,ze=`\0PERIOD`+Math.random()+`\0`,Be=new RegExp(Fe,`g`),Ve=new RegExp(Ie,`g`),He=new RegExp(Le,`g`),Ue=new RegExp(Re,`g`),We=new RegExp(ze,`g`),Ge=/\\\\/g,Ke=/\\{/g,qe=/\\}/g,Je=/\\,/g,Ye=/\\./g;function Xe(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function Ze(e){return e.replace(Ge,Fe).replace(Ke,Ie).replace(qe,Le).replace(Je,Re).replace(Ye,ze)}function Qe(e){return e.replace(Be,`\\`).replace(Ve,`{`).replace(He,`}`).replace(Ue,`,`).replace(We,`.`)}function $e(e){if(!e)return[``];let t=[],n=Me(`{`,`}`,e);if(!n)return e.split(`,`);let{pre:r,body:i,post:a}=n,o=r.split(`,`);o[o.length-1]+=`{`+i+`}`;let s=$e(a);return a.length&&(o[o.length-1]+=s.shift(),o.push.apply(o,s)),t.push.apply(t,o),t}function et(e){return e?(e.slice(0,2)===`{}`&&(e=`\\{\\}`+e.slice(2)),at(Ze(e),!0).map(Qe)):[]}function tt(e){return`{`+e+`}`}function nt(e){return/^-?0\d/.test(e)}function rt(e,t){return e<=t}function it(e,t){return e>=t}function at(e,t){let n=[],r=Me(`{`,`}`,e);if(!r)return[e];let i=r.pre,a=r.post.length?at(r.post,!1):[``];if(/\$$/.test(r.pre))for(let e=0;e<a.length;e++){let t=i+`{`+r.body+`}`+a[e];n.push(t)}else{let o=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(r.body),s=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(r.body),c=o||s,l=r.body.indexOf(`,`)>=0;if(!c&&!l)return r.post.match(/,(?!,).*\}/)?(e=r.pre+`{`+r.body+Le+r.post,at(e)):[e];let u;if(c)u=r.body.split(/\.\./);else if(u=$e(r.body),u.length===1&&u[0]!==void 0&&(u=at(u[0],!1).map(tt),u.length===1))return a.map(e=>r.pre+u[0]+e);let d;if(c&&u[0]!==void 0&&u[1]!==void 0){let e=Xe(u[0]),t=Xe(u[1]),n=Math.max(u[0].length,u[1].length),r=u.length===3&&u[2]!==void 0?Math.abs(Xe(u[2])):1,i=rt,a=t<e;a&&(r*=-1,i=it);let o=u.some(nt);d=[];for(let a=e;i(a,t);a+=r){let e;if(s)e=String.fromCharCode(a),e===`\\`&&(e=``);else if(e=String(a),o){let t=n-e.length;if(t>0){let n=Array(t+1).join(`0`);e=a<0?`-`+n+e.slice(1):n+e}}d.push(e)}}else{d=[];for(let e=0;e<u.length;e++)d.push.apply(d,at(u[e],!1))}for(let e=0;e<d.length;e++)for(let r=0;r<a.length;r++){let o=i+d[e]+a[r];(!t||c||o)&&n.push(o)}}return n}const ot=1024*64,st=e=>{if(typeof e!=`string`)throw TypeError(`invalid pattern`);if(e.length>ot)throw TypeError(`pattern is too long`)},ct={"[:alnum:]":[`\\p{L}\\p{Nl}\\p{Nd}`,!0],"[:alpha:]":[`\\p{L}\\p{Nl}`,!0],"[:ascii:]":[`\\x00-\\x7f`,!1],"[:blank:]":[`\\p{Zs}\\t`,!0],"[:cntrl:]":[`\\p{Cc}`,!0],"[:digit:]":[`\\p{Nd}`,!0],"[:graph:]":[`\\p{Z}\\p{C}`,!0,!0],"[:lower:]":[`\\p{Ll}`,!0],"[:print:]":[`\\p{C}`,!0],"[:punct:]":[`\\p{P}`,!0],"[:space:]":[`\\p{Z}\\t\\r\\n\\v\\f`,!0],"[:upper:]":[`\\p{Lu}`,!0],"[:word:]":[`\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}`,!0],"[:xdigit:]":[`A-Fa-f0-9`,!1]},lt=e=>e.replace(/[[\]\\-]/g,`\\$&`),ut=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),dt=e=>e.join(``),ft=(e,t)=>{let n=t;if(e.charAt(n)!==`[`)throw Error(`not in a brace expression`);let r=[],i=[],a=n+1,o=!1,s=!1,c=!1,l=!1,u=n,d=``;WHILE:for(;a<e.length;){let t=e.charAt(a);if((t===`!`||t===`^`)&&a===n+1){l=!0,a++;continue}if(t===`]`&&o&&!c){u=a+1;break}if(o=!0,t===`\\`&&!c){c=!0,a++;continue}if(t===`[`&&!c){for(let[t,[o,c,l]]of Object.entries(ct))if(e.startsWith(t,a)){if(d)return[`$.`,!1,e.length-n,!0];a+=t.length,l?i.push(o):r.push(o),s=s||c;continue WHILE}}if(c=!1,d){t>d?r.push(lt(d)+`-`+lt(t)):t===d&&r.push(lt(t)),d=``,a++;continue}if(e.startsWith(`-]`,a+1)){r.push(lt(t+`-`)),a+=2;continue}if(e.startsWith(`-`,a+1)){d=t,a+=2;continue}r.push(lt(t)),a++}if(u<a)return[``,!1,0,!1];if(!r.length&&!i.length)return[`$.`,!1,e.length-n,!0];if(i.length===0&&r.length===1&&/^\\?.$/.test(r[0])&&!l){let e=r[0].length===2?r[0].slice(-1):r[0];return[ut(e),!1,u-n,!1]}let f=`[`+(l?`^`:``)+dt(r)+`]`,p=`[`+(l?``:`^`)+dt(i)+`]`,m=r.length&&i.length?`(`+f+`|`+p+`)`:r.length?f:p;return[m,s,u-n,!0]},pt=(e,{windowsPathsNoEscape:t=!1}={})=>t?e.replace(/\[([^\/\\])\]/g,`$1`):e.replace(/((?!\\).|^)\[([^\/\\])\]/g,`$1$2`).replace(/\\([^\/])/g,`$1`),mt=new Set([`!`,`?`,`+`,`*`,`@`]),ht=e=>mt.has(e),gt=`(?!(?:^|/)\\.\\.?(?:$|/))`,_t=`(?!\\.)`,vt=new Set([`[`,`.`]),yt=new Set([`..`,`.`]),bt=new Set(`().*{}+?[]^$\\!`),xt=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),St=`[^/]`,Ct=St+`*?`,wt=St+`+?`;var Tt=class e{type;#root;#hasMagic;#uflag=!1;#parts=[];#parent;#parentIndex;#negs;#filledNegs=!1;#options;#toString;#emptyExt=!1;constructor(e,t,n={}){this.type=e,e&&(this.#hasMagic=!0),this.#parent=t,this.#root=this.#parent?this.#parent.#root:this,this.#options=this.#root===this?n:this.#root.#options,this.#negs=this.#root===this?[]:this.#root.#negs,e===`!`&&!this.#root.#filledNegs&&this.#negs.push(this),this.#parentIndex=this.#parent?this.#parent.#parts.length:0}get hasMagic(){if(this.#hasMagic!==void 0)return this.#hasMagic;for(let e of this.#parts){if(typeof e==`string`)continue;if(e.type||e.hasMagic)return this.#hasMagic=!0}return this.#hasMagic}toString(){return this.#toString===void 0?this.type?this.#toString=this.type+`(`+this.#parts.map(e=>String(e)).join(`|`)+`)`:this.#toString=this.#parts.map(e=>String(e)).join(``):this.#toString}#fillNegs(){if(this!==this.#root)throw Error(`should only call on root`);if(this.#filledNegs)return this;this.toString(),this.#filledNegs=!0;let e;for(;e=this.#negs.pop();){if(e.type!==`!`)continue;let t=e,n=t.#parent;for(;n;){for(let r=t.#parentIndex+1;!n.type&&r<n.#parts.length;r++)for(let t of e.#parts){if(typeof t==`string`)throw Error(`string part in extglob AST??`);t.copyIn(n.#parts[r])}t=n,n=t.#parent}}return this}push(...t){for(let n of t){if(n===``)continue;if(typeof n!=`string`&&!(n instanceof e&&n.#parent===this))throw Error(`invalid part: `+n);this.#parts.push(n)}}toJSON(){let e=this.type===null?this.#parts.slice().map(e=>typeof e==`string`?e:e.toJSON()):[this.type,...this.#parts.map(e=>e.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#root||this.#root.#filledNegs&&this.#parent?.type===`!`)&&e.push({}),e}isStart(){if(this.#root===this)return!0;if(!this.#parent?.isStart())return!1;if(this.#parentIndex===0)return!0;let t=this.#parent;for(let n=0;n<this.#parentIndex;n++){let r=t.#parts[n];if(!(r instanceof e&&r.type===`!`))return!1}return!0}isEnd(){if(this.#root===this||this.#parent?.type===`!`)return!0;if(!this.#parent?.isEnd())return!1;if(!this.type)return this.#parent?.isEnd();let e=this.#parent?this.#parent.#parts.length:0;return this.#parentIndex===e-1}copyIn(e){typeof e==`string`?this.push(e):this.push(e.clone(this))}clone(t){let n=new e(this.type,t);for(let e of this.#parts)n.copyIn(e);return n}static#parseAST(t,n,r,i){let a=!1,o=!1,s=-1,c=!1;if(n.type===null){let l=r,u=``;for(;l<t.length;){let r=t.charAt(l++);if(a||r===`\\`){a=!a,u+=r;continue}if(o){l===s+1?(r===`^`||r===`!`)&&(c=!0):r===`]`&&!(l===s+2&&c)&&(o=!1),u+=r;continue}else if(r===`[`){o=!0,s=l,c=!1,u+=r;continue}if(!i.noext&&ht(r)&&t.charAt(l)===`(`){n.push(u),u=``;let a=new e(r,n);l=e.#parseAST(t,a,l,i),n.push(a);continue}u+=r}return n.push(u),l}let l=r+1,u=new e(null,n),d=[],f=``;for(;l<t.length;){let r=t.charAt(l++);if(a||r===`\\`){a=!a,f+=r;continue}if(o){l===s+1?(r===`^`||r===`!`)&&(c=!0):r===`]`&&!(l===s+2&&c)&&(o=!1),f+=r;continue}else if(r===`[`){o=!0,s=l,c=!1,f+=r;continue}if(ht(r)&&t.charAt(l)===`(`){u.push(f),f=``;let n=new e(r,u);u.push(n),l=e.#parseAST(t,n,l,i);continue}if(r===`|`){u.push(f),f=``,d.push(u),u=new e(null,n);continue}if(r===`)`)return f===``&&n.#parts.length===0&&(n.#emptyExt=!0),u.push(f),f=``,n.push(...d,u),l;f+=r}return n.type=null,n.#hasMagic=void 0,n.#parts=[t.substring(r-1)],l}static fromGlob(t,n={}){let r=new e(null,void 0,n);return e.#parseAST(t,r,0,n),r}toMMPattern(){if(this!==this.#root)return this.#root.toMMPattern();let e=this.toString(),[t,n,r,i]=this.toRegExpSource(),a=r||this.#hasMagic||this.#options.nocase&&!this.#options.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase();if(!a)return n;let o=(this.#options.nocase?`i`:``)+(i?`u`:``);return Object.assign(RegExp(`^${t}$`,o),{_src:t,_glob:e})}get options(){return this.#options}toRegExpSource(t){let n=t??!!this.#options.dot;if(this.#root===this&&this.#fillNegs(),!this.type){let r=this.isStart()&&this.isEnd(),i=this.#parts.map(n=>{let[i,a,o,s]=typeof n==`string`?e.#parseGlob(n,this.#hasMagic,r):n.toRegExpSource(t);return this.#hasMagic=this.#hasMagic||o,this.#uflag=this.#uflag||s,i}).join(``),a=``;if(this.isStart()&&typeof this.#parts[0]==`string`){let e=this.#parts.length===1&&yt.has(this.#parts[0]);if(!e){let e=vt,r=n&&e.has(i.charAt(0))||i.startsWith(`\\.`)&&e.has(i.charAt(2))||i.startsWith(`\\.\\.`)&&e.has(i.charAt(4)),o=!n&&!t&&e.has(i.charAt(0));a=r?gt:o?_t:``}}let o=``;this.isEnd()&&this.#root.#filledNegs&&this.#parent?.type===`!`&&(o=`(?:$|\\/)`);let s=a+i+o;return[s,pt(i),this.#hasMagic=!!this.#hasMagic,this.#uflag]}let r=this.type===`*`||this.type===`+`,i=this.type===`!`?`(?:(?!(?:`:`(?:`,a=this.#partsToRegExp(n);if(this.isStart()&&this.isEnd()&&!a&&this.type!==`!`){let e=this.toString();return this.#parts=[e],this.type=null,this.#hasMagic=void 0,[e,pt(this.toString()),!1,!1]}let o=!r||t||n?``:this.#partsToRegExp(!0);o===a&&(o=``),o&&(a=`(?:${a})(?:${o})*?`);let s=``;if(this.type===`!`&&this.#emptyExt)s=(this.isStart()&&!n?_t:``)+wt;else{let e=this.type===`!`?`))`+(this.isStart()&&!n&&!t?_t:``)+Ct+`)`:this.type===`@`?`)`:this.type===`?`?`)?`:this.type===`+`&&o?`)`:this.type===`*`&&o?`)?`:`)${this.type}`;s=i+a+e}return[s,pt(a),this.#hasMagic=!!this.#hasMagic,this.#uflag]}#partsToRegExp(e){return this.#parts.map(t=>{if(typeof t==`string`)throw Error(`string type in extglob ast??`);let[n,r,i,a]=t.toRegExpSource(e);return this.#uflag=this.#uflag||a,n}).filter(e=>!(this.isStart()&&this.isEnd())||!!e).join(`|`)}static#parseGlob(e,t,n=!1){let r=!1,i=``,a=!1;for(let o=0;o<e.length;o++){let s=e.charAt(o);if(r){r=!1,i+=(bt.has(s)?`\\`:``)+s;continue}if(s===`\\`){o===e.length-1?i+=`\\\\`:r=!0;continue}if(s===`[`){let[n,r,s,c]=ft(e,o);if(s){i+=n,a=a||r,o+=s-1,t=t||c;continue}}if(s===`*`){n&&e===`*`?i+=wt:i+=Ct,t=!0;continue}if(s===`?`){i+=St,t=!0;continue}i+=xt(s)}return[i,pt(e),!!t,a]}};const Et=(e,{windowsPathsNoEscape:t=!1}={})=>t?e.replace(/[?*()[\]]/g,`[$&]`):e.replace(/[?*()[\]\\]/g,`\\$&`),b=(e,t,n={})=>(st(t),!n.nocomment&&t.charAt(0)===`#`?!1:new ln(t,n).match(e)),Dt=/^\*+([^+@!?\*\[\(]*)$/,Ot=e=>t=>!t.startsWith(`.`)&&t.endsWith(e),kt=e=>t=>t.endsWith(e),At=e=>(e=e.toLowerCase(),t=>!t.startsWith(`.`)&&t.toLowerCase().endsWith(e)),jt=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),Mt=/^\*+\.\*+$/,Nt=e=>!e.startsWith(`.`)&&e.includes(`.`),Pt=e=>e!==`.`&&e!==`..`&&e.includes(`.`),Ft=/^\.\*+$/,It=e=>e!==`.`&&e!==`..`&&e.startsWith(`.`),Lt=/^\*+$/,Rt=e=>e.length!==0&&!e.startsWith(`.`),zt=e=>e.length!==0&&e!==`.`&&e!==`..`,Bt=/^\?+([^+@!?\*\[\(]*)?$/,Vt=([e,t=``])=>{let n=Gt([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},Ht=([e,t=``])=>{let n=Kt([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},Ut=([e,t=``])=>{let n=Kt([e]);return t?e=>n(e)&&e.endsWith(t):n},Wt=([e,t=``])=>{let n=Gt([e]);return t?e=>n(e)&&e.endsWith(t):n},Gt=([e])=>{let t=e.length;return e=>e.length===t&&!e.startsWith(`.`)},Kt=([e])=>{let t=e.length;return e=>e.length===t&&e!==`.`&&e!==`..`},qt=typeof process==`object`&&process?typeof process.env==`object`&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:`posix`,Jt={win32:{sep:`\\`},posix:{sep:`/`}},Yt=qt===`win32`?Jt.win32.sep:Jt.posix.sep;b.sep=Yt;const x=Symbol(`globstar **`);b.GLOBSTAR=x;const Xt=`[^/]`,Zt=Xt+`*?`,Qt=`(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?`,$t=`(?:(?!(?:\\/|^)\\.).)*?`,en=(e,t={})=>n=>b(n,e,t);b.filter=en;const tn=(e,t={})=>Object.assign({},e,t),nn=e=>{if(!e||typeof e!=`object`||!Object.keys(e).length)return b;let t=b,n=(n,r,i={})=>t(n,r,tn(e,i));return Object.assign(n,{Minimatch:class extends t.Minimatch{constructor(t,n={}){super(t,tn(e,n))}static defaults(n){return t.defaults(tn(e,n)).Minimatch}},AST:class extends t.AST{constructor(t,n,r={}){super(t,n,tn(e,r))}static fromGlob(n,r={}){return t.AST.fromGlob(n,tn(e,r))}},unescape:(n,r={})=>t.unescape(n,tn(e,r)),escape:(n,r={})=>t.escape(n,tn(e,r)),filter:(n,r={})=>t.filter(n,tn(e,r)),defaults:n=>t.defaults(tn(e,n)),makeRe:(n,r={})=>t.makeRe(n,tn(e,r)),braceExpand:(n,r={})=>t.braceExpand(n,tn(e,r)),match:(n,r,i={})=>t.match(n,r,tn(e,i)),sep:t.sep,GLOBSTAR:x})};b.defaults=nn;const rn=(e,t={})=>(st(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:et(e));b.braceExpand=rn;const an=(e,t={})=>new ln(e,t).makeRe();b.makeRe=an;const on=(e,t,n={})=>{let r=new ln(t,n);return e=e.filter(e=>r.match(e)),r.options.nonull&&!e.length&&e.push(t),e};b.match=on;const sn=/[?*]|[+@!]\(.*?\)|\[|\]/,cn=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`);var ln=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,t={}){st(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||qt,this.isWindows=this.platform===`win32`,this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,`/`)),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!t.nonegate,this.comment=!1,this.empty=!1,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot===void 0?!!(this.isWindows&&this.nocase):t.windowsNoMagicRoot,this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let t of e)if(typeof t!=`string`)return!0;return!1}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)===`#`){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...e)=>console.error(...e)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(e=>this.slashSplit(e));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let r=this.globParts.map((e,t,n)=>{if(this.isWindows&&this.windowsNoMagicRoot){let t=e[0]===``&&e[1]===``&&(e[2]===`?`||!sn.test(e[2]))&&!sn.test(e[3]),n=/^[a-z]:/i.test(e[0]);if(t)return[...e.slice(0,4),...e.slice(4).map(e=>this.parse(e))];if(n)return[e[0],...e.slice(1).map(e=>this.parse(e))]}return e.map(e=>this.parse(e))});if(this.debug(this.pattern,r),this.set=r.filter(e=>e.indexOf(!1)===-1),this.isWindows)for(let e=0;e<this.set.length;e++){let t=this.set[e];t[0]===``&&t[1]===``&&this.globParts[e][2]===`?`&&typeof t[3]==`string`&&/^[a-z]:$/i.test(t[3])&&(t[2]=`?`)}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let t=0;t<e.length;t++)for(let n=0;n<e[t].length;n++)e[t][n]===`**`&&(e[t][n]=`*`);let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):e=t>=1?this.levelOneOptimize(e):this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(e=>{let t=-1;for(;(t=e.indexOf(`**`,t+1))!==-1;){let n=t;for(;e[n+1]===`**`;)n++;n!==t&&e.splice(t,n-t)}return e})}levelOneOptimize(e){return e.map(e=>(e=e.reduce((e,t)=>{let n=e[e.length-1];return t===`**`&&n===`**`?e:t===`..`&&n&&n!==`..`&&n!==`.`&&n!==`**`?(e.pop(),e):(e.push(t),e)},[]),e.length===0?[``]:e))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let n=1;n<e.length-1;n++){let r=e[n];n===1&&r===``&&e[0]===``||(r===`.`||r===``)&&(t=!0,e.splice(n,1),n--)}e[0]===`.`&&e.length===2&&(e[1]===`.`||e[1]===``)&&(t=!0,e.pop())}let n=0;for(;(n=e.indexOf(`..`,n+1))!==-1;){let r=e[n-1];r&&r!==`.`&&r!==`..`&&r!==`**`&&(t=!0,e.splice(n-1,2),n-=2)}}while(t);return e.length===0?[``]:e}firstPhasePreProcess(e){let t=!1;do{t=!1;for(let n of e){let r=-1;for(;(r=n.indexOf(`**`,r+1))!==-1;){let i=r;for(;n[i+1]===`**`;)i++;i>r&&n.splice(r+1,i-r);let a=n[r+1],o=n[r+2],s=n[r+3];if(a!==`..`||!o||o===`.`||o===`..`||!s||s===`.`||s===`..`)continue;t=!0,n.splice(r,1);let c=n.slice(0);c[r]=`**`,e.push(c),r--}if(!this.preserveMultipleSlashes){for(let e=1;e<n.length-1;e++){let r=n[e];e===1&&r===``&&n[0]===``||(r===`.`||r===``)&&(t=!0,n.splice(e,1),e--)}n[0]===`.`&&n.length===2&&(n[1]===`.`||n[1]===``)&&(t=!0,n.pop())}let i=0;for(;(i=n.indexOf(`..`,i+1))!==-1;){let e=n[i-1];if(e&&e!==`.`&&e!==`..`&&e!==`**`){t=!0;let e=i===1&&n[i+1]===`**`,r=e?[`.`]:[];n.splice(i-1,2,...r),n.length===0&&n.push(``),i-=2}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let n=t+1;n<e.length;n++){let r=this.partsMatch(e[t],e[n],!this.preserveMultipleSlashes);if(r){e[t]=[],e[n]=r;break}}return e.filter(e=>e.length)}partsMatch(e,t,n=!1){let r=0,i=0,a=[],o=``;for(;r<e.length&&i<t.length;)if(e[r]===t[i])a.push(o===`b`?t[i]:e[r]),r++,i++;else if(n&&e[r]===`**`&&t[i]===e[r+1])a.push(e[r]),r++;else if(n&&t[i]===`**`&&e[r]===t[i+1])a.push(t[i]),i++;else if(e[r]===`*`&&t[i]&&(this.options.dot||!t[i].startsWith(`.`))&&t[i]!==`**`){if(o===`b`)return!1;o=`a`,a.push(e[r]),r++,i++}else if(t[i]===`*`&&e[r]&&(this.options.dot||!e[r].startsWith(`.`))&&e[r]!==`**`){if(o===`a`)return!1;o=`b`,a.push(t[i]),r++,i++}else return!1;return e.length===t.length&&a}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=!1,n=0;for(let r=0;r<e.length&&e.charAt(r)===`!`;r++)t=!t,n++;n&&(this.pattern=e.slice(n)),this.negate=t}matchOne(e,t,n=!1){let r=this.options;if(this.isWindows){let n=typeof e[0]==`string`&&/^[a-z]:$/i.test(e[0]),r=!n&&e[0]===``&&e[1]===``&&e[2]===`?`&&/^[a-z]:$/i.test(e[3]),i=typeof t[0]==`string`&&/^[a-z]:$/i.test(t[0]),a=!i&&t[0]===``&&t[1]===``&&t[2]===`?`&&typeof t[3]==`string`&&/^[a-z]:$/i.test(t[3]),o=r?3:n?0:void 0,s=a?3:i?0:void 0;if(typeof o==`number`&&typeof s==`number`){let[n,r]=[e[o],t[s]];n.toLowerCase()===r.toLowerCase()&&(t[s]=n,s>o?t=t.slice(s):o>s&&(e=e.slice(o)))}}let{optimizationLevel:i=1}=this.options;i>=2&&(e=this.levelTwoFileOptimize(e)),this.debug(`matchOne`,this,{file:e,pattern:t}),this.debug(`matchOne`,e.length,t.length);for(var a=0,o=0,s=e.length,c=t.length;a<s&&o<c;a++,o++){this.debug(`matchOne loop`);var l=t[o],u=e[a];if(this.debug(t,l,u),l===!1)return!1;if(l===x){this.debug(`GLOBSTAR`,[t,l,u]);var d=a,f=o+1;if(f===c){for(this.debug(`** at the end`);a<s;a++)if(e[a]===`.`||e[a]===`..`||!r.dot&&e[a].charAt(0)===`.`)return!1;return!0}for(;d<s;){var p=e[d];if(this.debug(`
|
|
2
|
+
globstar while`,e,d,t,f,p),this.matchOne(e.slice(d),t.slice(f),n))return this.debug(`globstar found match!`,d,s,p),!0;if(p===`.`||p===`..`||!r.dot&&p.charAt(0)===`.`){this.debug(`dot detected!`,e,d,t,f);break}this.debug(`globstar swallow a segment, and continue`),d++}return!!(n&&(this.debug(`
|
|
3
|
+
>>> no match, partial?`,e,d,t,f),d===s))}let i;if(typeof l==`string`?(i=u===l,this.debug(`string match`,l,u,i)):(i=l.test(u),this.debug(`pattern match`,l,u,i)),!i)return!1}if(a===s&&o===c)return!0;if(a===s)return n;if(o===c)return a===s-1&&e[a]===``;throw Error(`wtf?`)}braceExpand(){return rn(this.pattern,this.options)}parse(e){st(e);let t=this.options;if(e===`**`)return x;if(e===``)return``;let n,r=null;(n=e.match(Lt))?r=t.dot?zt:Rt:(n=e.match(Dt))?r=(t.nocase?t.dot?jt:At:t.dot?kt:Ot)(n[1]):(n=e.match(Bt))?r=(t.nocase?t.dot?Ht:Vt:t.dot?Ut:Wt)(n):(n=e.match(Mt))?r=t.dot?Pt:Nt:(n=e.match(Ft))&&(r=It);let i=Tt.fromGlob(e,this.options).toMMPattern();return r&&typeof i==`object`&&Reflect.defineProperty(i,`test`,{value:r}),i}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let t=this.options,n=t.noglobstar?Zt:t.dot?Qt:$t,r=new Set(t.nocase?[`i`]:[]),i=e.map(e=>{let t=e.map(e=>{if(e instanceof RegExp)for(let t of e.flags.split(``))r.add(t);return typeof e==`string`?cn(e):e===x?x:e._src});return t.forEach((e,r)=>{let i=t[r+1],a=t[r-1];e!==x||a===x||(a===void 0?i!==void 0&&i!==x?t[r+1]=`(?:\\/|`+n+`\\/)?`+i:t[r]=n:i===void 0?t[r-1]=a+`(?:\\/|`+n+`)?`:i!==x&&(t[r-1]=a+`(?:\\/|\\/`+n+`\\/)`+i,t[r+1]=x))}),t.filter(e=>e!==x).join(`/`)}).join(`|`),[a,o]=e.length>1?[`(?:`,`)`]:[``,``];i=`^`+a+i+o+`$`,this.negate&&(i=`^(?!`+i+`).+$`);try{this.regexp=new RegExp(i,[...r].join(``))}catch(e){this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split(`/`):this.isWindows&&/^\/\/[^\/]+/.test(e)?[``,...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug(`match`,e,this.pattern),this.comment)return!1;if(this.empty)return e===``;if(e===`/`&&t)return!0;let n=this.options;this.isWindows&&(e=e.split(`\\`).join(`/`));let r=this.slashSplit(e);this.debug(this.pattern,`split`,r);let i=this.set;this.debug(this.pattern,`set`,i);let a=r[r.length-1];if(!a)for(let e=r.length-2;!a&&e>=0;e--)a=r[e];for(let e=0;e<i.length;e++){let o=i[e],s=r;n.matchBase&&o.length===1&&(s=[a]);let c=this.matchOne(s,o,t);if(c)return n.flipNegate?!0:!this.negate}return n.flipNegate?!1:this.negate}static defaults(e){return b.defaults(e).Minimatch}};b.AST=Tt,b.Minimatch=ln,b.escape=Et,b.unescape=pt;const un=typeof performance==`object`&&performance&&typeof performance.now==`function`?performance:Date,dn=new Set,fn=typeof process==`object`&&process?process:{},pn=(e,t,n,r)=>{typeof fn.emitWarning==`function`?fn.emitWarning(e,t,n,r):console.error(`[${n}] ${t}: ${e}`)};let mn=globalThis.AbortController,hn=globalThis.AbortSignal;if(mn===void 0){hn=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,t){this._onabort.push(t)}},mn=class{constructor(){t()}signal=new hn;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(let t of this.signal._onabort)t(e);this.signal.onabort?.(e)}}};let e=fn.env?.LRU_CACHE_IGNORE_AC_WARNING!==`1`,t=()=>{e&&(e=!1,pn("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.",`NO_ABORT_CONTROLLER`,`ENOTSUP`,t))}}const gn=e=>!dn.has(e);Symbol(`type`);const _n=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),vn=e=>_n(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=9007199254740991?yn:null:null;var yn=class extends Array{constructor(e){super(e),this.fill(0)}},bn=class e{heap;length;static#constructing=!1;static create(t){let n=vn(t);if(!n)return[];e.#constructing=!0;let r=new e(t,n);return e.#constructing=!1,r}constructor(t,n){if(!e.#constructing)throw TypeError(`instantiate Stack using Stack.create(n)`);this.heap=new n(t),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},xn=class e{#max;#maxSize;#dispose;#onInsert;#disposeAfter;#fetchMethod;#memoMethod;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#size;#calculatedSize;#keyMap;#keyList;#valList;#next;#prev;#head;#tail;#free;#disposed;#sizes;#starts;#ttls;#hasDispose;#hasFetchMethod;#hasDisposeAfter;#hasOnInsert;static unsafeExposeInternals(e){return{starts:e.#starts,ttls:e.#ttls,sizes:e.#sizes,keyMap:e.#keyMap,keyList:e.#keyList,valList:e.#valList,next:e.#next,prev:e.#prev,get head(){return e.#head},get tail(){return e.#tail},free:e.#free,isBackgroundFetch:t=>e.#isBackgroundFetch(t),backgroundFetch:(t,n,r,i)=>e.#backgroundFetch(t,n,r,i),moveToTail:t=>e.#moveToTail(t),indexes:t=>e.#indexes(t),rindexes:t=>e.#rindexes(t),isStale:t=>e.#isStale(t)}}get max(){return this.#max}get maxSize(){return this.#maxSize}get calculatedSize(){return this.#calculatedSize}get size(){return this.#size}get fetchMethod(){return this.#fetchMethod}get memoMethod(){return this.#memoMethod}get dispose(){return this.#dispose}get onInsert(){return this.#onInsert}get disposeAfter(){return this.#disposeAfter}constructor(t){let{max:n=0,ttl:r,ttlResolution:i=1,ttlAutopurge:a,updateAgeOnGet:o,updateAgeOnHas:s,allowStale:c,dispose:l,onInsert:u,disposeAfter:d,noDisposeOnSet:f,noUpdateTTL:p,maxSize:m=0,maxEntrySize:h=0,sizeCalculation:g,fetchMethod:_,memoMethod:v,noDeleteOnFetchRejection:y,noDeleteOnStaleGet:ee,allowStaleOnFetchRejection:te,allowStaleOnFetchAbort:ne,ignoreFetchAbort:re}=t;if(n!==0&&!_n(n))throw TypeError(`max option must be a nonnegative integer`);let ie=n?vn(n):Array;if(!ie)throw Error(`invalid max value: `+n);if(this.#max=n,this.#maxSize=m,this.maxEntrySize=h||this.#maxSize,this.sizeCalculation=g,this.sizeCalculation){if(!this.#maxSize&&!this.maxEntrySize)throw TypeError(`cannot set sizeCalculation without setting maxSize or maxEntrySize`);if(typeof this.sizeCalculation!=`function`)throw TypeError(`sizeCalculation set to non-function`)}if(v!==void 0&&typeof v!=`function`)throw TypeError(`memoMethod must be a function if defined`);if(this.#memoMethod=v,_!==void 0&&typeof _!=`function`)throw TypeError(`fetchMethod must be a function if specified`);if(this.#fetchMethod=_,this.#hasFetchMethod=!!_,this.#keyMap=new Map,this.#keyList=Array(n).fill(void 0),this.#valList=Array(n).fill(void 0),this.#next=new ie(n),this.#prev=new ie(n),this.#head=0,this.#tail=0,this.#free=bn.create(n),this.#size=0,this.#calculatedSize=0,typeof l==`function`&&(this.#dispose=l),typeof u==`function`&&(this.#onInsert=u),typeof d==`function`?(this.#disposeAfter=d,this.#disposed=[]):(this.#disposeAfter=void 0,this.#disposed=void 0),this.#hasDispose=!!this.#dispose,this.#hasOnInsert=!!this.#onInsert,this.#hasDisposeAfter=!!this.#disposeAfter,this.noDisposeOnSet=!!f,this.noUpdateTTL=!!p,this.noDeleteOnFetchRejection=!!y,this.allowStaleOnFetchRejection=!!te,this.allowStaleOnFetchAbort=!!ne,this.ignoreFetchAbort=!!re,this.maxEntrySize!==0){if(this.#maxSize!==0&&!_n(this.#maxSize))throw TypeError(`maxSize must be a positive integer if specified`);if(!_n(this.maxEntrySize))throw TypeError(`maxEntrySize must be a positive integer if specified`);this.#initializeSizeTracking()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!ee,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!s,this.ttlResolution=_n(i)||i===0?i:1,this.ttlAutopurge=!!a,this.ttl=r||0,this.ttl){if(!_n(this.ttl))throw TypeError(`ttl must be a positive integer if specified`);this.#initializeTTLTracking()}if(this.#max===0&&this.ttl===0&&this.#maxSize===0)throw TypeError(`At least one of max, maxSize, or ttl is required`);if(!this.ttlAutopurge&&!this.#max&&!this.#maxSize){let t=`LRU_CACHE_UNBOUNDED`;if(gn(t)){dn.add(t);let n=`TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.`;pn(n,`UnboundedCacheWarning`,t,e)}}}getRemainingTTL(e){return this.#keyMap.has(e)?1/0:0}#initializeTTLTracking(){let e=new yn(this.#max),t=new yn(this.#max);this.#ttls=e,this.#starts=t,this.#setItemTTL=(n,r,i=un.now())=>{if(t[n]=r===0?0:i,e[n]=r,r!==0&&this.ttlAutopurge){let e=setTimeout(()=>{this.#isStale(n)&&this.#delete(this.#keyList[n],`expire`)},r+1);e.unref&&e.unref()}},this.#updateItemAge=n=>{t[n]=e[n]===0?0:un.now()},this.#statusTTL=(i,a)=>{if(e[a]){let o=e[a],s=t[a];if(!o||!s)return;i.ttl=o,i.start=s,i.now=n||r();let c=i.now-s;i.remainingTTL=o-c}};let n=0,r=()=>{let e=un.now();if(this.ttlResolution>0){n=e;let t=setTimeout(()=>n=0,this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=i=>{let a=this.#keyMap.get(i);if(a===void 0)return 0;let o=e[a],s=t[a];if(!o||!s)return 1/0;let c=(n||r())-s;return o-c},this.#isStale=i=>{let a=t[i],o=e[i];return!!o&&!!a&&(n||r())-a>o}}#updateItemAge=()=>{};#statusTTL=()=>{};#setItemTTL=()=>{};#isStale=()=>!1;#initializeSizeTracking(){let e=new yn(this.#max);this.#calculatedSize=0,this.#sizes=e,this.#removeItemSize=t=>{this.#calculatedSize-=e[t],e[t]=0},this.#requireSize=(e,t,n,r)=>{if(this.#isBackgroundFetch(t))return 0;if(!_n(n))if(r){if(typeof r!=`function`)throw TypeError(`sizeCalculation must be a function`);if(n=r(t,e),!_n(n))throw TypeError(`sizeCalculation return invalid (expect positive integer)`)}else throw TypeError(`invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.`);return n},this.#addItemSize=(t,n,r)=>{if(e[t]=n,this.#maxSize){let n=this.#maxSize-e[t];for(;this.#calculatedSize>n;)this.#evict(!0)}this.#calculatedSize+=e[t],r&&(r.entrySize=n,r.totalCalculatedSize=this.#calculatedSize)}}#removeItemSize=e=>{};#addItemSize=(e,t,n)=>{};#requireSize=(e,t,n,r)=>{if(n||r)throw TypeError(`cannot set size without setting maxSize or maxEntrySize on cache`);return 0};*#indexes({allowStale:e=this.allowStale}={}){if(this.#size)for(let t=this.#tail;!(!this.#isValidIndex(t)||((e||!this.#isStale(t))&&(yield t),t===this.#head));)t=this.#prev[t]}*#rindexes({allowStale:e=this.allowStale}={}){if(this.#size)for(let t=this.#head;!(!this.#isValidIndex(t)||((e||!this.#isStale(t))&&(yield t),t===this.#tail));)t=this.#next[t]}#isValidIndex(e){return e!==void 0&&this.#keyMap.get(this.#keyList[e])===e}*entries(){for(let e of this.#indexes())this.#valList[e]!==void 0&&this.#keyList[e]!==void 0&&!this.#isBackgroundFetch(this.#valList[e])&&(yield[this.#keyList[e],this.#valList[e]])}*rentries(){for(let e of this.#rindexes())this.#valList[e]!==void 0&&this.#keyList[e]!==void 0&&!this.#isBackgroundFetch(this.#valList[e])&&(yield[this.#keyList[e],this.#valList[e]])}*keys(){for(let e of this.#indexes()){let t=this.#keyList[e];t!==void 0&&!this.#isBackgroundFetch(this.#valList[e])&&(yield t)}}*rkeys(){for(let e of this.#rindexes()){let t=this.#keyList[e];t!==void 0&&!this.#isBackgroundFetch(this.#valList[e])&&(yield t)}}*values(){for(let e of this.#indexes()){let t=this.#valList[e];t!==void 0&&!this.#isBackgroundFetch(this.#valList[e])&&(yield this.#valList[e])}}*rvalues(){for(let e of this.#rindexes()){let t=this.#valList[e];t!==void 0&&!this.#isBackgroundFetch(this.#valList[e])&&(yield this.#valList[e])}}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]=`LRUCache`;find(e,t={}){for(let n of this.#indexes()){let r=this.#valList[n],i=this.#isBackgroundFetch(r)?r.__staleWhileFetching:r;if(i===void 0)continue;if(e(i,this.#keyList[n],this))return this.get(this.#keyList[n],t)}}forEach(e,t=this){for(let n of this.#indexes()){let r=this.#valList[n],i=this.#isBackgroundFetch(r)?r.__staleWhileFetching:r;if(i===void 0)continue;e.call(t,i,this.#keyList[n],this)}}rforEach(e,t=this){for(let n of this.#rindexes()){let r=this.#valList[n],i=this.#isBackgroundFetch(r)?r.__staleWhileFetching:r;if(i===void 0)continue;e.call(t,i,this.#keyList[n],this)}}purgeStale(){let e=!1;for(let t of this.#rindexes({allowStale:!0}))this.#isStale(t)&&(this.#delete(this.#keyList[t],`expire`),e=!0);return e}info(e){let t=this.#keyMap.get(e);if(t===void 0)return;let n=this.#valList[t],r=this.#isBackgroundFetch(n)?n.__staleWhileFetching:n;if(r===void 0)return;let i={value:r};if(this.#ttls&&this.#starts){let e=this.#ttls[t],n=this.#starts[t];if(e&&n){let t=e-(un.now()-n);i.ttl=t,i.start=Date.now()}}return this.#sizes&&(i.size=this.#sizes[t]),i}dump(){let e=[];for(let t of this.#indexes({allowStale:!0})){let n=this.#keyList[t],r=this.#valList[t],i=this.#isBackgroundFetch(r)?r.__staleWhileFetching:r;if(i===void 0||n===void 0)continue;let a={value:i};if(this.#ttls&&this.#starts){a.ttl=this.#ttls[t];let e=un.now()-this.#starts[t];a.start=Math.floor(Date.now()-e)}this.#sizes&&(a.size=this.#sizes[t]),e.unshift([n,a])}return e}load(e){this.clear();for(let[t,n]of e){if(n.start){let e=Date.now()-n.start;n.start=un.now()-e}this.set(t,n.value,n)}}set(e,t,n={}){if(t===void 0)return this.delete(e),this;let{ttl:r=this.ttl,start:i,noDisposeOnSet:a=this.noDisposeOnSet,sizeCalculation:o=this.sizeCalculation,status:s}=n,{noUpdateTTL:c=this.noUpdateTTL}=n,l=this.#requireSize(e,t,n.size||0,o);if(this.maxEntrySize&&l>this.maxEntrySize)return s&&(s.set=`miss`,s.maxEntrySizeExceeded=!0),this.#delete(e,`set`),this;let u=this.#size===0?void 0:this.#keyMap.get(e);if(u===void 0)u=this.#size===0?this.#tail:this.#free.length===0?this.#size===this.#max?this.#evict(!1):this.#size:this.#free.pop(),this.#keyList[u]=e,this.#valList[u]=t,this.#keyMap.set(e,u),this.#next[this.#tail]=u,this.#prev[u]=this.#tail,this.#tail=u,this.#size++,this.#addItemSize(u,l,s),s&&(s.set=`add`),c=!1,this.#hasOnInsert&&this.#onInsert?.(t,e,`add`);else{this.#moveToTail(u);let n=this.#valList[u];if(t!==n){if(this.#hasFetchMethod&&this.#isBackgroundFetch(n)){n.__abortController.abort(Error(`replaced`));let{__staleWhileFetching:t}=n;t!==void 0&&!a&&(this.#hasDispose&&this.#dispose?.(t,e,`set`),this.#hasDisposeAfter&&this.#disposed?.push([t,e,`set`]))}else a||(this.#hasDispose&&this.#dispose?.(n,e,`set`),this.#hasDisposeAfter&&this.#disposed?.push([n,e,`set`]));if(this.#removeItemSize(u),this.#addItemSize(u,l,s),this.#valList[u]=t,s){s.set=`replace`;let e=n&&this.#isBackgroundFetch(n)?n.__staleWhileFetching:n;e!==void 0&&(s.oldValue=e)}}else s&&(s.set=`update`);this.#hasOnInsert&&this.onInsert?.(t,e,t===n?`update`:`replace`)}if(r!==0&&!this.#ttls&&this.#initializeTTLTracking(),this.#ttls&&(c||this.#setItemTTL(u,r,i),s&&this.#statusTTL(s,u)),!a&&this.#hasDisposeAfter&&this.#disposed){let e=this.#disposed,t;for(;t=e?.shift();)this.#disposeAfter?.(...t)}return this}pop(){try{for(;this.#size;){let e=this.#valList[this.#head];if(this.#evict(!0),this.#isBackgroundFetch(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#hasDisposeAfter&&this.#disposed){let e=this.#disposed,t;for(;t=e?.shift();)this.#disposeAfter?.(...t)}}}#evict(e){let t=this.#head,n=this.#keyList[t],r=this.#valList[t];return this.#hasFetchMethod&&this.#isBackgroundFetch(r)?r.__abortController.abort(Error(`evicted`)):(this.#hasDispose||this.#hasDisposeAfter)&&(this.#hasDispose&&this.#dispose?.(r,n,`evict`),this.#hasDisposeAfter&&this.#disposed?.push([r,n,`evict`])),this.#removeItemSize(t),e&&(this.#keyList[t]=void 0,this.#valList[t]=void 0,this.#free.push(t)),this.#size===1?(this.#head=this.#tail=0,this.#free.length=0):this.#head=this.#next[t],this.#keyMap.delete(n),this.#size--,t}has(e,t={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:r}=t,i=this.#keyMap.get(e);if(i!==void 0){let e=this.#valList[i];if(this.#isBackgroundFetch(e)&&e.__staleWhileFetching===void 0)return!1;if(this.#isStale(i))r&&(r.has=`stale`,this.#statusTTL(r,i));else return n&&this.#updateItemAge(i),r&&(r.has=`hit`,this.#statusTTL(r,i)),!0}else r&&(r.has=`miss`);return!1}peek(e,t={}){let{allowStale:n=this.allowStale}=t,r=this.#keyMap.get(e);if(r===void 0||!n&&this.#isStale(r))return;let i=this.#valList[r];return this.#isBackgroundFetch(i)?i.__staleWhileFetching:i}#backgroundFetch(e,t,n,r){let i=t===void 0?void 0:this.#valList[t];if(this.#isBackgroundFetch(i))return i;let a=new mn,{signal:o}=n;o?.addEventListener(`abort`,()=>a.abort(o.reason),{signal:a.signal});let s={signal:a.signal,options:n,context:r},c=(r,i=!1)=>{let{aborted:o}=a.signal,c=n.ignoreFetchAbort&&r!==void 0;if(n.status&&(o&&!i?(n.status.fetchAborted=!0,n.status.fetchError=a.signal.reason,c&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),o&&!c&&!i)return u(a.signal.reason);let l=f;return this.#valList[t]===f&&(r===void 0?l.__staleWhileFetching?this.#valList[t]=l.__staleWhileFetching:this.#delete(e,`fetch`):(n.status&&(n.status.fetchUpdated=!0),this.set(e,r,s.options))),r},l=e=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=e),u(e)),u=r=>{let{aborted:i}=a.signal,o=i&&n.allowStaleOnFetchAbort,s=o||n.allowStaleOnFetchRejection,c=s||n.noDeleteOnFetchRejection,l=f;if(this.#valList[t]===f){let n=!c||l.__staleWhileFetching===void 0;n?this.#delete(e,`fetch`):o||(this.#valList[t]=l.__staleWhileFetching)}if(s)return n.status&&l.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),l.__staleWhileFetching;if(l.__returned===l)throw r},d=(t,r)=>{let o=this.#fetchMethod?.(e,i,s);o&&o instanceof Promise&&o.then(e=>t(e===void 0?void 0:e),r),a.signal.addEventListener(`abort`,()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(t(void 0),n.allowStaleOnFetchAbort&&(t=e=>c(e,!0)))})};n.status&&(n.status.fetchDispatched=!0);let f=new Promise(d).then(c,l),p=Object.assign(f,{__abortController:a,__staleWhileFetching:i,__returned:void 0});return t===void 0?(this.set(e,p,{...s.options,status:void 0}),t=this.#keyMap.get(e)):this.#valList[t]=p,p}#isBackgroundFetch(e){if(!this.#hasFetchMethod)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty(`__staleWhileFetching`)&&t.__abortController instanceof mn}async fetch(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:a=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:s=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:l=this.noUpdateTTL,noDeleteOnFetchRejection:u=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:m,forceRefresh:h=!1,status:g,signal:_}=t;if(!this.#hasFetchMethod)return g&&(g.fetch=`get`),this.get(e,{allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,status:g});let v={allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,ttl:a,noDisposeOnSet:o,size:s,sizeCalculation:c,noUpdateTTL:l,noDeleteOnFetchRejection:u,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:p,ignoreFetchAbort:f,status:g,signal:_},y=this.#keyMap.get(e);if(y===void 0){g&&(g.fetch=`miss`);let t=this.#backgroundFetch(e,y,v,m);return t.__returned=t}else{let t=this.#valList[y];if(this.#isBackgroundFetch(t)){let e=n&&t.__staleWhileFetching!==void 0;return g&&(g.fetch=`inflight`,e&&(g.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}let i=this.#isStale(y);if(!h&&!i)return g&&(g.fetch=`hit`),this.#moveToTail(y),r&&this.#updateItemAge(y),g&&this.#statusTTL(g,y),t;let a=this.#backgroundFetch(e,y,v,m),o=a.__staleWhileFetching!==void 0,s=o&&n;return g&&(g.fetch=i?`stale`:`refresh`,s&&i&&(g.returnedStale=!0)),s?a.__staleWhileFetching:a.__returned=a}}async forceFetch(e,t={}){let n=await this.fetch(e,t);if(n===void 0)throw Error(`fetch() returned undefined`);return n}memo(e,t={}){let n=this.#memoMethod;if(!n)throw Error(`no memoMethod provided to constructor`);let{context:r,forceRefresh:i,...a}=t,o=this.get(e,a);if(!i&&o!==void 0)return o;let s=n(e,o,{options:a,context:r});return this.set(e,s,a),s}get(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:a}=t,o=this.#keyMap.get(e);if(o!==void 0){let t=this.#valList[o],s=this.#isBackgroundFetch(t);return a&&this.#statusTTL(a,o),this.#isStale(o)?(a&&(a.get=`stale`),s?(a&&n&&t.__staleWhileFetching!==void 0&&(a.returnedStale=!0),n?t.__staleWhileFetching:void 0):(i||this.#delete(e,`expire`),a&&n&&(a.returnedStale=!0),n?t:void 0)):(a&&(a.get=`hit`),s?t.__staleWhileFetching:(this.#moveToTail(o),r&&this.#updateItemAge(o),t))}else a&&(a.get=`miss`)}#connect(e,t){this.#prev[t]=e,this.#next[e]=t}#moveToTail(e){e!==this.#tail&&(e===this.#head?this.#head=this.#next[e]:this.#connect(this.#prev[e],this.#next[e]),this.#connect(this.#tail,e),this.#tail=e)}delete(e){return this.#delete(e,`delete`)}#delete(e,t){let n=!1;if(this.#size!==0){let r=this.#keyMap.get(e);if(r!==void 0)if(n=!0,this.#size===1)this.#clear(t);else{this.#removeItemSize(r);let n=this.#valList[r];if(this.#isBackgroundFetch(n)?n.__abortController.abort(Error(`deleted`)):(this.#hasDispose||this.#hasDisposeAfter)&&(this.#hasDispose&&this.#dispose?.(n,e,t),this.#hasDisposeAfter&&this.#disposed?.push([n,e,t])),this.#keyMap.delete(e),this.#keyList[r]=void 0,this.#valList[r]=void 0,r===this.#tail)this.#tail=this.#prev[r];else if(r===this.#head)this.#head=this.#next[r];else{let e=this.#prev[r];this.#next[e]=this.#next[r];let t=this.#next[r];this.#prev[t]=this.#prev[r]}this.#size--,this.#free.push(r)}}if(this.#hasDisposeAfter&&this.#disposed?.length){let e=this.#disposed,t;for(;t=e?.shift();)this.#disposeAfter?.(...t)}return n}clear(){return this.#clear(`delete`)}#clear(e){for(let t of this.#rindexes({allowStale:!0})){let n=this.#valList[t];if(this.#isBackgroundFetch(n))n.__abortController.abort(Error(`deleted`));else{let r=this.#keyList[t];this.#hasDispose&&this.#dispose?.(n,r,e),this.#hasDisposeAfter&&this.#disposed?.push([n,r,e])}}if(this.#keyMap.clear(),this.#valList.fill(void 0),this.#keyList.fill(void 0),this.#ttls&&this.#starts&&(this.#ttls.fill(0),this.#starts.fill(0)),this.#sizes&&this.#sizes.fill(0),this.#head=0,this.#tail=0,this.#free.length=0,this.#calculatedSize=0,this.#size=0,this.#hasDisposeAfter&&this.#disposed){let e=this.#disposed,t;for(;t=e?.shift();)this.#disposeAfter?.(...t)}}};const Sn=typeof process==`object`&&process?process:{stdout:null,stderr:null},Cn=e=>!!e&&typeof e==`object`&&(e instanceof sr||e instanceof pe||wn(e)||Tn(e)),wn=e=>!!e&&typeof e==`object`&&e instanceof fe&&typeof e.pipe==`function`&&e.pipe!==pe.Writable.prototype.pipe,Tn=e=>!!e&&typeof e==`object`&&e instanceof fe&&typeof e.write==`function`&&typeof e.end==`function`,En=Symbol(`EOF`),Dn=Symbol(`maybeEmitEnd`),On=Symbol(`emittedEnd`),kn=Symbol(`emittingEnd`),An=Symbol(`emittedError`),jn=Symbol(`closed`),Mn=Symbol(`read`),Nn=Symbol(`flush`),Pn=Symbol(`flushChunk`),Fn=Symbol(`encoding`),In=Symbol(`decoder`),S=Symbol(`flowing`),Ln=Symbol(`paused`),Rn=Symbol(`resume`),C=Symbol(`buffer`),zn=Symbol(`pipes`),w=Symbol(`bufferLength`),Bn=Symbol(`bufferPush`),Vn=Symbol(`bufferShift`),T=Symbol(`objectMode`),E=Symbol(`destroyed`),Hn=Symbol(`error`),Un=Symbol(`emitData`),Wn=Symbol(`emitEnd`),Gn=Symbol(`emitEnd2`),Kn=Symbol(`async`),qn=Symbol(`abort`),Jn=Symbol(`aborted`),Yn=Symbol(`signal`),Xn=Symbol(`dataListeners`),Zn=Symbol(`discarded`),Qn=e=>Promise.resolve().then(e),$n=e=>e(),er=e=>e===`end`||e===`finish`||e===`prefinish`,tr=e=>e instanceof ArrayBuffer||!!e&&typeof e==`object`&&e.constructor&&e.constructor.name===`ArrayBuffer`&&e.byteLength>=0,nr=e=>!Buffer.isBuffer(e)&&ArrayBuffer.isView(e);var rr=class{src;dest;opts;ondrain;constructor(e,t,n){this.src=e,this.dest=t,this.opts=n,this.ondrain=()=>e[Rn](),this.dest.on(`drain`,this.ondrain)}unpipe(){this.dest.removeListener(`drain`,this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},ir=class extends rr{unpipe(){this.src.removeListener(`error`,this.proxyErrors),super.unpipe()}constructor(e,t,n){super(e,t,n),this.proxyErrors=e=>t.emit(`error`,e),e.on(`error`,this.proxyErrors)}};const ar=e=>!!e.objectMode,or=e=>!e.objectMode&&!!e.encoding&&e.encoding!==`buffer`;var sr=class extends fe{[S]=!1;[Ln]=!1;[zn]=[];[C]=[];[T];[Fn];[Kn];[In];[En]=!1;[On]=!1;[kn]=!1;[jn]=!1;[An]=null;[w]=0;[E]=!1;[Yn];[Jn]=!1;[Xn]=0;[Zn]=!1;writable=!0;readable=!0;constructor(...e){let t=e[0]||{};if(super(),t.objectMode&&typeof t.encoding==`string`)throw TypeError(`Encoding and objectMode may not be used together`);ar(t)?(this[T]=!0,this[Fn]=null):or(t)?(this[Fn]=t.encoding,this[T]=!1):(this[T]=!1,this[Fn]=null),this[Kn]=!!t.async,this[In]=this[Fn]?new me(this[Fn]):null,t&&t.debugExposeBuffer===!0&&Object.defineProperty(this,`buffer`,{get:()=>this[C]}),t&&t.debugExposePipes===!0&&Object.defineProperty(this,`pipes`,{get:()=>this[zn]});let{signal:n}=t;n&&(this[Yn]=n,n.aborted?this[qn]():n.addEventListener(`abort`,()=>this[qn]()))}get bufferLength(){return this[w]}get encoding(){return this[Fn]}set encoding(e){throw Error(`Encoding must be set at instantiation time`)}setEncoding(e){throw Error(`Encoding must be set at instantiation time`)}get objectMode(){return this[T]}set objectMode(e){throw Error(`objectMode must be set at instantiation time`)}get async(){return this[Kn]}set async(e){this[Kn]=this[Kn]||!!e}[qn](){this[Jn]=!0,this.emit(`abort`,this[Yn]?.reason),this.destroy(this[Yn]?.reason)}get aborted(){return this[Jn]}set aborted(e){}write(e,t,n){if(this[Jn])return!1;if(this[En])throw Error(`write after end`);if(this[E])return this.emit(`error`,Object.assign(Error(`Cannot call write after a stream was destroyed`),{code:`ERR_STREAM_DESTROYED`})),!0;typeof t==`function`&&(n=t,t=`utf8`),t||(t=`utf8`);let r=this[Kn]?Qn:$n;if(!this[T]&&!Buffer.isBuffer(e)){if(nr(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(tr(e))e=Buffer.from(e);else if(typeof e!=`string`)throw Error(`Non-contiguous data written to non-objectMode stream`)}return this[T]?(this[S]&&this[w]!==0&&this[Nn](!0),this[S]?this.emit(`data`,e):this[Bn](e),this[w]!==0&&this.emit(`readable`),n&&r(n),this[S]):e.length?(typeof e==`string`&&!(t===this[Fn]&&!this[In]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[Fn]&&(e=this[In].write(e)),this[S]&&this[w]!==0&&this[Nn](!0),this[S]?this.emit(`data`,e):this[Bn](e),this[w]!==0&&this.emit(`readable`),n&&r(n),this[S]):(this[w]!==0&&this.emit(`readable`),n&&r(n),this[S])}read(e){if(this[E])return null;if(this[Zn]=!1,this[w]===0||e===0||e&&e>this[w])return this[Dn](),null;this[T]&&(e=null),this[C].length>1&&!this[T]&&(this[C]=[this[Fn]?this[C].join(``):Buffer.concat(this[C],this[w])]);let t=this[Mn](e||null,this[C][0]);return this[Dn](),t}[Mn](e,t){if(this[T])this[Vn]();else{let n=t;e===n.length||e===null?this[Vn]():typeof n==`string`?(this[C][0]=n.slice(e),t=n.slice(0,e),this[w]-=e):(this[C][0]=n.subarray(e),t=n.subarray(0,e),this[w]-=e)}return this.emit(`data`,t),!this[C].length&&!this[En]&&this.emit(`drain`),t}end(e,t,n){return typeof e==`function`&&(n=e,e=void 0),typeof t==`function`&&(n=t,t=`utf8`),e!==void 0&&this.write(e,t),n&&this.once(`end`,n),this[En]=!0,this.writable=!1,(this[S]||!this[Ln])&&this[Dn](),this}[Rn](){this[E]||(!this[Xn]&&!this[zn].length&&(this[Zn]=!0),this[Ln]=!1,this[S]=!0,this.emit(`resume`),this[C].length?this[Nn]():this[En]?this[Dn]():this.emit(`drain`))}resume(){return this[Rn]()}pause(){this[S]=!1,this[Ln]=!0,this[Zn]=!1}get destroyed(){return this[E]}get flowing(){return this[S]}get paused(){return this[Ln]}[Bn](e){this[T]?this[w]+=1:this[w]+=e.length,this[C].push(e)}[Vn](){return this[T]?--this[w]:this[w]-=this[C][0].length,this[C].shift()}[Nn](e=!1){do;while(this[Pn](this[Vn]())&&this[C].length);!e&&!this[C].length&&!this[En]&&this.emit(`drain`)}[Pn](e){return this.emit(`data`,e),this[S]}pipe(e,t){if(this[E])return e;this[Zn]=!1;let n=this[On];return t=t||{},e===Sn.stdout||e===Sn.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,n?t.end&&e.end():(this[zn].push(t.proxyErrors?new ir(this,e,t):new rr(this,e,t)),this[Kn]?Qn(()=>this[Rn]()):this[Rn]()),e}unpipe(e){let t=this[zn].find(t=>t.dest===e);t&&(this[zn].length===1?(this[S]&&this[Xn]===0&&(this[S]=!1),this[zn]=[]):this[zn].splice(this[zn].indexOf(t),1),t.unpipe())}addListener(e,t){return this.on(e,t)}on(e,t){let n=super.on(e,t);if(e===`data`)this[Zn]=!1,this[Xn]++,!this[zn].length&&!this[S]&&this[Rn]();else if(e===`readable`&&this[w]!==0)super.emit(`readable`);else if(er(e)&&this[On])super.emit(e),this.removeAllListeners(e);else if(e===`error`&&this[An]){let e=t;this[Kn]?Qn(()=>e.call(this,this[An])):e.call(this,this[An])}return n}removeListener(e,t){return this.off(e,t)}off(e,t){let n=super.off(e,t);return e===`data`&&(this[Xn]=this.listeners(`data`).length,this[Xn]===0&&!this[Zn]&&!this[zn].length&&(this[S]=!1)),n}removeAllListeners(e){let t=super.removeAllListeners(e);return(e===`data`||e===void 0)&&(this[Xn]=0,!this[Zn]&&!this[zn].length&&(this[S]=!1)),t}get emittedEnd(){return this[On]}[Dn](){!this[kn]&&!this[On]&&!this[E]&&this[C].length===0&&this[En]&&(this[kn]=!0,this.emit(`end`),this.emit(`prefinish`),this.emit(`finish`),this[jn]&&this.emit(`close`),this[kn]=!1)}emit(e,...t){let n=t[0];if(e!==`error`&&e!==`close`&&e!==E&&this[E])return!1;if(e===`data`)return!this[T]&&!n?!1:this[Kn]?(Qn(()=>this[Un](n)),!0):this[Un](n);if(e===`end`)return this[Wn]();if(e===`close`){if(this[jn]=!0,!this[On]&&!this[E])return!1;let e=super.emit(`close`);return this.removeAllListeners(`close`),e}else if(e===`error`){this[An]=n,super.emit(Hn,n);let e=!this[Yn]||this.listeners(`error`).length?super.emit(`error`,n):!1;return this[Dn](),e}else if(e===`resume`){let e=super.emit(`resume`);return this[Dn](),e}else if(e===`finish`||e===`prefinish`){let t=super.emit(e);return this.removeAllListeners(e),t}let r=super.emit(e,...t);return this[Dn](),r}[Un](e){for(let t of this[zn])t.dest.write(e)===!1&&this.pause();let t=this[Zn]?!1:super.emit(`data`,e);return this[Dn](),t}[Wn](){return this[On]?!1:(this[On]=!0,this.readable=!1,this[Kn]?(Qn(()=>this[Gn]()),!0):this[Gn]())}[Gn](){if(this[In]){let e=this[In].end();if(e){for(let t of this[zn])t.dest.write(e);this[Zn]||super.emit(`data`,e)}}for(let e of this[zn])e.end();let e=super.emit(`end`);return this.removeAllListeners(`end`),e}async collect(){let e=Object.assign([],{dataLength:0});this[T]||(e.dataLength=0);let t=this.promise();return this.on(`data`,t=>{e.push(t),this[T]||(e.dataLength+=t.length)}),await t,e}async concat(){if(this[T])throw Error(`cannot concat in objectMode`);let e=await this.collect();return this[Fn]?e.join(``):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(E,()=>t(Error(`stream destroyed`))),this.on(`error`,e=>t(e)),this.on(`end`,()=>e())})}[Symbol.asyncIterator](){this[Zn]=!1;let e=!1,t=async()=>(this.pause(),e=!0,{value:void 0,done:!0}),n=()=>{if(e)return t();let n=this.read();if(n!==null)return Promise.resolve({done:!1,value:n});if(this[En])return t();let r,i,a=e=>{this.off(`data`,o),this.off(`end`,s),this.off(E,c),t(),i(e)},o=e=>{this.off(`error`,a),this.off(`end`,s),this.off(E,c),this.pause(),r({value:e,done:!!this[En]})},s=()=>{this.off(`error`,a),this.off(`data`,o),this.off(E,c),t(),r({done:!0,value:void 0})},c=()=>a(Error(`stream destroyed`));return new Promise((e,t)=>{i=t,r=e,this.once(E,c),this.once(`error`,a),this.once(`end`,s),this.once(`data`,o)})};return{next:n,throw:t,return:t,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[Zn]=!1;let e=!1,t=()=>(this.pause(),this.off(Hn,t),this.off(E,t),this.off(`end`,t),e=!0,{done:!0,value:void 0}),n=()=>{if(e)return t();let n=this.read();return n===null?t():{done:!1,value:n}};return this.once(`end`,t),this.once(Hn,t),this.once(E,t),{next:n,throw:t,return:t,[Symbol.iterator](){return this}}}destroy(e){if(this[E])return e?this.emit(`error`,e):this.emit(E),this;this[E]=!0,this[Zn]=!0,this[C].length=0,this[w]=0;let t=this;return typeof t.close==`function`&&!this[jn]&&t.close(),e?this.emit(`error`,e):this.emit(E),this}static get isStream(){return Cn}};const cr=d.native,lr={lstatSync:o,readdir:c,readdirSync:l,readlinkSync:u,realpathSync:cr,promises:{lstat:ce,readdir:le,readlink:ue,realpath:de}},ur=e=>!e||e===lr||e===y?lr:{...lr,...e,promises:{...lr.promises,...e.promises||{}}},dr=/^\\\\\?\\([a-z]:)\\?$/i,fr=e=>e.replace(/\//g,`\\`).replace(dr,`$1\\`),pr=/[\\\/]/,mr=0,hr=1,gr=2,_r=4,vr=6,yr=8,br=10,xr=12,Sr=15,Cr=~Sr,wr=16,Tr=32,Er=64,Dr=128,Or=256,kr=512,Ar=Dr|576,jr=1023,Mr=e=>e.isFile()?yr:e.isDirectory()?_r:e.isSymbolicLink()?br:e.isCharacterDevice()?gr:e.isBlockDevice()?vr:e.isSocket()?xr:e.isFIFO()?hr:mr,Nr=new Map,Pr=e=>{let t=Nr.get(e);if(t)return t;let n=e.normalize(`NFKD`);return Nr.set(e,n),n},Fr=new Map,Ir=e=>{let t=Fr.get(e);if(t)return t;let n=Pr(e.toLowerCase());return Fr.set(e,n),n};var Lr=class extends xn{constructor(){super({max:256})}},Rr=class extends xn{constructor(e=16*1024){super({maxSize:e,sizeCalculation:e=>e.length+1})}};const zr=Symbol(`PathScurry setAsCwd`);var Br=class{name;root;roots;parent;nocase;isCWD=!1;#fs;#dev;get dev(){return this.#dev}#mode;get mode(){return this.#mode}#nlink;get nlink(){return this.#nlink}#uid;get uid(){return this.#uid}#gid;get gid(){return this.#gid}#rdev;get rdev(){return this.#rdev}#blksize;get blksize(){return this.#blksize}#ino;get ino(){return this.#ino}#size;get size(){return this.#size}#blocks;get blocks(){return this.#blocks}#atimeMs;get atimeMs(){return this.#atimeMs}#mtimeMs;get mtimeMs(){return this.#mtimeMs}#ctimeMs;get ctimeMs(){return this.#ctimeMs}#birthtimeMs;get birthtimeMs(){return this.#birthtimeMs}#atime;get atime(){return this.#atime}#mtime;get mtime(){return this.#mtime}#ctime;get ctime(){return this.#ctime}#birthtime;get birthtime(){return this.#birthtime}#matchName;#depth;#fullpath;#fullpathPosix;#relative;#relativePosix;#type;#children;#linkTarget;#realpath;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,t=mr,n,r,i,a,o){this.name=e,this.#matchName=i?Ir(e):Pr(e),this.#type=t&jr,this.nocase=i,this.roots=r,this.root=n||this,this.#children=a,this.#fullpath=o.fullpath,this.#relative=o.relative,this.#relativePosix=o.relativePosix,this.parent=o.parent,this.parent?this.#fs=this.parent.#fs:this.#fs=ur(o.fs)}depth(){return this.#depth===void 0?this.parent?this.#depth=this.parent.depth()+1:this.#depth=0:this.#depth}childrenCache(){return this.#children}resolve(e){if(!e)return this;let t=this.getRootString(e),n=e.substring(t.length),r=n.split(this.splitSep),i=t?this.getRoot(t).#resolveParts(r):this.#resolveParts(r);return i}#resolveParts(e){let t=this;for(let n of e)t=t.child(n);return t}children(){let e=this.#children.get(this);if(e)return e;let t=Object.assign([],{provisional:0});return this.#children.set(this,t),this.#type&=~wr,t}child(e,t){if(e===``||e===`.`)return this;if(e===`..`)return this.parent||this;let n=this.children(),r=this.nocase?Ir(e):Pr(e);for(let e of n)if(e.#matchName===r)return e;let i=this.parent?this.sep:``,a=this.#fullpath?this.#fullpath+i+e:void 0,o=this.newChild(e,mr,{...t,parent:this,fullpath:a});return this.canReaddir()||(o.#type|=Dr),n.push(o),o}relative(){if(this.isCWD)return``;if(this.#relative!==void 0)return this.#relative;let e=this.name,t=this.parent;if(!t)return this.#relative=this.name;let n=t.relative();return n+(!n||!t.parent?``:this.sep)+e}relativePosix(){if(this.sep===`/`)return this.relative();if(this.isCWD)return``;if(this.#relativePosix!==void 0)return this.#relativePosix;let e=this.name,t=this.parent;if(!t)return this.#relativePosix=this.fullpathPosix();let n=t.relativePosix();return n+(!n||!t.parent?``:`/`)+e}fullpath(){if(this.#fullpath!==void 0)return this.#fullpath;let e=this.name,t=this.parent;if(!t)return this.#fullpath=this.name;let n=t.fullpath(),r=n+(t.parent?this.sep:``)+e;return this.#fullpath=r}fullpathPosix(){if(this.#fullpathPosix!==void 0)return this.#fullpathPosix;if(this.sep===`/`)return this.#fullpathPosix=this.fullpath();if(!this.parent){let e=this.fullpath().replace(/\\/g,`/`);return/^[a-z]:\//i.test(e)?this.#fullpathPosix=`//?/${e}`:this.#fullpathPosix=e}let e=this.parent,t=e.fullpathPosix(),n=t+(!t||!e.parent?``:`/`)+this.name;return this.#fullpathPosix=n}isUnknown(){return(this.#type&Sr)===mr}isType(e){return this[`is${e}`]()}getType(){return this.isUnknown()?`Unknown`:this.isDirectory()?`Directory`:this.isFile()?`File`:this.isSymbolicLink()?`SymbolicLink`:this.isFIFO()?`FIFO`:this.isCharacterDevice()?`CharacterDevice`:this.isBlockDevice()?`BlockDevice`:this.isSocket()?`Socket`:`Unknown`}isFile(){return(this.#type&Sr)===yr}isDirectory(){return(this.#type&Sr)===_r}isCharacterDevice(){return(this.#type&Sr)===gr}isBlockDevice(){return(this.#type&Sr)===vr}isFIFO(){return(this.#type&Sr)===hr}isSocket(){return(this.#type&Sr)===xr}isSymbolicLink(){return(this.#type&br)===br}lstatCached(){return this.#type&Tr?this:void 0}readlinkCached(){return this.#linkTarget}realpathCached(){return this.#realpath}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(this.#linkTarget)return!0;if(!this.parent)return!1;let e=this.#type&Sr;return!(e!==mr&&e!==br||this.#type&Or||this.#type&Dr)}calledReaddir(){return!!(this.#type&wr)}isENOENT(){return!!(this.#type&Dr)}isNamed(e){return this.nocase?this.#matchName===Ir(e):this.#matchName===Pr(e)}async readlink(){let e=this.#linkTarget;if(e)return e;if(this.canReadlink()&&this.parent)try{let e=await this.#fs.promises.readlink(this.fullpath()),t=(await this.parent.realpath())?.resolve(e);if(t)return this.#linkTarget=t}catch(e){this.#readlinkFail(e.code);return}}readlinkSync(){let e=this.#linkTarget;if(e)return e;if(this.canReadlink()&&this.parent)try{let e=this.#fs.readlinkSync(this.fullpath()),t=this.parent.realpathSync()?.resolve(e);if(t)return this.#linkTarget=t}catch(e){this.#readlinkFail(e.code);return}}#readdirSuccess(e){this.#type|=wr;for(let t=e.provisional;t<e.length;t++){let n=e[t];n&&n.#markENOENT()}}#markENOENT(){this.#type&Dr||(this.#type=(this.#type|Dr)&Cr,this.#markChildrenENOENT())}#markChildrenENOENT(){let e=this.children();e.provisional=0;for(let t of e)t.#markENOENT()}#markENOREALPATH(){this.#type|=kr,this.#markENOTDIR()}#markENOTDIR(){if(this.#type&Er)return;let e=this.#type;(e&Sr)===_r&&(e&=Cr),this.#type=e|Er,this.#markChildrenENOENT()}#readdirFail(e=``){e===`ENOTDIR`||e===`EPERM`?this.#markENOTDIR():e===`ENOENT`?this.#markENOENT():this.children().provisional=0}#lstatFail(e=``){if(e===`ENOTDIR`){let e=this.parent;e.#markENOTDIR()}else e===`ENOENT`&&this.#markENOENT()}#readlinkFail(e=``){let t=this.#type;t|=Or,e===`ENOENT`&&(t|=Dr),(e===`EINVAL`||e===`UNKNOWN`)&&(t&=Cr),this.#type=t,e===`ENOTDIR`&&this.parent&&this.parent.#markENOTDIR()}#readdirAddChild(e,t){return this.#readdirMaybePromoteChild(e,t)||this.#readdirAddNewChild(e,t)}#readdirAddNewChild(e,t){let n=Mr(e),r=this.newChild(e.name,n,{parent:this}),i=r.#type&Sr;return i!==_r&&i!==br&&i!==mr&&(r.#type|=Er),t.unshift(r),t.provisional++,r}#readdirMaybePromoteChild(e,t){for(let n=t.provisional;n<t.length;n++){let r=t[n],i=this.nocase?Ir(e.name):Pr(e.name);if(i===r.#matchName)return this.#readdirPromoteChild(e,r,n,t)}}#readdirPromoteChild(e,t,n,r){let i=t.name;return t.#type=t.#type&Cr|Mr(e),i!==e.name&&(t.name=e.name),n!==r.provisional&&(n===r.length-1?r.pop():r.splice(n,1),r.unshift(t)),r.provisional++,t}async lstat(){if((this.#type&Dr)===0)try{return this.#applyStat(await this.#fs.promises.lstat(this.fullpath())),this}catch(e){this.#lstatFail(e.code)}}lstatSync(){if((this.#type&Dr)===0)try{return this.#applyStat(this.#fs.lstatSync(this.fullpath())),this}catch(e){this.#lstatFail(e.code)}}#applyStat(e){let{atime:t,atimeMs:n,birthtime:r,birthtimeMs:i,blksize:a,blocks:o,ctime:s,ctimeMs:c,dev:l,gid:u,ino:d,mode:f,mtime:p,mtimeMs:m,nlink:h,rdev:g,size:_,uid:v}=e;this.#atime=t,this.#atimeMs=n,this.#birthtime=r,this.#birthtimeMs=i,this.#blksize=a,this.#blocks=o,this.#ctime=s,this.#ctimeMs=c,this.#dev=l,this.#gid=u,this.#ino=d,this.#mode=f,this.#mtime=p,this.#mtimeMs=m,this.#nlink=h,this.#rdev=g,this.#size=_,this.#uid=v;let y=Mr(e);this.#type=this.#type&Cr|y|Tr,y!==mr&&y!==_r&&y!==br&&(this.#type|=Er)}#onReaddirCB=[];#readdirCBInFlight=!1;#callOnReaddirCB(e){this.#readdirCBInFlight=!1;let t=this.#onReaddirCB.slice();this.#onReaddirCB.length=0,t.forEach(t=>t(null,e))}readdirCB(e,t=!1){if(!this.canReaddir()){t?e(null,[]):queueMicrotask(()=>e(null,[]));return}let n=this.children();if(this.calledReaddir()){let r=n.slice(0,n.provisional);t?e(null,r):queueMicrotask(()=>e(null,r));return}if(this.#onReaddirCB.push(e),this.#readdirCBInFlight)return;this.#readdirCBInFlight=!0;let r=this.fullpath();this.#fs.readdir(r,{withFileTypes:!0},(e,t)=>{if(e)this.#readdirFail(e.code),n.provisional=0;else{for(let e of t)this.#readdirAddChild(e,n);this.#readdirSuccess(n)}this.#callOnReaddirCB(n.slice(0,n.provisional))})}#asyncReaddirInFlight;async readdir(){if(!this.canReaddir())return[];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();if(this.#asyncReaddirInFlight)await this.#asyncReaddirInFlight;else{let n=()=>{};this.#asyncReaddirInFlight=new Promise(e=>n=e);try{for(let n of await this.#fs.promises.readdir(t,{withFileTypes:!0}))this.#readdirAddChild(n,e);this.#readdirSuccess(e)}catch(t){this.#readdirFail(t.code),e.provisional=0}this.#asyncReaddirInFlight=void 0,n()}return e.slice(0,e.provisional)}readdirSync(){if(!this.canReaddir())return[];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();try{for(let n of this.#fs.readdirSync(t,{withFileTypes:!0}))this.#readdirAddChild(n,e);this.#readdirSuccess(e)}catch(t){this.#readdirFail(t.code),e.provisional=0}return e.slice(0,e.provisional)}canReaddir(){if(this.#type&Ar)return!1;let e=Sr&this.#type;return e===mr||e===_r||e===br}shouldWalk(e,t){return(this.#type&_r)===_r&&!(this.#type&Ar)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#realpath)return this.#realpath;if(!((Or|640)&this.#type))try{let e=await this.#fs.promises.realpath(this.fullpath());return this.#realpath=this.resolve(e)}catch(e){this.#markENOREALPATH()}}realpathSync(){if(this.#realpath)return this.#realpath;if(!((Or|640)&this.#type))try{let e=this.#fs.realpathSync(this.fullpath());return this.#realpath=this.resolve(e)}catch(e){this.#markENOREALPATH()}}[zr](e){if(e===this)return;e.isCWD=!1,this.isCWD=!0;let t=new Set([]),n=[],r=this;for(;r&&r.parent;)t.add(r),r.#relative=n.join(this.sep),r.#relativePosix=n.join(`/`),r=r.parent,n.push(`..`);for(r=e;r&&r.parent&&!t.has(r);)r.#relative=void 0,r.#relativePosix=void 0,r=r.parent}},Vr=class e extends Br{sep=`\\`;splitSep=pr;constructor(e,t=mr,n,r,i,a,o){super(e,t,n,r,i,a,o)}newChild(t,n=mr,r={}){return new e(t,n,this.root,this.roots,this.nocase,this.childrenCache(),r)}getRootString(e){return v.parse(e).root}getRoot(e){if(e=fr(e.toUpperCase()),e===this.root.name)return this.root;for(let[t,n]of Object.entries(this.roots))if(this.sameRoot(e,t))return this.roots[e]=n;return this.roots[e]=new Wr(e,this).root}sameRoot(e,t=this.root.name){return e=e.toUpperCase().replace(/\//g,`\\`).replace(dr,`$1\\`),e===t}},Hr=class e extends Br{splitSep=`/`;sep=`/`;constructor(e,t=mr,n,r,i,a,o){super(e,t,n,r,i,a,o)}getRootString(e){return e.startsWith(`/`)?`/`:``}getRoot(e){return this.root}newChild(t,n=mr,r={}){return new e(t,n,this.root,this.roots,this.nocase,this.childrenCache(),r)}},Ur=class{root;rootPath;roots;cwd;#resolveCache;#resolvePosixCache;#children;nocase;#fs;constructor(e=process.cwd(),t,n,{nocase:r,childrenCacheSize:i=16*1024,fs:a=lr}={}){this.#fs=ur(a),(e instanceof URL||e.startsWith(`file://`))&&(e=se(e));let o=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),this.#resolveCache=new Lr,this.#resolvePosixCache=new Lr,this.#children=new Rr(i);let s=o.substring(this.rootPath.length).split(n);if(s.length===1&&!s[0]&&s.pop(),r===void 0)throw TypeError(`must provide nocase setting to PathScurryBase ctor`);this.nocase=r,this.root=this.newRoot(this.#fs),this.roots[this.rootPath]=this.root;let c=this.root,l=s.length-1,u=t.sep,d=this.rootPath,f=!1;for(let e of s){let t=l--;c=c.child(e,{relative:Array(t).fill(`..`).join(u),relativePosix:Array(t).fill(`..`).join(`/`),fullpath:d+=(f?``:u)+e}),f=!0}this.cwd=c}depth(e=this.cwd){return typeof e==`string`&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return this.#children}resolve(...e){let t=``;for(let n=e.length-1;n>=0;n--){let r=e[n];if(!(!r||r===`.`)&&(t=t?`${r}/${t}`:r,this.isAbsolute(r)))break}let n=this.#resolveCache.get(t);if(n!==void 0)return n;let r=this.cwd.resolve(t).fullpath();return this.#resolveCache.set(t,r),r}resolvePosix(...e){let t=``;for(let n=e.length-1;n>=0;n--){let r=e[n];if(!(!r||r===`.`)&&(t=t?`${r}/${t}`:r,this.isAbsolute(r)))break}let n=this.#resolvePosixCache.get(t);if(n!==void 0)return n;let r=this.cwd.resolve(t).fullpathPosix();return this.#resolvePosixCache.set(t,r),r}relative(e=this.cwd){return typeof e==`string`&&(e=this.cwd.resolve(e)),e.relative()}relativePosix(e=this.cwd){return typeof e==`string`&&(e=this.cwd.resolve(e)),e.relativePosix()}basename(e=this.cwd){return typeof e==`string`&&(e=this.cwd.resolve(e)),e.name}dirname(e=this.cwd){return typeof e==`string`&&(e=this.cwd.resolve(e)),(e.parent||e).fullpath()}async readdir(e=this.cwd,t={withFileTypes:!0}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof Br||(t=e,e=this.cwd);let{withFileTypes:n}=t;if(e.canReaddir()){let t=await e.readdir();return n?t:t.map(e=>e.name)}else return[]}readdirSync(e=this.cwd,t={withFileTypes:!0}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof Br||(t=e,e=this.cwd);let{withFileTypes:n=!0}=t;return e.canReaddir()?n?e.readdirSync():e.readdirSync().map(e=>e.name):[]}async lstat(e=this.cwd){return typeof e==`string`&&(e=this.cwd.resolve(e)),e.lstat()}lstatSync(e=this.cwd){return typeof e==`string`&&(e=this.cwd.resolve(e)),e.lstatSync()}async readlink(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof Br||(t=e.withFileTypes,e=this.cwd);let n=await e.readlink();return t?n:n?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof Br||(t=e.withFileTypes,e=this.cwd);let n=e.readlinkSync();return t?n:n?.fullpath()}async realpath(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof Br||(t=e.withFileTypes,e=this.cwd);let n=await e.realpath();return t?n:n?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof Br||(t=e.withFileTypes,e=this.cwd);let n=e.realpathSync();return t?n:n?.fullpath()}async walk(e=this.cwd,t={}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof Br||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:r=!1,filter:i,walkFilter:a}=t,o=[];(!i||i(e))&&o.push(n?e:e.fullpath());let s=new Set,c=(e,t)=>{s.add(e),e.readdirCB((e,l)=>{if(e)return t(e);let u=l.length;if(!u)return t();let d=()=>{--u===0&&t()};for(let e of l)(!i||i(e))&&o.push(n?e:e.fullpath()),r&&e.isSymbolicLink()?e.realpath().then(e=>e?.isUnknown()?e.lstat():e).then(e=>e?.shouldWalk(s,a)?c(e,d):d()):e.shouldWalk(s,a)?c(e,d):d()},!0)},l=e;return new Promise((e,t)=>{c(l,n=>{if(n)return t(n);e(o)})})}walkSync(e=this.cwd,t={}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof Br||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:r=!1,filter:i,walkFilter:a}=t,o=[];(!i||i(e))&&o.push(n?e:e.fullpath());let s=new Set([e]);for(let e of s){let t=e.readdirSync();for(let e of t){(!i||i(e))&&o.push(n?e:e.fullpath());let t=e;if(e.isSymbolicLink()){if(!(r&&(t=e.realpathSync())))continue;t.isUnknown()&&t.lstatSync()}t.shouldWalk(s,a)&&s.add(t)}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return typeof e==`string`?e=this.cwd.resolve(e):e instanceof Br||(t=e,e=this.cwd),this.stream(e,t)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(e=this.cwd,t={}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof Br||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:r=!1,filter:i,walkFilter:a}=t;(!i||i(e))&&(yield n?e:e.fullpath());let o=new Set([e]);for(let e of o){let t=e.readdirSync();for(let e of t){(!i||i(e))&&(yield n?e:e.fullpath());let t=e;if(e.isSymbolicLink()){if(!(r&&(t=e.realpathSync())))continue;t.isUnknown()&&t.lstatSync()}t.shouldWalk(o,a)&&o.add(t)}}}stream(e=this.cwd,t={}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof Br||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:r=!1,filter:i,walkFilter:a}=t,o=new sr({objectMode:!0});(!i||i(e))&&o.write(n?e:e.fullpath());let s=new Set,c=[e],l=0,u=()=>{let e=!1;for(;!e;){let t=c.shift();if(!t){l===0&&o.end();return}l++,s.add(t);let d=(t,p,m=!1)=>{if(t)return o.emit(`error`,t);if(r&&!m){let e=[];for(let t of p)t.isSymbolicLink()&&e.push(t.realpath().then(e=>e?.isUnknown()?e.lstat():e));if(e.length){Promise.all(e).then(()=>d(null,p,!0));return}}for(let t of p)t&&(!i||i(t))&&(o.write(n?t:t.fullpath())||(e=!0));l--;for(let e of p){let t=e.realpathCached()||e;t.shouldWalk(s,a)&&c.push(t)}e&&!o.flowing?o.once(`drain`,u):f||u()},f=!0;t.readdirCB(d,!0),f=!1}};return u(),o}streamSync(e=this.cwd,t={}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof Br||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:r=!1,filter:i,walkFilter:a}=t,o=new sr({objectMode:!0}),s=new Set;(!i||i(e))&&o.write(n?e:e.fullpath());let c=[e],l=0,u=()=>{let e=!1;for(;!e;){let t=c.shift();if(!t){l===0&&o.end();return}l++,s.add(t);let u=t.readdirSync();for(let t of u)(!i||i(t))&&(o.write(n?t:t.fullpath())||(e=!0));l--;for(let e of u){let t=e;if(e.isSymbolicLink()){if(!(r&&(t=e.realpathSync())))continue;t.isUnknown()&&t.lstatSync()}t.shouldWalk(s,a)&&c.push(t)}}e&&!o.flowing&&o.once(`drain`,u)};return u(),o}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e==`string`?this.cwd.resolve(e):e,this.cwd[zr](t)}},Wr=class extends Ur{sep=`\\`;constructor(e=process.cwd(),t={}){let{nocase:n=!0}=t;super(e,v,`\\`,{...t,nocase:n}),this.nocase=n;for(let e=this.cwd;e;e=e.parent)e.nocase=this.nocase}parseRootPath(e){return v.parse(e).root.toUpperCase()}newRoot(e){return new Vr(this.rootPath,_r,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith(`/`)||e.startsWith(`\\`)||/^[a-z]:(\/|\\)/i.test(e)}},Gr=class extends Ur{sep=`/`;constructor(e=process.cwd(),t={}){let{nocase:n=!1}=t;super(e,g,`/`,{...t,nocase:n}),this.nocase=n}parseRootPath(e){return`/`}newRoot(e){return new Hr(this.rootPath,_r,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith(`/`)}},Kr=class extends Gr{constructor(e=process.cwd(),t={}){let{nocase:n=!0}=t;super(e,{...t,nocase:n})}};process.platform;const qr=process.platform===`win32`?Wr:process.platform===`darwin`?Kr:Gr,Jr=e=>e.length>=1,Yr=e=>e.length>=1;var Xr=class e{#patternList;#globList;#index;length;#platform;#rest;#globString;#isDrive;#isUNC;#isAbsolute;#followGlobstar=!0;constructor(e,t,n,r){if(!Jr(e))throw TypeError(`empty pattern list`);if(!Yr(t))throw TypeError(`empty glob list`);if(t.length!==e.length)throw TypeError(`mismatched pattern list and glob list lengths`);if(this.length=e.length,n<0||n>=this.length)throw TypeError(`index out of range`);if(this.#patternList=e,this.#globList=t,this.#index=n,this.#platform=r,this.#index===0){if(this.isUNC()){let[e,t,n,r,...i]=this.#patternList,[a,o,s,c,...l]=this.#globList;i[0]===``&&(i.shift(),l.shift());let u=[e,t,n,r,``].join(`/`),d=[a,o,s,c,``].join(`/`);this.#patternList=[u,...i],this.#globList=[d,...l],this.length=this.#patternList.length}else if(this.isDrive()||this.isAbsolute()){let[e,...t]=this.#patternList,[n,...r]=this.#globList;t[0]===``&&(t.shift(),r.shift());let i=e+`/`,a=n+`/`;this.#patternList=[i,...t],this.#globList=[a,...r],this.length=this.#patternList.length}}}pattern(){return this.#patternList[this.#index]}isString(){return typeof this.#patternList[this.#index]==`string`}isGlobstar(){return this.#patternList[this.#index]===x}isRegExp(){return this.#patternList[this.#index]instanceof RegExp}globString(){return this.#globString=this.#globString||(this.#index===0?this.isAbsolute()?this.#globList[0]+this.#globList.slice(1).join(`/`):this.#globList.join(`/`):this.#globList.slice(this.#index).join(`/`))}hasMore(){return this.length>this.#index+1}rest(){return this.#rest===void 0?this.hasMore()?(this.#rest=new e(this.#patternList,this.#globList,this.#index+1,this.#platform),this.#rest.#isAbsolute=this.#isAbsolute,this.#rest.#isUNC=this.#isUNC,this.#rest.#isDrive=this.#isDrive,this.#rest):this.#rest=null:this.#rest}isUNC(){let e=this.#patternList;return this.#isUNC===void 0?this.#isUNC=this.#platform===`win32`&&this.#index===0&&e[0]===``&&e[1]===``&&typeof e[2]==`string`&&!!e[2]&&typeof e[3]==`string`&&!!e[3]:this.#isUNC}isDrive(){let e=this.#patternList;return this.#isDrive===void 0?this.#isDrive=this.#platform===`win32`&&this.#index===0&&this.length>1&&typeof e[0]==`string`&&/^[a-z]:$/i.test(e[0]):this.#isDrive}isAbsolute(){let e=this.#patternList;return this.#isAbsolute===void 0?this.#isAbsolute=e[0]===``&&e.length>1||this.isDrive()||this.isUNC():this.#isAbsolute}root(){let e=this.#patternList[0];return typeof e==`string`&&this.isAbsolute()&&this.#index===0?e:``}checkFollowGlobstar(){return!(this.#index===0||!this.isGlobstar()||!this.#followGlobstar)}markFollowGlobstar(){return this.#index===0||!this.isGlobstar()||!this.#followGlobstar?!1:(this.#followGlobstar=!1,!0)}};const Zr=typeof process==`object`&&process&&typeof process.platform==`string`?process.platform:`linux`;var Qr=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:t,nocase:n,noext:r,noglobstar:i,platform:a=Zr}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=a,this.mmopts={dot:!0,nobrace:t,nocase:n,noext:r,noglobstar:i,optimizationLevel:2,platform:a,nocomment:!0,nonegate:!0};for(let t of e)this.add(t)}add(e){let t=new ln(e,this.mmopts);for(let e=0;e<t.set.length;e++){let n=t.set[e],r=t.globParts[e];if(!n||!r)throw Error(`invalid pattern object`);for(;n[0]===`.`&&r[0]===`.`;)n.shift(),r.shift();let i=new Xr(n,r,0,this.platform),a=new ln(i.globString(),this.mmopts),o=r[r.length-1]===`**`,s=i.isAbsolute();s?this.absolute.push(a):this.relative.push(a),o&&(s?this.absoluteChildren.push(a):this.relativeChildren.push(a))}}ignored(e){let t=e.fullpath(),n=`${t}/`,r=e.relative()||`.`,i=`${r}/`;for(let e of this.relative)if(e.match(r)||e.match(i))return!0;for(let e of this.absolute)if(e.match(t)||e.match(n))return!0;return!1}childrenIgnored(e){let t=e.fullpath()+`/`,n=(e.relative()||`.`)+`/`;for(let e of this.relativeChildren)if(e.match(n))return!0;for(let e of this.absoluteChildren)if(e.match(t))return!0;return!1}},$r=class e{store;constructor(e=new Map){this.store=e}copy(){return new e(new Map(this.store))}hasWalked(e,t){return this.store.get(e.fullpath())?.has(t.globString())}storeWalked(e,t){let n=e.fullpath(),r=this.store.get(n);r?r.add(t.globString()):this.store.set(n,new Set([t.globString()]))}},ei=class{store=new Map;add(e,t,n){let r=(t?2:0)|(n?1:0),i=this.store.get(e);this.store.set(e,i===void 0?r:r&i)}entries(){return[...this.store.entries()].map(([e,t])=>[e,!!(t&2),!!(t&1)])}},ti=class{store=new Map;add(e,t){if(!e.canReaddir())return;let n=this.store.get(e);n?n.find(e=>e.globString()===t.globString())||n.push(t):this.store.set(e,[t])}get(e){let t=this.store.get(e);if(!t)throw Error(`attempting to walk unknown path`);return t}entries(){return this.keys().map(e=>[e,this.store.get(e)])}keys(){return[...this.store.keys()].filter(e=>e.canReaddir())}},ni=class e{hasWalkedCache;matches=new ei;subwalks=new ti;patterns;follow;dot;opts;constructor(e,t){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=t?t.copy():new $r}processPatterns(e,t){this.patterns=t;let n=t.map(t=>[e,t]);for(let[e,t]of n){this.hasWalkedCache.storeWalked(e,t);let n=t.root(),r=t.isAbsolute()&&this.opts.absolute!==!1;if(n){e=e.resolve(n===`/`&&this.opts.root!==void 0?this.opts.root:n);let r=t.rest();if(r)t=r;else{this.matches.add(e,!0,!1);continue}}if(e.isENOENT())continue;let i,a,o=!1;for(;typeof(i=t.pattern())==`string`&&(a=t.rest());){let n=e.resolve(i);e=n,t=a,o=!0}if(i=t.pattern(),a=t.rest(),o){if(this.hasWalkedCache.hasWalked(e,t))continue;this.hasWalkedCache.storeWalked(e,t)}if(typeof i==`string`){let t=i===`..`||i===``||i===`.`;this.matches.add(e.resolve(i),r,t);continue}else if(i===x){(!e.isSymbolicLink()||this.follow||t.checkFollowGlobstar())&&this.subwalks.add(e,t);let n=a?.pattern(),i=a?.rest();if(!a||(n===``||n===`.`)&&!i)this.matches.add(e,r,n===``||n===`.`);else if(n===`..`){let t=e.parent||e;i?this.hasWalkedCache.hasWalked(t,i)||this.subwalks.add(t,i):this.matches.add(t,r,!0)}}else i instanceof RegExp&&this.subwalks.add(e,t)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new e(this.opts,this.hasWalkedCache)}filterEntries(e,t){let n=this.subwalks.get(e),r=this.child();for(let e of t)for(let t of n){let n=t.isAbsolute(),i=t.pattern(),a=t.rest();i===x?r.testGlobstar(e,t,a,n):i instanceof RegExp?r.testRegExp(e,i,a,n):r.testString(e,i,a,n)}return r}testGlobstar(e,t,n,r){if((this.dot||!e.name.startsWith(`.`))&&(t.hasMore()||this.matches.add(e,r,!1),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,t):e.isSymbolicLink()&&(n&&t.checkFollowGlobstar()?this.subwalks.add(e,n):t.markFollowGlobstar()&&this.subwalks.add(e,t)))),n){let t=n.pattern();if(typeof t==`string`&&t!==`..`&&t!==``&&t!==`.`)this.testString(e,t,n.rest(),r);else if(t===`..`){let t=e.parent||e;this.subwalks.add(t,n)}else t instanceof RegExp&&this.testRegExp(e,t,n.rest(),r)}}testRegExp(e,t,n,r){t.test(e.name)&&(n?this.subwalks.add(e,n):this.matches.add(e,r,!1))}testString(e,t,n,r){e.isNamed(t)&&(n?this.subwalks.add(e,n):this.matches.add(e,r,!1))}};const ri=(e,t)=>typeof e==`string`?new Qr([e],t):Array.isArray(e)?new Qr(e,t):e;var ii=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#onResume=[];#ignore;#sep;signal;maxDepth;includeChildMatches;constructor(e,t,n){if(this.patterns=e,this.path=t,this.opts=n,this.#sep=!n.posix&&n.platform===`win32`?`\\`:`/`,this.includeChildMatches=n.includeChildMatches!==!1,(n.ignore||!this.includeChildMatches)&&(this.#ignore=ri(n.ignore??[],n),!this.includeChildMatches&&typeof this.#ignore.add!=`function`)){let e=`cannot ignore child matches, ignore lacks add() method.`;throw Error(e)}this.maxDepth=n.maxDepth||1/0,n.signal&&(this.signal=n.signal,this.signal.addEventListener(`abort`,()=>{this.#onResume.length=0}))}#ignored(e){return this.seen.has(e)||!!this.#ignore?.ignored?.(e)}#childrenIgnored(e){return!!this.#ignore?.childrenIgnored?.(e)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let e;for(;!this.paused&&(e=this.#onResume.shift());)e()}onResume(e){this.signal?.aborted||(this.paused?this.#onResume.push(e):e())}async matchCheck(e,t){if(t&&this.opts.nodir)return;let n;if(this.opts.realpath){if(n=e.realpathCached()||await e.realpath(),!n)return;e=n}let r=e.isUnknown()||this.opts.stat,i=r?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&i?.isSymbolicLink()){let e=await i.realpath();e&&(e.isUnknown()||this.opts.stat)&&await e.lstat()}return this.matchCheckTest(i,t)}matchCheckTest(e,t){return e&&(this.maxDepth===1/0||e.depth()<=this.maxDepth)&&(!t||e.canReaddir())&&(!this.opts.nodir||!e.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!e.isSymbolicLink()||!e.realpathCached()?.isDirectory())&&!this.#ignored(e)?e:void 0}matchCheckSync(e,t){if(t&&this.opts.nodir)return;let n;if(this.opts.realpath){if(n=e.realpathCached()||e.realpathSync(),!n)return;e=n}let r=e.isUnknown()||this.opts.stat,i=r?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&i?.isSymbolicLink()){let e=i.realpathSync();e&&(e?.isUnknown()||this.opts.stat)&&e.lstatSync()}return this.matchCheckTest(i,t)}matchFinish(e,t){if(this.#ignored(e))return;if(!this.includeChildMatches&&this.#ignore?.add){let t=`${e.relativePosix()}/**`;this.#ignore.add(t)}let n=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e);let r=this.opts.mark&&e.isDirectory()?this.#sep:``;if(this.opts.withFileTypes)this.matchEmit(e);else if(n){let t=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(t+r)}else{let t=this.opts.posix?e.relativePosix():e.relative(),n=this.opts.dotRelative&&!t.startsWith(`..`+this.#sep)?`.`+this.#sep:``;this.matchEmit(t?n+t+r:`.`+r)}}async match(e,t,n){let r=await this.matchCheck(e,n);r&&this.matchFinish(r,t)}matchSync(e,t,n){let r=this.matchCheckSync(e,n);r&&this.matchFinish(r,t)}walkCB(e,t,n){this.signal?.aborted&&n(),this.walkCB2(e,t,new ni(this.opts),n)}walkCB2(e,t,n,r){if(this.#childrenIgnored(e))return r();if(this.signal?.aborted&&r(),this.paused){this.onResume(()=>this.walkCB2(e,t,n,r));return}n.processPatterns(e,t);let i=1,a=()=>{--i===0&&r()};for(let[e,t,r]of n.matches.entries()){if(this.#ignored(e))continue;i++,this.match(e,t,r).then(()=>a())}for(let e of n.subwalkTargets()){if(this.maxDepth!==1/0&&e.depth()>=this.maxDepth)continue;i++;let t=e.readdirCached();e.calledReaddir()?this.walkCB3(e,t,n,a):e.readdirCB((t,r)=>this.walkCB3(e,r,n,a),!0)}a()}walkCB3(e,t,n,r){n=n.filterEntries(e,t);let i=1,a=()=>{--i===0&&r()};for(let[e,t,r]of n.matches.entries()){if(this.#ignored(e))continue;i++,this.match(e,t,r).then(()=>a())}for(let[e,t]of n.subwalks.entries())i++,this.walkCB2(e,t,n.child(),a);a()}walkCBSync(e,t,n){this.signal?.aborted&&n(),this.walkCB2Sync(e,t,new ni(this.opts),n)}walkCB2Sync(e,t,n,r){if(this.#childrenIgnored(e))return r();if(this.signal?.aborted&&r(),this.paused){this.onResume(()=>this.walkCB2Sync(e,t,n,r));return}n.processPatterns(e,t);let i=1,a=()=>{--i===0&&r()};for(let[e,t,r]of n.matches.entries()){if(this.#ignored(e))continue;this.matchSync(e,t,r)}for(let e of n.subwalkTargets()){if(this.maxDepth!==1/0&&e.depth()>=this.maxDepth)continue;i++;let t=e.readdirSync();this.walkCB3Sync(e,t,n,a)}a()}walkCB3Sync(e,t,n,r){n=n.filterEntries(e,t);let i=1,a=()=>{--i===0&&r()};for(let[e,t,r]of n.matches.entries()){if(this.#ignored(e))continue;this.matchSync(e,t,r)}for(let[e,t]of n.subwalks.entries())i++,this.walkCB2Sync(e,t,n.child(),a);a()}},ai=class extends ii{matches=new Set;constructor(e,t,n){super(e,t,n)}matchEmit(e){this.matches.add(e)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((e,t)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?t(this.signal.reason):e(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},oi=class extends ii{results;constructor(e,t,n){super(e,t,n),this.results=new sr({signal:this.signal,objectMode:!0}),this.results.on(`drain`,()=>this.resume()),this.results.on(`resume`,()=>this.resume())}matchEmit(e){this.results.write(e),this.results.flowing||this.pause()}stream(){let e=this.path;return e.isUnknown()?e.lstat().then(()=>{this.walkCB(e,this.patterns,()=>this.results.end())}):this.walkCB(e,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}};const si=typeof process==`object`&&process&&typeof process.platform==`string`?process.platform:`linux`;var ci=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(e,t){if(!t)throw TypeError(`glob options required`);if(this.withFileTypes=!!t.withFileTypes,this.signal=t.signal,this.follow=!!t.follow,this.dot=!!t.dot,this.dotRelative=!!t.dotRelative,this.nodir=!!t.nodir,this.mark=!!t.mark,t.cwd?(t.cwd instanceof URL||t.cwd.startsWith(`file://`))&&(t.cwd=se(t.cwd)):this.cwd=``,this.cwd=t.cwd||``,this.root=t.root,this.magicalBraces=!!t.magicalBraces,this.nobrace=!!t.nobrace,this.noext=!!t.noext,this.realpath=!!t.realpath,this.absolute=t.absolute,this.includeChildMatches=t.includeChildMatches!==!1,this.noglobstar=!!t.noglobstar,this.matchBase=!!t.matchBase,this.maxDepth=typeof t.maxDepth==`number`?t.maxDepth:1/0,this.stat=!!t.stat,this.ignore=t.ignore,this.withFileTypes&&this.absolute!==void 0)throw Error(`cannot set absolute and withFileTypes:true`);if(typeof e==`string`&&(e=[e]),this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(e=e.map(e=>e.replace(/\\/g,`/`))),this.matchBase){if(t.noglobstar)throw TypeError(`base matching requires globstar`);e=e.map(e=>e.includes(`/`)?e:`./**/${e}`)}if(this.pattern=e,this.platform=t.platform||si,this.opts={...t,platform:this.platform},t.scurry){if(this.scurry=t.scurry,t.nocase!==void 0&&t.nocase!==t.scurry.nocase)throw Error(`nocase option contradicts provided scurry option`)}else{let e=t.platform===`win32`?Wr:t.platform===`darwin`?Kr:t.platform?Gr:qr;this.scurry=new e(this.cwd,{nocase:t.nocase,fs:t.fs})}this.nocase=this.scurry.nocase;let n=this.platform===`darwin`||this.platform===`win32`,r={...t,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:n,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},i=this.pattern.map(e=>new ln(e,r)),[a,o]=i.reduce((e,t)=>(e[0].push(...t.set),e[1].push(...t.globParts),e),[[],[]]);this.patterns=a.map((e,t)=>{let n=o[t];if(!n)throw Error(`invalid pattern object`);return new Xr(e,n,0,this.platform)})}async walk(){return[...await new ai(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth===1/0?1/0:this.maxDepth+this.scurry.cwd.depth(),platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return[...new ai(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth===1/0?1/0:this.maxDepth+this.scurry.cwd.depth(),platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new oi(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth===1/0?1/0:this.maxDepth+this.scurry.cwd.depth(),platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new oi(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth===1/0?1/0:this.maxDepth+this.scurry.cwd.depth(),platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}};const li=(e,t={})=>{Array.isArray(e)||(e=[e]);for(let n of e)if(new ln(n,t).hasMagic())return!0;return!1};function ui(e,t={}){return new ci(e,t).streamSync()}function di(e,t={}){return new ci(e,t).stream()}function fi(e,t={}){return new ci(e,t).walkSync()}async function pi(e,t={}){return new ci(e,t).walk()}function mi(e,t={}){return new ci(e,t).iterateSync()}function hi(e,t={}){return new ci(e,t).iterate()}const gi=ui,_i=Object.assign(di,{sync:ui}),vi=mi,yi=Object.assign(hi,{sync:mi}),bi=Object.assign(fi,{stream:ui,iterate:mi}),xi=Object.assign(pi,{glob:pi,globSync:fi,sync:bi,globStream:di,stream:_i,globStreamSync:ui,streamSync:gi,globIterate:hi,iterate:yi,globIterateSync:mi,iterateSync:vi,Glob:ci,hasMagic:li,escape:Et,unescape:pt});xi.glob=xi;var Si=class{emitter;constructor(){this.emitter=Ae()}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 Ci(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 wi=class extends Si{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()})}};Ci(wi);var Ti=class e extends Si{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=m(this.logPath,this.getFileName(this.currentDate));if(!a(e))try{p(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=m(this.logPath,this.getFileName(this.currentDate));return i(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=l(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{f(m(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 Ei=()=>h.join(process.env.APPDATA??``,`overlayed`),Di=e=>h.join(Ei(),`apps`,e),Oi=e=>h.join(Di(e),`logs`);var ki=class{fileLogger;path;appId;messageQueue=new je;fileName;constructor(e){this.fileName=e}init(e){this.appId=e,this.path=Oi(e),this.fileLogger=new Ti(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})}};Ci(ki,`main.log`);const Ai=e(import.meta.url),{PipeEventServer:ji,PipeEventClient:Mi,PipeEventBase:Ni,ProcessMonitor:Pi,Process:Fi,InjectionMethod:Ii,AccessLevel:Li,HardwareInterface:Ri}=Ai(`@overlayed/app/dist/native-interface/build/overlayed_native_interface_x64.node`);var zi=class extends Si{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 ji(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 Bi=Ci(zi,`stats-cc`);function Vi(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 Hi=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)}}};const Ui=(e,t,n)=>{let r=e instanceof RegExp?Wi(e,n):e,i=t instanceof RegExp?Wi(t,n):t,a=r!==null&&i!=null&&Gi(r,i,n);return a&&{start:a[0],end:a[1],pre:n.slice(0,a[0]),body:n.slice(a[0]+r.length,a[1]),post:n.slice(a[1]+i.length)}},Wi=(e,t)=>{let n=t.match(e);return n?n[0]:null},Gi=(e,t,n)=>{let r,i,a,o,s,c=n.indexOf(e),l=n.indexOf(t,c+1),u=c;if(c>=0&&l>0){if(e===t)return[c,l];for(r=[],a=n.length;u>=0&&!s;){if(u===c)r.push(u),c=n.indexOf(e,u+1);else if(r.length===1){let e=r.pop();e!==void 0&&(s=[e,l])}else i=r.pop(),i!==void 0&&i<a&&(a=i,o=l),l=n.indexOf(t,u+1);u=c<l&&c>=0?c:l}r.length&&o!==void 0&&(s=[a,o])}return s},Ki=`\0SLASH`+Math.random()+`\0`,qi=`\0OPEN`+Math.random()+`\0`,Ji=`\0CLOSE`+Math.random()+`\0`,Yi=`\0COMMA`+Math.random()+`\0`,Xi=`\0PERIOD`+Math.random()+`\0`,Zi=new RegExp(Ki,`g`),Qi=new RegExp(qi,`g`),$i=new RegExp(Ji,`g`),ea=new RegExp(Yi,`g`),ta=new RegExp(Xi,`g`),na=/\\\\/g,ra=/\\{/g,ia=/\\}/g,aa=/\\,/g,oa=/\\./g;function sa(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function ca(e){return e.replace(na,Ki).replace(ra,qi).replace(ia,Ji).replace(aa,Yi).replace(oa,Xi)}function la(e){return e.replace(Zi,`\\`).replace(Qi,`{`).replace($i,`}`).replace(ea,`,`).replace(ta,`.`)}function ua(e){if(!e)return[``];let t=[],n=Ui(`{`,`}`,e);if(!n)return e.split(`,`);let{pre:r,body:i,post:a}=n,o=r.split(`,`);o[o.length-1]+=`{`+i+`}`;let s=ua(a);return a.length&&(o[o.length-1]+=s.shift(),o.push.apply(o,s)),t.push.apply(t,o),t}function da(e){return e?(e.slice(0,2)===`{}`&&(e=`\\{\\}`+e.slice(2)),ga(ca(e),!0).map(la)):[]}function fa(e){return`{`+e+`}`}function pa(e){return/^-?0\d/.test(e)}function ma(e,t){return e<=t}function ha(e,t){return e>=t}function ga(e,t){let n=[],r=Ui(`{`,`}`,e);if(!r)return[e];let i=r.pre,a=r.post.length?ga(r.post,!1):[``];if(/\$$/.test(r.pre))for(let e=0;e<a.length;e++){let t=i+`{`+r.body+`}`+a[e];n.push(t)}else{let o=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(r.body),s=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(r.body),c=o||s,l=r.body.indexOf(`,`)>=0;if(!c&&!l)return r.post.match(/,(?!,).*\}/)?(e=r.pre+`{`+r.body+Ji+r.post,ga(e)):[e];let u;if(c)u=r.body.split(/\.\./);else if(u=ua(r.body),u.length===1&&u[0]!==void 0&&(u=ga(u[0],!1).map(fa),u.length===1))return a.map(e=>r.pre+u[0]+e);let d;if(c&&u[0]!==void 0&&u[1]!==void 0){let e=sa(u[0]),t=sa(u[1]),n=Math.max(u[0].length,u[1].length),r=u.length===3&&u[2]!==void 0?Math.abs(sa(u[2])):1,i=ma,a=t<e;a&&(r*=-1,i=ha);let o=u.some(pa);d=[];for(let a=e;i(a,t);a+=r){let e;if(s)e=String.fromCharCode(a),e===`\\`&&(e=``);else if(e=String(a),o){let t=n-e.length;if(t>0){let n=Array(t+1).join(`0`);e=a<0?`-`+n+e.slice(1):n+e}}d.push(e)}}else{d=[];for(let e=0;e<u.length;e++)d.push.apply(d,ga(u[e],!1))}for(let e=0;e<d.length;e++)for(let r=0;r<a.length;r++){let o=i+d[e]+a[r];(!t||c||o)&&n.push(o)}}return n}const _a=1024*64,va=e=>{if(typeof e!=`string`)throw TypeError(`invalid pattern`);if(e.length>_a)throw TypeError(`pattern is too long`)},ya={"[:alnum:]":[`\\p{L}\\p{Nl}\\p{Nd}`,!0],"[:alpha:]":[`\\p{L}\\p{Nl}`,!0],"[:ascii:]":[`\\x00-\\x7f`,!1],"[:blank:]":[`\\p{Zs}\\t`,!0],"[:cntrl:]":[`\\p{Cc}`,!0],"[:digit:]":[`\\p{Nd}`,!0],"[:graph:]":[`\\p{Z}\\p{C}`,!0,!0],"[:lower:]":[`\\p{Ll}`,!0],"[:print:]":[`\\p{C}`,!0],"[:punct:]":[`\\p{P}`,!0],"[:space:]":[`\\p{Z}\\t\\r\\n\\v\\f`,!0],"[:upper:]":[`\\p{Lu}`,!0],"[:word:]":[`\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}`,!0],"[:xdigit:]":[`A-Fa-f0-9`,!1]},ba=e=>e.replace(/[[\]\\-]/g,`\\$&`),xa=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),Sa=e=>e.join(``),Ca=(e,t)=>{let n=t;if(e.charAt(n)!==`[`)throw Error(`not in a brace expression`);let r=[],i=[],a=n+1,o=!1,s=!1,c=!1,l=!1,u=n,d=``;WHILE:for(;a<e.length;){let t=e.charAt(a);if((t===`!`||t===`^`)&&a===n+1){l=!0,a++;continue}if(t===`]`&&o&&!c){u=a+1;break}if(o=!0,t===`\\`&&!c){c=!0,a++;continue}if(t===`[`&&!c){for(let[t,[o,c,l]]of Object.entries(ya))if(e.startsWith(t,a)){if(d)return[`$.`,!1,e.length-n,!0];a+=t.length,l?i.push(o):r.push(o),s=s||c;continue WHILE}}if(c=!1,d){t>d?r.push(ba(d)+`-`+ba(t)):t===d&&r.push(ba(t)),d=``,a++;continue}if(e.startsWith(`-]`,a+1)){r.push(ba(t+`-`)),a+=2;continue}if(e.startsWith(`-`,a+1)){d=t,a+=2;continue}r.push(ba(t)),a++}if(u<a)return[``,!1,0,!1];if(!r.length&&!i.length)return[`$.`,!1,e.length-n,!0];if(i.length===0&&r.length===1&&/^\\?.$/.test(r[0])&&!l){let e=r[0].length===2?r[0].slice(-1):r[0];return[xa(e),!1,u-n,!1]}let f=`[`+(l?`^`:``)+Sa(r)+`]`,p=`[`+(l?``:`^`)+Sa(i)+`]`,m=r.length&&i.length?`(`+f+`|`+p+`)`:r.length?f:p;return[m,s,u-n,!0]},wa=(e,{windowsPathsNoEscape:t=!1}={})=>t?e.replace(/\[([^\/\\])\]/g,`$1`):e.replace(/((?!\\).|^)\[([^\/\\])\]/g,`$1$2`).replace(/\\([^\/])/g,`$1`),Ta=new Set([`!`,`?`,`+`,`*`,`@`]),Ea=e=>Ta.has(e),Da=`(?!(?:^|/)\\.\\.?(?:$|/))`,Oa=`(?!\\.)`,ka=new Set([`[`,`.`]),Aa=new Set([`..`,`.`]),ja=new Set(`().*{}+?[]^$\\!`),Ma=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),Na=`[^/]`,Pa=Na+`*?`,Fa=Na+`+?`;var Ia=class e{type;#root;#hasMagic;#uflag=!1;#parts=[];#parent;#parentIndex;#negs;#filledNegs=!1;#options;#toString;#emptyExt=!1;constructor(e,t,n={}){this.type=e,e&&(this.#hasMagic=!0),this.#parent=t,this.#root=this.#parent?this.#parent.#root:this,this.#options=this.#root===this?n:this.#root.#options,this.#negs=this.#root===this?[]:this.#root.#negs,e===`!`&&!this.#root.#filledNegs&&this.#negs.push(this),this.#parentIndex=this.#parent?this.#parent.#parts.length:0}get hasMagic(){if(this.#hasMagic!==void 0)return this.#hasMagic;for(let e of this.#parts){if(typeof e==`string`)continue;if(e.type||e.hasMagic)return this.#hasMagic=!0}return this.#hasMagic}toString(){return this.#toString===void 0?this.type?this.#toString=this.type+`(`+this.#parts.map(e=>String(e)).join(`|`)+`)`:this.#toString=this.#parts.map(e=>String(e)).join(``):this.#toString}#fillNegs(){if(this!==this.#root)throw Error(`should only call on root`);if(this.#filledNegs)return this;this.toString(),this.#filledNegs=!0;let e;for(;e=this.#negs.pop();){if(e.type!==`!`)continue;let t=e,n=t.#parent;for(;n;){for(let r=t.#parentIndex+1;!n.type&&r<n.#parts.length;r++)for(let t of e.#parts){if(typeof t==`string`)throw Error(`string part in extglob AST??`);t.copyIn(n.#parts[r])}t=n,n=t.#parent}}return this}push(...t){for(let n of t){if(n===``)continue;if(typeof n!=`string`&&!(n instanceof e&&n.#parent===this))throw Error(`invalid part: `+n);this.#parts.push(n)}}toJSON(){let e=this.type===null?this.#parts.slice().map(e=>typeof e==`string`?e:e.toJSON()):[this.type,...this.#parts.map(e=>e.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#root||this.#root.#filledNegs&&this.#parent?.type===`!`)&&e.push({}),e}isStart(){if(this.#root===this)return!0;if(!this.#parent?.isStart())return!1;if(this.#parentIndex===0)return!0;let t=this.#parent;for(let n=0;n<this.#parentIndex;n++){let r=t.#parts[n];if(!(r instanceof e&&r.type===`!`))return!1}return!0}isEnd(){if(this.#root===this||this.#parent?.type===`!`)return!0;if(!this.#parent?.isEnd())return!1;if(!this.type)return this.#parent?.isEnd();let e=this.#parent?this.#parent.#parts.length:0;return this.#parentIndex===e-1}copyIn(e){typeof e==`string`?this.push(e):this.push(e.clone(this))}clone(t){let n=new e(this.type,t);for(let e of this.#parts)n.copyIn(e);return n}static#parseAST(t,n,r,i){let a=!1,o=!1,s=-1,c=!1;if(n.type===null){let l=r,u=``;for(;l<t.length;){let r=t.charAt(l++);if(a||r===`\\`){a=!a,u+=r;continue}if(o){l===s+1?(r===`^`||r===`!`)&&(c=!0):r===`]`&&!(l===s+2&&c)&&(o=!1),u+=r;continue}else if(r===`[`){o=!0,s=l,c=!1,u+=r;continue}if(!i.noext&&Ea(r)&&t.charAt(l)===`(`){n.push(u),u=``;let a=new e(r,n);l=e.#parseAST(t,a,l,i),n.push(a);continue}u+=r}return n.push(u),l}let l=r+1,u=new e(null,n),d=[],f=``;for(;l<t.length;){let r=t.charAt(l++);if(a||r===`\\`){a=!a,f+=r;continue}if(o){l===s+1?(r===`^`||r===`!`)&&(c=!0):r===`]`&&!(l===s+2&&c)&&(o=!1),f+=r;continue}else if(r===`[`){o=!0,s=l,c=!1,f+=r;continue}if(Ea(r)&&t.charAt(l)===`(`){u.push(f),f=``;let n=new e(r,u);u.push(n),l=e.#parseAST(t,n,l,i);continue}if(r===`|`){u.push(f),f=``,d.push(u),u=new e(null,n);continue}if(r===`)`)return f===``&&n.#parts.length===0&&(n.#emptyExt=!0),u.push(f),f=``,n.push(...d,u),l;f+=r}return n.type=null,n.#hasMagic=void 0,n.#parts=[t.substring(r-1)],l}static fromGlob(t,n={}){let r=new e(null,void 0,n);return e.#parseAST(t,r,0,n),r}toMMPattern(){if(this!==this.#root)return this.#root.toMMPattern();let e=this.toString(),[t,n,r,i]=this.toRegExpSource(),a=r||this.#hasMagic||this.#options.nocase&&!this.#options.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase();if(!a)return n;let o=(this.#options.nocase?`i`:``)+(i?`u`:``);return Object.assign(RegExp(`^${t}$`,o),{_src:t,_glob:e})}get options(){return this.#options}toRegExpSource(t){let n=t??!!this.#options.dot;if(this.#root===this&&this.#fillNegs(),!this.type){let r=this.isStart()&&this.isEnd(),i=this.#parts.map(n=>{let[i,a,o,s]=typeof n==`string`?e.#parseGlob(n,this.#hasMagic,r):n.toRegExpSource(t);return this.#hasMagic=this.#hasMagic||o,this.#uflag=this.#uflag||s,i}).join(``),a=``;if(this.isStart()&&typeof this.#parts[0]==`string`){let e=this.#parts.length===1&&Aa.has(this.#parts[0]);if(!e){let e=ka,r=n&&e.has(i.charAt(0))||i.startsWith(`\\.`)&&e.has(i.charAt(2))||i.startsWith(`\\.\\.`)&&e.has(i.charAt(4)),o=!n&&!t&&e.has(i.charAt(0));a=r?Da:o?Oa:``}}let o=``;this.isEnd()&&this.#root.#filledNegs&&this.#parent?.type===`!`&&(o=`(?:$|\\/)`);let s=a+i+o;return[s,wa(i),this.#hasMagic=!!this.#hasMagic,this.#uflag]}let r=this.type===`*`||this.type===`+`,i=this.type===`!`?`(?:(?!(?:`:`(?:`,a=this.#partsToRegExp(n);if(this.isStart()&&this.isEnd()&&!a&&this.type!==`!`){let e=this.toString();return this.#parts=[e],this.type=null,this.#hasMagic=void 0,[e,wa(this.toString()),!1,!1]}let o=!r||t||n?``:this.#partsToRegExp(!0);o===a&&(o=``),o&&(a=`(?:${a})(?:${o})*?`);let s=``;if(this.type===`!`&&this.#emptyExt)s=(this.isStart()&&!n?Oa:``)+Fa;else{let e=this.type===`!`?`))`+(this.isStart()&&!n&&!t?Oa:``)+Pa+`)`:this.type===`@`?`)`:this.type===`?`?`)?`:this.type===`+`&&o?`)`:this.type===`*`&&o?`)?`:`)${this.type}`;s=i+a+e}return[s,wa(a),this.#hasMagic=!!this.#hasMagic,this.#uflag]}#partsToRegExp(e){return this.#parts.map(t=>{if(typeof t==`string`)throw Error(`string type in extglob ast??`);let[n,r,i,a]=t.toRegExpSource(e);return this.#uflag=this.#uflag||a,n}).filter(e=>!(this.isStart()&&this.isEnd())||!!e).join(`|`)}static#parseGlob(e,t,n=!1){let r=!1,i=``,a=!1;for(let o=0;o<e.length;o++){let s=e.charAt(o);if(r){r=!1,i+=(ja.has(s)?`\\`:``)+s;continue}if(s===`\\`){o===e.length-1?i+=`\\\\`:r=!0;continue}if(s===`[`){let[n,r,s,c]=Ca(e,o);if(s){i+=n,a=a||r,o+=s-1,t=t||c;continue}}if(s===`*`){n&&e===`*`?i+=Fa:i+=Pa,t=!0;continue}if(s===`?`){i+=Na,t=!0;continue}i+=Ma(s)}return[i,wa(e),!!t,a]}};const La=(e,{windowsPathsNoEscape:t=!1}={})=>t?e.replace(/[?*()[\]]/g,`[$&]`):e.replace(/[?*()[\]\\]/g,`\\$&`),Ra=(e,t,n={})=>(va(t),!n.nocomment&&t.charAt(0)===`#`?!1:new So(t,n).match(e)),za=/^\*+([^+@!?\*\[\(]*)$/,Ba=e=>t=>!t.startsWith(`.`)&&t.endsWith(e),Va=e=>t=>t.endsWith(e),Ha=e=>(e=e.toLowerCase(),t=>!t.startsWith(`.`)&&t.toLowerCase().endsWith(e)),Ua=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),Wa=/^\*+\.\*+$/,Ga=e=>!e.startsWith(`.`)&&e.includes(`.`),Ka=e=>e!==`.`&&e!==`..`&&e.includes(`.`),qa=/^\.\*+$/,Ja=e=>e!==`.`&&e!==`..`&&e.startsWith(`.`),Ya=/^\*+$/,Xa=e=>e.length!==0&&!e.startsWith(`.`),Za=e=>e.length!==0&&e!==`.`&&e!==`..`,Qa=/^\?+([^+@!?\*\[\(]*)?$/,$a=([e,t=``])=>{let n=ro([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},eo=([e,t=``])=>{let n=io([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},to=([e,t=``])=>{let n=io([e]);return t?e=>n(e)&&e.endsWith(t):n},no=([e,t=``])=>{let n=ro([e]);return t?e=>n(e)&&e.endsWith(t):n},ro=([e])=>{let t=e.length;return e=>e.length===t&&!e.startsWith(`.`)},io=([e])=>{let t=e.length;return e=>e.length===t&&e!==`.`&&e!==`..`},ao=typeof process==`object`&&process?typeof process.env==`object`&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:`posix`,oo={win32:{sep:`\\`},posix:{sep:`/`}},so=ao===`win32`?oo.win32.sep:oo.posix.sep;Ra.sep=so;const co=Symbol(`globstar **`);Ra.GLOBSTAR=co;const lo=`[^/]`,uo=lo+`*?`,fo=`(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?`,po=`(?:(?!(?:\\/|^)\\.).)*?`,mo=(e,t={})=>n=>Ra(n,e,t);Ra.filter=mo;const ho=(e,t={})=>Object.assign({},e,t),go=e=>{if(!e||typeof e!=`object`||!Object.keys(e).length)return Ra;let t=Ra,n=(n,r,i={})=>t(n,r,ho(e,i));return Object.assign(n,{Minimatch:class extends t.Minimatch{constructor(t,n={}){super(t,ho(e,n))}static defaults(n){return t.defaults(ho(e,n)).Minimatch}},AST:class extends t.AST{constructor(t,n,r={}){super(t,n,ho(e,r))}static fromGlob(n,r={}){return t.AST.fromGlob(n,ho(e,r))}},unescape:(n,r={})=>t.unescape(n,ho(e,r)),escape:(n,r={})=>t.escape(n,ho(e,r)),filter:(n,r={})=>t.filter(n,ho(e,r)),defaults:n=>t.defaults(ho(e,n)),makeRe:(n,r={})=>t.makeRe(n,ho(e,r)),braceExpand:(n,r={})=>t.braceExpand(n,ho(e,r)),match:(n,r,i={})=>t.match(n,r,ho(e,i)),sep:t.sep,GLOBSTAR:co})};Ra.defaults=go;const _o=(e,t={})=>(va(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:da(e));Ra.braceExpand=_o;const vo=(e,t={})=>new So(e,t).makeRe();Ra.makeRe=vo;const yo=(e,t,n={})=>{let r=new So(t,n);return e=e.filter(e=>r.match(e)),r.options.nonull&&!e.length&&e.push(t),e};Ra.match=yo;const bo=/[?*]|[+@!]\(.*?\)|\[|\]/,xo=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`);var So=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,t={}){va(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||ao,this.isWindows=this.platform===`win32`,this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,`/`)),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!t.nonegate,this.comment=!1,this.empty=!1,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot===void 0?!!(this.isWindows&&this.nocase):t.windowsNoMagicRoot,this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let t of e)if(typeof t!=`string`)return!0;return!1}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)===`#`){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...e)=>console.error(...e)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(e=>this.slashSplit(e));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let r=this.globParts.map((e,t,n)=>{if(this.isWindows&&this.windowsNoMagicRoot){let t=e[0]===``&&e[1]===``&&(e[2]===`?`||!bo.test(e[2]))&&!bo.test(e[3]),n=/^[a-z]:/i.test(e[0]);if(t)return[...e.slice(0,4),...e.slice(4).map(e=>this.parse(e))];if(n)return[e[0],...e.slice(1).map(e=>this.parse(e))]}return e.map(e=>this.parse(e))});if(this.debug(this.pattern,r),this.set=r.filter(e=>e.indexOf(!1)===-1),this.isWindows)for(let e=0;e<this.set.length;e++){let t=this.set[e];t[0]===``&&t[1]===``&&this.globParts[e][2]===`?`&&typeof t[3]==`string`&&/^[a-z]:$/i.test(t[3])&&(t[2]=`?`)}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let t=0;t<e.length;t++)for(let n=0;n<e[t].length;n++)e[t][n]===`**`&&(e[t][n]=`*`);let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):e=t>=1?this.levelOneOptimize(e):this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(e=>{let t=-1;for(;(t=e.indexOf(`**`,t+1))!==-1;){let n=t;for(;e[n+1]===`**`;)n++;n!==t&&e.splice(t,n-t)}return e})}levelOneOptimize(e){return e.map(e=>(e=e.reduce((e,t)=>{let n=e[e.length-1];return t===`**`&&n===`**`?e:t===`..`&&n&&n!==`..`&&n!==`.`&&n!==`**`?(e.pop(),e):(e.push(t),e)},[]),e.length===0?[``]:e))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let n=1;n<e.length-1;n++){let r=e[n];n===1&&r===``&&e[0]===``||(r===`.`||r===``)&&(t=!0,e.splice(n,1),n--)}e[0]===`.`&&e.length===2&&(e[1]===`.`||e[1]===``)&&(t=!0,e.pop())}let n=0;for(;(n=e.indexOf(`..`,n+1))!==-1;){let r=e[n-1];r&&r!==`.`&&r!==`..`&&r!==`**`&&(t=!0,e.splice(n-1,2),n-=2)}}while(t);return e.length===0?[``]:e}firstPhasePreProcess(e){let t=!1;do{t=!1;for(let n of e){let r=-1;for(;(r=n.indexOf(`**`,r+1))!==-1;){let i=r;for(;n[i+1]===`**`;)i++;i>r&&n.splice(r+1,i-r);let a=n[r+1],o=n[r+2],s=n[r+3];if(a!==`..`||!o||o===`.`||o===`..`||!s||s===`.`||s===`..`)continue;t=!0,n.splice(r,1);let c=n.slice(0);c[r]=`**`,e.push(c),r--}if(!this.preserveMultipleSlashes){for(let e=1;e<n.length-1;e++){let r=n[e];e===1&&r===``&&n[0]===``||(r===`.`||r===``)&&(t=!0,n.splice(e,1),e--)}n[0]===`.`&&n.length===2&&(n[1]===`.`||n[1]===``)&&(t=!0,n.pop())}let i=0;for(;(i=n.indexOf(`..`,i+1))!==-1;){let e=n[i-1];if(e&&e!==`.`&&e!==`..`&&e!==`**`){t=!0;let e=i===1&&n[i+1]===`**`,r=e?[`.`]:[];n.splice(i-1,2,...r),n.length===0&&n.push(``),i-=2}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let n=t+1;n<e.length;n++){let r=this.partsMatch(e[t],e[n],!this.preserveMultipleSlashes);if(r){e[t]=[],e[n]=r;break}}return e.filter(e=>e.length)}partsMatch(e,t,n=!1){let r=0,i=0,a=[],o=``;for(;r<e.length&&i<t.length;)if(e[r]===t[i])a.push(o===`b`?t[i]:e[r]),r++,i++;else if(n&&e[r]===`**`&&t[i]===e[r+1])a.push(e[r]),r++;else if(n&&t[i]===`**`&&e[r]===t[i+1])a.push(t[i]),i++;else if(e[r]===`*`&&t[i]&&(this.options.dot||!t[i].startsWith(`.`))&&t[i]!==`**`){if(o===`b`)return!1;o=`a`,a.push(e[r]),r++,i++}else if(t[i]===`*`&&e[r]&&(this.options.dot||!e[r].startsWith(`.`))&&e[r]!==`**`){if(o===`a`)return!1;o=`b`,a.push(t[i]),r++,i++}else return!1;return e.length===t.length&&a}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=!1,n=0;for(let r=0;r<e.length&&e.charAt(r)===`!`;r++)t=!t,n++;n&&(this.pattern=e.slice(n)),this.negate=t}matchOne(e,t,n=!1){let r=this.options;if(this.isWindows){let n=typeof e[0]==`string`&&/^[a-z]:$/i.test(e[0]),r=!n&&e[0]===``&&e[1]===``&&e[2]===`?`&&/^[a-z]:$/i.test(e[3]),i=typeof t[0]==`string`&&/^[a-z]:$/i.test(t[0]),a=!i&&t[0]===``&&t[1]===``&&t[2]===`?`&&typeof t[3]==`string`&&/^[a-z]:$/i.test(t[3]),o=r?3:n?0:void 0,s=a?3:i?0:void 0;if(typeof o==`number`&&typeof s==`number`){let[n,r]=[e[o],t[s]];n.toLowerCase()===r.toLowerCase()&&(t[s]=n,s>o?t=t.slice(s):o>s&&(e=e.slice(o)))}}let{optimizationLevel:i=1}=this.options;i>=2&&(e=this.levelTwoFileOptimize(e)),this.debug(`matchOne`,this,{file:e,pattern:t}),this.debug(`matchOne`,e.length,t.length);for(var a=0,o=0,s=e.length,c=t.length;a<s&&o<c;a++,o++){this.debug(`matchOne loop`);var l=t[o],u=e[a];if(this.debug(t,l,u),l===!1)return!1;if(l===co){this.debug(`GLOBSTAR`,[t,l,u]);var d=a,f=o+1;if(f===c){for(this.debug(`** at the end`);a<s;a++)if(e[a]===`.`||e[a]===`..`||!r.dot&&e[a].charAt(0)===`.`)return!1;return!0}for(;d<s;){var p=e[d];if(this.debug(`
|
|
4
|
+
globstar while`,e,d,t,f,p),this.matchOne(e.slice(d),t.slice(f),n))return this.debug(`globstar found match!`,d,s,p),!0;if(p===`.`||p===`..`||!r.dot&&p.charAt(0)===`.`){this.debug(`dot detected!`,e,d,t,f);break}this.debug(`globstar swallow a segment, and continue`),d++}return!!(n&&(this.debug(`
|
|
5
|
+
>>> no match, partial?`,e,d,t,f),d===s))}let i;if(typeof l==`string`?(i=u===l,this.debug(`string match`,l,u,i)):(i=l.test(u),this.debug(`pattern match`,l,u,i)),!i)return!1}if(a===s&&o===c)return!0;if(a===s)return n;if(o===c)return a===s-1&&e[a]===``;throw Error(`wtf?`)}braceExpand(){return _o(this.pattern,this.options)}parse(e){va(e);let t=this.options;if(e===`**`)return co;if(e===``)return``;let n,r=null;(n=e.match(Ya))?r=t.dot?Za:Xa:(n=e.match(za))?r=(t.nocase?t.dot?Ua:Ha:t.dot?Va:Ba)(n[1]):(n=e.match(Qa))?r=(t.nocase?t.dot?eo:$a:t.dot?to:no)(n):(n=e.match(Wa))?r=t.dot?Ka:Ga:(n=e.match(qa))&&(r=Ja);let i=Ia.fromGlob(e,this.options).toMMPattern();return r&&typeof i==`object`&&Reflect.defineProperty(i,`test`,{value:r}),i}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let t=this.options,n=t.noglobstar?uo:t.dot?fo:po,r=new Set(t.nocase?[`i`]:[]),i=e.map(e=>{let t=e.map(e=>{if(e instanceof RegExp)for(let t of e.flags.split(``))r.add(t);return typeof e==`string`?xo(e):e===co?co:e._src});return t.forEach((e,r)=>{let i=t[r+1],a=t[r-1];e!==co||a===co||(a===void 0?i!==void 0&&i!==co?t[r+1]=`(?:\\/|`+n+`\\/)?`+i:t[r]=n:i===void 0?t[r-1]=a+`(?:\\/|`+n+`)?`:i!==co&&(t[r-1]=a+`(?:\\/|\\/`+n+`\\/)`+i,t[r+1]=co))}),t.filter(e=>e!==co).join(`/`)}).join(`|`),[a,o]=e.length>1?[`(?:`,`)`]:[``,``];i=`^`+a+i+o+`$`,this.negate&&(i=`^(?!`+i+`).+$`);try{this.regexp=new RegExp(i,[...r].join(``))}catch(e){this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split(`/`):this.isWindows&&/^\/\/[^\/]+/.test(e)?[``,...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug(`match`,e,this.pattern),this.comment)return!1;if(this.empty)return e===``;if(e===`/`&&t)return!0;let n=this.options;this.isWindows&&(e=e.split(`\\`).join(`/`));let r=this.slashSplit(e);this.debug(this.pattern,`split`,r);let i=this.set;this.debug(this.pattern,`set`,i);let a=r[r.length-1];if(!a)for(let e=r.length-2;!a&&e>=0;e--)a=r[e];for(let e=0;e<i.length;e++){let o=i[e],s=r;n.matchBase&&o.length===1&&(s=[a]);let c=this.matchOne(s,o,t);if(c)return n.flipNegate?!0:!this.negate}return n.flipNegate?!1:this.negate}static defaults(e){return Ra.defaults(e).Minimatch}};Ra.AST=Ia,Ra.Minimatch=So,Ra.escape=La,Ra.unescape=wa;const Co=typeof performance==`object`&&performance&&typeof performance.now==`function`?performance:Date,wo=new Set,To=typeof process==`object`&&process?process:{},Eo=(e,t,n,r)=>{typeof To.emitWarning==`function`?To.emitWarning(e,t,n,r):console.error(`[${n}] ${t}: ${e}`)};let Do=globalThis.AbortController,Oo=globalThis.AbortSignal;if(Do===void 0){Oo=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,t){this._onabort.push(t)}},Do=class{constructor(){t()}signal=new Oo;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(let t of this.signal._onabort)t(e);this.signal.onabort?.(e)}}};let e=To.env?.LRU_CACHE_IGNORE_AC_WARNING!==`1`,t=()=>{e&&(e=!1,Eo("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.",`NO_ABORT_CONTROLLER`,`ENOTSUP`,t))}}const ko=e=>!wo.has(e);Symbol(`type`);const Ao=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),jo=e=>Ao(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=9007199254740991?Mo:null:null;var Mo=class extends Array{constructor(e){super(e),this.fill(0)}},No=class e{heap;length;static#constructing=!1;static create(t){let n=jo(t);if(!n)return[];e.#constructing=!0;let r=new e(t,n);return e.#constructing=!1,r}constructor(t,n){if(!e.#constructing)throw TypeError(`instantiate Stack using Stack.create(n)`);this.heap=new n(t),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},Po=class e{#max;#maxSize;#dispose;#onInsert;#disposeAfter;#fetchMethod;#memoMethod;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#size;#calculatedSize;#keyMap;#keyList;#valList;#next;#prev;#head;#tail;#free;#disposed;#sizes;#starts;#ttls;#hasDispose;#hasFetchMethod;#hasDisposeAfter;#hasOnInsert;static unsafeExposeInternals(e){return{starts:e.#starts,ttls:e.#ttls,sizes:e.#sizes,keyMap:e.#keyMap,keyList:e.#keyList,valList:e.#valList,next:e.#next,prev:e.#prev,get head(){return e.#head},get tail(){return e.#tail},free:e.#free,isBackgroundFetch:t=>e.#isBackgroundFetch(t),backgroundFetch:(t,n,r,i)=>e.#backgroundFetch(t,n,r,i),moveToTail:t=>e.#moveToTail(t),indexes:t=>e.#indexes(t),rindexes:t=>e.#rindexes(t),isStale:t=>e.#isStale(t)}}get max(){return this.#max}get maxSize(){return this.#maxSize}get calculatedSize(){return this.#calculatedSize}get size(){return this.#size}get fetchMethod(){return this.#fetchMethod}get memoMethod(){return this.#memoMethod}get dispose(){return this.#dispose}get onInsert(){return this.#onInsert}get disposeAfter(){return this.#disposeAfter}constructor(t){let{max:n=0,ttl:r,ttlResolution:i=1,ttlAutopurge:a,updateAgeOnGet:o,updateAgeOnHas:s,allowStale:c,dispose:l,onInsert:u,disposeAfter:d,noDisposeOnSet:f,noUpdateTTL:p,maxSize:m=0,maxEntrySize:h=0,sizeCalculation:g,fetchMethod:_,memoMethod:v,noDeleteOnFetchRejection:y,noDeleteOnStaleGet:ee,allowStaleOnFetchRejection:te,allowStaleOnFetchAbort:ne,ignoreFetchAbort:re}=t;if(n!==0&&!Ao(n))throw TypeError(`max option must be a nonnegative integer`);let ie=n?jo(n):Array;if(!ie)throw Error(`invalid max value: `+n);if(this.#max=n,this.#maxSize=m,this.maxEntrySize=h||this.#maxSize,this.sizeCalculation=g,this.sizeCalculation){if(!this.#maxSize&&!this.maxEntrySize)throw TypeError(`cannot set sizeCalculation without setting maxSize or maxEntrySize`);if(typeof this.sizeCalculation!=`function`)throw TypeError(`sizeCalculation set to non-function`)}if(v!==void 0&&typeof v!=`function`)throw TypeError(`memoMethod must be a function if defined`);if(this.#memoMethod=v,_!==void 0&&typeof _!=`function`)throw TypeError(`fetchMethod must be a function if specified`);if(this.#fetchMethod=_,this.#hasFetchMethod=!!_,this.#keyMap=new Map,this.#keyList=Array(n).fill(void 0),this.#valList=Array(n).fill(void 0),this.#next=new ie(n),this.#prev=new ie(n),this.#head=0,this.#tail=0,this.#free=No.create(n),this.#size=0,this.#calculatedSize=0,typeof l==`function`&&(this.#dispose=l),typeof u==`function`&&(this.#onInsert=u),typeof d==`function`?(this.#disposeAfter=d,this.#disposed=[]):(this.#disposeAfter=void 0,this.#disposed=void 0),this.#hasDispose=!!this.#dispose,this.#hasOnInsert=!!this.#onInsert,this.#hasDisposeAfter=!!this.#disposeAfter,this.noDisposeOnSet=!!f,this.noUpdateTTL=!!p,this.noDeleteOnFetchRejection=!!y,this.allowStaleOnFetchRejection=!!te,this.allowStaleOnFetchAbort=!!ne,this.ignoreFetchAbort=!!re,this.maxEntrySize!==0){if(this.#maxSize!==0&&!Ao(this.#maxSize))throw TypeError(`maxSize must be a positive integer if specified`);if(!Ao(this.maxEntrySize))throw TypeError(`maxEntrySize must be a positive integer if specified`);this.#initializeSizeTracking()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!ee,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!s,this.ttlResolution=Ao(i)||i===0?i:1,this.ttlAutopurge=!!a,this.ttl=r||0,this.ttl){if(!Ao(this.ttl))throw TypeError(`ttl must be a positive integer if specified`);this.#initializeTTLTracking()}if(this.#max===0&&this.ttl===0&&this.#maxSize===0)throw TypeError(`At least one of max, maxSize, or ttl is required`);if(!this.ttlAutopurge&&!this.#max&&!this.#maxSize){let t=`LRU_CACHE_UNBOUNDED`;if(ko(t)){wo.add(t);let n=`TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.`;Eo(n,`UnboundedCacheWarning`,t,e)}}}getRemainingTTL(e){return this.#keyMap.has(e)?1/0:0}#initializeTTLTracking(){let e=new Mo(this.#max),t=new Mo(this.#max);this.#ttls=e,this.#starts=t,this.#setItemTTL=(n,r,i=Co.now())=>{if(t[n]=r===0?0:i,e[n]=r,r!==0&&this.ttlAutopurge){let e=setTimeout(()=>{this.#isStale(n)&&this.#delete(this.#keyList[n],`expire`)},r+1);e.unref&&e.unref()}},this.#updateItemAge=n=>{t[n]=e[n]===0?0:Co.now()},this.#statusTTL=(i,a)=>{if(e[a]){let o=e[a],s=t[a];if(!o||!s)return;i.ttl=o,i.start=s,i.now=n||r();let c=i.now-s;i.remainingTTL=o-c}};let n=0,r=()=>{let e=Co.now();if(this.ttlResolution>0){n=e;let t=setTimeout(()=>n=0,this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=i=>{let a=this.#keyMap.get(i);if(a===void 0)return 0;let o=e[a],s=t[a];if(!o||!s)return 1/0;let c=(n||r())-s;return o-c},this.#isStale=i=>{let a=t[i],o=e[i];return!!o&&!!a&&(n||r())-a>o}}#updateItemAge=()=>{};#statusTTL=()=>{};#setItemTTL=()=>{};#isStale=()=>!1;#initializeSizeTracking(){let e=new Mo(this.#max);this.#calculatedSize=0,this.#sizes=e,this.#removeItemSize=t=>{this.#calculatedSize-=e[t],e[t]=0},this.#requireSize=(e,t,n,r)=>{if(this.#isBackgroundFetch(t))return 0;if(!Ao(n))if(r){if(typeof r!=`function`)throw TypeError(`sizeCalculation must be a function`);if(n=r(t,e),!Ao(n))throw TypeError(`sizeCalculation return invalid (expect positive integer)`)}else throw TypeError(`invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.`);return n},this.#addItemSize=(t,n,r)=>{if(e[t]=n,this.#maxSize){let n=this.#maxSize-e[t];for(;this.#calculatedSize>n;)this.#evict(!0)}this.#calculatedSize+=e[t],r&&(r.entrySize=n,r.totalCalculatedSize=this.#calculatedSize)}}#removeItemSize=e=>{};#addItemSize=(e,t,n)=>{};#requireSize=(e,t,n,r)=>{if(n||r)throw TypeError(`cannot set size without setting maxSize or maxEntrySize on cache`);return 0};*#indexes({allowStale:e=this.allowStale}={}){if(this.#size)for(let t=this.#tail;!(!this.#isValidIndex(t)||((e||!this.#isStale(t))&&(yield t),t===this.#head));)t=this.#prev[t]}*#rindexes({allowStale:e=this.allowStale}={}){if(this.#size)for(let t=this.#head;!(!this.#isValidIndex(t)||((e||!this.#isStale(t))&&(yield t),t===this.#tail));)t=this.#next[t]}#isValidIndex(e){return e!==void 0&&this.#keyMap.get(this.#keyList[e])===e}*entries(){for(let e of this.#indexes())this.#valList[e]!==void 0&&this.#keyList[e]!==void 0&&!this.#isBackgroundFetch(this.#valList[e])&&(yield[this.#keyList[e],this.#valList[e]])}*rentries(){for(let e of this.#rindexes())this.#valList[e]!==void 0&&this.#keyList[e]!==void 0&&!this.#isBackgroundFetch(this.#valList[e])&&(yield[this.#keyList[e],this.#valList[e]])}*keys(){for(let e of this.#indexes()){let t=this.#keyList[e];t!==void 0&&!this.#isBackgroundFetch(this.#valList[e])&&(yield t)}}*rkeys(){for(let e of this.#rindexes()){let t=this.#keyList[e];t!==void 0&&!this.#isBackgroundFetch(this.#valList[e])&&(yield t)}}*values(){for(let e of this.#indexes()){let t=this.#valList[e];t!==void 0&&!this.#isBackgroundFetch(this.#valList[e])&&(yield this.#valList[e])}}*rvalues(){for(let e of this.#rindexes()){let t=this.#valList[e];t!==void 0&&!this.#isBackgroundFetch(this.#valList[e])&&(yield this.#valList[e])}}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]=`LRUCache`;find(e,t={}){for(let n of this.#indexes()){let r=this.#valList[n],i=this.#isBackgroundFetch(r)?r.__staleWhileFetching:r;if(i===void 0)continue;if(e(i,this.#keyList[n],this))return this.get(this.#keyList[n],t)}}forEach(e,t=this){for(let n of this.#indexes()){let r=this.#valList[n],i=this.#isBackgroundFetch(r)?r.__staleWhileFetching:r;if(i===void 0)continue;e.call(t,i,this.#keyList[n],this)}}rforEach(e,t=this){for(let n of this.#rindexes()){let r=this.#valList[n],i=this.#isBackgroundFetch(r)?r.__staleWhileFetching:r;if(i===void 0)continue;e.call(t,i,this.#keyList[n],this)}}purgeStale(){let e=!1;for(let t of this.#rindexes({allowStale:!0}))this.#isStale(t)&&(this.#delete(this.#keyList[t],`expire`),e=!0);return e}info(e){let t=this.#keyMap.get(e);if(t===void 0)return;let n=this.#valList[t],r=this.#isBackgroundFetch(n)?n.__staleWhileFetching:n;if(r===void 0)return;let i={value:r};if(this.#ttls&&this.#starts){let e=this.#ttls[t],n=this.#starts[t];if(e&&n){let t=e-(Co.now()-n);i.ttl=t,i.start=Date.now()}}return this.#sizes&&(i.size=this.#sizes[t]),i}dump(){let e=[];for(let t of this.#indexes({allowStale:!0})){let n=this.#keyList[t],r=this.#valList[t],i=this.#isBackgroundFetch(r)?r.__staleWhileFetching:r;if(i===void 0||n===void 0)continue;let a={value:i};if(this.#ttls&&this.#starts){a.ttl=this.#ttls[t];let e=Co.now()-this.#starts[t];a.start=Math.floor(Date.now()-e)}this.#sizes&&(a.size=this.#sizes[t]),e.unshift([n,a])}return e}load(e){this.clear();for(let[t,n]of e){if(n.start){let e=Date.now()-n.start;n.start=Co.now()-e}this.set(t,n.value,n)}}set(e,t,n={}){if(t===void 0)return this.delete(e),this;let{ttl:r=this.ttl,start:i,noDisposeOnSet:a=this.noDisposeOnSet,sizeCalculation:o=this.sizeCalculation,status:s}=n,{noUpdateTTL:c=this.noUpdateTTL}=n,l=this.#requireSize(e,t,n.size||0,o);if(this.maxEntrySize&&l>this.maxEntrySize)return s&&(s.set=`miss`,s.maxEntrySizeExceeded=!0),this.#delete(e,`set`),this;let u=this.#size===0?void 0:this.#keyMap.get(e);if(u===void 0)u=this.#size===0?this.#tail:this.#free.length===0?this.#size===this.#max?this.#evict(!1):this.#size:this.#free.pop(),this.#keyList[u]=e,this.#valList[u]=t,this.#keyMap.set(e,u),this.#next[this.#tail]=u,this.#prev[u]=this.#tail,this.#tail=u,this.#size++,this.#addItemSize(u,l,s),s&&(s.set=`add`),c=!1,this.#hasOnInsert&&this.#onInsert?.(t,e,`add`);else{this.#moveToTail(u);let n=this.#valList[u];if(t!==n){if(this.#hasFetchMethod&&this.#isBackgroundFetch(n)){n.__abortController.abort(Error(`replaced`));let{__staleWhileFetching:t}=n;t!==void 0&&!a&&(this.#hasDispose&&this.#dispose?.(t,e,`set`),this.#hasDisposeAfter&&this.#disposed?.push([t,e,`set`]))}else a||(this.#hasDispose&&this.#dispose?.(n,e,`set`),this.#hasDisposeAfter&&this.#disposed?.push([n,e,`set`]));if(this.#removeItemSize(u),this.#addItemSize(u,l,s),this.#valList[u]=t,s){s.set=`replace`;let e=n&&this.#isBackgroundFetch(n)?n.__staleWhileFetching:n;e!==void 0&&(s.oldValue=e)}}else s&&(s.set=`update`);this.#hasOnInsert&&this.onInsert?.(t,e,t===n?`update`:`replace`)}if(r!==0&&!this.#ttls&&this.#initializeTTLTracking(),this.#ttls&&(c||this.#setItemTTL(u,r,i),s&&this.#statusTTL(s,u)),!a&&this.#hasDisposeAfter&&this.#disposed){let e=this.#disposed,t;for(;t=e?.shift();)this.#disposeAfter?.(...t)}return this}pop(){try{for(;this.#size;){let e=this.#valList[this.#head];if(this.#evict(!0),this.#isBackgroundFetch(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#hasDisposeAfter&&this.#disposed){let e=this.#disposed,t;for(;t=e?.shift();)this.#disposeAfter?.(...t)}}}#evict(e){let t=this.#head,n=this.#keyList[t],r=this.#valList[t];return this.#hasFetchMethod&&this.#isBackgroundFetch(r)?r.__abortController.abort(Error(`evicted`)):(this.#hasDispose||this.#hasDisposeAfter)&&(this.#hasDispose&&this.#dispose?.(r,n,`evict`),this.#hasDisposeAfter&&this.#disposed?.push([r,n,`evict`])),this.#removeItemSize(t),e&&(this.#keyList[t]=void 0,this.#valList[t]=void 0,this.#free.push(t)),this.#size===1?(this.#head=this.#tail=0,this.#free.length=0):this.#head=this.#next[t],this.#keyMap.delete(n),this.#size--,t}has(e,t={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:r}=t,i=this.#keyMap.get(e);if(i!==void 0){let e=this.#valList[i];if(this.#isBackgroundFetch(e)&&e.__staleWhileFetching===void 0)return!1;if(this.#isStale(i))r&&(r.has=`stale`,this.#statusTTL(r,i));else return n&&this.#updateItemAge(i),r&&(r.has=`hit`,this.#statusTTL(r,i)),!0}else r&&(r.has=`miss`);return!1}peek(e,t={}){let{allowStale:n=this.allowStale}=t,r=this.#keyMap.get(e);if(r===void 0||!n&&this.#isStale(r))return;let i=this.#valList[r];return this.#isBackgroundFetch(i)?i.__staleWhileFetching:i}#backgroundFetch(e,t,n,r){let i=t===void 0?void 0:this.#valList[t];if(this.#isBackgroundFetch(i))return i;let a=new Do,{signal:o}=n;o?.addEventListener(`abort`,()=>a.abort(o.reason),{signal:a.signal});let s={signal:a.signal,options:n,context:r},c=(r,i=!1)=>{let{aborted:o}=a.signal,c=n.ignoreFetchAbort&&r!==void 0;if(n.status&&(o&&!i?(n.status.fetchAborted=!0,n.status.fetchError=a.signal.reason,c&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),o&&!c&&!i)return u(a.signal.reason);let l=f;return this.#valList[t]===f&&(r===void 0?l.__staleWhileFetching?this.#valList[t]=l.__staleWhileFetching:this.#delete(e,`fetch`):(n.status&&(n.status.fetchUpdated=!0),this.set(e,r,s.options))),r},l=e=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=e),u(e)),u=r=>{let{aborted:i}=a.signal,o=i&&n.allowStaleOnFetchAbort,s=o||n.allowStaleOnFetchRejection,c=s||n.noDeleteOnFetchRejection,l=f;if(this.#valList[t]===f){let n=!c||l.__staleWhileFetching===void 0;n?this.#delete(e,`fetch`):o||(this.#valList[t]=l.__staleWhileFetching)}if(s)return n.status&&l.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),l.__staleWhileFetching;if(l.__returned===l)throw r},d=(t,r)=>{let o=this.#fetchMethod?.(e,i,s);o&&o instanceof Promise&&o.then(e=>t(e===void 0?void 0:e),r),a.signal.addEventListener(`abort`,()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(t(void 0),n.allowStaleOnFetchAbort&&(t=e=>c(e,!0)))})};n.status&&(n.status.fetchDispatched=!0);let f=new Promise(d).then(c,l),p=Object.assign(f,{__abortController:a,__staleWhileFetching:i,__returned:void 0});return t===void 0?(this.set(e,p,{...s.options,status:void 0}),t=this.#keyMap.get(e)):this.#valList[t]=p,p}#isBackgroundFetch(e){if(!this.#hasFetchMethod)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty(`__staleWhileFetching`)&&t.__abortController instanceof Do}async fetch(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:a=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:s=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:l=this.noUpdateTTL,noDeleteOnFetchRejection:u=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:m,forceRefresh:h=!1,status:g,signal:_}=t;if(!this.#hasFetchMethod)return g&&(g.fetch=`get`),this.get(e,{allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,status:g});let v={allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,ttl:a,noDisposeOnSet:o,size:s,sizeCalculation:c,noUpdateTTL:l,noDeleteOnFetchRejection:u,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:p,ignoreFetchAbort:f,status:g,signal:_},y=this.#keyMap.get(e);if(y===void 0){g&&(g.fetch=`miss`);let t=this.#backgroundFetch(e,y,v,m);return t.__returned=t}else{let t=this.#valList[y];if(this.#isBackgroundFetch(t)){let e=n&&t.__staleWhileFetching!==void 0;return g&&(g.fetch=`inflight`,e&&(g.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}let i=this.#isStale(y);if(!h&&!i)return g&&(g.fetch=`hit`),this.#moveToTail(y),r&&this.#updateItemAge(y),g&&this.#statusTTL(g,y),t;let a=this.#backgroundFetch(e,y,v,m),o=a.__staleWhileFetching!==void 0,s=o&&n;return g&&(g.fetch=i?`stale`:`refresh`,s&&i&&(g.returnedStale=!0)),s?a.__staleWhileFetching:a.__returned=a}}async forceFetch(e,t={}){let n=await this.fetch(e,t);if(n===void 0)throw Error(`fetch() returned undefined`);return n}memo(e,t={}){let n=this.#memoMethod;if(!n)throw Error(`no memoMethod provided to constructor`);let{context:r,forceRefresh:i,...a}=t,o=this.get(e,a);if(!i&&o!==void 0)return o;let s=n(e,o,{options:a,context:r});return this.set(e,s,a),s}get(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:a}=t,o=this.#keyMap.get(e);if(o!==void 0){let t=this.#valList[o],s=this.#isBackgroundFetch(t);return a&&this.#statusTTL(a,o),this.#isStale(o)?(a&&(a.get=`stale`),s?(a&&n&&t.__staleWhileFetching!==void 0&&(a.returnedStale=!0),n?t.__staleWhileFetching:void 0):(i||this.#delete(e,`expire`),a&&n&&(a.returnedStale=!0),n?t:void 0)):(a&&(a.get=`hit`),s?t.__staleWhileFetching:(this.#moveToTail(o),r&&this.#updateItemAge(o),t))}else a&&(a.get=`miss`)}#connect(e,t){this.#prev[t]=e,this.#next[e]=t}#moveToTail(e){e!==this.#tail&&(e===this.#head?this.#head=this.#next[e]:this.#connect(this.#prev[e],this.#next[e]),this.#connect(this.#tail,e),this.#tail=e)}delete(e){return this.#delete(e,`delete`)}#delete(e,t){let n=!1;if(this.#size!==0){let r=this.#keyMap.get(e);if(r!==void 0)if(n=!0,this.#size===1)this.#clear(t);else{this.#removeItemSize(r);let n=this.#valList[r];if(this.#isBackgroundFetch(n)?n.__abortController.abort(Error(`deleted`)):(this.#hasDispose||this.#hasDisposeAfter)&&(this.#hasDispose&&this.#dispose?.(n,e,t),this.#hasDisposeAfter&&this.#disposed?.push([n,e,t])),this.#keyMap.delete(e),this.#keyList[r]=void 0,this.#valList[r]=void 0,r===this.#tail)this.#tail=this.#prev[r];else if(r===this.#head)this.#head=this.#next[r];else{let e=this.#prev[r];this.#next[e]=this.#next[r];let t=this.#next[r];this.#prev[t]=this.#prev[r]}this.#size--,this.#free.push(r)}}if(this.#hasDisposeAfter&&this.#disposed?.length){let e=this.#disposed,t;for(;t=e?.shift();)this.#disposeAfter?.(...t)}return n}clear(){return this.#clear(`delete`)}#clear(e){for(let t of this.#rindexes({allowStale:!0})){let n=this.#valList[t];if(this.#isBackgroundFetch(n))n.__abortController.abort(Error(`deleted`));else{let r=this.#keyList[t];this.#hasDispose&&this.#dispose?.(n,r,e),this.#hasDisposeAfter&&this.#disposed?.push([n,r,e])}}if(this.#keyMap.clear(),this.#valList.fill(void 0),this.#keyList.fill(void 0),this.#ttls&&this.#starts&&(this.#ttls.fill(0),this.#starts.fill(0)),this.#sizes&&this.#sizes.fill(0),this.#head=0,this.#tail=0,this.#free.length=0,this.#calculatedSize=0,this.#size=0,this.#hasDisposeAfter&&this.#disposed){let e=this.#disposed,t;for(;t=e?.shift();)this.#disposeAfter?.(...t)}}};const Fo=typeof process==`object`&&process?process:{stdout:null,stderr:null},Io=e=>!!e&&typeof e==`object`&&(e instanceof xs||e instanceof pe||Lo(e)||Ro(e)),Lo=e=>!!e&&typeof e==`object`&&e instanceof fe&&typeof e.pipe==`function`&&e.pipe!==pe.Writable.prototype.pipe,Ro=e=>!!e&&typeof e==`object`&&e instanceof fe&&typeof e.write==`function`&&typeof e.end==`function`,zo=Symbol(`EOF`),Bo=Symbol(`maybeEmitEnd`),Vo=Symbol(`emittedEnd`),Ho=Symbol(`emittingEnd`),Uo=Symbol(`emittedError`),Wo=Symbol(`closed`),Go=Symbol(`read`),Ko=Symbol(`flush`),qo=Symbol(`flushChunk`),Jo=Symbol(`encoding`),Yo=Symbol(`decoder`),D=Symbol(`flowing`),Xo=Symbol(`paused`),Zo=Symbol(`resume`),O=Symbol(`buffer`),k=Symbol(`pipes`),A=Symbol(`bufferLength`),Qo=Symbol(`bufferPush`),$o=Symbol(`bufferShift`),j=Symbol(`objectMode`),M=Symbol(`destroyed`),es=Symbol(`error`),ts=Symbol(`emitData`),ns=Symbol(`emitEnd`),rs=Symbol(`emitEnd2`),os=Symbol(`async`),ss=Symbol(`abort`),cs=Symbol(`aborted`),ls=Symbol(`signal`),us=Symbol(`dataListeners`),ds=Symbol(`discarded`),fs=e=>Promise.resolve().then(e),ps=e=>e(),ms=e=>e===`end`||e===`finish`||e===`prefinish`,hs=e=>e instanceof ArrayBuffer||!!e&&typeof e==`object`&&e.constructor&&e.constructor.name===`ArrayBuffer`&&e.byteLength>=0,gs=e=>!Buffer.isBuffer(e)&&ArrayBuffer.isView(e);var _s=class{src;dest;opts;ondrain;constructor(e,t,n){this.src=e,this.dest=t,this.opts=n,this.ondrain=()=>e[Zo](),this.dest.on(`drain`,this.ondrain)}unpipe(){this.dest.removeListener(`drain`,this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},vs=class extends _s{unpipe(){this.src.removeListener(`error`,this.proxyErrors),super.unpipe()}constructor(e,t,n){super(e,t,n),this.proxyErrors=e=>t.emit(`error`,e),e.on(`error`,this.proxyErrors)}};const ys=e=>!!e.objectMode,bs=e=>!e.objectMode&&!!e.encoding&&e.encoding!==`buffer`;var xs=class extends fe{[D]=!1;[Xo]=!1;[k]=[];[O]=[];[j];[Jo];[os];[Yo];[zo]=!1;[Vo]=!1;[Ho]=!1;[Wo]=!1;[Uo]=null;[A]=0;[M]=!1;[ls];[cs]=!1;[us]=0;[ds]=!1;writable=!0;readable=!0;constructor(...e){let t=e[0]||{};if(super(),t.objectMode&&typeof t.encoding==`string`)throw TypeError(`Encoding and objectMode may not be used together`);ys(t)?(this[j]=!0,this[Jo]=null):bs(t)?(this[Jo]=t.encoding,this[j]=!1):(this[j]=!1,this[Jo]=null),this[os]=!!t.async,this[Yo]=this[Jo]?new me(this[Jo]):null,t&&t.debugExposeBuffer===!0&&Object.defineProperty(this,`buffer`,{get:()=>this[O]}),t&&t.debugExposePipes===!0&&Object.defineProperty(this,`pipes`,{get:()=>this[k]});let{signal:n}=t;n&&(this[ls]=n,n.aborted?this[ss]():n.addEventListener(`abort`,()=>this[ss]()))}get bufferLength(){return this[A]}get encoding(){return this[Jo]}set encoding(e){throw Error(`Encoding must be set at instantiation time`)}setEncoding(e){throw Error(`Encoding must be set at instantiation time`)}get objectMode(){return this[j]}set objectMode(e){throw Error(`objectMode must be set at instantiation time`)}get async(){return this[os]}set async(e){this[os]=this[os]||!!e}[ss](){this[cs]=!0,this.emit(`abort`,this[ls]?.reason),this.destroy(this[ls]?.reason)}get aborted(){return this[cs]}set aborted(e){}write(e,t,n){if(this[cs])return!1;if(this[zo])throw Error(`write after end`);if(this[M])return this.emit(`error`,Object.assign(Error(`Cannot call write after a stream was destroyed`),{code:`ERR_STREAM_DESTROYED`})),!0;typeof t==`function`&&(n=t,t=`utf8`),t||(t=`utf8`);let r=this[os]?fs:ps;if(!this[j]&&!Buffer.isBuffer(e)){if(gs(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(hs(e))e=Buffer.from(e);else if(typeof e!=`string`)throw Error(`Non-contiguous data written to non-objectMode stream`)}return this[j]?(this[D]&&this[A]!==0&&this[Ko](!0),this[D]?this.emit(`data`,e):this[Qo](e),this[A]!==0&&this.emit(`readable`),n&&r(n),this[D]):e.length?(typeof e==`string`&&!(t===this[Jo]&&!this[Yo]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[Jo]&&(e=this[Yo].write(e)),this[D]&&this[A]!==0&&this[Ko](!0),this[D]?this.emit(`data`,e):this[Qo](e),this[A]!==0&&this.emit(`readable`),n&&r(n),this[D]):(this[A]!==0&&this.emit(`readable`),n&&r(n),this[D])}read(e){if(this[M])return null;if(this[ds]=!1,this[A]===0||e===0||e&&e>this[A])return this[Bo](),null;this[j]&&(e=null),this[O].length>1&&!this[j]&&(this[O]=[this[Jo]?this[O].join(``):Buffer.concat(this[O],this[A])]);let t=this[Go](e||null,this[O][0]);return this[Bo](),t}[Go](e,t){if(this[j])this[$o]();else{let n=t;e===n.length||e===null?this[$o]():typeof n==`string`?(this[O][0]=n.slice(e),t=n.slice(0,e),this[A]-=e):(this[O][0]=n.subarray(e),t=n.subarray(0,e),this[A]-=e)}return this.emit(`data`,t),!this[O].length&&!this[zo]&&this.emit(`drain`),t}end(e,t,n){return typeof e==`function`&&(n=e,e=void 0),typeof t==`function`&&(n=t,t=`utf8`),e!==void 0&&this.write(e,t),n&&this.once(`end`,n),this[zo]=!0,this.writable=!1,(this[D]||!this[Xo])&&this[Bo](),this}[Zo](){this[M]||(!this[us]&&!this[k].length&&(this[ds]=!0),this[Xo]=!1,this[D]=!0,this.emit(`resume`),this[O].length?this[Ko]():this[zo]?this[Bo]():this.emit(`drain`))}resume(){return this[Zo]()}pause(){this[D]=!1,this[Xo]=!0,this[ds]=!1}get destroyed(){return this[M]}get flowing(){return this[D]}get paused(){return this[Xo]}[Qo](e){this[j]?this[A]+=1:this[A]+=e.length,this[O].push(e)}[$o](){return this[j]?--this[A]:this[A]-=this[O][0].length,this[O].shift()}[Ko](e=!1){do;while(this[qo](this[$o]())&&this[O].length);!e&&!this[O].length&&!this[zo]&&this.emit(`drain`)}[qo](e){return this.emit(`data`,e),this[D]}pipe(e,t){if(this[M])return e;this[ds]=!1;let n=this[Vo];return t=t||{},e===Fo.stdout||e===Fo.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,n?t.end&&e.end():(this[k].push(t.proxyErrors?new vs(this,e,t):new _s(this,e,t)),this[os]?fs(()=>this[Zo]()):this[Zo]()),e}unpipe(e){let t=this[k].find(t=>t.dest===e);t&&(this[k].length===1?(this[D]&&this[us]===0&&(this[D]=!1),this[k]=[]):this[k].splice(this[k].indexOf(t),1),t.unpipe())}addListener(e,t){return this.on(e,t)}on(e,t){let n=super.on(e,t);if(e===`data`)this[ds]=!1,this[us]++,!this[k].length&&!this[D]&&this[Zo]();else if(e===`readable`&&this[A]!==0)super.emit(`readable`);else if(ms(e)&&this[Vo])super.emit(e),this.removeAllListeners(e);else if(e===`error`&&this[Uo]){let e=t;this[os]?fs(()=>e.call(this,this[Uo])):e.call(this,this[Uo])}return n}removeListener(e,t){return this.off(e,t)}off(e,t){let n=super.off(e,t);return e===`data`&&(this[us]=this.listeners(`data`).length,this[us]===0&&!this[ds]&&!this[k].length&&(this[D]=!1)),n}removeAllListeners(e){let t=super.removeAllListeners(e);return(e===`data`||e===void 0)&&(this[us]=0,!this[ds]&&!this[k].length&&(this[D]=!1)),t}get emittedEnd(){return this[Vo]}[Bo](){!this[Ho]&&!this[Vo]&&!this[M]&&this[O].length===0&&this[zo]&&(this[Ho]=!0,this.emit(`end`),this.emit(`prefinish`),this.emit(`finish`),this[Wo]&&this.emit(`close`),this[Ho]=!1)}emit(e,...t){let n=t[0];if(e!==`error`&&e!==`close`&&e!==M&&this[M])return!1;if(e===`data`)return!this[j]&&!n?!1:this[os]?(fs(()=>this[ts](n)),!0):this[ts](n);if(e===`end`)return this[ns]();if(e===`close`){if(this[Wo]=!0,!this[Vo]&&!this[M])return!1;let e=super.emit(`close`);return this.removeAllListeners(`close`),e}else if(e===`error`){this[Uo]=n,super.emit(es,n);let e=!this[ls]||this.listeners(`error`).length?super.emit(`error`,n):!1;return this[Bo](),e}else if(e===`resume`){let e=super.emit(`resume`);return this[Bo](),e}else if(e===`finish`||e===`prefinish`){let t=super.emit(e);return this.removeAllListeners(e),t}let r=super.emit(e,...t);return this[Bo](),r}[ts](e){for(let t of this[k])t.dest.write(e)===!1&&this.pause();let t=this[ds]?!1:super.emit(`data`,e);return this[Bo](),t}[ns](){return this[Vo]?!1:(this[Vo]=!0,this.readable=!1,this[os]?(fs(()=>this[rs]()),!0):this[rs]())}[rs](){if(this[Yo]){let e=this[Yo].end();if(e){for(let t of this[k])t.dest.write(e);this[ds]||super.emit(`data`,e)}}for(let e of this[k])e.end();let e=super.emit(`end`);return this.removeAllListeners(`end`),e}async collect(){let e=Object.assign([],{dataLength:0});this[j]||(e.dataLength=0);let t=this.promise();return this.on(`data`,t=>{e.push(t),this[j]||(e.dataLength+=t.length)}),await t,e}async concat(){if(this[j])throw Error(`cannot concat in objectMode`);let e=await this.collect();return this[Jo]?e.join(``):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(M,()=>t(Error(`stream destroyed`))),this.on(`error`,e=>t(e)),this.on(`end`,()=>e())})}[Symbol.asyncIterator](){this[ds]=!1;let e=!1,t=async()=>(this.pause(),e=!0,{value:void 0,done:!0}),n=()=>{if(e)return t();let n=this.read();if(n!==null)return Promise.resolve({done:!1,value:n});if(this[zo])return t();let r,i,a=e=>{this.off(`data`,o),this.off(`end`,s),this.off(M,c),t(),i(e)},o=e=>{this.off(`error`,a),this.off(`end`,s),this.off(M,c),this.pause(),r({value:e,done:!!this[zo]})},s=()=>{this.off(`error`,a),this.off(`data`,o),this.off(M,c),t(),r({done:!0,value:void 0})},c=()=>a(Error(`stream destroyed`));return new Promise((e,t)=>{i=t,r=e,this.once(M,c),this.once(`error`,a),this.once(`end`,s),this.once(`data`,o)})};return{next:n,throw:t,return:t,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[ds]=!1;let e=!1,t=()=>(this.pause(),this.off(es,t),this.off(M,t),this.off(`end`,t),e=!0,{done:!0,value:void 0}),n=()=>{if(e)return t();let n=this.read();return n===null?t():{done:!1,value:n}};return this.once(`end`,t),this.once(es,t),this.once(M,t),{next:n,throw:t,return:t,[Symbol.iterator](){return this}}}destroy(e){if(this[M])return e?this.emit(`error`,e):this.emit(M),this;this[M]=!0,this[ds]=!0,this[O].length=0,this[A]=0;let t=this;return typeof t.close==`function`&&!this[Wo]&&t.close(),e?this.emit(`error`,e):this.emit(M),this}static get isStream(){return Io}};const Ss=d.native,Cs={lstatSync:o,readdir:c,readdirSync:l,readlinkSync:u,realpathSync:Ss,promises:{lstat:ce,readdir:le,readlink:ue,realpath:de}},ws=e=>!e||e===Cs||e===y?Cs:{...Cs,...e,promises:{...Cs.promises,...e.promises||{}}},Ts=/^\\\\\?\\([a-z]:)\\?$/i,Es=e=>e.replace(/\//g,`\\`).replace(Ts,`$1\\`),Ds=/[\\\/]/,Os=0,ks=1,As=2,js=4,Ms=6,Ns=8,Ps=10,Fs=12,Is=15,Ls=~Is,Rs=16,zs=32,Bs=64,Vs=128,Hs=256,Us=512,Ws=Vs|576,Gs=1023,Ks=e=>e.isFile()?Ns:e.isDirectory()?js:e.isSymbolicLink()?Ps:e.isCharacterDevice()?As:e.isBlockDevice()?Ms:e.isSocket()?Fs:e.isFIFO()?ks:Os,qs=new Map,Js=e=>{let t=qs.get(e);if(t)return t;let n=e.normalize(`NFKD`);return qs.set(e,n),n},Ys=new Map,Xs=e=>{let t=Ys.get(e);if(t)return t;let n=Js(e.toLowerCase());return Ys.set(e,n),n};var Zs=class extends Po{constructor(){super({max:256})}},Qs=class extends Po{constructor(e=16*1024){super({maxSize:e,sizeCalculation:e=>e.length+1})}};const $s=Symbol(`PathScurry setAsCwd`);var ec=class{name;root;roots;parent;nocase;isCWD=!1;#fs;#dev;get dev(){return this.#dev}#mode;get mode(){return this.#mode}#nlink;get nlink(){return this.#nlink}#uid;get uid(){return this.#uid}#gid;get gid(){return this.#gid}#rdev;get rdev(){return this.#rdev}#blksize;get blksize(){return this.#blksize}#ino;get ino(){return this.#ino}#size;get size(){return this.#size}#blocks;get blocks(){return this.#blocks}#atimeMs;get atimeMs(){return this.#atimeMs}#mtimeMs;get mtimeMs(){return this.#mtimeMs}#ctimeMs;get ctimeMs(){return this.#ctimeMs}#birthtimeMs;get birthtimeMs(){return this.#birthtimeMs}#atime;get atime(){return this.#atime}#mtime;get mtime(){return this.#mtime}#ctime;get ctime(){return this.#ctime}#birthtime;get birthtime(){return this.#birthtime}#matchName;#depth;#fullpath;#fullpathPosix;#relative;#relativePosix;#type;#children;#linkTarget;#realpath;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,t=Os,n,r,i,a,o){this.name=e,this.#matchName=i?Xs(e):Js(e),this.#type=t&Gs,this.nocase=i,this.roots=r,this.root=n||this,this.#children=a,this.#fullpath=o.fullpath,this.#relative=o.relative,this.#relativePosix=o.relativePosix,this.parent=o.parent,this.parent?this.#fs=this.parent.#fs:this.#fs=ws(o.fs)}depth(){return this.#depth===void 0?this.parent?this.#depth=this.parent.depth()+1:this.#depth=0:this.#depth}childrenCache(){return this.#children}resolve(e){if(!e)return this;let t=this.getRootString(e),n=e.substring(t.length),r=n.split(this.splitSep),i=t?this.getRoot(t).#resolveParts(r):this.#resolveParts(r);return i}#resolveParts(e){let t=this;for(let n of e)t=t.child(n);return t}children(){let e=this.#children.get(this);if(e)return e;let t=Object.assign([],{provisional:0});return this.#children.set(this,t),this.#type&=~Rs,t}child(e,t){if(e===``||e===`.`)return this;if(e===`..`)return this.parent||this;let n=this.children(),r=this.nocase?Xs(e):Js(e);for(let e of n)if(e.#matchName===r)return e;let i=this.parent?this.sep:``,a=this.#fullpath?this.#fullpath+i+e:void 0,o=this.newChild(e,Os,{...t,parent:this,fullpath:a});return this.canReaddir()||(o.#type|=Vs),n.push(o),o}relative(){if(this.isCWD)return``;if(this.#relative!==void 0)return this.#relative;let e=this.name,t=this.parent;if(!t)return this.#relative=this.name;let n=t.relative();return n+(!n||!t.parent?``:this.sep)+e}relativePosix(){if(this.sep===`/`)return this.relative();if(this.isCWD)return``;if(this.#relativePosix!==void 0)return this.#relativePosix;let e=this.name,t=this.parent;if(!t)return this.#relativePosix=this.fullpathPosix();let n=t.relativePosix();return n+(!n||!t.parent?``:`/`)+e}fullpath(){if(this.#fullpath!==void 0)return this.#fullpath;let e=this.name,t=this.parent;if(!t)return this.#fullpath=this.name;let n=t.fullpath(),r=n+(t.parent?this.sep:``)+e;return this.#fullpath=r}fullpathPosix(){if(this.#fullpathPosix!==void 0)return this.#fullpathPosix;if(this.sep===`/`)return this.#fullpathPosix=this.fullpath();if(!this.parent){let e=this.fullpath().replace(/\\/g,`/`);return/^[a-z]:\//i.test(e)?this.#fullpathPosix=`//?/${e}`:this.#fullpathPosix=e}let e=this.parent,t=e.fullpathPosix(),n=t+(!t||!e.parent?``:`/`)+this.name;return this.#fullpathPosix=n}isUnknown(){return(this.#type&Is)===Os}isType(e){return this[`is${e}`]()}getType(){return this.isUnknown()?`Unknown`:this.isDirectory()?`Directory`:this.isFile()?`File`:this.isSymbolicLink()?`SymbolicLink`:this.isFIFO()?`FIFO`:this.isCharacterDevice()?`CharacterDevice`:this.isBlockDevice()?`BlockDevice`:this.isSocket()?`Socket`:`Unknown`}isFile(){return(this.#type&Is)===Ns}isDirectory(){return(this.#type&Is)===js}isCharacterDevice(){return(this.#type&Is)===As}isBlockDevice(){return(this.#type&Is)===Ms}isFIFO(){return(this.#type&Is)===ks}isSocket(){return(this.#type&Is)===Fs}isSymbolicLink(){return(this.#type&Ps)===Ps}lstatCached(){return this.#type&zs?this:void 0}readlinkCached(){return this.#linkTarget}realpathCached(){return this.#realpath}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(this.#linkTarget)return!0;if(!this.parent)return!1;let e=this.#type&Is;return!(e!==Os&&e!==Ps||this.#type&Hs||this.#type&Vs)}calledReaddir(){return!!(this.#type&Rs)}isENOENT(){return!!(this.#type&Vs)}isNamed(e){return this.nocase?this.#matchName===Xs(e):this.#matchName===Js(e)}async readlink(){let e=this.#linkTarget;if(e)return e;if(this.canReadlink()&&this.parent)try{let e=await this.#fs.promises.readlink(this.fullpath()),t=(await this.parent.realpath())?.resolve(e);if(t)return this.#linkTarget=t}catch(e){this.#readlinkFail(e.code);return}}readlinkSync(){let e=this.#linkTarget;if(e)return e;if(this.canReadlink()&&this.parent)try{let e=this.#fs.readlinkSync(this.fullpath()),t=this.parent.realpathSync()?.resolve(e);if(t)return this.#linkTarget=t}catch(e){this.#readlinkFail(e.code);return}}#readdirSuccess(e){this.#type|=Rs;for(let t=e.provisional;t<e.length;t++){let n=e[t];n&&n.#markENOENT()}}#markENOENT(){this.#type&Vs||(this.#type=(this.#type|Vs)&Ls,this.#markChildrenENOENT())}#markChildrenENOENT(){let e=this.children();e.provisional=0;for(let t of e)t.#markENOENT()}#markENOREALPATH(){this.#type|=Us,this.#markENOTDIR()}#markENOTDIR(){if(this.#type&Bs)return;let e=this.#type;(e&Is)===js&&(e&=Ls),this.#type=e|Bs,this.#markChildrenENOENT()}#readdirFail(e=``){e===`ENOTDIR`||e===`EPERM`?this.#markENOTDIR():e===`ENOENT`?this.#markENOENT():this.children().provisional=0}#lstatFail(e=``){if(e===`ENOTDIR`){let e=this.parent;e.#markENOTDIR()}else e===`ENOENT`&&this.#markENOENT()}#readlinkFail(e=``){let t=this.#type;t|=Hs,e===`ENOENT`&&(t|=Vs),(e===`EINVAL`||e===`UNKNOWN`)&&(t&=Ls),this.#type=t,e===`ENOTDIR`&&this.parent&&this.parent.#markENOTDIR()}#readdirAddChild(e,t){return this.#readdirMaybePromoteChild(e,t)||this.#readdirAddNewChild(e,t)}#readdirAddNewChild(e,t){let n=Ks(e),r=this.newChild(e.name,n,{parent:this}),i=r.#type&Is;return i!==js&&i!==Ps&&i!==Os&&(r.#type|=Bs),t.unshift(r),t.provisional++,r}#readdirMaybePromoteChild(e,t){for(let n=t.provisional;n<t.length;n++){let r=t[n],i=this.nocase?Xs(e.name):Js(e.name);if(i===r.#matchName)return this.#readdirPromoteChild(e,r,n,t)}}#readdirPromoteChild(e,t,n,r){let i=t.name;return t.#type=t.#type&Ls|Ks(e),i!==e.name&&(t.name=e.name),n!==r.provisional&&(n===r.length-1?r.pop():r.splice(n,1),r.unshift(t)),r.provisional++,t}async lstat(){if((this.#type&Vs)===0)try{return this.#applyStat(await this.#fs.promises.lstat(this.fullpath())),this}catch(e){this.#lstatFail(e.code)}}lstatSync(){if((this.#type&Vs)===0)try{return this.#applyStat(this.#fs.lstatSync(this.fullpath())),this}catch(e){this.#lstatFail(e.code)}}#applyStat(e){let{atime:t,atimeMs:n,birthtime:r,birthtimeMs:i,blksize:a,blocks:o,ctime:s,ctimeMs:c,dev:l,gid:u,ino:d,mode:f,mtime:p,mtimeMs:m,nlink:h,rdev:g,size:_,uid:v}=e;this.#atime=t,this.#atimeMs=n,this.#birthtime=r,this.#birthtimeMs=i,this.#blksize=a,this.#blocks=o,this.#ctime=s,this.#ctimeMs=c,this.#dev=l,this.#gid=u,this.#ino=d,this.#mode=f,this.#mtime=p,this.#mtimeMs=m,this.#nlink=h,this.#rdev=g,this.#size=_,this.#uid=v;let y=Ks(e);this.#type=this.#type&Ls|y|zs,y!==Os&&y!==js&&y!==Ps&&(this.#type|=Bs)}#onReaddirCB=[];#readdirCBInFlight=!1;#callOnReaddirCB(e){this.#readdirCBInFlight=!1;let t=this.#onReaddirCB.slice();this.#onReaddirCB.length=0,t.forEach(t=>t(null,e))}readdirCB(e,t=!1){if(!this.canReaddir()){t?e(null,[]):queueMicrotask(()=>e(null,[]));return}let n=this.children();if(this.calledReaddir()){let r=n.slice(0,n.provisional);t?e(null,r):queueMicrotask(()=>e(null,r));return}if(this.#onReaddirCB.push(e),this.#readdirCBInFlight)return;this.#readdirCBInFlight=!0;let r=this.fullpath();this.#fs.readdir(r,{withFileTypes:!0},(e,t)=>{if(e)this.#readdirFail(e.code),n.provisional=0;else{for(let e of t)this.#readdirAddChild(e,n);this.#readdirSuccess(n)}this.#callOnReaddirCB(n.slice(0,n.provisional))})}#asyncReaddirInFlight;async readdir(){if(!this.canReaddir())return[];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();if(this.#asyncReaddirInFlight)await this.#asyncReaddirInFlight;else{let n=()=>{};this.#asyncReaddirInFlight=new Promise(e=>n=e);try{for(let n of await this.#fs.promises.readdir(t,{withFileTypes:!0}))this.#readdirAddChild(n,e);this.#readdirSuccess(e)}catch(t){this.#readdirFail(t.code),e.provisional=0}this.#asyncReaddirInFlight=void 0,n()}return e.slice(0,e.provisional)}readdirSync(){if(!this.canReaddir())return[];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();try{for(let n of this.#fs.readdirSync(t,{withFileTypes:!0}))this.#readdirAddChild(n,e);this.#readdirSuccess(e)}catch(t){this.#readdirFail(t.code),e.provisional=0}return e.slice(0,e.provisional)}canReaddir(){if(this.#type&Ws)return!1;let e=Is&this.#type;return e===Os||e===js||e===Ps}shouldWalk(e,t){return(this.#type&js)===js&&!(this.#type&Ws)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#realpath)return this.#realpath;if(!((Hs|640)&this.#type))try{let e=await this.#fs.promises.realpath(this.fullpath());return this.#realpath=this.resolve(e)}catch(e){this.#markENOREALPATH()}}realpathSync(){if(this.#realpath)return this.#realpath;if(!((Hs|640)&this.#type))try{let e=this.#fs.realpathSync(this.fullpath());return this.#realpath=this.resolve(e)}catch(e){this.#markENOREALPATH()}}[$s](e){if(e===this)return;e.isCWD=!1,this.isCWD=!0;let t=new Set([]),n=[],r=this;for(;r&&r.parent;)t.add(r),r.#relative=n.join(this.sep),r.#relativePosix=n.join(`/`),r=r.parent,n.push(`..`);for(r=e;r&&r.parent&&!t.has(r);)r.#relative=void 0,r.#relativePosix=void 0,r=r.parent}},tc=class e extends ec{sep=`\\`;splitSep=Ds;constructor(e,t=Os,n,r,i,a,o){super(e,t,n,r,i,a,o)}newChild(t,n=Os,r={}){return new e(t,n,this.root,this.roots,this.nocase,this.childrenCache(),r)}getRootString(e){return v.parse(e).root}getRoot(e){if(e=Es(e.toUpperCase()),e===this.root.name)return this.root;for(let[t,n]of Object.entries(this.roots))if(this.sameRoot(e,t))return this.roots[e]=n;return this.roots[e]=new ic(e,this).root}sameRoot(e,t=this.root.name){return e=e.toUpperCase().replace(/\//g,`\\`).replace(Ts,`$1\\`),e===t}},nc=class e extends ec{splitSep=`/`;sep=`/`;constructor(e,t=Os,n,r,i,a,o){super(e,t,n,r,i,a,o)}getRootString(e){return e.startsWith(`/`)?`/`:``}getRoot(e){return this.root}newChild(t,n=Os,r={}){return new e(t,n,this.root,this.roots,this.nocase,this.childrenCache(),r)}},rc=class{root;rootPath;roots;cwd;#resolveCache;#resolvePosixCache;#children;nocase;#fs;constructor(e=process.cwd(),t,n,{nocase:r,childrenCacheSize:i=16*1024,fs:a=Cs}={}){this.#fs=ws(a),(e instanceof URL||e.startsWith(`file://`))&&(e=se(e));let o=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),this.#resolveCache=new Zs,this.#resolvePosixCache=new Zs,this.#children=new Qs(i);let s=o.substring(this.rootPath.length).split(n);if(s.length===1&&!s[0]&&s.pop(),r===void 0)throw TypeError(`must provide nocase setting to PathScurryBase ctor`);this.nocase=r,this.root=this.newRoot(this.#fs),this.roots[this.rootPath]=this.root;let c=this.root,l=s.length-1,u=t.sep,d=this.rootPath,f=!1;for(let e of s){let t=l--;c=c.child(e,{relative:Array(t).fill(`..`).join(u),relativePosix:Array(t).fill(`..`).join(`/`),fullpath:d+=(f?``:u)+e}),f=!0}this.cwd=c}depth(e=this.cwd){return typeof e==`string`&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return this.#children}resolve(...e){let t=``;for(let n=e.length-1;n>=0;n--){let r=e[n];if(!(!r||r===`.`)&&(t=t?`${r}/${t}`:r,this.isAbsolute(r)))break}let n=this.#resolveCache.get(t);if(n!==void 0)return n;let r=this.cwd.resolve(t).fullpath();return this.#resolveCache.set(t,r),r}resolvePosix(...e){let t=``;for(let n=e.length-1;n>=0;n--){let r=e[n];if(!(!r||r===`.`)&&(t=t?`${r}/${t}`:r,this.isAbsolute(r)))break}let n=this.#resolvePosixCache.get(t);if(n!==void 0)return n;let r=this.cwd.resolve(t).fullpathPosix();return this.#resolvePosixCache.set(t,r),r}relative(e=this.cwd){return typeof e==`string`&&(e=this.cwd.resolve(e)),e.relative()}relativePosix(e=this.cwd){return typeof e==`string`&&(e=this.cwd.resolve(e)),e.relativePosix()}basename(e=this.cwd){return typeof e==`string`&&(e=this.cwd.resolve(e)),e.name}dirname(e=this.cwd){return typeof e==`string`&&(e=this.cwd.resolve(e)),(e.parent||e).fullpath()}async readdir(e=this.cwd,t={withFileTypes:!0}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof ec||(t=e,e=this.cwd);let{withFileTypes:n}=t;if(e.canReaddir()){let t=await e.readdir();return n?t:t.map(e=>e.name)}else return[]}readdirSync(e=this.cwd,t={withFileTypes:!0}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof ec||(t=e,e=this.cwd);let{withFileTypes:n=!0}=t;return e.canReaddir()?n?e.readdirSync():e.readdirSync().map(e=>e.name):[]}async lstat(e=this.cwd){return typeof e==`string`&&(e=this.cwd.resolve(e)),e.lstat()}lstatSync(e=this.cwd){return typeof e==`string`&&(e=this.cwd.resolve(e)),e.lstatSync()}async readlink(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof ec||(t=e.withFileTypes,e=this.cwd);let n=await e.readlink();return t?n:n?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof ec||(t=e.withFileTypes,e=this.cwd);let n=e.readlinkSync();return t?n:n?.fullpath()}async realpath(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof ec||(t=e.withFileTypes,e=this.cwd);let n=await e.realpath();return t?n:n?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof ec||(t=e.withFileTypes,e=this.cwd);let n=e.realpathSync();return t?n:n?.fullpath()}async walk(e=this.cwd,t={}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof ec||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:r=!1,filter:i,walkFilter:a}=t,o=[];(!i||i(e))&&o.push(n?e:e.fullpath());let s=new Set,c=(e,t)=>{s.add(e),e.readdirCB((e,l)=>{if(e)return t(e);let u=l.length;if(!u)return t();let d=()=>{--u===0&&t()};for(let e of l)(!i||i(e))&&o.push(n?e:e.fullpath()),r&&e.isSymbolicLink()?e.realpath().then(e=>e?.isUnknown()?e.lstat():e).then(e=>e?.shouldWalk(s,a)?c(e,d):d()):e.shouldWalk(s,a)?c(e,d):d()},!0)},l=e;return new Promise((e,t)=>{c(l,n=>{if(n)return t(n);e(o)})})}walkSync(e=this.cwd,t={}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof ec||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:r=!1,filter:i,walkFilter:a}=t,o=[];(!i||i(e))&&o.push(n?e:e.fullpath());let s=new Set([e]);for(let e of s){let t=e.readdirSync();for(let e of t){(!i||i(e))&&o.push(n?e:e.fullpath());let t=e;if(e.isSymbolicLink()){if(!(r&&(t=e.realpathSync())))continue;t.isUnknown()&&t.lstatSync()}t.shouldWalk(s,a)&&s.add(t)}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return typeof e==`string`?e=this.cwd.resolve(e):e instanceof ec||(t=e,e=this.cwd),this.stream(e,t)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(e=this.cwd,t={}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof ec||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:r=!1,filter:i,walkFilter:a}=t;(!i||i(e))&&(yield n?e:e.fullpath());let o=new Set([e]);for(let e of o){let t=e.readdirSync();for(let e of t){(!i||i(e))&&(yield n?e:e.fullpath());let t=e;if(e.isSymbolicLink()){if(!(r&&(t=e.realpathSync())))continue;t.isUnknown()&&t.lstatSync()}t.shouldWalk(o,a)&&o.add(t)}}}stream(e=this.cwd,t={}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof ec||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:r=!1,filter:i,walkFilter:a}=t,o=new xs({objectMode:!0});(!i||i(e))&&o.write(n?e:e.fullpath());let s=new Set,c=[e],l=0,u=()=>{let e=!1;for(;!e;){let t=c.shift();if(!t){l===0&&o.end();return}l++,s.add(t);let d=(t,p,m=!1)=>{if(t)return o.emit(`error`,t);if(r&&!m){let e=[];for(let t of p)t.isSymbolicLink()&&e.push(t.realpath().then(e=>e?.isUnknown()?e.lstat():e));if(e.length){Promise.all(e).then(()=>d(null,p,!0));return}}for(let t of p)t&&(!i||i(t))&&(o.write(n?t:t.fullpath())||(e=!0));l--;for(let e of p){let t=e.realpathCached()||e;t.shouldWalk(s,a)&&c.push(t)}e&&!o.flowing?o.once(`drain`,u):f||u()},f=!0;t.readdirCB(d,!0),f=!1}};return u(),o}streamSync(e=this.cwd,t={}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof ec||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:r=!1,filter:i,walkFilter:a}=t,o=new xs({objectMode:!0}),s=new Set;(!i||i(e))&&o.write(n?e:e.fullpath());let c=[e],l=0,u=()=>{let e=!1;for(;!e;){let t=c.shift();if(!t){l===0&&o.end();return}l++,s.add(t);let u=t.readdirSync();for(let t of u)(!i||i(t))&&(o.write(n?t:t.fullpath())||(e=!0));l--;for(let e of u){let t=e;if(e.isSymbolicLink()){if(!(r&&(t=e.realpathSync())))continue;t.isUnknown()&&t.lstatSync()}t.shouldWalk(s,a)&&c.push(t)}}e&&!o.flowing&&o.once(`drain`,u)};return u(),o}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e==`string`?this.cwd.resolve(e):e,this.cwd[$s](t)}},ic=class extends rc{sep=`\\`;constructor(e=process.cwd(),t={}){let{nocase:n=!0}=t;super(e,v,`\\`,{...t,nocase:n}),this.nocase=n;for(let e=this.cwd;e;e=e.parent)e.nocase=this.nocase}parseRootPath(e){return v.parse(e).root.toUpperCase()}newRoot(e){return new tc(this.rootPath,js,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith(`/`)||e.startsWith(`\\`)||/^[a-z]:(\/|\\)/i.test(e)}},ac=class extends rc{sep=`/`;constructor(e=process.cwd(),t={}){let{nocase:n=!1}=t;super(e,g,`/`,{...t,nocase:n}),this.nocase=n}parseRootPath(e){return`/`}newRoot(e){return new nc(this.rootPath,js,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith(`/`)}},oc=class extends ac{constructor(e=process.cwd(),t={}){let{nocase:n=!0}=t;super(e,{...t,nocase:n})}};process.platform;const sc=process.platform===`win32`?ic:process.platform===`darwin`?oc:ac,cc=e=>e.length>=1,lc=e=>e.length>=1;var uc=class e{#patternList;#globList;#index;length;#platform;#rest;#globString;#isDrive;#isUNC;#isAbsolute;#followGlobstar=!0;constructor(e,t,n,r){if(!cc(e))throw TypeError(`empty pattern list`);if(!lc(t))throw TypeError(`empty glob list`);if(t.length!==e.length)throw TypeError(`mismatched pattern list and glob list lengths`);if(this.length=e.length,n<0||n>=this.length)throw TypeError(`index out of range`);if(this.#patternList=e,this.#globList=t,this.#index=n,this.#platform=r,this.#index===0){if(this.isUNC()){let[e,t,n,r,...i]=this.#patternList,[a,o,s,c,...l]=this.#globList;i[0]===``&&(i.shift(),l.shift());let u=[e,t,n,r,``].join(`/`),d=[a,o,s,c,``].join(`/`);this.#patternList=[u,...i],this.#globList=[d,...l],this.length=this.#patternList.length}else if(this.isDrive()||this.isAbsolute()){let[e,...t]=this.#patternList,[n,...r]=this.#globList;t[0]===``&&(t.shift(),r.shift());let i=e+`/`,a=n+`/`;this.#patternList=[i,...t],this.#globList=[a,...r],this.length=this.#patternList.length}}}pattern(){return this.#patternList[this.#index]}isString(){return typeof this.#patternList[this.#index]==`string`}isGlobstar(){return this.#patternList[this.#index]===co}isRegExp(){return this.#patternList[this.#index]instanceof RegExp}globString(){return this.#globString=this.#globString||(this.#index===0?this.isAbsolute()?this.#globList[0]+this.#globList.slice(1).join(`/`):this.#globList.join(`/`):this.#globList.slice(this.#index).join(`/`))}hasMore(){return this.length>this.#index+1}rest(){return this.#rest===void 0?this.hasMore()?(this.#rest=new e(this.#patternList,this.#globList,this.#index+1,this.#platform),this.#rest.#isAbsolute=this.#isAbsolute,this.#rest.#isUNC=this.#isUNC,this.#rest.#isDrive=this.#isDrive,this.#rest):this.#rest=null:this.#rest}isUNC(){let e=this.#patternList;return this.#isUNC===void 0?this.#isUNC=this.#platform===`win32`&&this.#index===0&&e[0]===``&&e[1]===``&&typeof e[2]==`string`&&!!e[2]&&typeof e[3]==`string`&&!!e[3]:this.#isUNC}isDrive(){let e=this.#patternList;return this.#isDrive===void 0?this.#isDrive=this.#platform===`win32`&&this.#index===0&&this.length>1&&typeof e[0]==`string`&&/^[a-z]:$/i.test(e[0]):this.#isDrive}isAbsolute(){let e=this.#patternList;return this.#isAbsolute===void 0?this.#isAbsolute=e[0]===``&&e.length>1||this.isDrive()||this.isUNC():this.#isAbsolute}root(){let e=this.#patternList[0];return typeof e==`string`&&this.isAbsolute()&&this.#index===0?e:``}checkFollowGlobstar(){return!(this.#index===0||!this.isGlobstar()||!this.#followGlobstar)}markFollowGlobstar(){return this.#index===0||!this.isGlobstar()||!this.#followGlobstar?!1:(this.#followGlobstar=!1,!0)}};const dc=typeof process==`object`&&process&&typeof process.platform==`string`?process.platform:`linux`;var fc=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:t,nocase:n,noext:r,noglobstar:i,platform:a=dc}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=a,this.mmopts={dot:!0,nobrace:t,nocase:n,noext:r,noglobstar:i,optimizationLevel:2,platform:a,nocomment:!0,nonegate:!0};for(let t of e)this.add(t)}add(e){let t=new So(e,this.mmopts);for(let e=0;e<t.set.length;e++){let n=t.set[e],r=t.globParts[e];if(!n||!r)throw Error(`invalid pattern object`);for(;n[0]===`.`&&r[0]===`.`;)n.shift(),r.shift();let i=new uc(n,r,0,this.platform),a=new So(i.globString(),this.mmopts),o=r[r.length-1]===`**`,s=i.isAbsolute();s?this.absolute.push(a):this.relative.push(a),o&&(s?this.absoluteChildren.push(a):this.relativeChildren.push(a))}}ignored(e){let t=e.fullpath(),n=`${t}/`,r=e.relative()||`.`,i=`${r}/`;for(let e of this.relative)if(e.match(r)||e.match(i))return!0;for(let e of this.absolute)if(e.match(t)||e.match(n))return!0;return!1}childrenIgnored(e){let t=e.fullpath()+`/`,n=(e.relative()||`.`)+`/`;for(let e of this.relativeChildren)if(e.match(n))return!0;for(let e of this.absoluteChildren)if(e.match(t))return!0;return!1}},pc=class e{store;constructor(e=new Map){this.store=e}copy(){return new e(new Map(this.store))}hasWalked(e,t){return this.store.get(e.fullpath())?.has(t.globString())}storeWalked(e,t){let n=e.fullpath(),r=this.store.get(n);r?r.add(t.globString()):this.store.set(n,new Set([t.globString()]))}},mc=class{store=new Map;add(e,t,n){let r=(t?2:0)|(n?1:0),i=this.store.get(e);this.store.set(e,i===void 0?r:r&i)}entries(){return[...this.store.entries()].map(([e,t])=>[e,!!(t&2),!!(t&1)])}},hc=class{store=new Map;add(e,t){if(!e.canReaddir())return;let n=this.store.get(e);n?n.find(e=>e.globString()===t.globString())||n.push(t):this.store.set(e,[t])}get(e){let t=this.store.get(e);if(!t)throw Error(`attempting to walk unknown path`);return t}entries(){return this.keys().map(e=>[e,this.store.get(e)])}keys(){return[...this.store.keys()].filter(e=>e.canReaddir())}},gc=class e{hasWalkedCache;matches=new mc;subwalks=new hc;patterns;follow;dot;opts;constructor(e,t){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=t?t.copy():new pc}processPatterns(e,t){this.patterns=t;let n=t.map(t=>[e,t]);for(let[e,t]of n){this.hasWalkedCache.storeWalked(e,t);let n=t.root(),r=t.isAbsolute()&&this.opts.absolute!==!1;if(n){e=e.resolve(n===`/`&&this.opts.root!==void 0?this.opts.root:n);let r=t.rest();if(r)t=r;else{this.matches.add(e,!0,!1);continue}}if(e.isENOENT())continue;let i,a,o=!1;for(;typeof(i=t.pattern())==`string`&&(a=t.rest());){let n=e.resolve(i);e=n,t=a,o=!0}if(i=t.pattern(),a=t.rest(),o){if(this.hasWalkedCache.hasWalked(e,t))continue;this.hasWalkedCache.storeWalked(e,t)}if(typeof i==`string`){let t=i===`..`||i===``||i===`.`;this.matches.add(e.resolve(i),r,t);continue}else if(i===co){(!e.isSymbolicLink()||this.follow||t.checkFollowGlobstar())&&this.subwalks.add(e,t);let n=a?.pattern(),i=a?.rest();if(!a||(n===``||n===`.`)&&!i)this.matches.add(e,r,n===``||n===`.`);else if(n===`..`){let t=e.parent||e;i?this.hasWalkedCache.hasWalked(t,i)||this.subwalks.add(t,i):this.matches.add(t,r,!0)}}else i instanceof RegExp&&this.subwalks.add(e,t)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new e(this.opts,this.hasWalkedCache)}filterEntries(e,t){let n=this.subwalks.get(e),r=this.child();for(let e of t)for(let t of n){let n=t.isAbsolute(),i=t.pattern(),a=t.rest();i===co?r.testGlobstar(e,t,a,n):i instanceof RegExp?r.testRegExp(e,i,a,n):r.testString(e,i,a,n)}return r}testGlobstar(e,t,n,r){if((this.dot||!e.name.startsWith(`.`))&&(t.hasMore()||this.matches.add(e,r,!1),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,t):e.isSymbolicLink()&&(n&&t.checkFollowGlobstar()?this.subwalks.add(e,n):t.markFollowGlobstar()&&this.subwalks.add(e,t)))),n){let t=n.pattern();if(typeof t==`string`&&t!==`..`&&t!==``&&t!==`.`)this.testString(e,t,n.rest(),r);else if(t===`..`){let t=e.parent||e;this.subwalks.add(t,n)}else t instanceof RegExp&&this.testRegExp(e,t,n.rest(),r)}}testRegExp(e,t,n,r){t.test(e.name)&&(n?this.subwalks.add(e,n):this.matches.add(e,r,!1))}testString(e,t,n,r){e.isNamed(t)&&(n?this.subwalks.add(e,n):this.matches.add(e,r,!1))}};const _c=(e,t)=>typeof e==`string`?new fc([e],t):Array.isArray(e)?new fc(e,t):e;var vc=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#onResume=[];#ignore;#sep;signal;maxDepth;includeChildMatches;constructor(e,t,n){if(this.patterns=e,this.path=t,this.opts=n,this.#sep=!n.posix&&n.platform===`win32`?`\\`:`/`,this.includeChildMatches=n.includeChildMatches!==!1,(n.ignore||!this.includeChildMatches)&&(this.#ignore=_c(n.ignore??[],n),!this.includeChildMatches&&typeof this.#ignore.add!=`function`)){let e=`cannot ignore child matches, ignore lacks add() method.`;throw Error(e)}this.maxDepth=n.maxDepth||1/0,n.signal&&(this.signal=n.signal,this.signal.addEventListener(`abort`,()=>{this.#onResume.length=0}))}#ignored(e){return this.seen.has(e)||!!this.#ignore?.ignored?.(e)}#childrenIgnored(e){return!!this.#ignore?.childrenIgnored?.(e)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let e;for(;!this.paused&&(e=this.#onResume.shift());)e()}onResume(e){this.signal?.aborted||(this.paused?this.#onResume.push(e):e())}async matchCheck(e,t){if(t&&this.opts.nodir)return;let n;if(this.opts.realpath){if(n=e.realpathCached()||await e.realpath(),!n)return;e=n}let r=e.isUnknown()||this.opts.stat,i=r?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&i?.isSymbolicLink()){let e=await i.realpath();e&&(e.isUnknown()||this.opts.stat)&&await e.lstat()}return this.matchCheckTest(i,t)}matchCheckTest(e,t){return e&&(this.maxDepth===1/0||e.depth()<=this.maxDepth)&&(!t||e.canReaddir())&&(!this.opts.nodir||!e.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!e.isSymbolicLink()||!e.realpathCached()?.isDirectory())&&!this.#ignored(e)?e:void 0}matchCheckSync(e,t){if(t&&this.opts.nodir)return;let n;if(this.opts.realpath){if(n=e.realpathCached()||e.realpathSync(),!n)return;e=n}let r=e.isUnknown()||this.opts.stat,i=r?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&i?.isSymbolicLink()){let e=i.realpathSync();e&&(e?.isUnknown()||this.opts.stat)&&e.lstatSync()}return this.matchCheckTest(i,t)}matchFinish(e,t){if(this.#ignored(e))return;if(!this.includeChildMatches&&this.#ignore?.add){let t=`${e.relativePosix()}/**`;this.#ignore.add(t)}let n=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e);let r=this.opts.mark&&e.isDirectory()?this.#sep:``;if(this.opts.withFileTypes)this.matchEmit(e);else if(n){let t=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(t+r)}else{let t=this.opts.posix?e.relativePosix():e.relative(),n=this.opts.dotRelative&&!t.startsWith(`..`+this.#sep)?`.`+this.#sep:``;this.matchEmit(t?n+t+r:`.`+r)}}async match(e,t,n){let r=await this.matchCheck(e,n);r&&this.matchFinish(r,t)}matchSync(e,t,n){let r=this.matchCheckSync(e,n);r&&this.matchFinish(r,t)}walkCB(e,t,n){this.signal?.aborted&&n(),this.walkCB2(e,t,new gc(this.opts),n)}walkCB2(e,t,n,r){if(this.#childrenIgnored(e))return r();if(this.signal?.aborted&&r(),this.paused){this.onResume(()=>this.walkCB2(e,t,n,r));return}n.processPatterns(e,t);let i=1,a=()=>{--i===0&&r()};for(let[e,t,r]of n.matches.entries()){if(this.#ignored(e))continue;i++,this.match(e,t,r).then(()=>a())}for(let e of n.subwalkTargets()){if(this.maxDepth!==1/0&&e.depth()>=this.maxDepth)continue;i++;let t=e.readdirCached();e.calledReaddir()?this.walkCB3(e,t,n,a):e.readdirCB((t,r)=>this.walkCB3(e,r,n,a),!0)}a()}walkCB3(e,t,n,r){n=n.filterEntries(e,t);let i=1,a=()=>{--i===0&&r()};for(let[e,t,r]of n.matches.entries()){if(this.#ignored(e))continue;i++,this.match(e,t,r).then(()=>a())}for(let[e,t]of n.subwalks.entries())i++,this.walkCB2(e,t,n.child(),a);a()}walkCBSync(e,t,n){this.signal?.aborted&&n(),this.walkCB2Sync(e,t,new gc(this.opts),n)}walkCB2Sync(e,t,n,r){if(this.#childrenIgnored(e))return r();if(this.signal?.aborted&&r(),this.paused){this.onResume(()=>this.walkCB2Sync(e,t,n,r));return}n.processPatterns(e,t);let i=1,a=()=>{--i===0&&r()};for(let[e,t,r]of n.matches.entries()){if(this.#ignored(e))continue;this.matchSync(e,t,r)}for(let e of n.subwalkTargets()){if(this.maxDepth!==1/0&&e.depth()>=this.maxDepth)continue;i++;let t=e.readdirSync();this.walkCB3Sync(e,t,n,a)}a()}walkCB3Sync(e,t,n,r){n=n.filterEntries(e,t);let i=1,a=()=>{--i===0&&r()};for(let[e,t,r]of n.matches.entries()){if(this.#ignored(e))continue;this.matchSync(e,t,r)}for(let[e,t]of n.subwalks.entries())i++,this.walkCB2Sync(e,t,n.child(),a);a()}},yc=class extends vc{matches=new Set;constructor(e,t,n){super(e,t,n)}matchEmit(e){this.matches.add(e)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((e,t)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?t(this.signal.reason):e(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},bc=class extends vc{results;constructor(e,t,n){super(e,t,n),this.results=new xs({signal:this.signal,objectMode:!0}),this.results.on(`drain`,()=>this.resume()),this.results.on(`resume`,()=>this.resume())}matchEmit(e){this.results.write(e),this.results.flowing||this.pause()}stream(){let e=this.path;return e.isUnknown()?e.lstat().then(()=>{this.walkCB(e,this.patterns,()=>this.results.end())}):this.walkCB(e,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}};const xc=typeof process==`object`&&process&&typeof process.platform==`string`?process.platform:`linux`;var Sc=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(e,t){if(!t)throw TypeError(`glob options required`);if(this.withFileTypes=!!t.withFileTypes,this.signal=t.signal,this.follow=!!t.follow,this.dot=!!t.dot,this.dotRelative=!!t.dotRelative,this.nodir=!!t.nodir,this.mark=!!t.mark,t.cwd?(t.cwd instanceof URL||t.cwd.startsWith(`file://`))&&(t.cwd=se(t.cwd)):this.cwd=``,this.cwd=t.cwd||``,this.root=t.root,this.magicalBraces=!!t.magicalBraces,this.nobrace=!!t.nobrace,this.noext=!!t.noext,this.realpath=!!t.realpath,this.absolute=t.absolute,this.includeChildMatches=t.includeChildMatches!==!1,this.noglobstar=!!t.noglobstar,this.matchBase=!!t.matchBase,this.maxDepth=typeof t.maxDepth==`number`?t.maxDepth:1/0,this.stat=!!t.stat,this.ignore=t.ignore,this.withFileTypes&&this.absolute!==void 0)throw Error(`cannot set absolute and withFileTypes:true`);if(typeof e==`string`&&(e=[e]),this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(e=e.map(e=>e.replace(/\\/g,`/`))),this.matchBase){if(t.noglobstar)throw TypeError(`base matching requires globstar`);e=e.map(e=>e.includes(`/`)?e:`./**/${e}`)}if(this.pattern=e,this.platform=t.platform||xc,this.opts={...t,platform:this.platform},t.scurry){if(this.scurry=t.scurry,t.nocase!==void 0&&t.nocase!==t.scurry.nocase)throw Error(`nocase option contradicts provided scurry option`)}else{let e=t.platform===`win32`?ic:t.platform===`darwin`?oc:t.platform?ac:sc;this.scurry=new e(this.cwd,{nocase:t.nocase,fs:t.fs})}this.nocase=this.scurry.nocase;let n=this.platform===`darwin`||this.platform===`win32`,r={...t,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:n,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},i=this.pattern.map(e=>new So(e,r)),[a,o]=i.reduce((e,t)=>(e[0].push(...t.set),e[1].push(...t.globParts),e),[[],[]]);this.patterns=a.map((e,t)=>{let n=o[t];if(!n)throw Error(`invalid pattern object`);return new uc(e,n,0,this.platform)})}async walk(){return[...await new yc(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth===1/0?1/0:this.maxDepth+this.scurry.cwd.depth(),platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return[...new yc(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth===1/0?1/0:this.maxDepth+this.scurry.cwd.depth(),platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new bc(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth===1/0?1/0:this.maxDepth+this.scurry.cwd.depth(),platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new bc(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth===1/0?1/0:this.maxDepth+this.scurry.cwd.depth(),platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}};const Cc=(e,t={})=>{Array.isArray(e)||(e=[e]);for(let n of e)if(new So(n,t).hasMagic())return!0;return!1};function wc(e,t={}){return new Sc(e,t).streamSync()}function Tc(e,t={}){return new Sc(e,t).stream()}function Ec(e,t={}){return new Sc(e,t).walkSync()}async function Dc(e,t={}){return new Sc(e,t).walk()}function Oc(e,t={}){return new Sc(e,t).iterateSync()}function kc(e,t={}){return new Sc(e,t).iterate()}const Ac=wc,jc=Object.assign(Tc,{sync:wc}),Mc=Oc,Nc=Object.assign(kc,{sync:Oc}),Pc=Object.assign(Ec,{stream:wc,iterate:Oc}),Fc=Object.assign(Dc,{glob:Dc,globSync:Ec,sync:Pc,globStream:Tc,stream:jc,globStreamSync:wc,streamSync:Ac,globIterate:kc,iterate:Nc,globIterateSync:Oc,iterateSync:Mc,Glob:Sc,hasMagic:Cc,escape:La,unescape:wa});Fc.glob=Fc;var Ic=class{emitter;constructor(){this.emitter=Vi()}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()}},Lc=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 Rc(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 zc=class extends Ic{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 Bc=Rc(zc);var Vc=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{r.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=r.readFileSync(this.getFilePath(),`utf8`),t=this.onAfterLoad(this.parseStoredData(e));return this.data=t,t}catch{return this.data=this._defaultValue}}onBeforeSave(e){return e}onAfterLoad(e){return e}getFilePath(){return this._path}parseStoredData(e){try{let t=n(`string.json.parse`).to(`object`),r=t(e);if(r instanceof n.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 r.accessSync(e,r.constants.R_OK|r.constants.W_OK),!0}catch{return!1}}fileExists(e){try{return r.accessSync(e,r.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){Bc.getInstance().error(`Invalid config file`,`INVALID_CONFIG_FILE`,{issues:e.map(e=>e.message),filePath:this._path,data:this.data})}},Hc=class e extends Ic{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=m(this.logPath,this.getFileName(this.currentDate));if(!a(e))try{p(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=m(this.logPath,this.getFileName(this.currentDate));return i(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=l(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{f(m(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 Uc=()=>h.join(process.env.APPDATA??``,`overlayed`),Wc=()=>h.join(Uc(),`logs`),Gc=e=>h.join(Uc(),`apps`,e),Kc=e=>h.join(Gc(e),`logs`);var qc=class{fileLogger;path;appId;messageQueue=new Hi;fileName;constructor(e){this.fileName=e}init(e){this.appId=e,this.path=Kc(e),this.fileLogger=new Hc(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 Jc=Rc(qc,`main.log`);var Yc=class extends he{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 Xc(e){return ne(e)?ae(e).map(t=>[e,t]):[]}function Zc(e){return e}var Qc=class{logger;initialized=!1;constructor(e){this.logger=Jc.getInstance().scope(e)}init(){this.logger.log(`Initializing`),this.initialized=!0}destroy(){this.logger.log(`Destroying`),this.initialized=!1}},$c=class extends Ic{logger;initialized=!1;constructor(e){super(),this.logger=Jc.getInstance().scope(e)}init(){this.logger.log(`Initializing`),this.initialized=!0}destroy(){this.logger.log(`Destroying`),this.initialized=!1,this.removeAllListeners()}},el=class extends Lc{logger;initialized=!1;constructor(e){super(),this.logger=Jc.getInstance().scope(e)}init(){this.logger.log(`Initializing`),this.initialized=!0}destroy(){this.logger.log(`Destroying`),this.initialized=!1,this.removeAllListeners()}},tl=`object`,nl=`function`,rl=`prototype`,il=`text`,al=`json`,ol=`abort`,sl=`paramsSerializer`,cl=`addEventListener`,ll=`status`,ul=`headers`,dl=Object,fl=void 0,pl=null,ml=dl[rl],hl=dl.keys,gl=Array.isArray,_l=`method`,vl=`HEAD`,yl=`GET`,bl=`OPTIONS`,xl=`POST`,Sl=`PUT`,Cl=`PATCH`,wl=`DELETE`;function Tl(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[cl]){let e=()=>{r(t.reason)};i.push(()=>{var n;(n=t.removeEventListener)==null||n.call(t,ol,e)}),t[cl](ol,e)}}function a(){i.forEach(e=>e()),t?.()}let o=n.signal;return o.clear=a,o}var El=dl.getPrototypeOf,Dl=e=>{if(e!==pl&&typeof e===tl){if(typeof El===nl){let t=El(e);return t===ml||t===pl}return ml.toString.call(e)===`[${tl} Object]`}return!1},Ol=(...e)=>e.reduce((e,t)=>{if(gl(t))throw TypeError(`Arguments must be ${tl}s, not arrays.`);return hl(t).forEach(n=>{[`__proto__`,`constructor`,rl].includes(n)||(gl(e[n])&&gl(t[n])?e[n]=Array.from(new Set(e[n].concat(t[n]))):Dl(e[n])&&Dl(t[n])?e[n]=Ol(e[n],t[n]):e[n]=t[n])}),e},{});function kl(e,t=!0,n=pl,r){if(e===fl||e===pl)return``;let i=[],a=t?encodeURIComponent:e=>e,o=gl(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(ml.hasOwnProperty.call(e,o)){let s=e[o];if(s!==fl){let e=n?`${n}${u(o)}`:a(o);if(!isNaN(s)&&s instanceof Date&&(s=l?l(s):s.toISOString()),typeof s===tl){let n=kl(s,t,e,r);n!==``&&i.push(n)}else i.push(`${a(e)}=${a(s)}`)}}return i.join(`&`)}function Al(e){return gl(e)?e.map(Al):(e&&typeof e===tl&&hl(e).forEach(t=>{let n=e[t];n===fl?delete e[t]:Al(n)}),e)}function jl(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Ml(e,t){return e?t?(e.endsWith(`/`)?e:e+`/`)+(t[0]===`/`?t.slice(1):t):e:t||``}var Nl=`XiorError`,Pl=`XiorTimeoutError`,Fl=class extends Error{constructor(e,t,n){super(e),this.name=Nl,this.request=t,this.config=t,this.response=n}},Il=class extends Fl{constructor(e,t,n){super(e,t,n),this.name=Pl}},Ll=Object.defineProperty,Rl=Object.defineProperties,zl=Object.getOwnPropertyDescriptors,Bl=Object.getOwnPropertySymbols,Vl=Object.prototype.hasOwnProperty,Hl=Object.prototype.propertyIsEnumerable,Ul=(e,t,n)=>t in e?Ll(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Wl=(e,t)=>{for(var n in t||(t={}))Vl.call(t,n)&&Ul(e,n,t[n]);if(Bl)for(var n of Bl(t))Hl.call(t,n)&&Ul(e,n,t[n]);return e},Gl=(e,t)=>Rl(e,zl(t)),Kl=(e,t)=>{var n={};for(var r in e)Vl.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&Bl)for(var r of Bl(e))t.indexOf(r)<0&&Hl.call(e,r)&&(n[r]=e[r]);return n},ql=(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())}),Jl=`application/`,Yl=`${Jl}x-www-form-urlencoded`,Xl=RegExp,Zl=new Xl(`^${Yl}`,`i`),Ql=`${Jl}${al}`,$l=new Xl(`^${Jl}.*${al}.*`,`i`);function eu(e=yl){return[vl,yl,bl].includes(e)}var tu=typeof URLSearchParams!=`${fl}`;function nu(e){return ql(this,null,function*(){let t=e[sl]||kl,n=e.encodeURI!==!1,r=e[_l]&&e[_l].toUpperCase(),i=e.url,a=i,o=tu&&e.data instanceof URLSearchParams,s=o?dl.fromEntries(e.data.entries()):e.data,c=s,l=e!=null&&e[ul]?Wl({},e[ul]):{},u=e.params,d=eu(r);if(s&&typeof s.append!==nl){let n=``,r=`content-type`;if(e!=null&&e[ul]){let t=hl(e[ul]).find(e=>e.toLowerCase()===r);t&&(r=t,n=e[ul][t])}(!n||o)&&(n=d||o?Yl:Ql,l[r]=n),typeof s===tl&&(d&&u&&(u=Ol(s,u)),$l.test(n)?c=JSON.stringify(Al(s)):!d&&Zl.test(n)&&(c=t(s)))}if(u&&hl(u).length>0){let e=t(u,n);i+=i.includes(`?`)?`&${e}`:`?${e}`}return Gl(Wl({},e),{_data:c,_url:i,data:s,url:a,method:r,[ul]:l,isGet:d})})}var ru=typeof AbortController!=`${fl}`;function iu(e,t){return ql(this,null,function*(){let n;if(!t||!e.ok||[il,al].includes(t)){if(n=yield e[il](),n&&t!==il)try{n=JSON.parse(n)}catch(e){}}else{if(t===`blob`)return e.blob();if(t===`arraybuffer`)return e.arrayBuffer()}return n})}var au=e=>new ou(e),ou=class{constructor(e){this.REQI=[],this.RESI=[],this.P=[],this.config=e,this.defaults={params:{},[ul]:{}}}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 ql(this,null,function*(){let t=Ol(this.config||{},this.defaults,typeof e==`string`?{url:e}:e),n=`credentials`;t.withCredentials&&!t[n]&&(t[n]=`include`),t[sl]||(t[sl]=kl);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 ql(this,null,function*(){let t=yield nu(e),{url:n,method:r,headers:i,timeout:a,signal:o,data:s,_data:c,_url:l,isGet:u,fetch:d}=t,f=Kl(t,[`url`,`method`,`headers`,`timeout`,`signal`,`data`,`_data`,`_url`,`isGet`,`fetch`]);e._url=l;let p,m=[],h=fl;if(a&&ru){let t=new AbortController;h=setTimeout(()=>{t.abort(new Il(`timeout of ${a}ms exceeded`,e))},a),m.push(t.signal)}o&&m.push(o),p=m[0],m.length>1&&(p=Tl(m,()=>{clearTimeout(h)}));let g=l||n,_=`baseURL`;return e[_]&&!jl(g)&&(g=Ml(e[_],g)),(d||fetch)(g,Gl(Wl({body:u?fl:c},f),{signal:p,method:r,headers:i})).then(t=>ql(this,null,function*(){let{responseType:n}=e,r={data:yield iu(t,n),response:t,config:e,request:e,[ll]:t[ll],statusText:t.statusText,[ul]:t[ul]};if(!t.ok){let n=new Fl(t[ll]?`Request failed with status code ${t[ll]}`:`Network error`,e,r);return Promise.reject(n)}return r})).finally(()=>{var e;h&&clearTimeout(h),(e=p==null?void 0:p.clear)==null||e.call(p)})})}cG(e){return(t,n)=>this.request(n?Gl(Wl({},n),{method:e,url:t}):{method:e,url:t})}cP(e){return(t,n,r)=>this.request(r?Gl(Wl({},r),{method:e,url:t,data:n}):{method:e,url:t,data:n})}get(e,t){return this.cG(yl)(e,t)}head(e,t){return this.cG(vl)(e,t)}post(e,t,n){return this.cP(xl)(e,t,n)}put(e,t,n){return this.cP(Sl)(e,t,n)}patch(e,t,n){return this.cP(Cl)(e,t,n)}delete(e,t){return this.cG(wl)(e,t)}options(e,t){return this.cG(bl)(e,t)}};ou.create=au,ou.VERSION=`0.7.8`;var su=Object.assign(ou.create(),{create:ou.create,VERSION:ou.VERSION}),cu=su;const lu=cu.create({baseURL:`https://updater.stats.cc`,headers:{Accept:`application/json`,"Accept-Encoding":`gzip, deflate, br`}});let uu;function du(e){uu=e}const fu=cu.create({baseURL:`https://api.overlayed.gg`,headers:{Accept:`application/json`,"Accept-Encoding":`gzip, deflate, br`}});lu.interceptors.request.use(e=>{let t=uu?.();return t?(e.headers??={},e.headers.Authorization=t,e):e});function pu(e){return fu.get(`/v1/public/applications/${e}`)}function mu(e,t){return lu.get(`/v1/native/${gu(e)}/version.txt`,{params:{channel:t},responseType:`text`})}function hu(e,t){return lu.get(`/v1/native/${gu(e)}/files`,{params:{channel:t},responseType:`arraybuffer`})}function gu(e){return e===`01JXPFK6YQ3N00N2Y9JHFNG55D`||e===`01JZEBPGHT5M4Y6SGY4P7Q9EZT`?`siege-game-module`:e}function _u(){return fu.get(`/v1/public/raven/config`)}const vu=e=>Array.isArray(e)?e:[e],yu=(e,t)=>{let n=[[],[]];for(let r of e)t(r)?n[0].push(r):n[1].push(r);return n},bu=Array,xu=(e,t)=>e.includes(t),Su=(e,t=0)=>[...Array(e)].map((e,n)=>n+t),N=(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),Cu=(e,t)=>t==null?e??[]:e==null?vu(t):e.concat(t),wu=(...e)=>e.reduce(Cu,[]),Tu=(e,t,n)=>{if(e===void 0)return Array.isArray(t)?t:[t];let r=n?.isEqual??((e,t)=>e===t);for(let n of vu(t))e.some(e=>r(e,n))||e.push(n);return e},Eu=(e,t)=>e.reduce((e,n)=>{let r=n[t];return e[r]=N(e[r],n),e},{}),Du=(e,t,n)=>e.length===t.length&&e.every(n?.isEqual?(e,r)=>n.isEqual(e,t[r]):(e,n)=>e===t[n]),Ou=(e,t)=>ku(e)===t,ku=e=>{let t=typeof e;return t===`object`?e===null?`null`:`object`:t===`function`?`object`:t},Au={boolean:`boolean`,null:`null`,undefined:`undefined`,bigint:`a bigint`,number:`a number`,object:`an object`,string:`a string`,symbol:`a symbol`},ju={...Au,function:`a function`};var Mu=class extends Error{};const P=e=>Nu(e,Mu),Nu=(e,t=Error)=>{throw new t(e)};var Pu=class extends Error{name=`ParseError`};const F=e=>Nu(e,Pu),Fu=e=>` ${e}`,I=(e,t)=>{let n={},r=Array.isArray(e),i=!1;for(let[a,o]of Object.entries(e).entries()){let e=r?t(a,o[1]):t(...o,a);i||=typeof e[0]==`number`;let s=Array.isArray(e[0])||e.length===0?e:[e];for(let[e,t]of s)typeof e==`object`?n[e.group]=N(n[e.group],t):n[e]=t}return i?Object.values(n):n},Iu=Object.entries,Lu=(e,t)=>e in t,Ru=(e,t)=>t in e;var zu=class{constructor(e){Object.assign(this,e)}};const Bu=class{};var Vu=class extends Bu{};const Hu=(e,t)=>{let n={},r={},i;for(i in e)i in t?n[i]=e[i]:r[i]=e[i];return[n,r]},Uu=(e,t)=>Hu(e,t)[1],Wu=e=>Object.keys(e).length===0,Gu=e=>[...Object.entries(e),...Object.getOwnPropertySymbols(e).map(t=>[t,e[t]])],Ku=(e,t)=>Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)),qu=e=>{let t=Object.keys(e).sort(),n={};for(let r=0;r<t.length;r++)n[t[r]]=e[t[r]];return n},Ju=Fu(`represents an uninitialized value`),Yu=e=>Object.values(e).filter(t=>typeof t==`number`?!0:typeof e[t]!=`number`),Xu={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},Zu=globalThis.File??Blob,Qu={ArrayBuffer,Blob,File:Zu,FormData,Headers,Request,Response,URL},$u={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},ed={...Xu,...Qu,...$u,String,Number,Boolean},td=e=>{let t=Object.getPrototypeOf(e);for(;t?.constructor&&(!Lu(t.constructor.name,ed)||!(e instanceof ed[t.constructor.name]));)t=Object.getPrototypeOf(t);let n=t?.constructor?.name;if(!(n===void 0||n===`Object`))return n},nd=e=>typeof e==`object`&&e?td(e)??`object`:ku(e),L=Array.isArray,rd={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`},id={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`},ad={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`},od={...rd,...id,...ad},sd=e=>{let t=Object(e).name??null;return t&&Lu(t,ed)&&ed[t]===e?t:null},cd=e=>{let t=Object.getPrototypeOf(e),n=[];for(;t!==null;)n.push(t.constructor),t=Object.getPrototypeOf(t);return n},ld=(e,t)=>{let n=e.prototype;for(;n!==null;){if(n===t.prototype)return!0;n=Object.getPrototypeOf(n)}return!1},ud=e=>dd(e,new Map),dd=(e,t)=>{if(typeof e!=`object`||!e)return e;if(t?.has(e))return t.get(e);let n=sd(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=dd(e.value,t)}return Object.defineProperties(r,i),r},fd=e=>{let t=Ju;return()=>t===Ju?t=e():t},pd=e=>typeof e==`function`&&e.length===0,md=class extends Function{constructor(...e){let t=e.slice(0,-1),n=e.at(-1);try{super(...t,n)}catch(t){return P(`Encountered an unexpected error while compiling your definition:
|
|
2
6
|
Message: ${t}
|
|
3
7
|
Source: (${e.slice(0,-1)}) => {
|
|
4
8
|
${e.at(-1)}
|
|
5
|
-
}`)}}};var
|
|
6
|
-
`))}
|
|
7
|
-
|
|
8
|
-
`)}
|
|
9
|
-
|
|
10
|
-
`)),
|
|
9
|
+
}`)}}};var hd=class{constructor(e,...[t]){return Object.assign(Object.setPrototypeOf(e.bind(t?.bind??this),this.constructor.prototype),t?.attach)}};const gd=fd(()=>{try{return Function(`return false`)()}catch{return!0}});Fu(`brand`),Fu(`arkInferred`),Fu(`args`);var _d=class{constructor(){}};const vd=()=>{try{let e=Error(),t=e.stack?.split(`
|
|
10
|
+
`)[2]?.trim()||``,n=t.match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||`unknown`;return n.replace(/^file:\/\//,``)}catch{return`unknown`}},yd=globalThis.process?.env??{},bd={fileName:vd,env:yd},xd=e=>e[0].toUpperCase()+e.slice(1),Sd=e=>new RegExp(Cd(e),typeof e==`string`?``:e.flags),Cd=e=>{let t=typeof e==`string`?e:e.source;return`^(?:${t})$`},wd={negativeLookahead:e=>`(?!${e})`,nonCapturingGroup:e=>`(?:${e})`},Td=`\\`,Ed={" ":1,"\n":1," ":1},Dd=/^-0\.?0*$/.source,Od=/[1-9]\d*/.source,kd=/\.\d+/.source,Ad=/\.\d*[1-9]/.source,jd=e=>Sd(wd.negativeLookahead(Dd)+wd.nonCapturingGroup(`-?`+wd.nonCapturingGroup(wd.nonCapturingGroup(`0|`+Od)+wd.nonCapturingGroup(e.decimalPattern)+`?`)+(e.allowDecimalOnly?`|`+e.decimalPattern:``)+`?`)),Md=jd({decimalPattern:Ad,allowDecimalOnly:!1}),Nd=Md.test.bind(Md),Pd=jd({decimalPattern:kd,allowDecimalOnly:!0});Pd.test.bind(Pd);const Fd=/^-?\d*\.?\d*$/,Id=e=>e.length!==0&&Fd.test(e),Ld=Sd(wd.negativeLookahead(`^-0$`)+`-?`+wd.nonCapturingGroup(wd.nonCapturingGroup(`0|`+Od))),Rd=Ld.test.bind(Ld),zd=/^-?\d+$/,Bd=zd.test.bind(zd),Vd={number:`a number`,bigint:`a bigint`,integer:`an integer`},Hd=(e,t)=>`'${e}' was parsed as ${Vd[t]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,Ud=(e,t)=>t===`number`?Nd(e):Rd(e),Wd=(e,t)=>t===`number`?Number(e):Number.parseInt(e),Gd=(e,t)=>t===`number`?Id(e):Bd(e),Kd=(e,t)=>Yd(e,`number`,t),qd=(e,t)=>Yd(e,`number`,{...t,strict:!0}),Jd=(e,t)=>Yd(e,`integer`,t),Yd=(e,t,n)=>{let r=Wd(e,t);return!Number.isNaN(r)&&Gd(e,t)?n?.strict?Ud(e,t)?r:F(Hd(e,t)):r:n?.errorOnFail?F(n?.errorOnFail===!0?`Failed to parse ${Vd[t]} from '${e}'`:n?.errorOnFail):void 0},Xd=e=>{if(e[e.length-1]!==`n`)return;let t=e.slice(0,-1),n;try{n=BigInt(t)}catch{return}if(Ld.test(t))return n;if(zd.test(t))return F(Hd(e,`bigint`))},Zd=`0.46.0`,Qd={version:Zd,filename:bd.fileName(),FileConstructor:Zu},$d=Qd,ef=new Map,tf=Object.create(null),nf=e=>{let t=ef.get(e);if(t)return t;let n=af(e);return tf[n]?n=`${n}${tf[n]++}`:tf[n]=1,$d[n]=e,ef.set(e,n),n},rf=e=>/^[$A-Z_a-z][\w$]*$/.test(e),af=e=>{switch(typeof e){case`object`:{if(e===null)break;let t=td(e)??`object`;return t[0].toLowerCase()+t.slice(1)}case`function`:return rf(e.name)?e.name:`fn`;case`symbol`:return e.description&&rf(e.description)?e.description:`symbol`}return P(`Unexpected attempt to register serializable value of type ${ku(e)}`)},sf=e=>typeof e==`string`?JSON.stringify(e):typeof e==`bigint`?`${e}n`:`${e}`,cf=(e,t={})=>df(e,{onUndefined:`$ark.undefined`,onBigInt:e=>`$ark.bigint-${e}`,...t},[]),R=(e,t)=>{switch(ku(e)){case`object`:let n=e,r=n.constructor.name;return r===`Object`||r===`Array`?t?.quoteKeys===!1?lf(n,t?.indent??0,``):JSON.stringify(df(n,uf,[]),null,t?.indent):lf(n,t?.indent??0,``);case`symbol`:return uf.onSymbol(e);default:return sf(e)}},lf=(e,t,n)=>{if(typeof e==`function`)return uf.onFunction(e);if(typeof e!=`object`||!e)return sf(e);let r=n+` `.repeat(t);if(Array.isArray(e)){if(e.length===0)return`[]`;let i=e.map(e=>lf(e,t,r)).join(`,
|
|
11
|
+
`+r);return t?`[\n${r}${i}\n${n}]`:`[${i}]`}let i=e.constructor.name;if(i===`Object`){let i=Gu(e).map(([e,n])=>{let i=typeof e==`symbol`?uf.onSymbol(e):rf(e)?e:JSON.stringify(e),a=lf(n,t,r);return`${r}${i}: ${a}`});return i.length===0?`{}`:t?`{\n${i.join(`,
|
|
12
|
+
`)}\n${n}}`:`{${i.join(`, `)}}`}return e instanceof Date?ff(e):`expression`in e&&typeof e.expression==`string`?e.expression:i},uf={onCycle:()=>`(cycle)`,onSymbol:e=>`Symbol(${nf(e)})`,onFunction:e=>`Function(${nf(e)})`},df=(e,t,n)=>{switch(ku(e)){case`object`:{let r=e;if(`toJSON`in r&&typeof r.toJSON==`function`)return r.toJSON();if(typeof r==`function`)return uf.onFunction(r);if(n.includes(r))return`(cycle)`;let i=[...n,r];if(Array.isArray(r))return r.map(e=>df(e,t,i));if(r instanceof Date)return r.toDateString();let a={};for(let e in r)a[e]=df(r[e],t,i);for(let e of Object.getOwnPropertySymbols(r))a[t.onSymbol?.(e)??e.toString()]=df(r[e],t,i);return a}case`symbol`:return uf.onSymbol(e);case`bigint`:return t.onBigInt?.(e)??`${e}n`;case`undefined`:return t.onUndefined??`undefined`;case`string`:return e.replaceAll(`\\`,`\\\\`);default:return e}},ff=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=`${pf[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+=`.${hf(s,3)}`:mf.test(l)&&(l=l.slice(0,-3)),`${l+u}, ${c}`},pf=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],mf=/:\d\d:00$/,hf=(e,t)=>String(e).padStart(t,`0`),gf=(e,t,...[n])=>{let r=n?.stringifySymbol??R,i=e;switch(typeof t){case`string`:i=rf(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)}]`:F(`${R(t)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return i},_f=(e,...t)=>e.reduce((e,n)=>gf(e,n,...t),``);var vf=class extends bu{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`?R(this[e]):this[e]);return this.cache.json}stringify(){return this.cache.stringify?this.cache.stringify:this.cache.stringify=_f(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let e=``,t=[e];for(let n of this)e=gf(e,n),t.push(e);return this.cache.stringifyAncestors=t}},yf=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]===Td)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 Ed))}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 bf=Fu(`implementedTraits`),xf=e=>t=>Ou(t,`object`)?bf in t.constructor&&t.constructor[bf].includes(e)?!0:cd(t).includes(e):!1;(class extends Bu{static get[Symbol.hasInstance](){return xf(this)}traitsOf(){return bf in this.constructor?this.constructor[bf]:[]}});let Sf=`$ark`,Cf=2;for(;Sf in globalThis;)Sf=`$ark${Cf++}`;const wf=Sf;globalThis[wf]=$d;const z=$d,Tf=e=>`${wf}.${e}`,Ef=e=>Tf(nf(e));var Df=class extends Vu{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 kf(e,t)}index(e,t=!1){return jf(`${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`,t=0){return`${e}(${this.argNames.join(`, `)}) { ${t?this.body.split(`
|
|
13
|
+
`).map(e=>` `.repeat(t)+`${e}`).join(`
|
|
14
|
+
`):this.body} }`}compile(){return new md(...this.argNames,this.body)}};const Of=e=>Ou(e,`object`)||typeof e==`symbol`?Ef(e):sf(e),kf=(e,t=!1)=>typeof e==`string`&&rf(e)?`${t?`?`:``}.${e}`:jf(Af(e),t),Af=e=>typeof e==`symbol`?Ef(e):JSON.stringify(e),jf=(e,t=!1)=>`${t?`?.`:``}[${e}]`;var Mf=class extends Df{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 Nf=e=>I(e,(e,t)=>[e,L(t)?[...t]:t]),Pf=Fu(`arkKind`),B=(e,t)=>e?.[Pf]===t,V=e=>B(e,`root`)||B(e,`constraint`),Ff=[`unit`,`proto`,`domain`],If=[`required`,`optional`,`index`,`sequence`],Lf=[`pattern`,`divisor`,`exactLength`,`max`,`min`,`maxLength`,`minLength`,`before`,`after`],Rf=[...Lf,...If,`structure`,`predicate`],zf=[`alias`,`union`,`morph`,`unit`,`intersection`,`proto`,`domain`],Bf=[...zf,...Rf],Vf=I(Rf,(e,t)=>[t,1]),Hf=I([...If,`undeclared`],(e,t)=>[t,1]),Uf=I(Bf,(e,t)=>[t,e]),Wf=e=>typeof e==`string`&&e in Uf,Gf=e=>Uf[e],Kf=e=>zf.slice(Gf(e)+1);[...Kf(`union`)],[...Kf(`morph`)];const qf=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:Of(e),Jf=e=>{let t=`{ `;for(let[n,r]of Object.entries(e))t+=`${n}: ${Of(r)}, `;return t+` }`},H=e=>{let t=e;return t.hasAssociatedError&&(t.defaults.expected??=e=>`description`in e?e.description:t.defaults.description(e),t.defaults.actual??=e=>R(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};var Yf=class extends Error{name=`ToJsonSchemaError`;code;context;constructor(e,t){super(R(t,{quoteKeys:!1,indent:4})),this.code=e,this.context=t}hasCode(e){return this.code===e}};const Xf={dialect:`https://json-schema.org/draft/2020-12/schema`,useRefs:!1,fallback:{arrayObject:e=>U.throw(`arrayObject`,e),arrayPostfix:e=>U.throw(`arrayPostfix`,e),defaultValue:e=>U.throw(`defaultValue`,e),domain:e=>U.throw(`domain`,e),morph:e=>U.throw(`morph`,e),patternIntersection:e=>U.throw(`patternIntersection`,e),predicate:e=>U.throw(`predicate`,e),proto:e=>U.throw(`proto`,e),symbolKey:e=>U.throw(`symbolKey`,e),unit:e=>U.throw(`unit`,e),date:e=>U.throw(`date`,e)}},U={Error:Yf,throw:(...e)=>{throw new U.Error(...e)},throwInternalOperandError:(e,t)=>P(`Unexpected JSON Schema input for ${e}: ${R(t)}`),defaultConfig:Xf};z.config??={};const Zf=(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 r===`toJsonSchema`?n[r]=Qf(e.toJsonSchema,t.toJsonSchema):Wf(r)?n[r]={...e[r],...t[r]}:n[r]=t[r]}return n},Qf=((e,t)=>{if(!e)return t??{};if(!t)return e;let n={...e},r;for(r in t)r===`fallback`?n.fallback=$f(e.fallback,t.fallback):n[r]=t[r];return n}),$f=(e,t)=>{e=ep(e),t=ep(t);let n={},r;for(r in U.defaultConfig.fallback)n[r]=t[r]??t.default??e[r]??e.default??U.defaultConfig.fallback[r];return n},ep=e=>typeof e==`function`?{default:e}:e??{};var tp=class e extends Vu{[Pf]=`error`;path;data;nodeConfig;input;ctx;constructor({prefixPath:e,relativePath:t,...n},r){super(),this.input=n,this.ctx=r,Ku(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:wu(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 vf(...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 _f(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}},np=class e extends bu{[Pf]=`errors`;ctx;constructor(e){super(),this.ctx=e}byPath=Object.create(null);get flatByPath(){return I(this.byPath,(e,t)=>[e,t.flat])}get flatProblemsByPath(){return I(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 rp(this)}add(e){this.includes(e)||this._add(e)}transform(t){let n=new e(this.ctx);for(let e of this)n.add(t(e));return n}merge(e){for(let t of e){if(this.includes(t))continue;this._add(new tp({...t,path:[...this.ctx.path,...t.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(`
|
|
15
|
+
`)}_add(e){let t=this.byPath[e.propString];if(t){if(t.hasCode(`union`)&&t.errors.length===0)return;let n=e.hasCode(`union`)&&e.errors.length===0?e:new tp({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){for(let t of e.path.stringifyAncestors())this.byAncestorPath[t]=N(this.byAncestorPath[t],e)}},rp=class extends Error{name=`TraversalError`;constructor(e){e.length===1?super(e.summary):super(`
|
|
16
|
+
`+e.map(e=>` • ${ip(e)}`).join(`
|
|
17
|
+
`)),Object.defineProperty(this,`arkErrors`,{value:e,enumerable:!1})}};const ip=e=>e.toString().split(`
|
|
11
18
|
`).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}`,
|
|
19
|
+
`);var ap=class{path=[];errors=new np(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 _f(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 vf(...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 tp(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=V(e),i=e(r===void 0?this.root:r[n],this);if(i instanceof tp){this.errors.add(i);break}if(i instanceof np){t||this.errors.merge(i);break}r===void 0?this.root=i:r[n]=i,this.applyQueuedMorphs()}}};const op=(e,t,n)=>{if(!n)return t();n.path.push(e);let r=t();return n.path.pop(),r};var sp=class extends hd{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)=>gp(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=>mp(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 ap(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 ap(e,this.$.resolvedConfig);return this.traverseApply(e,n),n.finalize(t)};case`contextual`:return(e,t)=>{let n=new ap(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 ap(t,this.$.resolvedConfig);return this.traverseApply(t,r),r.finalize(n)};case`branchedOptimistic`:return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,P(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=fp(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=Gf(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]=L(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=V(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&&Nu(`${this.kind} node was not of asserted kind ${e}`),this}hasKindIn(...e){return e.includes(this.kind)}assertHasKindIn(...e){return xu(e,this.kind)||Nu(`${this.kind} node was not one of asserted kinds ${e}`),this}isBasis(){return xu(Ff,this.kind)}isConstraint(){return xu(Rf,this.kind)}isStructural(){return xu(If,this.kind)}isRefinement(){return xu(Lf,this.kind)}isRoot(){return xu(zf,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=cp.normalize(e);return this._select(t)}_select(e){let t=cp.applyBoundary[e.boundary??`references`](this);return e.kind&&(t=t.filter(t=>t.kind===e.kind)),e.where&&(t=t.filter(e.where)),cp.applyMethod[e.method??`filter`](t,this,e)}transform(e,t){return this._transform(e,this._createTransformContext(t))}_createTransformContext(e){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:e?.prereduced??!1},undeclaredKeyHandling:void 0,...e}}_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=I(this.inner,(n,r)=>{if(!this.impl.keys[n].child)return[n,r];let i=r;if(!L(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=t.selected&&!t.selected.includes(this)?a:e(this.kind,a,t);if(o===null)return null;if(V(o))return r=o;let s=Object.keys(o),c=s.length===0||s.length===1&&s[0]===`meta`;return c&&!Wu(this.inner)?null:(this.kind===`required`||this.kind===`optional`||this.kind===`index`)&&!(`value`in o)?t.undeclaredKeyHandling?{...o,value:z.intrinsic.unknown}:null:(this.kind===`morph`&&(o.in??=z.intrinsic.unknown),r=n.node(this.kind,o,t.parseOptions))}configureReferences(e,t=`references`){let n=cp.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=this._select(n),a=i&&vu(i),o=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:o,selected:a}))}};const cp={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&&Nu(lp(t,n)),e),find:e=>e[0],assertFind:(e,t,n)=>(e.length===0&&Nu(lp(t,n)),e[0])},normalize:e=>typeof e==`function`?{boundary:`references`,method:`filter`,where:e}:typeof e==`string`?Lu(e,cp.applyBoundary)?{method:`filter`,boundary:e}:{boundary:`references`,method:`filter`,kind:e}:{boundary:`references`,method:`filter`,...e}},lp=(e,t)=>`${e} had no references matching ${R(t)}.`,up=e=>_f(e,{stringifyNonKey:e=>e.expression}),dp=/"(\$ark\.[^"]+)"/g,fp=e=>JSON.stringify(e).replaceAll(dp,`$1`),pp=(e,t)=>({path:e,node:t,propString:up(e)}),mp=(e,t)=>e.propString===t.propString&&e.node.equals(t.node),hp=(e,t)=>Tu(e,t,{isEqual:mp}),gp=(e,t)=>Tu(e,t,{isEqual:(e,t)=>e.equals(t)});var W=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=_f(e);return yp(`Intersection${r&&` at ${r}`} of ${_p(t,n)}`)}return`The following intersections result in unsatisfiable types:\n• ${this.map(({path:e,l:t,r:n})=>`${e}: ${_p(t,n)}`).join(`
|
|
20
|
+
• `)}`}throw(){return F(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 z.intrinsic.never}};const _p=(e,t)=>`${vp(e)} and ${vp(t)}`,vp=e=>V(e)?e.expression:L(e)?e.map(vp).join(` | `)||`never`:String(e),yp=e=>`${e} results in an unsatisfiable type`,bp={},xp=(e,t,n)=>G(e,t,{$:n,invert:!1,pipe:!1}),Sp=(e,t,n)=>G(e,t,{$:n,invert:!1,pipe:!0}),G=((e,t,n)=>{let r=n.pipe?`|>`:`&`,i=`${e.hash}${r}${t.hash}`;if(bp[i]!==void 0)return bp[i];if(!n.pipe){let n=`${t.hash}${r}${e.hash}`;if(bp[n]!==void 0){let e=bp[n],t=e instanceof W?e.invert():e;return bp[i]=t,t}}let a=!n.pipe||!e.includesTransform&&!t.includesTransform;if(a&&e.equals(t))return e;let o=a?Cp(e,t,n):e.hasKindIn(...zf)?wp(e,t,n):Cp(e,t,n);return V(o)&&(e.equals(o)?o=e:t.equals(o)&&(o=t)),bp[i]=o,o}),Cp=(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 W&&(r=r.invert()),r}},wp=(e,t,n)=>e.includesTransform||t.includesTransform?n.invert?Tp(t,e,n):Tp(e,t,n):Cp(e,t,n),Tp=(e,t,n)=>e.distribute(e=>Ep(e,t,n),r=>{let i=r.filter(V);if(i.length===0)return W.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.configure(a,`self`)}):e}let o={branches:i};return a&&(o.meta=a),n.$.parseSchema(o)}),Ep=(e,t,n)=>{let r=e.hasKind(`morph`);if(r){let r=[...e.morphs];if(e.lastMorphIfNode){let i=G(e.lastMorphIfNode,t,n);if(i instanceof W)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=G(e,t.in,n);return r instanceof W?r:n.$.node(`morph`,{morphs:[t],in:r})}return n.$.node(`morph`,{morphs:[t],in:e})};var Dp=class extends sp{constructor(e,t){super(e,t),Object.defineProperty(this,Pf,{value:`constraint`,enumerable:!1})}impliedSiblings;intersect(e){return xp(this,e,this.$)}},Op=class extends Dp{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 Jf(this.errorContext)}};const kp=e=>(t,n)=>{if(L(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},Ap=e=>{let t=e.r.shift();if(!t){let t=e.l.length===0&&e.kind===`structure`?z.intrinsic.unknown.internal:e.ctx.$.node(e.kind,Object.assign(e.baseInner,Mp(e.l)),{prereduced:!0});for(let n of e.roots){if(t instanceof W)return t;t=G(n,t,e.ctx)}return t}let n=!1;for(let r=0;r<e.l.length;r++){let i=G(e.l[r],t,e.ctx);if(i!==null){if(i instanceof W)return i;if(n){if(!e.l.includes(i))return P(`Unexpectedly encountered multiple distinct intersection results for refinement ${i}`)}else{if(i.isRoot())return e.roots.push(i),e.l.splice(r),Ap(e);e.l[r]=i,n=!0}}}if(n||e.l.push(t),e.kind===`intersection`&&t.impliedSiblings)for(let n of t.impliedSiblings)Tu(e.r,n);return Ap(e)},jp=e=>{let t=Object.entries(e).flatMap(([e,t])=>e in Vf?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},Mp=e=>{let t={};for(let n of e)if(n.hasOpenIntersection())t[n.kind]=N(t[n.kind],n);else{if(t[n.kind])return P(`Unexpected intersection of closed refinements of kind ${n.kind}`);t[n.kind]=n}return t},Np=(...e)=>F(Pp(...e)),Pp=(e,t,n)=>{let r=n.hasKind(`morph`)?`a morph`:n.isUnknown()?`unknown`:n.exclude(t).defaultShortDescription;return`${xd(e)} operand must be ${t.description} (was ${r})`},Fp=(e,t,n)=>new Lp(e,t,n,n,null);var Ip=class extends hd{},Lp=class extends hd{[Pf]=`generic`;paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(e,t,n,r,i){super((...e)=>{let n=I(this.names,(t,n)=>{let r=this.arg$.parse(e[t]);return r.extends(this.constraints[t])||F(Rp(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 Ip}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:cf(this.bodyDef)})}get params(){return this.cacheGetter(`params`,this.paramDefs.map(e=>typeof e==`string`?[e,z.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 Rp=(e,t,n)=>`${e} must be assignable to ${t} (was ${n})`,zp=H({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 Bp=class extends Dp{serializedPredicate=Ef(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=Jf(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(e,t){return t.fallback.predicate({code:`predicate`,base:e,predicate:this.predicate})}};const Vp={implementation:zp,Node:Bp},Hp=H({kind:`divisor`,collapsibleKey:`rule`,keys:{rule:{parse:e=>Number.isInteger(e)?e:F(Gp(e))}},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/Kp(e.rule,t.rule))})},obviatesBasisDescription:!0});var Up=class extends Op{traverseAllows=e=>e%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=z.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(e){return e.type=`integer`,this.rule===1||(e.multipleOf=this.rule),e}};const Wp={implementation:Hp,Node:Up},Gp=e=>`divisor must be an integer (was ${e})`,Kp=(e,t)=>{let n,r=e,i=t;for(;i!==0;)n=i,i=r%i,r=n;return r};var qp=class extends Op{boundOperandKind=nm[this.kind];compiledActual=this.boundOperandKind===`value`?`data`:this.boundOperandKind===`length`?`data.length`:`data.valueOf()`;comparator=rm(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${Jp[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind===`date`?im(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 Jp={"<":`>=`,"<=":`>`,">":`<=`,">=":`<`},Yp={min:`max`,minLength:`maxLength`,after:`before`},Xp={parse:e=>e||void 0},Zp=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},Qp=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},$p=e=>typeof e==`string`||typeof e==`number`?new Date(e):e,em=(e,t)=>`${e} bound must be a positive integer (was ${t})`,tm=e=>t=>((!Number.isInteger(t)||t<0)&&F(em(e,t)),t),nm={min:`value`,max:`value`,minLength:`length`,maxLength:`length`,after:`date`,before:`date`},rm=(e,t)=>`${Lu(e,Yp)?`>`:`<`}${t?``:`=`}`,im=e=>typeof e==`string`?e:new Date(e).toLocaleString(),am=e=>`Bounded expression ${e} must be exactly one of number, string, Array, or Date`,om=H({kind:`after`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{parse:$p,serialize:e=>e.toISOString()}},normalize:Qp(`after`),defaults:{description:e=>`${e.collapsibleLimitString} or later`,actual:ff},intersections:{after:(e,t)=>e.isStricterThan(t)?e:t}});var sm=class extends qp{impliedBasis=z.intrinsic.Date.internal;collapsibleLimitString=ff(this.rule);traverseAllows=e=>e>=this.rule;reduceJsonSchema(e,t){return t.fallback.date({code:`date`,base:e,after:this.rule})}};const cm={implementation:om,Node:sm},lm=H({kind:`before`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{parse:$p,serialize:e=>e.toISOString()}},normalize:Qp(`before`),defaults:{description:e=>`${e.collapsibleLimitString} or earlier`,actual:ff},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:W.init(`range`,e,t)}});var um=class extends qp{collapsibleLimitString=ff(this.rule);traverseAllows=e=>e<=this.rule;impliedBasis=z.intrinsic.Date.internal;reduceJsonSchema(e,t){return t.fallback.date({code:`date`,base:e,before:this.rule})}};const dm={implementation:lm,Node:um},fm=H({kind:`exactLength`,collapsibleKey:`rule`,keys:{rule:{parse:tm(`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)=>W.init(`unit`,n.$.node(`unit`,{unit:e.rule}),n.$.node(`unit`,{unit:t.rule}),{path:[`length`]}),minLength:(e,t)=>e.rule>=t.rule?e:W.init(`range`,e,t),maxLength:(e,t)=>e.rule<=t.rule?e:W.init(`range`,e,t)}});var pm=class extends Op{traverseAllows=e=>e.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=z.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 mm={implementation:fm,Node:pm},hm=H({kind:`max`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{},exclusive:Xp},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:W.init(`range`,e,t)},obviatesBasisDescription:!0});var gm=class extends qp{impliedBasis=z.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 _m={implementation:hm,Node:gm},vm=H({kind:`maxLength`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{parse:tm(`maxLength`)}},reduce:(e,t)=>e.rule===0?t.node(`exactLength`,e):void 0,normalize:Zp(`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:W.init(`range`,e,t)}});var ym=class extends qp{impliedBasis=z.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 bm={implementation:vm,Node:ym},xm=H({kind:`min`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{},exclusive:Xp},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 Sm=class extends qp{impliedBasis=z.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 Cm={implementation:xm,Node:Sm},wm=H({kind:`minLength`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{parse:tm(`minLength`)}},reduce:e=>e.rule===0?z.intrinsic.unknown:void 0,normalize:Zp(`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 Tm=class extends qp{impliedBasis=z.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 Em={implementation:wm,Node:Tm},Dm={min:Cm.implementation,max:_m.implementation,minLength:Em.implementation,maxLength:bm.implementation,exactLength:mm.implementation,after:cm.implementation,before:dm.implementation},Om={min:Cm.Node,max:_m.Node,minLength:Em.Node,maxLength:bm.Node,exactLength:mm.Node,after:cm.Node,before:dm.Node},km=H({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,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:e=>`matched by ${e.rule}`},intersections:{pattern:()=>null}});var Am=class extends Op{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=z.intrinsic.string.internal;reduceJsonSchema(e,t){return e.pattern?t.fallback.patternIntersection({code:`patternIntersection`,base:e,pattern:this.rule}):(e.pattern=this.rule,e)}};const jm={implementation:km,Node:Am},Mm=(e,t)=>{let n=Nm(e);return t&&!t.includes(n)?F(`Root of kind ${n} should be one of ${t}`):n},Nm=e=>{if(B(e,`root`))return e.kind;if(typeof e==`string`)return e[0]===`$`?`alias`:e in Au?`domain`:`proto`;if(typeof e==`function`)return`proto`;if(typeof e!=`object`||!e)return F(Pm(e));if(`morphs`in e)return`morph`;if(`branches`in e||L(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 Vf)?`intersection`:`proto`in e?`proto`:`domain`in e?`domain`:F(Pm(e))},Pm=e=>`${R(e)} is not a valid type schema`,Fm={},Im=e=>L(e)?e.map(e=>e.collapsibleJson):e.collapsibleJson,Lm={};z.nodesByRegisteredId=Lm;const Rm=e=>(Fm[e]??=0,`${e}${++Fm[e]}`),zm=e=>{let t=Fg[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=Iu(a).sort(([e],[t])=>Wf(e)?Wf(t)?Gf(e)-Gf(t):1:Wf(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 F(`Key ${i} is not valid on ${e.kind} schema`);let o=a.parse?a.parse(n[1],e):n[1];o!==Ju&&(o!==void 0||a.preserveUndefined)&&(r[i]=o)}if(t.reduce&&!e.prereduced){let n=t.reduce(r,e.$);if(n)return n instanceof W?n.throw():Hm(n,o)}let c=Bm({id:e.id,kind:e.kind,inner:r,meta:o,$:e.$});return c},Bm=({id:e,kind:t,inner:n,meta:r,$:i,ignoreCache:a})=>{let o=Fg[t],s=Iu(n),c=[],l={};for(let[e,t]of s){let n=o.keys[e],r=n.serialize??(n.child?Im:qf);if(l[e]=r(t),n.child===!0){let e=t;L(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={};Wu(r)||(d=I(r,(e,t)=>[e,e===`examples`?t:qf(t)]),u.meta=Um(d,`description`,!0)),l=Um(l,o.collapsibleKey,!1);let f=JSON.stringify({kind:t,...l});u=Um(u,o.collapsibleKey,!1);let p=Um(u,o.collapsibleKey,!0),m=JSON.stringify({kind:t,...u});if(i.nodesByHash[m]&&!a)return i.nodesByHash[m];let h={id:e,kind:t,impl:o,inner:n,innerEntries:s,innerJson:l,innerHash:f,meta:r,metaJson:d,json:u,hash:m,collapsibleJson:p,children:c};if(t!==`intersection`)for(let e in n)e!==`in`&&e!==`out`&&(h[e]=n[e]);let g=new Ig[t](h,i);return i.nodesByHash[m]=g},Vm=(e,t)=>e.id===t?e:(V(Lm[t])&&P(`Unexpected attempt to overwrite node id ${t}`),Bm({id:t,kind:e.kind,inner:e.inner,meta:e.meta,$:e.$,ignoreCache:!0})),Hm=(e,t,n)=>(n&&V(Lm[n])&&P(`Unexpected attempt to overwrite node id ${n}`),Bm({id:n??Rm(t.alias??e.kind),kind:e.kind,inner:e.inner,meta:t,$:e.$})),Um=(e,t,n)=>{let r=Object.keys(e);if(r.length===1&&r[0]===t){let r=e[t];if(n||Ou(r,`object`)&&(Object.keys(r).length===1||Array.isArray(r)))return r}return e},Wm=(e,t,n)=>{if(e.key!==t.key)return null;let r=e.key,i=G(e.value,t.value,n),a=e.required||t.required?`required`:`optional`;if(i instanceof W)if(a===`optional`)i=z.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:F(Km(e.default,t.default)):e.default:t.hasDefault()?t.default:Ju;return n.$.node(`optional`,{key:r,value:i,default:o})};var Gm=class extends Dp{required=this.kind===`required`;optional=this.kind===`optional`;impliedBasis=z.intrinsic.object.internal;serializedKey=Of(this.key);compiledKey=typeof this.key==`string`?this.key:this.serializedKey;flatRefs=N(this.value.flatRefs.map(e=>pp([this.key,...e.path],e.node)),pp([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?op(this.key,()=>this.value.traverseAllows(e[this.key],t),t):this.optional;traverseApply=(e,t)=>{this.key in e?op(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 Km=(e,t)=>`Invalid intersection of default values ${R(e)} & ${R(t)}`,qm=H({kind:`optional`,hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(e,t)=>t.$.parseSchema(e)},default:{preserveUndefined:!0}},normalize:e=>e,reduce:(e,t)=>{if(t.resolvedConfig.exactOptionalPropertyTypes===!1&&!e.value.allows(void 0))return t.node(`optional`,{...e,value:e.value.or(q.undefined)},{prereduced:!0})},defaults:{description:e=>`${e.compiledKey}?: ${e.value.description}`},intersections:{optional:Wm}});var Jm=class extends Gm{constructor(...e){super(...e),`default`in this.inner&&$m(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} = ${R(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=Zm(this);defaultValueMorphRef=this.defaultValueMorph&&Ef(this.defaultValueMorph)};const Ym={implementation:qm,Node:Jm},Xm={},Zm=e=>{if(!e.hasDefault())return;let t=`{${e.compiledKey}: ${e.value.id} = ${qf(e.default)}}`;return Xm[t]??=Qm(e.key,e.value,e.default)},Qm=(e,t,n)=>{if(typeof n==`function`)return t.includesTransform?(r,i)=>(op(e,()=>t(r[e]=n(),i),i),r):t=>(t[e]=n(),t);let r=t.includesTransform?t.assert(n):n;return Ou(r,`object`)?(r,i)=>(op(e,()=>t(r[e]=n,i),i),r):t=>(t[e]=r,t)},$m=(e,t,n)=>{let r=pd(t);Ou(t,`object`)&&!r&&F(eh(n));let i=e.in(r?t():t);if(i instanceof np){n===null&&F(`Default ${i.summary}`);let e=i.transform(e=>e.transform(e=>({...e,prefixPath:[n]})));F(`Default for ${e.summary}`)}return t},eh=e=>{let t=e===null?``:typeof e==`number`?`for value at [${e}] `:`for ${Of(e)} `;return`Non-primitive default ${t}must be specified as a function like () => ({my: 'object'})`};var th=class extends sp{constructor(e,t){super(e,t),Object.defineProperty(this,Pf,{value:`root`,enumerable:!1})}get internal(){return this}get"~standard"(){return{vendor:`arktype`,version:1,validate:e=>{let t=this(e);return t instanceof np?t:{value:t}}}}as(){return this}brand(e){return e===``?F(nh):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}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(e={}){let t=Qf(this.$.resolvedConfig.toJsonSchema,e);t.useRefs||=this.isCyclic;let n=typeof t.dialect==`string`?{$schema:t.dialect}:{};return Object.assign(n,this.toJsonSchemaRecurse(t)),t.useRefs&&(n.$defs=I(this.references,(e,n)=>n.isRoot()&&!n.alwaysExpandJsonSchema?[n.id,n.toResolvedJsonSchema(t)]:[])),n}toJsonSchemaRecurse(e){return e.useRefs&&!this.alwaysExpandJsonSchema?{$ref:`#/$defs/${this.id}`}:this.toResolvedJsonSchema(e)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind===`alias`||this.hasKind(`union`)&&this.isBoolean}toResolvedJsonSchema(e){let t=this.innerToJsonSchema(e);return Object.assign(t,this.metaJson)}intersect(e){let t=this.$.parseDefinition(e),n=this.rawIntersect(t);return n instanceof W?n:this.$.finalize(n)}rawIntersect(e){return xp(this,e,this.$)}toNeverIfDisjoint(){return this}and(e){let t=this.intersect(e);return t instanceof W?t.throw():t}rawAnd(e){let t=this.rawIntersect(e);return t instanceof W?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(),z.intrinsic.unknown.internal);return e.branches.length===0&&F(yp(`keyof ${this.expression}`)),this._keyof=this.$.finalize(e)}get props(){return this.branches.length===1?[...this.applyStructuralOperation(`props`,[])[0]]:F(oh(this.expression))}merge(e){let t=this.$.parseDefinition(e);return this.$.schema(t.distribute(e=>this.applyStructuralOperation(`merge`,[ah(e)??F(sh(`merge`,e.expression))])))}applyStructuralOperation(e,t){return this.distribute(n=>{if(n.equals(z.intrinsic.object)&&e!==`merge`)return n;let r=ah(n);if(r||F(sh(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 W)}extends(e){let t=this.intersect(e);return!(t instanceof W)&&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.configureReferences(e,t)}describe(e,t=`shallow`){return this.configure({description:e},t)}optional(){return[this,`?`]}default(e){return $m(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(B(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=Sp(this,e,this.$);return t instanceof W?t.throw():t}rawPipeOnce(e){return B(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:P(`Unexpected constraint node ${r}`);let i=e===`root`?this:this[e];if(i.hasKind(`morph`)||r.impliedBasis&&!i.extends(r.impliedBasis))return Np(t,r.impliedBasis,this);let a=this.$.node(`intersection`,{[r.kind]:r}),o=e===`out`?Sp(this,a,this.$):xp(this,a,this.$);return o instanceof W&&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`?Uu(n,{undeclared:1}):{...n,undeclared:t}:n,n?void 0:{shouldTransform:e=>!xu(If,e.kind)}))}hasEqualMorphs(e){return!this.includesTransform&&!e.includesTransform?!0:!(!Du(this.shallowMorphs,e.shallowMorphs)||!Du(this.flatMorphs,e.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)}))}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`,rh(e))}lessThan(e){return this.constrain(`max`,rh(e))}atLeastLength(e){return this.constrain(`minLength`,e)}atMostLength(e){return this.constrain(`maxLength`,e)}moreThanLength(e){return this.constrain(`minLength`,rh(e))}lessThanLength(e){return this.constrain(`maxLength`,rh(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`,rh(e))}earlierThan(e){return this.constrain(`before`,rh(e))}};const nh=`Expected a non-empty brand name after #`,rh=e=>typeof e==`object`&&!(e instanceof Date)?{...e,exclusive:!0}:{rule:e,exclusive:!0},ih=(e,t)=>B(t,`root`)?B(e,`root`)?e.extends(t):t.allows(e):B(e,`root`)?e.hasUnit(t):t===e,ah=e=>e.hasKind(`morph`)?null:e.hasKind(`intersection`)?e.inner.structure??(e.basis?.domain===`object`?e.$.bindReference(z.intrinsic.emptyStructure):null):e.isBasis()&&e.domain===`object`?e.$.bindReference(z.intrinsic.emptyStructure):null,oh=e=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
|
|
21
|
+
${e}`,sh=(e,t)=>`${e} operand must be an object (was ${t})`,ch=(e,t)=>I(Kf(e),(e,n)=>[n,t]),lh=e=>typeof e==`string`?{reference:e}:e,uh=e=>e instanceof W?z.intrinsic.never.internal:e,dh=H({kind:`alias`,hasAssociatedError:!1,collapsibleKey:`reference`,keys:{reference:{serialize:e=>e.startsWith(`$`)?e:`$ark.${e}`},resolve:{}},normalize:lh,defaults:{description:e=>e.reference},intersections:{alias:(e,t,n)=>n.$.lazilyResolve(()=>uh(G(e.resolution,t.resolution,n)),`${e.reference}${n.pipe?`=>`:`&`}${t.reference}`),...ch(`alias`,(e,t,n)=>t.isUnknown()?e:t.isNever()?t:t.isBasis()&&!t.overlaps(z.intrinsic.object)?W.init(`assignability`,z.intrinsic.object,t):n.$.lazilyResolve(()=>uh(G(e.resolution,t,n)),`${e.reference}${n.pipe?`=>`:`&`}${t.id}`))}});var fh=class extends th{expression=this.reference;structure=void 0;get resolution(){let e=this._resolve();return Lm[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=Lm[e],n=[];for(;B(t,`context`);){if(n.includes(t.id))return F(ph(t.id,n));n.push(t.id),t=Lm[t.id]}return B(t,`root`)?t:P(`Unexpected resolution for reference ${this.reference}
|
|
15
22
|
Seen: [${n.join(`->`)}]
|
|
16
|
-
Resolution: ${
|
|
17
|
-
◦ `)}`,problem:e=>`(${e.actual}) must be...\n${e.expected}`},intersections:{intersection:(e,t,n)=>
|
|
23
|
+
Resolution: ${R(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:B(t,`root`)?t.id:P(`Unexpected resolution for reference ${this.reference}: ${R(t)}`)}get defaultShortDescription(){return Au.object}innerToJsonSchema(e){return this.resolution.toJsonSchemaRecurse(e)}traverseAllows=(e,t)=>{let n=t.seen[this.reference];return n?.includes(e)?!0:(t.seen[this.reference]=N(n,e),this.resolution.traverseAllows(e,t))};traverseApply=(e,t)=>{let n=t.seen[this.reference];n?.includes(e)||(t.seen[this.reference]=N(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 ph=(e,t)=>`Alias '${e}' has a shallow resolution cycle: ${[...t,e].join(`->`)}`,mh={implementation:dh,Node:fh};var hh=class extends th{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 Jf(this.errorContext)}compile(e){e.traversalKind===`Allows`?e.return(this.compiledCondition):e.if(this.compiledNegation,()=>e.line(`${e.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}};const gh=H({kind:`domain`,hasAssociatedError:!0,collapsibleKey:`domain`,keys:{domain:{},numberAllowsNaN:{}},normalize:e=>typeof e==`string`?{domain:e}:Ru(e,`numberAllowsNaN`)&&e.domain!==`number`?F(vh.writeBadAllowNanMessage(e.domain)):e,applyConfig:(e,t)=>e.numberAllowsNaN===void 0&&e.domain===`number`&&t.numberAllowsNaN?{...e,numberAllowsNaN:!0}:e,defaults:{description:e=>Au[e.domain],actual:e=>Number.isNaN(e)?`NaN`:Au[ku(e)]},intersections:{domain:(e,t)=>e.domain===`number`&&t.domain===`number`?e.numberAllowsNaN?t:e:W.init(`domain`,e,t)}});var _h=class extends hh{requiresNaNCheck=this.domain===`number`&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?e=>typeof e==`number`&&!Number.isNaN(e):e=>ku(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 defaultShortDescription(){return Au[this.domain]}innerToJsonSchema(e){return this.domain===`bigint`||this.domain===`symbol`?e.fallback.domain({code:`domain`,base:{},domain:this.domain}):{type:this.domain}}};const vh={implementation:gh,Node:_h,writeBadAllowNanMessage:e=>`numberAllowsNaN may only be specified with domain "number" (was ${e})`},yh=H({kind:`intersection`,hasAssociatedError:!0,normalize:e=>{if(V(e))return e;let{structure:t,...n}=e,r=!!t,i=t??{},a=I(n,(e,t)=>Lu(e,Hf)?(r&&F(`Flattened structure key ${e} cannot be specified alongside a root 'structure' key.`),i[e]=t,[]):[e,t]);return(B(i,`constraint`)||!Wu(i))&&(a.structure=i),a},finalizeInnerJson:({structure:e,...t})=>Ou(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:kp(`divisor`)},max:{child:!0,parse:kp(`max`)},min:{child:!0,parse:kp(`min`)},maxLength:{child:!0,parse:kp(`maxLength`)},minLength:{child:!0,parse:kp(`minLength`)},exactLength:{child:!0,parse:kp(`exactLength`)},before:{child:!0,parse:kp(`before`)},after:{child:!0,parse:kp(`after`)},pattern:{child:!0,parse:kp(`pattern`)},predicate:{child:!0,parse:kp(`predicate`)}},reduce:(e,t)=>Ch({},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(`
|
|
24
|
+
◦ `)}`,problem:e=>`(${e.actual}) must be...\n${e.expected}`},intersections:{intersection:(e,t,n)=>Ch(e.inner,t.inner,n),...ch(`intersection`,(e,t,n)=>{if(e.children.length===0)return t;let{domain:r,proto:i,...a}=e.inner,o=i??r,s=o?G(o,t,n):t;return s instanceof W?s:e?.basis?.equals(s)?e:e.$.node(`intersection`,{...a,[s.kind]:s},{prereduced:!0})})}});var bh=class extends th{basis=this.inner.domain??this.inner.proto??null;refinements=this.children.filter(e=>e.isRefinement());structure=this.inner.structure;expression=Sh(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??`present`}innerToJsonSchema(e){return this.children.reduce((t,n)=>n.isBasis()?n.toJsonSchemaRecurse(e):n.reduceJsonSchema(t,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`){for(let t of this.children)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 xh={implementation:yh,Node:bh},Sh=e=>{let t=e.structure?.expression||`${e.basis&&!e.refinements.some(e=>e.impl.obviatesBasisExpression)?e.basis.nestableExpression+` `:``}${e.refinements.map(e=>e.expression).join(` & `)}`||`unknown`;return t===`Array == 0`&&(t=`[]`),t},Ch=(e,t,n)=>{let r={},i=e.proto??e.domain,a=t.proto??t.domain,o=i?a?G(i,a,n):i:a;return o instanceof W?o:(o&&(r[o.kind]=o),Ap({kind:`intersection`,baseInner:r,l:jp(e),r:jp(t),roots:[],ctx:n}))},wh=H({kind:`morph`,hasAssociatedError:!1,keys:{in:{child:!0,parse:(e,t)=>t.$.parseSchema(e)},morphs:{parse:vu,serialize:e=>e.map(e=>B(e,`root`)?e.json:Ef(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 F(Dh(e.expression,t.expression));let r=G(e.in,t.in,n);if(r instanceof W)return r;let i={morphs:e.morphs};if(e.declaredIn||t.declaredIn){let r=G(e.in,t.in,n);if(r instanceof W)return r.throw();i.declaredIn=r}if(e.declaredOut||t.declaredOut){let r=G(e.out,t.out,n);if(r instanceof W)return r.throw();i.declaredOut=r}return r.distribute(e=>n.$.node(`morph`,{...i,in:e}),n.$.parseSchema)},...ch(`morph`,(e,t,n)=>{let r=e.inner.in?G(e.inner.in,t,n):t;return r instanceof W?r:r.equals(e.inner.in)?e:n.$.node(`morph`,{...e.inner,in:r})})}});var Th=class extends th{serializedMorphs=this.morphs.map(Ef);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs.at(-1);lastMorphIfNode=B(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??z.intrinsic.unknown.internal}get out(){return this.declaredOut??this.introspectableOut??z.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 defaultShortDescription(){return this.in.meta.description??this.in.defaultShortDescription}innerToJsonSchema(e){return e.fallback.morph({code:`morph`,base:this.in.toJsonSchemaRecurse(e),out:this.introspectableOut?.toJsonSchemaRecurse(e)??null})}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 Du(this.morphs,e.morphs,{isEqual:(e,t)=>e===t||B(e,`root`)&&B(t,`root`)&&e.equals(t)})}};const Eh={implementation:wh,Node:Th},Dh=(e,t)=>`The intersection of distinct morphs at a single path is indeterminate:
|
|
18
25
|
Left: ${e}
|
|
19
|
-
Right: ${t}`,
|
|
26
|
+
Right: ${t}`,Oh=H({kind:`proto`,hasAssociatedError:!0,collapsibleKey:`proto`,keys:{proto:{serialize:e=>sd(e)??qf(e)},dateAllowsInvalid:{}},normalize:e=>{let t=typeof e==`string`?{proto:ed[e]}:typeof e==`function`?V(e)?e:{proto:e}:typeof e.proto==`string`?{...e,proto:ed[e.proto]}:e;return typeof t.proto!=`function`&&F(Ah.writeInvalidSchemaMessage(t.proto)),Ru(t,`dateAllowsInvalid`)&&t.proto!==Date&&F(Ah.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?od[e.builtinName]:`an instance of ${e.proto.name}`,actual:e=>e instanceof Date&&e.toString()===`Invalid Date`?`an invalid Date`:nd(e)},intersections:{proto:(e,t)=>e.proto===Date&&t.proto===Date?e.dateAllowsInvalid?t:e:ld(e.proto,t.proto)?e:ld(t.proto,e.proto)?t:W.init(`proto`,e,t),domain:(e,t)=>t.domain===`object`?e:W.init(`domain`,z.intrinsic.object.internal,t)}});var kh=class extends hh{builtinName=sd(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(e){switch(this.builtinName){case`Array`:return{type:`array`};case`Date`:return e.fallback.date?.({code:`date`,base:{}})??e.fallback.proto({code:`proto`,base:{},proto:this.proto});default:return e.fallback.proto({code:`proto`,base:{},proto:this.proto})}}expression=this.dateAllowsInvalid?`Date | InvalidDate`:this.proto.name;get nestableExpression(){return this.dateAllowsInvalid?`(${this.expression})`:this.expression}domain=`object`;get defaultShortDescription(){return this.description}};const Ah={implementation:Oh,Node:kh,writeBadInvalidDateMessage:e=>`dateAllowsInvalid may only be specified with constructor Date (was ${e.name})`,writeInvalidSchemaMessage:e=>`instanceOf operand must be a function (was ${ku(e)})`},jh=H({kind:`union`,hasAssociatedError:!0,collapsibleKey:`branches`,keys:{ordered:{},branches:{child:!0,parse:(e,t)=>{let n=[];for(let r of e){let e=B(r,`root`)?r.branches:t.$.parseSchema(r).branches;for(let r of e)if(r.hasKind(`morph`)){let e=n.findIndex(e=>e.hasKind(`morph`)&&e.hasEqualMorphs(r));if(e===-1)n.push(r);else{let i=n[e];n[e]=t.$.node(`morph`,{...i.inner,in:i.in.rawOr(r.in)})}}else n.push(r)}return t.def.ordered||n.sort((e,t)=>e.hash<t.hash?-1:1),n}}},normalize:e=>L(e)?{branches:e}:e,reduce:(e,t)=>{let n=Kh(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,Wh),expected:e=>{let t=Eu(e.errors,`propString`),n=Object.entries(t).map(([e,t])=>{let n=[];for(let e of t)Tu(n,e.expected);let r=Wh(n),i=t.every(e=>e.actual===t[0].actual)?t[0].actual:R(t[0].data);return`${e&&`${e} `}must be ${r}${i&&` (was ${i})`}`});return Wh(n)},problem:e=>e.expected,message:e=>e.problem},intersections:{union:(e,t,n)=>{if(e.isNever!==t.isNever)return W.init(`presence`,e,t);let r;return e.ordered?(t.ordered&&F(Xh(e.expression,t.expression)),r=Gh(t.branches,e.branches,n),r instanceof W&&r.invert()):r=Gh(e.branches,t.branches,n),r instanceof W?r:n.$.parseSchema(e.ordered||t.ordered?{branches:r,ordered:!0}:{branches:r})},...ch(`union`,(e,t,n)=>{let r=Gh(e.branches,[t],n);return r instanceof W?r:r.length===1?r[0]:n.$.parseSchema(e.ordered?{branches:r,ordered:!0}:{branches:r})})}});var Mh=class extends th{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let e=[],t=-1;for(let n of this.branches){if(n.hasKind(`unit`)&&n.domain===`boolean`){t===-1?(t=e.length,e.push(n)):e[t]=z.intrinsic.boolean;continue}e.push(n)}return e}unitBranches=this.branches.filter(e=>e.in.hasKind(`unit`));discriminant=this.discriminate();discriminantJson=this.discriminant?Vh(this.discriminant):null;expression=this.distribute(e=>e.nestableExpression,Uh);createBranchedOptimisticRootApply(){return(e,t)=>{let n=this.traverseOptimistic(e);if(n!==Ju)return n;let r=new ap(e,this.$.resolvedConfig);return this.traverseApply(e,r),r.finalize(t)}}get shallowMorphs(){return this.branches.reduce((e,t)=>Tu(e,t.shallowMorphs),[])}get defaultShortDescription(){return this.distribute(e=>e.defaultShortDescription,Wh)}innerToJsonSchema(e){if(this.branchGroups.length===1&&this.branchGroups[0].equals(z.intrinsic.boolean))return{type:`boolean`};let t=this.branchGroups.map(t=>t.toJsonSchemaRecurse(e));return t.every(e=>Object.keys(e).length===1&&Ru(e,`const`))?{enum:t.map(e=>e.const)}:{anyOf:t}}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 Ju};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?`${Ef(r.contextFreeMorph)}(${e.data})`:e.data} : "${Ju}"`:e.invoke(r)}`)}return e}),e.traversalKind===`Allows`){e.return(i?`"${Ju}"`:!1);return}let a=Wh(this.discriminant.kind===`domain`?r.map(e=>{let t=e.slice(1,-1);return t===`function`?Au.object:Au[t]}):r),o=this.discriminant.path.map(e=>typeof e==`symbol`?Ef(e):JSON.stringify(e)),s=JSON.stringify(a),c=this.discriminant.kind===`domain`?`${Rh}[${t}]`:`${zh}(${t})`;e.line(`ctx.errorFromNodeContext({
|
|
20
27
|
code: "predicate",
|
|
21
28
|
expected: ${s},
|
|
22
29
|
actual: ${c},
|
|
23
30
|
relativePath: [${o}],
|
|
24
31
|
meta: ${this.compiledMeta}
|
|
25
|
-
})`)}compileIndiscriminable(e){if(e.traversalKind===`Apply`)e.const(`errors`,`[]`)
|
|
32
|
+
})`)}compileIndiscriminable(e){if(e.traversalKind===`Apply`){e.const(`errors`,`[]`);for(let t of this.branches)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;for(let n of this.branches)e.if(`${e.invoke(n)}`,()=>e.return(t?n.contextFreeMorph?`${Ef(n.contextFreeMorph)}(${e.data})`:e.data:!0));e.return(t?`"${Ju}"`:!1)}}get nestableExpression(){return this.isBoolean?`boolean`:`(${this.expression})`}discriminate(){if(this.branches.length<2||this.isCyclic)return null;if(this.unitBranches.length===this.branches.length){let e=I(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=xp(n.in,i.in,n.$);if(a instanceof W)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=>Du(e.path,n.path)&&e.kind===n.kind);o?(o.cases[i]?o.cases[i].branchIndices=Tu(o.cases[i].branchIndices,t):o.cases[i]??={branchIndices:[t],condition:n.l},o.cases[a]?o.cases[a].branchIndices=Tu(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?Fh(e,this.branches):e;if(!t.length)return null;let n=Nh(t,this),r={};for(let e in n.best.cases){let t=Ph(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 Nh=(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:Lh(n.path)},i=t.branches.map((e,t)=>({originalIndex:t,branch:e}));return{best:n,location:r,defaultEntries:i,node:t}},Ph=(e,t)=>{let n=e.best.cases[t],r=Ih(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=Jh(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=Jh(o.branch,e.location);i?.push({originalIndex:o.originalIndex,branch:t})}a.push(o)}}return e.defaultEntries=a,i},Fh=(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},Ih=(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:[...Su(i).map(e=>({})),r]}:{domain:`object`,required:[{key:i,value:r}]})}return r},Lh=e=>e.reduce((e,t)=>e+kf(t,!0),`data`),Rh=Ef(ju),zh=Ef(R),Bh={implementation:jh,Node:Mh},Vh=e=>({kind:e.kind,path:e.path.map(e=>typeof e==`string`?e:Of(e)),cases:I(e.cases,(e,t)=>[e,t===!0?t:t.hasKind(`union`)&&t.discriminantJson?t.discriminantJson:t.json])}),Hh={delimiter:` | `,finalDelimiter:` | `},Uh=e=>Wh(e,Hh),Wh=(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}`},Gh=(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=G(e[i],t[o],n);if(!(s instanceof W)){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?W.init(`union`,e,t):i},Kh=({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=xp(e[r].in,e[i].in,e[0].$);a instanceof W||(t||qh(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])},qh=(e,t)=>{!e.includesTransform&&!t.includesTransform||(Du(e.shallowMorphs,t.shallowMorphs)||F(Yh(e.expression,t.expression)),Du(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)})||F(Yh(e.expression,t.expression)))},Jh=(e,t)=>e.transform((e,t)=>e===`domain`||e===`unit`?null:t,{shouldTransform:(e,n)=>{let r=Lh(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}}),Yh=(e,t)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
|
|
26
33
|
Left: ${e}
|
|
27
|
-
Right: ${t}`,
|
|
34
|
+
Right: ${t}`,Xh=(e,t)=>`The intersection of two ordered unions is indeterminate:
|
|
28
35
|
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};
|
|
36
|
+
Right: ${t}`,Zh=H({kind:`unit`,hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:e=>e instanceof Date?e.toISOString():qf(e)}},normalize:e=>e,defaults:{description:e=>R(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)=>W.init(`unit`,e,t),...ch(`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:z.intrinsic.object;if(e.domain!==t.domain){let n=e.domain===`undefined`||e.domain===`null`||e.domain===`boolean`?e.domain:z.intrinsic[e.domain];return W.init(`domain`,n,t)}}return W.init(`assignability`,e,t.hasKind(`intersection`)?t.children.find(t=>!t.allows(e.unit)):t)})}});var Qh=class extends hh{compiledValue=this.json.unit;serializedValue=typeof this.unit==`string`||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=eg(this.unit,this.serializedValue);compiledNegation=eg(this.unit,this.serializedValue,`negated`);expression=R(this.unit);domain=ku(this.unit);get defaultShortDescription(){return this.domain===`object`?Au.object:this.description}innerToJsonSchema(e){return this.unit===null?{type:`null`}:z.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:e.fallback.unit({code:`unit`,base:{},unit:this.unit})}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 $h={implementation:Zh,Node:Qh},eg=(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}`},tg=H({kind:`index`,hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(e,t)=>{let n=t.$.parseSchema(e);if(!n.extends(z.intrinsic.key))return F(ag(n.expression));let r=n.branches.filter(e=>e.hasKind(`unit`));return r.length?F(ig(r.map(e=>R(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=G(e.value,t.value,n),i=r instanceof W?z.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 ng=class extends Dp{impliedBasis=z.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=N(this.value.flatRefs.map(e=>pp([this.signature,...e.path],e.node)),pp([this.signature],this.value));traverseAllows=(e,t)=>Gu(e).every(e=>this.signature.traverseAllows(e[0],t)?op(e[0],()=>this.value.traverseAllows(e[1],t),t):!0);traverseApply=(e,t)=>{for(let n of Gu(e))this.signature.traverseAllows(n[0],t)&&op(n[0],()=>this.value.traverseApply(n[1],t),t)};_transform(e,t){t.path.push(this.signature);let n=super._transform(e,t);return t.path.pop(),n}compile(){}};const rg={implementation:tg,Node:ng},ig=e=>`Index keys ${e.join(`, `)} should be specified as named props.`,ag=e=>`Indexed key definition '${e}' must be a string or symbol`,og=H({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:Wm,optional:Wm}});var sg=class extends Gm{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:`required`,missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=Jf(this.errorContext)};const cg={implementation:og,Node:sg},lg=H({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 $m(n,e[1],null),[n,e[1]]})},serialize:e=>e.map(e=>[e[0].collapsibleJson,qf(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 F(_g);if(e.optionals?.length||e.defaultables?.length)return F(gg)}return e.minVariadicLength&&!e.variadic?F(`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} = ${R(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=vg({l:e.tuple,r:t.tuple,disjoint:new W,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`,hg(i[0].result)):n.$.node(`union`,i.map(e=>({proto:Array,sequence:hg(e.result)})))}}});var ug=class extends Dp{impliedBasis=z.intrinsic.Array.internal;tuple=mg(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=Cu(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return hp(this.flatRefs,this.prevariadic.flatMap((e,t)=>N(e.node.flatRefs.map(e=>pp([`${t}`,...e.path],e.node)),pp([`${t}`],e.node)))),hp(this.flatRefs,this.variadicOrPostfix.flatMap(e=>N(e.flatRefs.map(e=>pp([z.intrinsic.nonNegativeIntegerString.internal,...e.path],e.node)),pp([z.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=fg(this);defaultValueMorphsReference=this.defaultValueMorphs.length?Ef(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??P(`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++)op(n,()=>this.elementAtIndex(e,n).node.traverseApply(e[n],t),t)};get element(){return this.cacheGetter(`element`,this.$.node(`union`,this.children))}compile(e){if(this.prefix)for(let[t,n]of this.prefix.entries())e.traverseKey(`${t}`,`data[${t}]`,n);for(let[t,n]of this.defaultablesAndOptionals.entries()){let r=`${t+this.prefixLength}`;e.if(`${r} >= ${e.data}.length`,()=>e.traversalKind===`Allows`?e.return(!0):e.return()),e.traverseKey(r,`data[${r}]`,n)}if(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))for(let[t,n]of this.postfix.entries()){let r=`firstPostfixIndex + ${t}`;e.traverseKey(r,`data[${r}]`,n)}e.traversalKind===`Allows`&&e.return(!0)}_transform(e,t){t.path.push(z.intrinsic.nonNegativeIntegerString.internal);let n=super._transform(e,t);return t.path.pop(),n}expression=this.description;reduceJsonSchema(e,t){if(this.prevariadic.length&&(e.prefixItems=this.prevariadic.map(e=>{let n=e.node.toJsonSchemaRecurse(t);if(e.kind===`defaultables`){let r=typeof e.default==`function`?e.default():e.default;n.default=z.intrinsic.jsonData.allows(r)?r:t.fallback.defaultValue({code:`defaultValue`,base:n,value:r})}return n})),this.minLength&&(e.minItems=this.minLength),this.variadic){let n=Object.assign(e,{items:this.variadic.toJsonSchemaRecurse(t)});if(this.maxLength&&(n.maxItems=this.maxLength),this.postfix){let r=this.postfix.map(e=>e.toJsonSchemaRecurse(t));e=t.fallback.arrayPostfix({code:`arrayPostfix`,base:n,elements:r})}}else e.items=!1,delete e.maxItems;return e}};const dg={},fg=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(Qm(i,r,a)),n+=`${i}: ${r.id} = ${qf(a)}, `}return n+=`]`,dg[n]??=t},pg={implementation:lg,Node:ug},mg=e=>{let t=[];if(e.prefix)for(let n of e.prefix)t.push({kind:`prefix`,node:n});if(e.defaultables)for(let[n,r]of e.defaultables)t.push({kind:`defaultables`,node:n,default:r});if(e.optionals)for(let n of e.optionals)t.push({kind:`optionals`,node:n});if(e.variadic&&t.push({kind:`variadic`,node:e.variadic}),e.postfix)for(let n of e.postfix)t.push({kind:`postfix`,node:n});return t},hg=e=>e.reduce((e,t)=>(t.kind===`variadic`?e.variadic=t.node:t.kind===`defaultables`?e.defaultables=N(e.defaultables,[[t.node,t.default]]):e[t.kind]=N(e[t.kind],t.node),e),{}),gg=`A postfix required element cannot follow an optional or defaultable element`,_g=`A postfix element requires a variadic element`,vg=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=vg({...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=vg({...e,fixedVariants:[],l:n.map(e=>({...e,kind:`prefix`}))});t.disjoint.length===0&&e.fixedVariants.push(t)}let c=G(t.node,r.node,e.ctx);if(c instanceof W)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:z.intrinsic.never.internal}];else if(s===`optionals`||s===`defaultables`)return e;else return vg({...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&&F(Km(t.default,r.default)),e.result=[...e.result,{kind:s,node:c,default:t.kind===`defaultables`?t.default:r.kind===`defaultables`?r.default:P(`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),vg(e)},yg=e=>t=>{if(t.props.length||t.index){let n=t.index?.map(t=>t[e])??[];for(let r of t.props)n.push(r[e]);t.undeclared&&n.push(`+ (undeclared): ${t.undeclared}`);let r=`{ ${n.join(`, `)} }`;return t.sequence?`${r} & ${t.sequence.description}`:r}return t.sequence?.description??`{}`},bg=yg(`description`),xg=yg(`expression`),Sg=(e,t,n)=>{let r=e.required?`required`:`optional`;if(!t.signature.allows(e.key))return null;let i=xp(e.value,t.value,n);return i instanceof W?r===`optional`?n.node(`optional`,{key:e.key,value:z.intrinsic.never.internal}):i.withPrefixKey(e.key,e.kind):null},Cg=H({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:kp(`required`),reduceIo:(e,t,n)=>{t.required=N(t.required,n.map(t=>t[e]))}},optional:{child:!0,parse:kp(`optional`),reduceIo:(e,t,n)=>{if(e===`in`){t.optional=n.map(e=>e.in);return}for(let e of n)t[e.outProp.kind]=N(t[e.outProp.kind],e.outProp.out)}},index:{child:!0,parse:kp(`index`)},sequence:{child:!0,parse:kp(`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:bg},intersections:{structure:(e,t,n)=>{let r={...e.inner},i={...t.inner},a=new W;if(e.undeclared){let r=e.keyof();for(let e of t.requiredKeys)r.allows(e)||a.add(`presence`,z.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=xp(r,e.signature,n.$);if(t instanceof W)return[];let a=Mg(t,e.value,n.$);return a.required&&(i.required=Cu(i.required,a.required)),a.optional&&(i.optional=Cu(i.optional,a.optional)),a.index??[]}))}if(t.undeclared){let i=t.keyof();for(let t of e.requiredKeys)i.allows(t)||a.add(`presence`,e.propsByKey[t].value,z.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=xp(i,e.signature,n.$);if(t instanceof W)return[];let a=Mg(t,e.value,n.$);return a.required&&(r.required=Cu(r.required,a.required)),a.optional&&(r.optional=Cu(r.optional,a.optional)),a.index??[]}))}let o={};(e.undeclared||t.undeclared)&&(o.undeclared=e.undeclared===`reject`||t.undeclared===`reject`?`reject`:`delete`);let s=Ap({kind:`structure`,baseInner:o,l:jp(r),r:jp(i),roots:[],ctx:n});return s instanceof W&&a.push(...s),a.length?a:s}},reduce:(e,t)=>{if(e.index){if(!(e.required||e.optional))return;let n=!1,r=e.required??[],i=e.optional??[],a=[...i];for(let o of e.index){for(let e of r){let n=Sg(e,o,t);if(n instanceof W)return n}for(let[e,r]of i.entries()){let i=Sg(r,o,t);if(i instanceof W)return i;if(i===null)continue;a[e]=i,n=!0}}if(n)return t.node(`structure`,{...e,optional:a},{prereduced:!0})}}});var wg=class extends Dp{impliedBasis=z.intrinsic.object.internal;impliedSiblings=this.children.flatMap(e=>e.impliedSiblings??[]);props=Cu(this.required,this.optional);propsByKey=I(this.props,(e,t)=>[t.key,t]);propsByKeyReference=Ef(this.propsByKey);expression=xg(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;if(this.index)for(let{signature:t}of this.index)e=e.concat(t.branches);return 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(V(t))return t.kind!==`required`&&t.kind!==`optional`?F(`Map result must have kind "required" or "optional" (was ${t.kind})`):(e[t.kind]=N(e[t.kind],t),e);let r=t.kind??n?.kind??`required`,i=I(t,(e,t)=>e in Ym.implementation.keys?[e,t]:[]);return e[r]=N(e[r],this.$.node(r,i)),e},{}))}assertHasKeys(e){let t=e.filter(e=>!ih(e,this.keyof()));if(t.length)return F(Pg(this.expression,t))}get(e,...t){let n,r=!1,i=Ag(e);if((typeof i==`string`||typeof i==`symbol`)&&this.propsByKey[i]&&(n=this.propsByKey[i].value,r=this.propsByKey[i].required),this.index)for(let e of this.index)ih(i,e.signature)&&(n=n?.and(e.value)??e.value);if(this.sequence&&ih(i,z.intrinsic.nonNegativeIntegerString))if(B(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&&B(i,`root`)&&i.extends(z.intrinsic.number)?F(jg(i.expression,this.sequence.expression)):F(Pg(this.expression,[i]));let a=n.get(...t);return r?a:a.or(z.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=N(t.required,e.required)),e.optional&&(t.optional=N(t.optional,e.optional)),e.index&&(t.index=N(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=Nf(this.inner),r=n=>{let r=t.some(e=>ih(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=op(o,()=>i.value.traverseAllows(t[o],n),n);if(!e)return!1}else if(op(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&&z.intrinsic.nonNegativeIntegerString.allows(e);_compileDeclaresKey(e){let t=[];if(this.props.length&&t.push(`k in ${this.propsByKeyReference}`),this.index)for(let n of this.index)t.push(e.invoke(n.signature,{kind:`Allows`,arg:`k`}));return this.sequence&&t.push(`$ark.intrinsic.nonNegativeIntegerString.allows(k)`),t.join(` || `)||`false`}get structuralMorph(){return this.cacheGetter(`structuralMorph`,Dg(this))}structuralMorphRef=this.structuralMorph&&Ef(this.structuralMorph);compile(e){e.traversalKind===`Apply`&&e.initializeErrorCount();for(let t of this.props)e.check(t),e.traversalKind===`Apply`&&e.returnIfFailFast();if(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([`),Og(e,this),e.line(`])`)))}compileExhaustiveEntry(e){if(e.const(`k`,`keys[i]`),this.index)for(let t of this.index)e.if(`${e.invoke(t.signature,{arg:`k`,kind:`Allows`})}`,()=>e.traverseKey(`k`,`data[k]`,t.value));return 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,t){switch(e.type){case`object`:return this.reduceObjectJsonSchema(e,t);case`array`:let n=this.sequence?.reduceJsonSchema(e,t)??e;return this.props.length||this.index?t.fallback.arrayObject({code:`arrayObject`,base:n,object:this.reduceObjectJsonSchema({type:`object`},t)}):n;default:return U.throwInternalOperandError(`structure`,e)}}reduceObjectJsonSchema(e,t){if(this.props.length){e.properties={};for(let n of this.props){let r=n.value.toJsonSchemaRecurse(t);if(typeof n.key==`symbol`){t.fallback.symbolKey({code:`symbolKey`,base:e,key:n.key,value:r,optional:n.optional});continue}if(n.hasDefault()){let e=typeof n.default==`function`?n.default():n.default;r.default=z.intrinsic.jsonData.allows(e)?e:t.fallback.defaultValue({code:`defaultValue`,base:r,value:e})}e.properties[n.key]=r}this.requiredKeys.length&&e.properties&&(e.required=this.requiredKeys.filter(t=>typeof t==`string`&&t in e.properties))}if(this.index)for(let n of this.index){let r=n.value.toJsonSchemaRecurse(t);if(n.signature.equals(z.intrinsic.string)){e.additionalProperties=r;continue}for(let i of n.signature.branches){if(!i.extends(z.intrinsic.string)){e=t.fallback.symbolKey({code:`symbolKey`,base:e,key:null,value:r,optional:!1});continue}let n={type:`string`};if(i.hasKind(`morph`)&&(n=t.fallback.morph({code:`morph`,base:i.in.toJsonSchemaRecurse(t),out:i.out.toJsonSchemaRecurse(t)})),!i.hasKind(`intersection`))return P(`Unexpected index branch kind ${i.kind}.`);let{pattern:a}=i.inner;if(a){let i=Object.assign(n,{pattern:a[0].rule});for(let e=1;e<a.length;e++)n=t.fallback.patternIntersection({code:`patternIntersection`,base:i,pattern:a[e].rule});e.patternProperties??={},e.patternProperties[i.pattern]=r}}}return this.undeclared&&!e.additionalProperties&&(e.additionalProperties=!1),e}};const Tg={},Eg=e=>{let t=``;for(let n=0;n<e.defaultable.length;n++)t+=e.defaultable[n].defaultValueMorphRef;if(e.sequence?.defaultValueMorphsReference&&(t+=e.sequence?.defaultValueMorphsReference),e.undeclared===`delete`){if(t+=`delete !(`,e.required)for(let n of e.required)t+=n.compiledKey+` | `;if(e.optional)for(let n of e.optional)t+=n.compiledKey+` | `;if(e.index)for(let n of e.index)t+=n.signature.id+` | `;if(e.sequence)if(e.sequence.maxLength===null)t+=q.nonNegativeIntegerString.id;else for(let n=0;n<e.sequence.tuple.length;n++)t+=n+` | `;t+=`)`}return t},Dg=e=>{let t=Eg(e);if(!t)return;if(Tg[t])return Tg[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 Tg[t]=n},Og=(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`)})},kg={implementation:Cg,Node:wg},Ag=e=>(B(e,`root`)&&e.hasKind(`unit`)&&(e=e.unit),typeof e==`number`&&(e=`${e}`),e),jg=(e,t)=>`${e} is not allowed as an array index on ${t}. Use the 'nonNegativeIntegerString' keyword instead.`,Mg=(e,t,n)=>{let[r,i]=yu(e.branches,e=>e.hasKind(`unit`));if(!r.length)return{index:n.node(`index`,{signature:e,value:t})};let a={};for(let e of r){let r=n.node(`required`,{key:e.unit,value:t});a[r.kind]=N(a[r.kind],r)}return i.length&&(a.index=n.node(`index`,{signature:i,value:t})),a},Ng=e=>B(e,`root`)?e.expression:R(e),Pg=(e,t)=>`Key${t.length===1?``:`s`} ${t.map(Ng).join(`, `)} ${t.length===1?`does`:`do`} not exist on ${e}`,Fg={...Dm,alias:mh.implementation,domain:vh.implementation,unit:$h.implementation,proto:Ah.implementation,union:Bh.implementation,morph:Eh.implementation,intersection:xh.implementation,divisor:Wp.implementation,pattern:jm.implementation,predicate:Vp.implementation,required:cg.implementation,optional:Ym.implementation,index:rg.implementation,sequence:pg.implementation,structure:kg.implementation};z.defaultConfig=qu(Object.assign(I(Fg,(e,t)=>[e,t.defaults]),{jitless:gd(),clone:ud,onUndeclaredKey:`ignore`,exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:U.defaultConfig})),z.resolvedConfig=Zf(z.defaultConfig,z.config);const Ig={...Om,alias:mh.Node,domain:vh.Node,unit:$h.Node,proto:Ah.Node,union:Bh.Node,morph:Eh.Node,intersection:xh.Node,divisor:Wp.Node,pattern:jm.Node,predicate:Vp.Node,required:cg.Node,optional:Ym.Node,index:rg.Node,sequence:pg.Node,structure:kg.Node};var Lg=class extends zu{get[Pf](){return`module`}};const Rg=(e,t)=>new Lg(I(e,(e,n)=>[e,B(n,`module`)?Rg(n,t):t.bindReference(n)])),zg=e=>L(e)?e:`branches`in e&&L(e.branches)?e.branches:void 0,Bg=(e,t)=>F(`Node of kind ${t} is not valid as a ${e} definition`),Vg=e=>`#${e} duplicates public alias ${e}`,Hg={};z.ambient??={};let Ug;const Wg=`function $`,Gg=e=>Kg(e,qg(e)),Kg=(e,t)=>{let n=t.write(Wg,4),r=t.compile()();for(let t of e){if(t.precompilation)continue;t.traverseAllows=r[`${t.id}Allows`].bind(r),t.isRoot()&&!t.allowsRequiresContext&&(t.allows=t.traverseAllows),t.traverseApply=r[`${t.id}Apply`].bind(r),r[`${t.id}Optimistic`]&&(t.traverseOptimistic=r[`${t.id}Optimistic`].bind(r)),t.precompilation=n}},qg=e=>new Df().return(e.reduce((e,t)=>{let n=new Mf({kind:`Allows`}).indent();t.compile(n);let r=n.write(`${t.id}Allows`),i=new Mf({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 Mf({kind:`Allows`,optimistic:!0}).indent();t.compile(s);let c=s.write(`${t.id}Optimistic`);return`${o}${c},\n`},`{
|
|
37
|
+
`)+`}`);var Jg=class{config;resolvedConfig;name;get[Pf](){return`scope`}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(e,t){this.config=Zf(z.config,t),this.resolvedConfig=Zf(z.resolvedConfig,t),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(Hg).length}`,this.name in Hg&&F(`A Scope already named ${this.name} already exists`),Hg[this.name]=this;let n=Object.entries(e).map(e=>this.preparseOwnAliasEntry(...e));for(let[e,t]of n){let n=e;if(e[0]===`#`?(n=e.slice(1),n in this.aliases&&F(Vg(n)),this.aliases[n]=t):(n in this.aliases&&F(Vg(e)),this.aliases[n]=t,this.exportedNames.push(n)),!B(t,`module`)&&!B(t,`generic`)&&!pd(t)){let e=this.preparseOwnDefinitionFormat(t,{alias:n});this.resolutions[n]=B(e,`root`)?this.bindReference(e):this.createParseContext(e).id}}Ug??=this.node(`union`,{branches:[`string`,`number`,`object`,`bigint`,`symbol`,{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[Ug.hash]=this.node(`intersection`,{},{prereduced:!0}),this.intrinsic=z.intrinsic?I(z.intrinsic,(e,t)=>e.startsWith(`json`)?[]:[e,this.bindReference(t)]):{}}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 Lp(e,r?new Ip(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(Mm(e),e,t);preparseNode(e,t,n){let r=typeof e==`string`?e:Mm(t,e);if(V(t)&&t.kind===r)return t;if(r===`alias`&&!n?.prereduced){let{reference:e}=mh.implementation.normalize(t,this);if(e.startsWith(`$`)){let n=this.resolveRoot(e.slice(1));t=n,r=n.kind}}else if(r===`union`&&Ou(t,`object`)){let e=zg(t);e?.length===1&&(t=e[0],r=Mm(t))}if(V(t)&&t.kind===r)return t;let i=Fg[r],a=i.normalize?.(t,this)??t;return V(a)?a.kind===r?a:Bg(r,a.kind):{...n,$:this,kind:r,def:a,prefix:n.alias??r}}bindReference(e){let t;return t=V(e)?e.$===this?e:new e.constructor(e.attachments,this):e.$===this?e:new Lp(e.params,e.bodyDef,e.$,this,e.hkt),this.resolved||Object.assign(this.referencesById,t.referencesById),t}resolveRoot(e){return this.maybeResolveRoot(e)??F(n_(e))}maybeResolveRoot(e){let t=this.maybeResolve(e);if(!B(t,`generic`))return t}maybeResolveSubalias(e){return Qg(this.aliases,e)??Qg(this.ambient,e)}get ambient(){return z.ambient}maybeResolve(e){let t=this.resolutions[e];if(t){if(typeof t!=`string`)return this.bindReference(t);let n=Lm[t];if(B(n,`root`))return this.resolutions[e]=n;if(B(n,`context`)){if(n.phase===`resolving`)return this.node(`alias`,{reference:`$${e}`},{prereduced:!0});if(n.phase===`resolved`)return P(`Unexpected resolved context for was uncached by its scope: ${R(n)}`);n.phase=`resolving`;let t=this.bindReference(this.parseOwnDefinitionFormat(n.def,n));return n.phase=`resolved`,Lm[t.id]=t,Lm[n.id]=t,this.resolutions[e]=t}return P(`Unexpected nodesById entry for ${t}: ${R(n)}`)}let n=this.aliases[e]??this.ambient?.[e];return n?(n=this.normalizeRootScopeValue(n),B(n,`generic`)?this.resolutions[e]=this.bindReference(n):B(n,`module`)?(n.root||F(i_(e)),this.resolutions[e]=this.bindReference(n.root)):this.resolutions[e]=this.parse(n,{alias:e})):this.maybeResolveSubalias(e)}createParseContext(e){let t=e.id??Rm(e.prefix);return Lm[t]=Object.assign(e,{[Pf]:`context`,$:this,id:t,phase:`unresolved`})}traversal(e){return new ap(e,this.resolvedConfig)}import(...e){return new Lg(I(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]=B(t,`module`)?Rg(t,this):Xg(this.maybeResolve(e))}for(let e of this.lazyResolutions)e.resolution;if(this._exportedResolutions=t_(this,this._exports),this._json=Zg(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let e=qg(this.references);this.precompilation=e.write(Wg,4),Kg(this.references,e)}this.resolved=!0}let t=e.length?e:this.exportedNames;return new Lg(I(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(V(r))return this.bindReference(r);let i=this.createParseContext(r),a=zm(i),o=this.bindReference(a);return Lm[i.id]=o};parse=(e,t={})=>this.finalize(this.parseDefinition(e,t));parseDefinition(e,t={}){if(B(e,`root`))return this.bindReference(e);let n=this.preparseOwnDefinitionFormat(e,t);if(B(n,`root`))return this.bindReference(n);let r=this.createParseContext(n);Lm[r.id]=r;let i=this.bindReference(this.parseOwnDefinitionFormat(e,r));return i.isCyclic&&(i=Vm(i,r.id)),Lm[r.id]=i,i}finalize(e){return Xg(e),!e.precompilation&&!this.resolvedConfig.jitless&&Gg(e.references),e}},Yg=class extends Jg{parseOwnDefinitionFormat(e,t){return zm(t)}preparseOwnDefinitionFormat(e,t){return this.preparseNode(Mm(e),e,t)}preparseOwnAliasEntry(e,t){return[e,t]}normalizeRootScopeValue(e){return e}};const Xg=e=>{let t=e.references.filter(e=>e.hasKind(`alias`));for(let n of t){Object.assign(n.referencesById,n.resolution.referencesById);for(let t of e.references)n.id in t.referencesById&&Object.assign(t.referencesById,n.referencesById)}return e},Zg=e=>I(e,(e,t)=>[e,B(t,`root`)||B(t,`generic`)?t.json:B(t,`module`)?Zg(t):P(`Unexpected resolution ${R(t)}`)]),Qg=(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(!B(i,`module`))return F(r_(r));let a=t.slice(n+1),o=i[a];if(o===void 0)return Qg(i,a);if(B(o,`root`)||B(o,`generic`))return o;if(B(o,`module`))return o.root??F(i_(t));P(`Unexpected resolution for alias '${t}': ${R(o)}`)},$g=(e,t)=>new Yg(e,t),e_=new Yg({}),t_=(e,t)=>{let n={};for(let r in t){let i=t[r];if(B(i,`module`)){let t=t_(e,i),a=I(t,(e,t)=>[`${r}.${e}`,t]);Object.assign(n,a)}else B(i,`root`)||B(i,`generic`)?n[r]=i:P(`Unexpected scope resolution ${R(i)}`)}return n},n_=e=>`'${e}' is unresolvable`,r_=e=>`'${e}' must reference a module to be accessed using dot syntax`,i_=e=>`Reference to submodule '${e}' must specify an alias`;e_.export();const K=e_.schema,a_=e_.node;e_.defineSchema;const o_=e_.generic,s_=`^(?:0|[1-9]\\d*)$`,c_=new RegExp(s_);Ef(c_);const l_=$g({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();z.intrinsic={...l_};const u_=$g({integer:{domain:`number`,divisor:1},lengthBoundable:[`string`,Array],key:[`string`,`symbol`],nonNegativeIntegerString:{domain:`string`,pattern:s_}},{prereducedAliases:!0}).export();Object.assign(z.intrinsic,u_);const d_=$g({jsonPrimitive:[`string`,`number`,{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:`object`,index:{signature:`string`,value:`$jsonData`}},jsonData:[`$jsonPrimitive`,`$jsonObject`]},{prereducedAliases:!0}).export(),q={...l_,...u_,...d_,emptyStructure:a_(`structure`,{},{prereduced:!0})};z.intrinsic={...q};const f_=e=>typeof e==`string`&&e[0]===`d`&&(e[1]===`'`||e[1]===`"`)&&e.at(-1)===e[1],p_=e=>e.toString()!==`Invalid Date`,m_=e=>e.slice(2,-1),h_=e=>`'${e}' could not be parsed by the Date constructor`,g_=(e,t)=>__(e,t),__=(e,t)=>{let n=new Date(e);if(p_(n))return n;let r=Kd(e);if(r!==void 0){let e=new Date(r);if(p_(e))return e}return t?F(t===!0?h_(e):t):void 0},v_=(e,t)=>{let n=e.scanner.shiftUntil(S_[x_[t]]);if(e.scanner.lookahead===``)return e.error(w_(n,t));if(e.scanner.shift(),t===`/`){try{new RegExp(n)}catch(e){F(String(e))}e.root=e.ctx.$.node(`intersection`,{domain:`string`,pattern:n},{prereduced:!0})}else if(Lu(t,y_))e.root=e.ctx.$.node(`unit`,{unit:n});else{let t=g_(n,h_(n));e.root=e.ctx.$.node(`unit`,{meta:n,unit:t})}},y_={"'":1,'"':1},b_={"/":1,"'":1,'"':1},x_={"d'":`'`,'d"':`"`,"'":`'`,'"':`"`,"/":`/`},S_={"'":e=>e.lookahead===`'`,'"':e=>e.lookahead===`"`,"/":e=>e.lookahead===`/`},C_={'"':`double-quote`,"'":`single-quote`,"/":`forward slash`},w_=(e,t)=>`${t}${e} requires a closing ${C_[x_[t]]}`,T_=e=>`Private type references should not include '#'. Use '${e}' instead.`,E_=`Optional definitions like 'string?' are only valid as properties in an object or tuple`,D_=`Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple`,O_={">":!0,">=":!0},k_={"<":!0,"<=":!0},A_={"<":`>`,">":`<`,"<=":`>=`,">=":`<=`,"==":`==`},j_=e=>`Unmatched )${e===``?``:` before ${e}`}`,M_=e=>`Missing ${e}`,N_=(e,t)=>`Left bounds are only valid when paired with right bounds (try ...${t}${e})`,P_=e=>`Left-bounded expressions must specify their limits using < or <= (was ${e})`,F_=(e,t,n,r)=>`An expression may have at most one left bound (parsed ${e}${A_[t]}, ${n}${A_[r]})`,I_=(e,t,n)=>L_(e,t,n,[]),L_=(e,t,n,r)=>{let i=n.parseUntilFinalizer();return r.push(i.root),i.finalizer===`>`?r.length===t.params.length?r:n.error(R_(e,t.names,r.map(e=>e.expression))):i.finalizer===`,`?L_(e,t,n,r):i.error(M_(`>`))},R_=(e,t,n)=>`${e}<${t.join(`, `)}> requires exactly ${t.length} args (got ${n.length}${n.length===0?``:`: ${n.join(`, `)}`})`,z_=e=>{let t=e.scanner.shiftUntilNextTerminator();t===`keyof`?e.addPrefix(`keyof`):e.root=V_(e,t)},B_=(e,t,n)=>{n.scanner.shiftUntilNonWhitespace();let r=n.scanner.shift();if(r!==`<`)return n.error(R_(e,t.names,[]));let i=I_(e,t,n);return t(...i)},V_=(e,t)=>H_(e,t)??U_(e,t)??e.error(t===``?e.scanner.lookahead===`#`?T_(e.shiftedByOne().scanner.shiftUntilNextTerminator()):W_(e):n_(t)),H_=(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(B(n,`root`))return n;if(n!==void 0)return B(n,`generic`)?B_(t,n,e):F(`Unexpected resolution ${R(n)}`)},U_=(e,t)=>{let n=qd(t);if(n!==void 0)return e.ctx.$.node(`unit`,{unit:n});let r=Xd(t);if(r!==void 0)return e.ctx.$.node(`unit`,{unit:r})},W_=e=>{let t=e.previousOperator();return t?G_(t,e.scanner.unscanned):K_(e.scanner.unscanned)},G_=(e,t=``)=>`Token '${e}' requires a right operand${t?` before '${t}'`:``}`,K_=e=>`Expected an expression${e?` before '${e}'`:``}`,q_=e=>e.scanner.lookahead===``?e.error(W_(e)):e.scanner.lookahead===`(`?e.shiftedByOne().reduceGroupOpen():e.scanner.lookaheadIsIn(b_)?v_(e,e.scanner.shift()):e.scanner.lookaheadIsIn(Ed)?q_(e.shiftedByOne()):e.scanner.lookahead===`d`&&e.scanner.nextLookahead in y_?v_(e,`${e.scanner.shift()}${e.scanner.shift()}`):z_(e);var J_=class e extends yf{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,...Ed};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(t,n)=>t===`>`?n[0]===`=`?n[1]===`=`:n.trimStart()===``||Lu(n.trimStart()[0],e.terminatingChars):t===`=`?n[0]!==`=`:t===`,`||t===`?`};const Y_=(e,t)=>{let n=Z_(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 ev(e,n)},X_={"<":1,">":1,"=":1},Z_=(e,t)=>e.scanner.lookaheadIs(`=`)?`${t}${e.scanner.shift()}`:t,Q_=(e,t,n,r)=>n.extends(z.intrinsic.number)?typeof t==`number`?e===`==`?[`min`,`max`]:e[0]===`>`?[`min`]:[`max`]:F(tv(e,t,r)):n.extends(z.intrinsic.lengthBoundable)?typeof t==`number`?e===`==`?[`exactLength`]:e[0]===`>`?[`minLength`]:[`maxLength`]:F(tv(e,t,r)):n.extends(z.intrinsic.Date)?e===`==`?[`after`,`before`]:e[0]===`>`?[`after`]:[`before`]:F(am(n.expression)),$_=e=>({rule:f_(e.limit)?m_(e.limit):e.limit,exclusive:e.comparator.length===1}),ev=(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(tv(t,a,`right`));let o=i.unit,s=t.length===1,c=Q_(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(!Lu(t,k_))return e.error(P_(t));let l=Q_(e.branches.leftBound.comparator,e.branches.leftBound.limit,n,`left`);e.constrainRoot(l[0],$_(e.branches.leftBound)),e.branches.leftBound=null},tv=(e,t,n)=>`Comparator ${n===`left`?A_[e]:e} must be ${n===`left`?`preceded`:`followed`} by a corresponding literal (was ${t})`,nv=e=>{e.scanner.shiftUntilNonWhitespace();let t=e.scanner.shiftUntilNextTerminator();e.root=e.root.brand(t)},rv=e=>{let t=e.scanner.shiftUntilNextTerminator(),n=Jd(t,{errorOnFail:iv(t)});n===0&&e.error(iv(0)),e.root=e.root.constrain(`divisor`,n)},iv=e=>`% operator must be followed by a non-zero integer literal (was ${e})`,av=e=>{let t=e.scanner.shift();return t===``?e.finalize(``):t===`[`?e.scanner.shift()===`]`?e.setRoot(e.root.array()):e.error(sv):t===`|`?e.scanner.lookahead===`>`?e.shiftedByOne().pushRootToBranch(`|>`):e.pushRootToBranch(t):t===`&`?e.pushRootToBranch(t):t===`)`?e.finalizeGroup():J_.lookaheadIsFinalizing(t,e.scanner.unscanned)?e.finalize(t):Lu(t,X_)?Y_(e,t):t===`%`?rv(e):t===`#`?nv(e):t in Ed?av(e):e.error(ov(t))},ov=(e,t=``)=>`'${e}' is not allowed here${t&&` (should be ${t})`}`,sv=`Missing expected ']'`,cv=e=>{let t=e.unsetRoot();e.parseOperand();let n=e.unsetRoot();if(!n.hasKind(`unit`))return e.error(lv(n.expression));let r=n.unit instanceof Date?()=>new Date(n.unit):n.unit;return[t,`=`,r]},lv=e=>`Default value '${e}' must a literal value`,uv=(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 mv(new J_(e),t),i=dv(r);return r.finalizer===`>`&&F(ov(`>`)),i},dv=e=>{e.parseOperand();let t=fv(e).root;return t?(e.finalizer===`=`?t=cv(e):e.finalizer===`?`&&(t=[t,`?`]),e.scanner.shiftUntilNonWhitespace(),e.scanner.lookahead&&F(ov(e.scanner.lookahead)),t):P(`Root was unexpectedly unset after parsing string '${e.scanner.scanned}'`)},fv=e=>{for(;e.finalizer===void 0;)pv(e);return e},pv=e=>e.hasRoot()?e.parseOperator():e.parseOperand();var mv=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 F(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(M_(`)`));this.finalizeBranches(),this.finalizer=e}reduceLeftBound(e,t){let n=A_[t];if(!Lu(n,O_))return this.error(P_(t));if(this.branches.leftBound)return this.error(F_(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(j_(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():P(`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 fv(new e(this.scanner,this.ctx))}parseOperator(){return av(this)}parseOperand(){return q_(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(N_(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 hv=`An empty string is not a valid generic parameter name`,gv=(e,t,n)=>{e.shiftUntilNonWhitespace();let r=e.shiftUntilNextTerminator();return r===``?e.lookahead===``&&t.length?t:F(hv):(e.shiftUntilNonWhitespace(),vv(e,r,t,n))},_v=`extends `,vv=(e,t,n,r)=>{if(e.shiftUntilNonWhitespace(),e.unscanned.startsWith(_v))e.jumpForward(8);else return e.lookahead===`,`&&e.shift(),n.push(t),gv(e,n,r);let i=fv(new mv(e,r));return n.push([t,i.root]),gv(e,n,r)};var yv=class extends hd{$;constructor(e){super((...t)=>new bv(e)(...t),{bind:e}),this.$=e}in(e){return new bv(this.$,e===void 0?void 0:this.$.parse(e))}at(e,t){return new bv(this.$).at(e,t)}case(e,t){return new bv(this.$).case(e,t)}},bv=class extends hd{$;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&&F(Cv),this.branches.length&&F(Sv),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&&F(`default may only be specified as the last key of a switch definition`),this.default(r);if(typeof r!=`function`)return F(`Value for case "${n}" must be a function (was ${ku(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:xv});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.configureReferences({onFail:xv},`self`)),this.$.finalize(r)}};const xv=e=>e.throw(),Sv=`A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')`,Cv=`At most one key matcher may be specified per expression`,wv=(e,t)=>{if(L(e)){if(e[1]===`=`)return[t.$.parseOwnDefinitionFormat(e[0],t),`=`,e[2]];if(e[1]===`?`)return[t.$.parseOwnDefinitionFormat(e[0],t),`?`]}return cy(e,t)},Tv=`Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }`,Ev=`Only required keys may specify default values, e.g. { value: 'number = 0' }`,Dv=(e,t)=>{let n,r={},i=Gu(e);for(let[e,a]of i){let i=jv(e);if(i.kind===`spread`){if(!Wu(r))return F(Av);let e=t.$.parseOwnDefinitionFormat(a,t);if(e.equals(q.object))continue;if(!e.hasKind(`intersection`)||!e.basis?.equals(q.object))return F(Mv(e.expression));n=e.structure;continue}if(i.kind===`undeclared`){a!==`reject`&&a!==`delete`&&a!==`ignore`&&F(kv(a)),r.undeclared=a;continue}let o=wv(a,t),s=i;if(i.kind===`required`){L(o)?Ov(r,`optional`,o[1]===`=`?{key:i.normalized,value:o[0],default:o[2]}:{key:i.normalized,value:o[0]},t):Ov(r,`required`,{key:i.normalized,value:o},t);continue}if(L(o)&&(o[1]===`?`&&F(Tv),o[1]===`=`&&F(Ev)),i.kind===`optional`){Ov(r,`optional`,{key:i.normalized,value:o},t);continue}let c=t.$.parseOwnDefinitionFormat(s.normalized,t),l=Mg(c,o,t.$);l.index&&(r.index=N(r.index,l.index)),l.required&&(r.required=N(r.required,l.required))}let a=t.$.node(`structure`,r);return t.$.parseSchema({domain:`object`,structure:n?.merge(a)??a})},Ov=(e,t,n,r)=>{e[t]=N(e[t],r.$.node(t,n))},kv=e=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${R(e)})`,Av=`Spread operator may only be used as the first key in an object`,jv=e=>typeof e==`symbol`?{kind:`required`,normalized:e}:e.at(-1)===`?`?e.at(-2)===Td?{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]===Td&&e[1]===`[`&&e.at(-1)===`]`?{kind:`required`,normalized:e.slice(1)}:e===`...`?{kind:`spread`}:e===`+`?{kind:`undeclared`}:{kind:`required`,normalized:e===`\\...`?`...`:e===`\\+`?`+`:e},Mv=e=>`Spread operand must resolve to an object literal type (was ${e})`,Nv=(e,t)=>Jv(e)?qv[e[0]](e,t):Gv(e)?Wv[e[1]](e,t):null,Pv=(e,t)=>t.$.parseOwnDefinitionFormat(e[1],t).keyof(),Fv=(e,t)=>{if(e[2]===void 0)return F(G_(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]===`&`?xp(n,r,t.$):Sp(n,r,t.$);return i instanceof W?i.throw():i},Iv=(e,t)=>t.$.parseOwnDefinitionFormat(e[0],t).array(),Lv=(e,t)=>typeof e[2]==`function`?t.$.parseOwnDefinitionFormat(e[0],t).pipe(e[2]):F(Rv(`=>`,e[2])),Rv=(e,t)=>`${e===`:`?`Narrow`:`Morph`} expression requires a function following '${e}' (was ${typeof t})`,zv=(e,t)=>typeof e[2]==`function`?t.$.parseOwnDefinitionFormat(e[0],t).constrain(`predicate`,e[2]):F(Rv(`:`,e[2])),Bv=(e,t)=>t.$.parseOwnDefinitionFormat(e[0],t).configureReferences(e[2],`shallow`),Vv=e=>e,Hv=Vv({"[]":Iv,"?":()=>F(E_)}),Uv=Vv({"|":Fv,"&":Fv,":":zv,"=>":Lv,"|>":Fv,"@":Bv,"=":()=>F(D_)}),Wv={...Hv,...Uv},Gv=e=>Wv[e[1]]!==void 0,Kv=e=>e,qv=Kv({keyof:Pv,instanceof:(e,t)=>{if(typeof e[1]!=`function`)return F(Yv(nd(e[1])));let n=e.slice(1).map(e=>typeof e==`function`?t.$.node(`proto`,{proto:e}):F(Yv(nd(e))));return n.length===1?n[0]:t.$.node(`union`,{branches:n})},"===":(e,t)=>t.$.units(e.slice(1))}),Jv=e=>qv[e[0]]!==void 0,Yv=e=>`Expected a constructor following 'instanceof' operator (was ${e})`,Xv=(e,t)=>{let n=[{}],r=0;for(;r<e.length;){let i=!1;e[r]===`...`&&r<e.length-1&&(i=!0,r++);let a=wv(e[r],t),[o,s,c]=L(a)?a:[a];if(r++,i){if(!o.extends(z.intrinsic.Array))return F(ny(o.expression));n=n.flatMap(e=>o.distribute(t=>ty(Nf(e),t)))}else n=n.map(e=>s===`?`?Qv(e,o):s===`=`?$v(e,o,c):Zv(e,o))}return t.$.parseSchema(n.map(e=>Wu(e)?{proto:Array,exactLength:0}:{proto:Array,sequence:e}))},Zv=(e,t)=>e.defaultables||e.optionals?F(e.variadic?gg:iy):(e.variadic?e.postfix=N(e.postfix,t):e.prefix=N(e.prefix,t),e),Qv=(e,t)=>e.variadic?F(ay):(e.optionals=N(e.optionals,t),e),$v=(e,t,n)=>e.variadic?F(ay):e.optionals?F(oy):(e.defaultables=N(e.defaultables,[[t,n]]),e),ey=(e,t)=>(e.postfix&&F(ry),e.variadic?e.variadic.equals(t)||F(ry):e.variadic=t.internal,e),ty=(e,t)=>{let n=t.select({method:`find`,kind:`sequence`});if(!n)return ey(e,z.intrinsic.unknown);if(n.prefix)for(let t of n.prefix)Zv(e,t);if(n.optionals)for(let t of n.optionals)Qv(e,t);if(n.variadic&&ey(e,n.variadic),n.postfix)for(let t of n.postfix)Zv(e,t);return e},ny=e=>`Spread element must be an array (was ${e})`,ry=`A tuple may have at most one variadic element`,iy=`A required element may not follow an optional element`,ay=`An optional element may not follow a variadic element`,oy=`A defaultable element may not follow an optional element without a default`,sy={},cy=(e,t)=>{if(typeof e==`string`){if(t.args&&Object.keys(t.args).some(t=>e.includes(t)))return uv(e,t);let n=sy[t.$.name]??={};return n[e]??=uv(e,t)}return Ou(e,`object`)?ly(e,t):F(dy(ku(e)))},ly=(e,t)=>{let n=td(e);switch(n){case void 0:return B(e,`root`)?e:Dv(e,t);case`Array`:return uy(e,t);case`RegExp`:return t.$.node(`intersection`,{domain:`string`,pattern:e},{prereduced:!0});case`Function`:{let t=pd(e)?e():e;return B(t,`root`)?t:F(dy(`Function`))}default:return F(dy(n??R(e)))}},uy=(e,t)=>Nv(e,t)??Xv(e,t),dy=e=>`Type definitions must be strings or objects (was ${e})`;var fy=class extends hd{constructor(e){let t=Object.assign({errors:np,hkt:_d,$: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,or:e.or,and:e.and,merge:e.merge,pipe:e.pipe},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 Lp(r,t[1],e,e,null)}return e.parse(t)},{bind:e,attach:t})}};const py=z;var my=class e extends Jg{get ambientAttachments(){if(py.typeAttachments)return this.cacheGetter(`ambientAttachments`,I(py.typeAttachments,(e,t)=>[e,this.bindReference(t)]))}preparseOwnAliasEntry(e,t){let n=e.indexOf(`<`);if(n===-1){if(B(t,`module`)||B(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)!==`>`&&F(`'>' 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=Fp(e,t,this);return n}]}parseGenericParams(e,t){return gv(new J_(e),[],this.createParseContext({...t,def:e,prefix:`generic`}))}normalizeRootScopeValue(e){return pd(e)&&!B(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=cy(e,t);if(L(r)){if(r[1]===`=`)return F(D_);if(r[1]===`?`)return F(E_)}return r}unit=e=>this.units([e]);valueOf=e=>this.units(Yu(e));enumerated=(...e)=>this.units(e);instanceOf=e=>this.node(`proto`,{proto:e},{prereduced:!0});or=(...e)=>this.schema(e.map(e=>this.parse(e)));and=(...e)=>e.reduce((e,t)=>e.and(this.parse(t)),this.intrinsic.unknown);merge=(...e)=>e.reduce((e,t)=>e.merge(this.parse(t)),this.intrinsic.object);pipe=(...e)=>this.intrinsic.unknown.pipe(...e);match=new yv(this);declare=()=>({type:this.type});define(e){return e}type=new fy(this);static scope=((t,n={})=>new e(t,n));static module=((e,t={})=>this.scope(e,t).export())};const hy=Object.assign(my.scope,{define:e=>e}),J=my;var gy=class extends _d{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'};const _y=o_([`base`,q.object],[`props`,q.object])(e=>e.base.merge(e.props),gy),vy=J.module({Key:q.key,Merge:_y});var yy=class extends _d{};const by=o_(`element`)(e=>{let t=e.element.exclude(q.Array),n=t.array();return t.rawOr(n).pipe(vu).distribute(e=>e.assertHasKind(`morph`).declareOut(n),K)},yy),xy=J.module({root:q.Array,readonly:`root`,index:q.nonNegativeIntegerString,liftFrom:by},{name:`Array`}),Sy=K([`string`,$d.FileConstructor]),Cy=Sy.rawOr(Sy.array()),wy=K({meta:`an object representing parsed form data`,domain:`object`,index:{signature:`string`,value:Cy}}),Ty=J.module({root:[`instanceof`,FormData],value:Sy,parsed:wy,parse:K({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 $d.FileConstructor?t[n]=[e,r]:e.push(r)}else t[n]=r;return t},declaredOut:wy})},{name:`FormData`}),Ey=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`}),Dy={Boolean:1,Number:1,String:1},Oy=J.module({...I({...Xu,...Qu},(e,t)=>e in Dy?[]:[e,[`instanceof`,t]]),Array:xy,TypedArray:Ey,FormData:Ty}),ky=K({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`}),Ay=K({domain:`number`,divisor:1}),jy=J.module({root:q.number,integer:Ay,epoch:ky,safe:K({domain:{domain:`number`,numberAllowsNaN:!1},min:-9007199254740991,max:9007199254740991}),NaN:[`===`,NaN],Infinity:[`===`,1/0],NegativeInfinity:[`===`,-1/0]},{name:`number`}),Y=(e,t,n)=>{let r={domain:`string`,pattern:{rule:e.source,flags:e.flags,meta:t}};return n&&(r.meta={format:n}),a_(`intersection`,r)},My=Y(Ld,`a well-formed integer string`),Ny=J.module({root:My,parse:K({in:My,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`}),Py=Y(/^[\dA-Fa-f]+$/,`hex characters only`),Fy=J.module({root:Y(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,`base64-encoded`),url:Y(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,`base64url-encoded`)},{name:`string.base64`}),Iy=Y(/^[A-Z].*$/,`capitalized`),Ly=J.module({root:K({in:`string`,morphs:e=>e.charAt(0).toUpperCase()+e.slice(1),declaredOut:Iy}),preformatted:Iy},{name:`string.capitalize`}),Ry=e=>{let t=e.replaceAll(/[ -]+/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,n+=i>=10?i%10+1:i):n+=i,a=!a;return!!(n%10==0&&t)},zy=/^(?:4\d{12}(?:\d{3,6})?|5[1-5]\d{14}|(222[1-9]|22[3-9]\d|2[3-6]\d{2}|27[01]\d|2720)\d{12}|6(?:011|5\d\d)\d{12,15}|3[47]\d{13}|3(?:0[0-5]|[68]\d)\d{11}|(?:2131|1800|35\d{3})\d{11}|6[27]\d{14}|^(81\d{14,17}))$/,By=K({domain:`string`,pattern:{meta:`a credit card number`,rule:zy.source},predicate:{meta:`a credit card number`,predicate:Ry}}),Vy=/^([+-]?\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)?)?)?)?$/,Hy=e=>!Number.isNaN(new Date(e).valueOf()),Uy=K({domain:`string`,predicate:{meta:`a parsable date`,predicate:Hy}}).assertHasKind(`intersection`),Wy=Ny.root.internal.narrow((e,t)=>{let n=Number.parseInt(e),r=jy.epoch(n);return r instanceof np?(t.errors.merge(r),!1):!0}).configure({description:`an integer string representing a safe Unix timestamp`},`self`).assertHasKind(`intersection`),Gy=J.module({root:Wy,parse:K({in:Wy,morphs:e=>new Date(e),declaredOut:q.Date})},{name:`string.date.epoch`}),Ky=Y(Vy,`an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date`).internal.assertHasKind(`intersection`),qy=J.module({root:Ky,parse:K({in:Ky,morphs:e=>new Date(e),declaredOut:q.Date})},{name:`string.date.iso`}),Jy=J.module({root:Uy,parse:K({declaredIn:Uy,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:qy,epoch:Gy},{name:`string.date`}),Yy=Y(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,`an email address`,`email`),Xy=`(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])`,Zy=`(${Xy}[.]){3}${Xy}`,Qy=RegExp(`^${Zy}$`),X=`(?:[0-9a-fA-F]{1,4})`,$y=RegExp(`^((?:${X}:){7}(?:${X}|:)|(?:${X}:){6}(?:${Zy}|:${X}|:)|(?:${X}:){5}(?::${Zy}|(:${X}){1,2}|:)|(?:${X}:){4}(?:(:${X}){0,1}:${Zy}|(:${X}){1,3}|:)|(?:${X}:){3}(?:(:${X}){0,2}:${Zy}|(:${X}){1,4}|:)|(?:${X}:){2}(?:(:${X}){0,3}:${Zy}|(:${X}){1,5}|:)|(?:${X}:){1}(?:(:${X}){0,4}:${Zy}|(:${X}){1,6}|:)|(?::((?::${X}){0,5}:${Zy}|(?::${X}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?\$`),eb=J.module({root:[`v4 | v6`,`@`,`an IP address`],v4:Y(Qy,`an IPv4 address`,`ipv4`),v6:Y($y,`an IPv6 address`,`ipv6`)},{name:`string.ip`}),tb=`a JSON string`,nb=e=>{if(!(e instanceof SyntaxError))throw e;return`must be ${tb} (${e})`},rb=K({meta:tb,domain:`string`,predicate:{meta:tb,predicate:(e,t)=>{try{return JSON.parse(e),!0}catch(e){return t.reject({code:`predicate`,expected:tb,problem:nb(e)})}}}}),ib=(e,t)=>{if(e.length===0)return t.error({code:`predicate`,expected:tb,actual:`empty`});try{return JSON.parse(e)}catch(e){return t.error({code:`predicate`,expected:tb,problem:nb(e)})}},ab=J.module({root:rb,parse:K({meta:`safe JSON string parser`,in:`string`,morphs:ib,declaredOut:q.jsonObject})},{name:`string.json`}),ob=Y(/^[a-z]*$/,`only lowercase letters`),sb=J.module({root:K({in:`string`,morphs:e=>e.toLowerCase(),declaredOut:ob}),preformatted:ob},{name:`string.lower`}),cb=[`NFC`,`NFD`,`NFKC`,`NFKD`],lb=I(cb,(e,t)=>[t,K({domain:`string`,predicate:e=>e.normalize(t)===e,meta:`${t}-normalized unicode`})]),ub=I(cb,(e,t)=>[t,K({in:`string`,morphs:e=>e.normalize(t),declaredOut:lb[t]})]),db=J.module({root:ub.NFC,preformatted:lb.NFC},{name:`string.normalize.NFC`}),fb=J.module({root:ub.NFD,preformatted:lb.NFD},{name:`string.normalize.NFD`}),pb=J.module({root:ub.NFKC,preformatted:lb.NFKC},{name:`string.normalize.NFKC`}),mb=J.module({root:ub.NFKD,preformatted:lb.NFKD},{name:`string.normalize.NFKD`}),hb=J.module({root:`NFC`,NFC:db,NFD:fb,NFKC:pb,NFKD:mb},{name:`string.normalize`}),gb=Y(Pd,`a well-formed numeric string`),_b=J.module({root:gb,parse:K({in:gb,morphs:e=>Number.parseFloat(e),declaredOut:q.number})},{name:`string.numeric`}),vb=`a regex pattern`,yb=K({domain:`string`,predicate:{meta:vb,predicate:(e,t)=>{try{return new RegExp(e),!0}catch(e){return t.reject({code:`predicate`,expected:vb,problem:String(e)})}}},meta:{format:`regex`}}),bb=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*))*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/,xb=Y(bb,`a semantic version (see https://semver.org/)`),Sb=Y(/^\S.*\S$|^\S?$/,`trimmed`),Cb=J.module({root:K({in:`string`,morphs:e=>e.trim(),declaredOut:Sb}),preformatted:Sb},{name:`string.trim`}),wb=Y(/^[A-Z]*$/,`only uppercase letters`),Tb=J.module({root:K({in:`string`,morphs:e=>e.toUpperCase(),declaredOut:wb}),preformatted:wb},{name:`string.upper`}),Eb=e=>{if(URL.canParse)return URL.canParse(e);try{return new URL(e),!0}catch{return!1}},Db=K({domain:`string`,predicate:{meta:`a URL string`,predicate:Eb},meta:{format:`uri`}}),Ob=J.module({root:Db,parse:K({declaredIn:Db,in:`string`,morphs:(e,t)=>{try{return new URL(e)}catch{return t.error(`a URL string`)}},declaredOut:K(URL)})},{name:`string.url`}),kb=J.module({root:[`versioned | nil | max`,`@`,{description:`a UUID`,format:`uuid`}],"#nil":`'00000000-0000-0000-0000-000000000000'`,"#max":`'ffffffff-ffff-ffff-ffff-ffffffffffff'`,"#versioned":/[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}/i,v1:Y(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv1`),v2:Y(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv2`),v3:Y(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv3`),v4:Y(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv4`),v5:Y(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv5`),v6:Y(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv6`),v7:Y(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv7`),v8:Y(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv8`)},{name:`string.uuid`}),Ab=J.module({root:q.string,alpha:Y(/^[A-Za-z]*$/,`only letters`),alphanumeric:Y(/^[\dA-Za-z]*$/,`only letters and digits 0-9`),hex:Py,base64:Fy,capitalize:Ly,creditCard:By,date:Jy,digits:Y(/^\d*$/,`only digits 0-9`),email:Yy,integer:Ny,ip:eb,json:ab,lower:sb,normalize:hb,numeric:_b,regex:yb,semver:xb,trim:Cb,upper:Tb,url:Ob,uuid:kb},{name:`string`}),jb=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}),Mb=J.module({root:q.unknown,any:q.unknown},{name:`unknown`}),Nb=J.module({root:q.jsonObject,stringify:a_(`morph`,{in:q.jsonObject,morphs:e=>JSON.stringify(e),declaredOut:q.string})},{name:`object.json`}),Pb=J.module({root:q.object,json:Nb},{name:`object`});var Fb=class extends _d{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'};const Ib=o_([`K`,q.key],`V`)(e=>({domain:`object`,index:{signature:e.K,value:e.V}}),Fb);var Lb=class extends _d{description='pick a set of properties from an object like `Pick(User, "name | age")`'};const Rb=o_([`T`,q.object],[`K`,q.key])(e=>e.T.pick(e.K),Lb);var zb=class extends _d{description='omit a set of properties from an object like `Omit(User, "age")`'};const Bb=o_([`T`,q.object],[`K`,q.key])(e=>e.T.omit(e.K),zb);var Vb=class extends _d{description="make all named properties of an object optional like `Partial(User)`"};const Hb=o_([`T`,q.object])(e=>e.T.partial(),Vb);var Ub=class extends _d{description="make all named properties of an object required like `Required(User)`"};const Wb=o_([`T`,q.object])(e=>e.T.required(),Ub);var Gb=class extends _d{description='exclude branches of a union like `Exclude("boolean", "true")`'};const Kb=o_(`T`,`U`)(e=>e.T.exclude(e.U),Gb);var qb=class extends _d{description='extract branches of a union like `Extract("0 | false | 1", "number")`'};const Jb=o_(`T`,`U`)(e=>e.T.extract(e.U),qb),Yb=J.module({Exclude:Kb,Extract:Jb,Omit:Bb,Partial:Hb,Pick:Rb,Record:Ib,Required:Wb}),Xb=hy({...jb,...Yb,...Oy,...vy,string:Ab,number:jy,object:Pb,unknown:Mb},{prereducedAliases:!0,name:`ark`}),Z=Xb.export();Object.assign(py.ambient,Z),py.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(Xb.type,py.typeAttachments),Xb.match,Xb.generic,Xb.schema,Xb.define,Xb.declare;function Zb(e){return e}function Qb(e){return e?t=>(e(t),t):Zb}const $b=Qb();function ex(e,t){return fu.get(`/v1/public/raven/games/${e}/builds/${t}`)}function tx(e,t){return fu.post(`/v1/public/raven/games/${e}/builds/upload`,null,{params:t})}function nx(e,t){let n=new FormData;return n.append(`file`,t.chunk),fu.patch(`/v1/public/raven/games/${e}/builds/upload`,n,{params:t})}function rx(e){return e instanceof Error&&(e.name===`XiorError`||e.name===`XiorTimeoutError`)}function ix(e){return!!(e&&`kind`in e.data&&`message`in e.data)}let ax;function ox(e){ax=e}var sx=class extends $c{UPDATE_CHECK_INTERVAL_MS=1e3*60*5;targetDir;updateInterval;constructor(){super(`NativeModuleManager`),this.targetDir=h.join(Uc(),`resources`),this.logger.log(`Target directory`,this.targetDir)}async initWithDlls(e){super.init(),await ge.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=h.join(this.targetDir,e,`version.txt`);return await ge.readFile(t,`utf-8`)}catch{return null}}getTargetPath(e){return h.join(this.targetDir,e)}getTargetVersionPath(e,t){return h.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 ax?.();for(let n of e)try{let{data:e}=await mu(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 hu(e,n),a=this.getTargetPath(e),o=this.getTargetVersionPath(e,t);await ge.mkdir(o,{recursive:!0});let s=new _e;await s.loadAsync(i);let c=Object.keys(s.files).map(async t=>{let n=s.files[t];if(n&&!n.dir){let i=h.join(o,t);if(!r)try{await ge.access(i,ge.constants.F_OK);return}catch{this.logger.warn(`${e} > File missing, re-downloading: ${i}`)}let a=await n.async(`nodebuffer`);await ge.writeFile(i,a)}});await Promise.all(c);let l=h.join(a,`version.txt`);this.logger.log(`Saving version file`,l),await ge.writeFile(l,t)}async cleanupOldVersions(e,t){let n=h.join(this.targetDir,e),r=await ge.readdir(n,{withFileTypes:!0});for(let e of r)e.isDirectory()&&e.name!==t&&await ge.rm(h.join(n,e.name),{recursive:!0,force:!0})}};const cx=Rc(sx);var lx=class extends $c{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),cx.getInstance().destroy(),super.destroy()}async fetchRavenConfig(){try{let e=await _u(),t={games:[...e.data.games,{name:`Valorant`,identifier:$b(`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 cx.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 ux=Rc(lx),dx=e(import.meta.url),{PipeEventServer:fx,PipeEventClient:px,PipeEventBase:mx,ProcessMonitor:hx,Process:gx,InjectionMethod:_x,AccessLevel:vx,HardwareInterface:yx}=dx(`@overlayed/app/dist/native-interface/build/overlayed_native_interface_x64.node`);var bx=class extends $c{_processMonitor;_processes=new Map;boundOnRavenManagerExecutablesUpdated=this.onRavenManagerExecutablesUpdated.bind(this);constructor(){super(`ProcessManager`),this._processMonitor=new hx}get hasAnyActiveProcesses(){return this.activeProcesses.length>0}get activeProcesses(){return Array.from(this._processes.values()).flat().filter(e=>!e.destroyedAt)}init(){super.init(),ux.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(){ux.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 xx=Rc(bx),Sx=e(import.meta.url),{RenderInterface:Cx,renderHookPath:wx}=Sx(`@overlayed/app/dist/render-interface/build/overlayed_render_interface_x64.node`);var Tx=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}}},Ex=class{interfaces={};constructor(){}createInterface(e){return this.interfaces[e]||(this.interfaces[e]=new Tx(new Cx(e,{access:1}))),this.interfaces[e]}getInterface(e){return this.interfaces[e]?this.interfaces[e]:this.createInterface(e)}};const Dx=Rc(Ex);var Ox=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 Hi,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 kx=Rc(Ox),Ax=e(import.meta.url),jx=Ax.resolve(`@overlayed/app/dist/render-interface/build/overlayed_render_hook_x64.dll`);var Mx=class extends el{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(),Dx.getInstance().createInterface(`OGG_SIEGE`),xx.getInstance().on(`create`,this.boundOnProcessCreate),xx.getInstance().on(`destroy`,this.boundOnProcessDestroy)}destroy(){xx.getInstance().off(`create`,this.boundOnProcessCreate),xx.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: `,gx.currentProcess.isElevated),e.isElevated&&!gx.currentProcess.isElevated){Bc.getInstance().fatal(`Game is elevated but the App is not`,`ELEVATION_MISMATCH`,{appElevated:!!gx.currentProcess.isElevated,gameElevated:!!e.isElevated}),this.logger.log(`Game elevated but App is not`,{appElevated:gx.currentProcess.isElevated,gameElevated:e.isElevated});return}let r=this.copyDll(jx);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 cx.getInstance().getCurrentVersion(t);if(!n)return this.logger.error(`No version found for DLL`,{identifier:t}),Promise.resolve();let r=cx.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=h.basename(t),i=h.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}),kx.getInstance().track(`game_launch`,{game:t.identifier})}copyDll(e){let t=h.basename(e),n=_(e),r=h.join(Uc(),`resources`),i=h.join(r,t);this.logger.info(`Copying`,n,`to`,i);try{ne(r)||re(r,{recursive:!0});let e=ie(n);oe(i,e),ee(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 ge.readdir(e);return t.filter(e=>e.endsWith(`.dll`)).map(t=>h.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}),kx.getInstance().track(`game_close`,{game:t.identifier}))}getRavenGame(e){if(!e.name)return;let t=ux.getInstance().getExecutableData(e.name);if(!t){this.logger.error(`No raven game found for process`,{process:e});return}return t}};const Nx=Rc(Mx);var Px=class extends Qc{boundOnGameLaunch=this.onGameLaunch.bind(this);constructor(){super(`GameBuildManager`)}init(){super.init(),Nx.getInstance().on(`gameReadyInternal`,this.boundOnGameLaunch)}destroy(){Nx.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=ie(n.path),i=ve(`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 ex(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 _e;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 Yc(s,{chunkSizeMb:25,maxConcurrent:1}),n=await tx(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 nx(t.identifier,{chunk:e,build_hash:i,chunk_index:r,upload_token:n.data.upload_token})}),this.logger.log(`Build uploaded successfully`)}catch(e){rx(e)?ix(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 Fx=Rc(Px);function Ix(e=[]){return h.normalize(h.join(Gc(global.OVERLAYED.APPLICATION_ID),...e))}const Lx=n({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 Rx=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`]]),zx=new Map(Rx.entries().map(([e,t])=>[t,e])),Bx=n({"[string]":{keys:`string[]`,mode:n(`'toggle' | 'hold'`).pipe(e=>e??`toggle`)}});var Vx=class extends $c{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 Vc({path:Ix([`keybinds.json`]),schema:Bx,default:e})}init(){super.init();let e=Dx.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=Dx.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=Rx.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=Rx.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=>zx.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=>zx.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}`:``})`}},Hx=class extends Qc{renderInterface;globalCursorOverrideCount=new Set;globalMouseBlockCount=new Set;globalKeyboardBlockCount=new Set;keyInputBlocks={};constructor(e){super(`OverridesManager`),this.renderInterface=Dx.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 Ux=Rc(Hx,`OGG_SIEGE`);var Wx=De((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}}),Gx=ke(Wx(),1);let Kx=!1,qx;function Jx(e){let{init:t=!0}=e;if(Yx(e),Jc.getInstance().init(e.applicationId),Kx)return qx;function n(){uS(e);let t=new Map,r=Qx(e.modules,t),i=$x(),a=nS(e.keybinds),o=rS(),s=iS(),c=oS(),l=aS(),u=sS();Xx(e),tS(e,t),Kx=!0,qx={...r,...i,ads:c,keybinds:a,windows:o,input:s,cortex:l,hasAnyActiveProcesses:()=>xx.getInstance().hasAnyActiveProcesses,init:n,log:u,initialized:Kx}}return t?(n(),qx):new Proxy({init:n},{get:(e,t)=>{if(t!==`init`&&!Kx)throw Error(`overlayed was called before initialized: ${t}`);return t===`init`?e[t]:qx[t]}})}global.OVERLAYED=new Proxy({},{get:()=>{throw Error(`function overlayed was not called`)}});function Yx(e){global.OVERLAYED={APPLICATION_ID:e.applicationId,APP_BUILD_CHANNEL:e.channel??`alpha`,APP_VERSION:e.version??be.getVersion(),electron:e.electron}}function Xx(e){let t=e.universal?[`*`]:e.modules.map(e=>e.key);Nx.getInstance().setSubscribedGames(t),Fx.getInstance().init(),Nx.getInstance().init(),xx.getInstance().init(),ux.getInstance().init();async function n(){let e=pu(global.OVERLAYED.APPLICATION_ID).then(e=>e.data),t=yx.generateUniqueIdentifier();Jc.getInstance().log(`userId`,t);let n={...await e,userId:t};return Jc.getInstance().log(`appInfo`,n),n}let r;global.OVERLAYED.electron.ipcMain.handle(`getAppInfo`,async()=>(r=r??n(),r)),be.on(`quit`,()=>{Zx()})}function Zx(){ux.getInstance().destroy(),Nx.getInstance().destroy(),Fx.getInstance().destroy(),xx.getInstance().destroy(),Dx.getInstance().getInterface(`OGG_SIEGE`).destroy(),Bi.getInstance().destroy(),Bc.getInstance().destroy()}function Qx(e,t){return e.reduce((e,n)=>{let r=n.key;return e[r]={on(e,n){let i=eS(r,e),a=t.get(i)??new Set;a.add(n),t.set(i,a)},onAny(e){let n=eS(r,`*`),i=t.get(n)??new Set;i.add(e),t.set(n,i)},off(e,n){let i=eS(r,e),a=t.get(i)??new Set;a.delete(n),t.set(i,a)},offAny(e){let n=eS(r,`*`),i=t.get(n)??new Set;i.delete(e),t.set(n,i)}},e},{})}function $x(){let e=Bc.getInstance(),t=Nx.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 eS(e,t){return`${e}:${t}`}function tS(e,t){let r=Bi.getInstance();function i(r){let i=Lx(r);if(i instanceof n.errors){Bc.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 n.errors){Bc.getInstance().warn(`Invalid event`,`INVALID_EVENT`,{summary:s.summary});return}let c=eS(a.key,s.type),l=eS(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 r.on(`data`,e=>e.forEach(i)),r.on(`error`,e=>{Bc.getInstance().error(`Pipe server error`,`PIPE_SERVER_ERROR`,{error:e})}),r}function nS(e){let t=new Vx(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(),be.on(`quit`,()=>{t.destroy()}),r}function rS(){return{createWindow:e=>$().instance.newWindowInternal(ye.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=Bi.getInstance();return{resolution:e.resolution,isConnected:t.hasConnection}}}}function iS(){return{scope:e=>Ux.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 aS(){return{track:(e,t)=>kx.getInstance().track(`custom__${e}`,t)}}function oS(){return{registerWindow:e=>{(0,Gx.setupRevUtils)(e,global.OVERLAYED.electron)}}}function sS(){let e=new qc(`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=cS(t),r=await n.generateAsync({type:`base64`}),i=await lS(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 cS(e){let t=Kc(global.OVERLAYED.APPLICATION_ID),n=Xc(t),r=Wc(),i=Xc(r);Jc.getInstance().info(`Logs path: `,t),Jc.getInstance().info(`Overlayed logs path: `,r);let a=new _e;return[...n,...i].forEach(([e,t])=>{Jc.getInstance().info(`Zipping: `,e,t);let n=`${e}/${t}`,r=te(n);a.file(t,r,{compression:`DEFLATE`})}),Object.entries(e?.additionalFiles??{}).forEach(([e,t])=>{Jc.getInstance().info(`Zipping extra file: `,e),a.file(e,t,{compression:`DEFLATE`})}),a}async function lS(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 uS(e){kx.getInstance().clientId=e.applicationId,kx.getInstance().userId=yx.generateUniqueIdentifier(),Bc.getInstance().on(`fatal`,e=>{kx.getInstance().track(`fatal`,{message:e.message,code:e.code,data:e.data})}),Bc.getInstance().on(`error`,e=>{kx.getInstance().track(`error`,{message:e.message,code:e.code,data:e.data})}),Bc.getInstance().on(`warning`,e=>{kx.getInstance().track(`warning`,{message:e.message,code:e.code,data:e.data})})}function $(){return Dx.getInstance().getInterface(`OGG_SIEGE`)}export{Zc as defineConfig,Jx as overlayed,ox as setFetchLatestTokenCallback,du as setUpdaterTokenResolver};
|